From andre.roberge at gmail.com Fri Jan 21 20:01:00 2005 From: andre.roberge at gmail.com (=?UTF-8?B?QW5kcsOpIFJvYmVyZ2U=?=) Date: Fri, 21 Jan 2005 21:01:00 -0400 Subject: finding name of instances created In-Reply-To: <1106353764.19065.89.camel@bucket.localnet> References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> Message-ID: Craig Ringer wrote: > On Fri, 2005-01-21 at 16:13 -0800, Andr? wrote: > >>Short version of what I am looking for: >> >>Given a class "public_class" which is instantiated a few times e.g. >> >>a = public_class() >>b = public_class() >>c = public_class() >> >>I would like to find out the name of the instances so that I could >>create a list of them e.g. >>['a', 'b', 'c'] [snip] > > > I'm not really able to grasp what you're trying to do (but others > might). It wouldn't hurt if you could post a description of what you're > actually trying to achieve - /why/ you want this - as that can often be > very helpful both in understanding what you're thinking and in > suggesting a suitable approach or alternative. > Ok, here it goes... I am designing a "learning environment" for Python. (See rur-ple.sourceforge.org for details of a *very early, still buggy* relase). I have a "world" in which a "robot" can accomplish four built-in instructions: move(), turn_left(), pick_beeper(), put_beeper(). turn_left() corresponds to a 90 degree left turn. One can define a function to simulate a 90 degree right turn as follows: def turn_right(): turn_left() turn_left() turn_left() and call it as a built-in instruction thereafter. By giving more and more complicated tasks for the robot to accomplish, one can learn various programming concepts using python syntax: def (as above), while, if, else, elif, ...... I have all of that working well so far (not on sourceforge yet). Next, I want to introduce the concept of classes and objects, again using python's syntax. Behind the scene, I have something like: robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') } and have mapped move() to correspond to robot_dict['robot'].move() (which does lots of stuff behind the scene.) I have tested robot_dict[] with more than one robot (each with its own unique name) and am now at the point where I would like to have the ability to interpret something like: alex = CreateRobot() anna = CreateRobot() alex.move() anna.move() etc. Since I want the user to learn Python's syntax, I don't want to require him/her to write alex = CreateRobot(name = 'alex') to then be able to do alex.move() I have tried various things at the interpreter, found that to a class 'a', I could see the instance 'b' created in locals(): 'a': , 'b': <__main__.a object at 0x011515D0> which tells me that there must be a way to catch b's name as it is created, and do what I want to do. Does this clarify what I am trying to do and why? Andr? From http Sat Jan 22 19:04:46 2005 From: http (Paul Rubin) Date: 22 Jan 2005 16:04:46 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> Message-ID: <7xhdl9huxt.fsf@ruckus.brouhaha.com> "A.M. Kuchling" writes: > It was discussed in this thread: > http://mail.python.org/pipermail/python-dev/2003-April/034959.html In that thread, you wrote: > Rubin wanted to come up with a nice interface for the module, and > has posted some notes toward it. I have an existing implementation > that's 2212 lines of code; I like the interface, but opinions may > vary. :) Does that mean you have a 2212-line C implementation of the interface that I proposed? Do you plan to release it? BTW, I just looked at the other messages in that thread and I realize that I've looked at them before, and that's where I saw the concern about importing crypto into some countries including Holland. Again, I think the reasoning is bizarre. I'm sure there are tons of Firefox users in Holland, and Firefox definitely contains an SSL stack that doesn't have to be downloaded separately. From r.roelofsen at tuxed.de Tue Jan 4 19:50:43 2005 From: r.roelofsen at tuxed.de (Roman Roelofsen) Date: Wed, 5 Jan 2005 01:50:43 +0100 Subject: coding conventions, PEP vs. practice Message-ID: <200501050150.43556.r.roelofsen@tuxed.de> Dear python-list, while looking for some coding conventions for python programs, i found the PEP8 at http://www.python.org/peps/pep-0008.html. It defines the rules very well and leaves no space for interpretations. I guess thats a good thing :-) But when i started playing a bit with python and frameworks like Zope, Webworks, etc., i noticed, that a lot frameworks are using a different convention for methodnames. These frameworks are using "mixedCase" but PEP8 suggests "lower_case_with_underscores" except "in contexts where that's already the prevailing style" which is not the case here IMHO. So, are there any specific reasons for breaking the rules here? I think consistent conventions are very important. Being a Java developer in the last couple of years, i learned how practical it can be to have only one naming style. Best regards, Roman From duncan.booth at invalid.invalid Fri Jan 28 10:30:43 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Jan 2005 15:30:43 GMT Subject: a sequence question References: Message-ID: Chris Wright wrote: > 1) I want to iterate over a list "N at a time" > sort of like: > > # Two at a time... won't work, obviously > > >>> for a, b in [1,2,3,4]: > ... print a,b > ... Try this: l = [1, 2, 3, 4] for a, b in zip(*[iter(l)]*2): print a, b zip(*[iter(seq)]*N) will group by N (but if there are any odd items at the end it will ignore them). map(None, *[iter(seq)]*N) will group by N padding the last item with None if it needs to. From davorss at gmail.com Tue Jan 25 18:01:23 2005 From: davorss at gmail.com (Davor) Date: 25 Jan 2005 15:01:23 -0800 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <1106694083.199064.240680@f14g2000cwb.googlegroups.com> Thanks, I do not hate OO - I just do not need it for the project size I'm dealing with - and the project will eventually become open-source and have additional developers - so I would prefer that we all stick to "simple procedural" stuff rather than having to deal with a developer that will be convincing me that his 50 layers inheritance hierarchy is good since it exists in some weird pattern that he saw somewhere on some Java design patterns discussion board :-) and other "proper" OO design issues... Once I opted for C++ in a very small project and believed everyone will stick with C subset + better type checking offered through C++ - but I simply could not manage to keep them off using OO stuff which was just making program more complicated than it should have been. (note, I am not an experienced developer, nor the others I'll be working with (even though some think they are:-)), so I prefer preemptively dealing with issue of everyone showing off their OO design skills) Davor From gosselit at norwich.edu Tue Jan 11 18:40:36 2005 From: gosselit at norwich.edu (Tim Gosselin) Date: Tue, 11 Jan 2005 23:40:36 +0000 Subject: Detecting shutdown of remote socket endpoint. Message-ID: <1105504107.d645f57ce935d6cb8e82567c0be1e97e@onlynews> I am writing a tcp tunnel but cannot find a way of detecting when a socket shuts down its read end without writing to the socket. For testing the write end of the remote endpoint I just do a: if not sock.recv(buffsize) I cannot write to the socket and check if send returns 0 though, because that involves sending data out of the which may not have come in yet. When I try polling the socket with: r, w, e=select([],[sock],[], 0) w returns with the socket still writable, even if the other end was closed. #For example: s=socket() s.bind(('localhost', 5000)) s.listen(5) s2, addr=s.accept() #then create a socket to connect, s=socket() s.connect(('localhost', 5000)) #then I close the server side, s2.close() #or s2.shutdown(0) #and poll s to see if it's still writable, r, w, e=select([],[s],[], 0) #this returns that the socket is writable! and i can even write to it, s.send('test') #succeeds #but the second write finally throws an exception. Is there any other way to check if a the remote endpoint on a socket has shutdown its read end? Is it difficult to implement a sock.is_shutdown(1) with some additional c code? From dbickett at gmail.com Sun Jan 23 10:57:25 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 23 Jan 2005 10:57:25 -0500 Subject: how to write a tutorial In-Reply-To: <1106472508.591411.40140@c13g2000cwb.googlegroups.com> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: <1d6cdae3050123075756536a66@mail.gmail.com> > Most texts in computing are written by authors to defend and showcase > their existence against their peers. When you aren't busy `showcasing' your ignorance, this is *all* i see in everything you write. > In a tutorial, nobody cares how > the language compared to x y and z, or what technicality is it all > about, or some humorous snippet of history only funny to the author > himself. You couldn't be farther from the truth. To preface a document by illustrating it's similarities to other languages is to better prepare a reader who may have experience in those languages. As for the snippet of history, few people desire to live life as cynical as you do, and one would hope even fewer take their own opinion and assume it applies to their peers, as you have just done. > Particularly for texts in a tutorial context, you want to write it as > simple as possible covering the most useful basic functionalities and > concepts, and self-contained. Not showcasing your knowledge of history > of languages or your linguistic lineage byways. You of all people are the least qualified to say this, as you are the most guilty of such a crime. > For example this chapter 9 on Objects, it is not difficult to write it > without making a show of lingoes. One simply write what is of Python, > without thinking about relation to xyz languages or the "computer > science" establishment and their ways of thinkings of namespaces and > scopes and dynamic and statics and inheritances ... fucking bags of > shit. Then please be so kind as to give us all a pleasant surprise, and take the place of the productive reformer rather than the angsty criticizer. Your vision as to the errors in the tutorial is *clearly* less clouded than ours, so only *you* are in the position to write the proper replacement. Daniel Bickett From foo at bar.com Sun Jan 23 01:06:35 2005 From: foo at bar.com (Steve Menard) Date: Sun, 23 Jan 2005 01:06:35 -0500 Subject: JPype and classpath (Was Re: embedding jython in CPython... ) In-Reply-To: <1106446384.384110.25150@z14g2000cwz.googlegroups.com> References: <1106446384.384110.25150@z14g2000cwz.googlegroups.com> Message-ID: > While we are on topic, I am having some trouble understanding JPype > classpath. How do I init the JVM with the folder in which the Python > program is located included in the classpath? > > I tried > t = JPackage('.').test > > That did not work. > > My environment variable includes current folder in the classpath > > I tried passing it as an argument to startJVM. Didn't help. > > I think my main use is going to be using CPython with a few Java custom > classes and if anyone has a snippet on this it would really help me. > Thanks > That's easy. First realise that "." denotes the current working directory, not the "directory where the python program is located". Second, JPackage uses Java package names. So, assuming you java classes are properly stord in a directory called "classes" at the same level as your python script (see how java looks up classes on the filesystem for what "properly" means), here is a snippet that will do what you wanted : #============================================================== import os, os.path, jpype root = os.path.abspath(os.path.dirname(__file__)) jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.class.path=%s%sclasses" % (root, os.sep)) #============================================================== Or alternately, if the Java classes you want to use ar in JAR files, in a lib directory at the same level as your python script : #============================================================== import os, os.path, jpype root = os.path.abspath(os.path.dirname(__file__)) jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s%slib" % (root, os.sep)) #============================================================== The magic in the above script is the __file__ variable, which stores the absolute path to the currently executing Python script. If you have both situation (you classes in the classes directory and some JARS containing stuff that they uses) you can combine the above : #============================================================== import os, os.path, jpype root = os.path.abspath(os.path.dirname(__file__)) jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.class.path=%s%sclasses" % (root, os.sep), "-Djava.ext.dirs=%s%slib" % (root, os.sep)) #============================================================== Hopefully this will help. -- Steve Menard -------------------- Maintainer of http://jpype.sourceforge.net From bokr at oz.net Thu Jan 13 01:26:08 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 06:26:08 GMT Subject: why are people still using classic classes? References: <7x6522gegg.fsf@ruckus.brouhaha.com> Message-ID: <41e612dc.719526364@news.oz.net> On 12 Jan 2005 20:06:39 -0800, Paul Rubin wrote: >Simon Wittber writes: >> > Is there a reason NOT to use them? If a classic class works fine, what >> > incentive is there to switch to new style classes? >> >> Perhaps classic classes will eventually disappear? > >It just means that the formerly "classic" syntax will define a >new-style class. Try to write code that works either way. > >It would be nice if a __future__ directive were added right now (if >it's not there already) that processes all class definitions as >new-style. Otherwise there's no easy way to test for compatibility. UIAM, it's not so bad: >>> class C: pass ... >>> type(C) >>> class D(object): pass ... >>> type(D) >>> __metaclass__ = type >>> class E: pass ... >>> type(E) So I guess you can put __metaclass__ = type where you would have done the __future__ thing. If you want to do a special metaclass thing (even using a proper class ;-), you can override the global __metaclass__ >>> def MC(*a): print a; return type(*a) ... >>> class F: ... __metaclass__ = MC ... pass ... ('F', (), {'__module__': '__main__', '__metaclass__': }) Regards, Bengt Richter From gurpreet.sachdeva at gmail.com Thu Jan 20 08:23:06 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Thu, 20 Jan 2005 18:53:06 +0530 Subject: Problem in importing MySQLdb Message-ID: I am using Mysql version 5.0.2-alpha on RedHat 9.0 (python2.2) When I try to import MySQldb I get: Python 2.2.2 (#1, Feb 24 2003, 19:13:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import MySQLdb Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/site-packages/MySQLdb/__init__.py", line 27, in ? import _mysql ImportError: /usr/lib/libmysqlclient.so.10: symbol errno, version GLIBC_2.0 not defined in file libc.so.6 with link time reference Is there any problem in library files?? Do I need to install anything I have installed MySQL-shared-3.23.54a-1.i386.rpm, MySQL-devel-5.0.2-0.i386.rpm, MySQL-client-5.0.2-0.i386.rpm, MySQL-server-5.0.2-0.i386.rpm Please help, Garry From ianb at colorstudy.com Fri Jan 7 16:52:27 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Fri, 07 Jan 2005 15:52:27 -0600 Subject: Exception report library In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E3398134@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E3398134@exchange.hqamor.amorhq.net> Message-ID: <41DF049B.2070003@colorstudy.com> Robert Brewer wrote: >>I've been using one of several systems to catch unexpected exceptions >>and log them (e.g., write to a file, display on web page, email me, >>etc). But many are built into a particular system, or have an >>interesting but incomplete set of features. E.g., many web >>frameworks have exception reporters (and the stdlib includes cgitb), >>but I want to handle non-web exceptions in the same way as exceptions >>from web requests, and that's not generally easy. > > ... > >>I feel like there must be something out there, since every Python >>programmer has to deal with this sort of thing to some degree...? > > > I feel that way, too, but haven't found it. I broke my webapp framework > out of my ORM late last year, and quickly realized how small the core > framework really is (22k, versus 250k for the web bits). Features like > the logging handler could be provided as separate modules, rather than > built into the Application object, and I've been meaning to get around > to that. If we could put our many heads together, I think this would be > doable for the stdlib. I'm not optimistic about a good exception handler in the standard library; development slows down a lot at that point, and it's not a reasonable candidate until it is designed and used (in part because of that slowdown -- if it's not mature, it is a diservice to the project to calcify the interface with such strong backward compatibility requirements). But anyway, hopefully multiple people/frameworks/projects could use such a library, done well, as a start. > Here are the pieces of the framework, by the way, which might also > benefit from some standardization (I was thinking about them all at > once): > > 1. Thread-safe application state > 2. Logging (+ exception handling) > 3. Configuration data (reading from various sources) > 4. Registry of Workers for getting things done on a schedule, > possibly recurring > 5. Registry of startup/shutdown functions > 6. Registry of active user interfaces > > I think the first three are all good candidates for a standard. If we > had a standard, thread-safe Application object, the rest could be > registerable plugins for that. You'd basically register callbacks for > app.startup and .shutdown methods to iterate over. Hmm... I'm confused by these bits. Are you talking about libraries for other parts of a web framework, besides exception handling? If so, you might want to look into WSGI and then discuss these things on the web-sig list (WSGI as a starting point; it doesn't specifically relate to many of these ideas, but provides a context in which to develop them). Some of these have been discussed there, like logging, configuration, and perhaps aspects of the registration you are thinking about. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From dalke at dalkescientific.com Sat Jan 8 20:30:15 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sun, 09 Jan 2005 01:30:15 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin: > Lately there are people trying to program PC's to > simulate the Lisp hardware and to get the Lisp Machine software > released (now that the commercial market for it has long since dried > up). However, both of those projects have a ways to go. There's a video of someone demoing how to use a Lisp Machine at http://lemonodor.com/archives/000103.html Andrew dalke at dalkescientific.com From bjourne at gmail.com Thu Jan 13 14:14:39 2005 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Thu, 13 Jan 2005 20:14:39 +0100 Subject: Refactoring; arbitrary expression in lists In-Reply-To: References: Message-ID: <740c3aec05011311141ce10b8e@mail.gmail.com> > # do other non-extension-related tests here > if basename.find( "Makefile" ) != -1: > return "text/x-makefile" I believe this can be nicelier written as: if "Makefile" in basename: -- mvh Bj?rn From stephane.bronsart at bea.be Fri Jan 28 05:02:38 2005 From: stephane.bronsart at bea.be (StepH) Date: Fri, 28 Jan 2005 11:02:38 +0100 Subject: How to test that an exception is raised ? Message-ID: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> Hi, I've this module : from optparse import OptionParser import re _version = "P1" def writeVar(f, line): """Output a line in .xml format in the file f.""" f.write('\t\n') name = line.split()[0] adr = line.split()[3] f.write('\t\t' + name + '\n') f.write('\t\t' + adr + '\n') f.write('\t\n') def mps2xml(mps,verbose): """Convert '.mps' to '.xml'.""" try: f = open(mps) f.close() xmlfile = mps + ".xml" f = open(xmlfile, "w+") f.write('\n') f.writelines('\n') pat = re.compile(".*Var.*g.*0x00.*") lines = list(open(mps)) nbScan = nbFound = 0 for line in lines: nbScan = nbScan + 1 if pat.match(line): writeVar(f, line) nbFound = nbFound + 1 f.writelines('\n') f.close() if verbose: print "Output to file %s..." % xmlfile print "Lines scanned:", nbScan print "Lines found:", nbFound except: if verbose: print "FileError" if __name__ == "__main__": usage = "usage: %prog [options] filename" parser = OptionParser(usage) parser.add_option("-v", "--verbose", action="store_true", dest="verbose") parser.add_option("-q", "--quiet", action="store_false", dest="verbose") (options, args) = parser.parse_args() if len(args) != 1: parser.error("incorrect number of arguments") exit(1) if options.verbose: print "mps2xml -", _version mps2xml(args[0],options.verbose) And this "unittest" module : import mps2xml import os import unittest class Tests(unittest.TestCase): def setUp(self): self.mps = "test.mps" def tearDown(self): pass def test_badFile(self): """Check that an exception is raised if a bad filename is passed to mps2xml""" self.assertRaises((IOError),mps2xml.mps2xml, "thisfiledoesntexists", False) def test_writeVar_Output(self): """Check the output of the 'writeVar' method""" line = " irM1slotnoisePPtmp Var. g 0x0002F6" file = open("testWriteVar.xml","w+") mps2xml.writeVar(file, line) file.close() outputlines = list(open("testWriteVar.xml")) goodlines = list(open("testWriteVar.xml.good")) self.assertEquals(outputlines, goodlines, 'bad output format') def test_mps2xml_Creation(self): """Check if test.mps.xml is created""" mps2xml.mps2xml(self.mps, False) self.assert_(os.path.exists(self.mps + ".xml"), 'test.mps.xml not created') if __name__ == '__main__': unittest.main() But i've prob with the 1st test : test_badFile. When I run the test, unittest say that no error is Raised. But when I run the mps2xml module with a bad file as arg., the exception is well Raised. What i'm doing wrong ? It is because the exception in catched in the mps2xml module ? Thanks for your helps. StepH. From peter at engcorp.com Wed Jan 12 11:01:20 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 Jan 2005 11:01:20 -0500 Subject: 2 versions of python on 1 machine In-Reply-To: <4446BD725249914A801A2C8ED5BFA4CADE2D59@cernne02.cern.ch> References: <4446BD725249914A801A2C8ED5BFA4CADE2D59@cernne02.cern.ch> Message-ID: flupke wrote: > I searched with Google and on this newsgroups and i didn't find any info > regarding this. If there is more info, please redirect me to that info. [snip] The above looks like a glitch or accidental repost of the post that started this thread: http://groups.google.ca/groups?threadm=YLedndIVKMWwhn3cRVn-rA%40powergate.ca (Was it just on my server or did others get this strange repost?) -Peter From john at grulic.org.ar Thu Jan 13 19:14:53 2005 From: john at grulic.org.ar (John Lenton) Date: Thu, 13 Jan 2005 21:14:53 -0300 Subject: how to control the mouse pointer with python? In-Reply-To: <1105650438.311153.167410@f14g2000cwb.googlegroups.com> References: <1105650438.311153.167410@f14g2000cwb.googlegroups.com> Message-ID: <20050114001453.GC3727@grulic.org.ar> On Thu, Jan 13, 2005 at 01:07:18PM -0800, oglycans at yahoo.com wrote: > Hi. > Anybody know a way to control the mouse pointer > (move it around and click on things) using python? in X11, you could use Xlib to do so. In debian unstable, that's "apt-get install python-xlib{,-doc}", and start reading. -- John Lenton (john at grulic.org.ar) -- Random fortune: Obviously I was either onto something, or on something. -- Larry Wall on the creation of Perl -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From f.geiger at vol.at Thu Jan 13 01:50:18 2005 From: f.geiger at vol.at (F. GEIGER) Date: Thu, 13 Jan 2005 07:50:18 +0100 Subject: java 5 could like python? References: Message-ID: "vegetax" schrieb im Newsbeitrag news:mailman.568.1105544231.22381.python-list at python.org... > I was a java developer one year ago ,before i moved to python i realy liked > it at the beggining, but i got very disapointed lately since my > previus two python proyects where relatively big,and python didnt feel > well suited for the task. > > The reasons are mainly due to the standard library,the language > performance was aceptable, but the library, in my opinion has several grave > issues: > > -No naming convention. The speech of "it fits in my head" is no longer valid > when i use a lot of functionality,modules,classes in a large proyect. > > For example if i remember a function i want ie:get attribute, i dont > remember if the module implementer coded it as > getAttribute,GetAttribute,get_attribute, then i have to go and check the > doc, every time,which is a waste of time. Too many getters indicate bad design. But, ok, that's not the point here. I ask myself all the time, how people can dev software in *any* language w/o an IDE offering Intellisense (besides a decent clas browser, of course). You simply type "myObj.get" and the IDE looks the proper names up for you. Then you choose the right one and you are done with. WingIDE is such an IDE, and Kommodo too, I think. HTH Franz GEIGER From mahs at telcopartners.com Sat Jan 22 17:06:22 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sat, 22 Jan 2005 14:06:22 -0800 Subject: What YAML engine do you use? In-Reply-To: <7xoefhtavd.fsf@ruckus.brouhaha.com> References: <35a6tpF4gmat2U1@individual.net> <35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fpq0F4mh1ffU1@individual.net> <7xoefhtavd.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > YAML looks to me to be completely insane, even compared to Python > lists. I think it would be great if the Python library exposed an > interface for parsing constant list and dict expressions, e.g.: > > [1, 2, 'Joe Smith', 8237972883334L, # comment > {'Favorite fruits': ['apple', 'banana', 'pear']}, # another comment > 'xyzzy', [3, 5, [3.14159, 2.71828, []]]] > > I don't see what YAML accomplishes that something like the above wouldn't. > > Note that all the values in the above have to be constant literals. > Don't suggest using eval. That would be a huge security hole. Not hard at all, thanks to compiler.ast: >>> import compiler ... >>> class AbstractVisitor(object): ... def __init__(self): ... self._cache = {} # dispatch table ... ... def visit(self, node,**kw): ... cls = node.__class__ ... meth = self._cache.setdefault(cls, ... getattr(self,'visit'+cls.__name__,self.default)) ... return meth(node, **kw) ... ... def default(self, node, **kw): ... for child in node.getChildNodes(): ... return self.visit(child, **kw) ... >>> class ConstEval(AbstractVisitor): ... def visitConst(self, node, **kw): ... return node.value ... ... def visitName(self,node, **kw): ... raise NameError, "Names are not resolved" ... ... def visitDict(self,node,**kw): ... return dict([(self.visit(k),self.visit(v)) for k,v in node.items]) ... ... def visitTuple(self,node, **kw): ... return tuple(self.visit(i) for i in node.nodes) ... ... def visitList(self,node, **kw): ... return [self.visit(i) for i in node.nodes] ... >>> ast = compiler.parse(source,"eval") >>> walker = ConstEval() >>> walker.visit(ast) [1, 2, 'Joe Smith', 8237972883334L, {'Favorite fruits': ['apple', 'banana', 'pear']}, 'xyzzy', [3, 5, [3.1415899999999999, 2.71828, []]]] Add sugar to taste Regards Michael From tim at zeos.net Tue Jan 25 03:45:21 2005 From: tim at zeos.net (Timothy Babytch) Date: Tue, 25 Jan 2005 10:45:21 +0200 Subject: ANN: LJ pyGTK clien Zapys-0.3 released Message-ID: Usable simple app for posting messages to LiveJournal. Easy extandable. Main feature: character substitution. I mean (tm) to ?, (c) to ?, quote to matching pairs and so on. The list can be easily extended with your own regexps. submit on Ctrl+Enter. Edit/delete last entry. screenshot: http://img.lj.com.ua/ilishin/zapys-3.png download: http://firefox.org.ua/misc/zapys-0.3.tar.bz2 From emschwar at fc.hp.com Wed Jan 26 20:19:49 2005 From: emschwar at fc.hp.com (Eric Schwartz) Date: Wed, 26 Jan 2005 18:19:49 -0700 Subject: [perl-python] 20050126 find replace strings in file References: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> Message-ID: To follow up on Jurgen Exner's critique, I present Xah Lee's version, and then my rewritten version. "Xah Lee" writes: > if (scalar @ARGV != 4) {die "Wrong arg! Unix BNF: $0 > \n"} > $stext=$ARGV[0]; > $rtext=$ARGV[1]; > $infile = $ARGV[2]; > $outfile = $ARGV[3]; > open(F1, "<$infile") or die "Perl fucked up. Reason: $!"; > open(F2, ">$outfile") or die "Perl fucked up. Reason: $!"; > while ($line = ) { > chomp($line); > $line =~ s/$stext/$rtext/g; > print F2 "$line\n"; > } > close(F1) or die "Perl fucked up. Reason: $!"; > close(F2) or die "Perl fucked up. Reason: $!"; #!/usr/bin/perl use warnings; use strict; if (@ARGV != 4) { die "Wrong arg! Unix BNF: $0 " } my ($stext, $rtext, $infile, $outfile) = @ARGV; open my $infh, '<', $infile or die "Error opening input file [$infile]: $!"; open my $outfh, '>', $outfile or die "Error opening output file [$outfile]: $!"; while(<$infh>) { s/$stext/$rtext/g; print { $outfh } $_; } close($infh) or die "Error closing input file [$infile]: $!"; close($outfh) or die "Error closing output file [$outfile]: $!"; My version takes up more lines, but I don't count whitespace-- whitespace is not expensive, and when used properly adds greatly to the readability of your program. I've set followups to the only appropriate group for Mr. Lee's postings. -=Eric -- Come to think of it, there are already a million monkeys on a million typewriters, and Usenet is NOTHING like Shakespeare. -- Blair Houghton. From ramen at lackingtalent.com Tue Jan 18 12:53:43 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 18 Jan 2005 10:53:43 -0700 Subject: One-Shot Property? In-Reply-To: <20050118115456510-0500@braeburn.themorgue.org> References: <20050118115456510-0500@braeburn.themorgue.org> Message-ID: <%2cHd.21965$ql2.16363@okepread04> Kevin Smith wrote: > I have many cases in my code where I use a property for calculating a > value on-demand. Quite a few of these only need to be called once. > After that the value is always the same. In these properties, I set a > variable in the instance as a cached value and return that value on > subsequent calls. It would be nice if there was a descriptor that would > do this automatically. Actually, what would be really nice is if I > could replace the property altogether and put the calculated value in > its place after the first call, but the property itself prevents me from > doing that. Is this possible? I was going to recommend taking a look at the "memoize" example on the Python wiki, but it seems to be missing at the moment. In any case, here's the URL: http://www.python.org/moin/PythonDecoratorLibrary There are also a few examples on the Cookbook, like this one: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325205 It shouldn't be too difficult to adapt this technique so that it can be used to create properties. I wouldn't bother replacing the property with an attribute unless you have a specific reason to do so (performance, perhaps). HTH, Dave From fredrik at pythonware.com Sun Jan 23 08:15:59 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 14:15:59 +0100 Subject: compile python to binary References: Message-ID: "sam" wrote: > I have seen some software written in python and delivered as binary form. > > How does these binary code get generated by python compiler? see section 6.1.2 in the tutorial: http://docs.python.org/tut/node8.html From donn at u.washington.edu Tue Jan 11 16:33:57 2005 From: donn at u.washington.edu (Donn Cave) Date: Tue, 11 Jan 2005 13:33:57 -0800 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <10u5fu3o7v4h9e3@corp.supernews.com> <10u8e65lju3atbd@corp.supernews.com> Message-ID: In article <10u8e65lju3atbd at corp.supernews.com>, Jeff Shannon wrote: ... > From the sounds of it, you may have the opposite experience with > reading map/lambda vs. reading list comps, though, so we could go back > and forth on this all week without convincing the other. :) I'm with him. List incomprehensions do not parse well in my eyes. I am reduced to guessing what they mean by a kind of process of elimination. map is simply a function, so it doesn't pose any extra reading problem, and while lambda is awkward it isn't syntactically all that novel. Donn Cave, donn at u.washington.edu From jaydonnell at gmail.com Fri Jan 21 20:19:49 2005 From: jaydonnell at gmail.com (Jay donnell) Date: 21 Jan 2005 17:19:49 -0800 Subject: why am I getting a segmentation fault? In-Reply-To: <1106351339.457714.214940@f14g2000cwb.googlegroups.com> References: <1106330476.419418.46920@f14g2000cwb.googlegroups.com> <1106351339.457714.214940@f14g2000cwb.googlegroups.com> Message-ID: <1106356789.748649.259090@f14g2000cwb.googlegroups.com> >### Have you looked in your database to see if the >script has actually >updated item.goodImage? Do you have a test plan? Thank you for the help. Sorry for the messy code. I was under time constraints. I had class, and I was rushing to get this working before class. I should waited a day and read over it before I asked. Sorry again. From cbfalconer at yahoo.com Fri Jan 21 11:30:55 2005 From: cbfalconer at yahoo.com (CBFalconer) Date: Fri, 21 Jan 2005 16:30:55 GMT Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> Message-ID: <41F12912.3748FFB7@yahoo.com> Xah Lee wrote: > > i've started to read python tutorial recently. > http://python.org/doc/2.3.4/tut/tut.html > > Here are some quick critique: This has absolutely nothing to do with c.l.c, nor most of the cross-posted groups. F'ups set. Why did you do such a foul cross-posting in the first place. -- "If you want to post a followup via groups.google.com, don't use the broken "Reply" link at the bottom of the article. Click on "show options" at the top of the article, then click on the "Reply" at the bottom of the article headers." - Keith Thompson From reinhold-birkenfeld-nospam at wolke7.net Mon Jan 17 14:03:16 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 17 Jan 2005 20:03:16 +0100 Subject: Assigning to self In-Reply-To: References: Message-ID: <352gfkF4gq9a2U1@individual.net> Frans Englich wrote: > Hello, > > I am having trouble with throwing class instances around. Perhaps I'm > approaching my goals with the wrong solution, but here's nevertheless a > stripped down example which demonstrates my scenario: > > #------------------------------------------------------------------------------------------ > > class foo: > tests = {} > def __init__( self, id ): > > try: > me = self.__class__.tests[ id ] > > except KeyError: > print "Did not exist, initializing myself.." > self.attr = "exists" > self.__class__.tests[ id ] = self > > else: > print "Already exists! Re-using existing instance" > self = me > > print "Me", self.attr + "!" # line 18 > > def yo(self): > return self.attr # line 21 As 'self' is a method parameter, changing it only affects the current function. When __init__ is called, the instance is already created, so you can't change it. What you are looking for is a class factory (is this term correct?), here is a sample implementation (using 2.4 decorators): class foo: tests = {} @classmethod def get_test(cls, id): if cls.tests.has_key(id): return cls.tests[id] else: inst = cls() inst.attr = "exists" cls.tests[id] = inst return inst def yo(self): return self.attr Here you define get_test as a classmethod, that is, it does not receive the instance as first argument, but the class. It can be called from the class (foo.get_test) or an instance (foo().get_test). An alternative might be to override __new__, but I'm sure someone other will suggest this. Reinhold From francis.girard at free.fr Tue Jan 25 16:11:41 2005 From: francis.girard at free.fr (Francis Girard) Date: Tue, 25 Jan 2005 22:11:41 +0100 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: <1106624803.825442.73870@f14g2000cwb.googlegroups.com> Message-ID: <200501252211.43386.francis.girard@free.fr> Hi, I'm really not sure but there might be some way to embed Java Script within Jython. Or to run Jython from inside Java much like the jEdit editor. You then have Python to make some glue code between the C++ core and the Java Script. Java Script must be secure since it runs in browsers everywhere from my worst sex web sites ! I'm not really sure why the original poster want to use Python, I think it's to make the glue between C++ and the scripting engine. Nor am I really sure why java runs inside my browser ... Francis Girard FRANCE Le mardi 25 Janvier 2005 18:08, Cameron Laird a ?crit?: > In article <1106624803.825442.73870 at f14g2000cwb.googlegroups.com>, > Carl Banks wrote: > . > . > . > > >> Python, or Perl, or TCL, or Ruby, or PHP, > > > >Not PHP. PHP is one of the better (meaning less terrible) examples of > >what happens when you do this sort of thing, which is not saying a lot. > >PHP was originally not much more than a template engine with some > >crude operations and decision-making ability. Only its restricted > >problem domain has saved it from the junkheap where it belongs. > > > >TCL isn't that great in this regard, either, as it makes a lot of > >common operations that ought to be very simple terribly unweildy. > > . > . > . > I've lost track of the antecedent by the time of our arrival at > "this regard". I want to make it clear that, while Tcl certainly > is different from C and its imitators, and, in particular, insists > that arithmetic be expressed more verbosely than in most languages, > the cause is quite distinct from the imperfections perceived in > PHP. PHP is certainly an instance of "scope creep" in its semantics. > Tcl was designed from the beginning, though, and has budged little in > over a decade in its fundamentals; Tcl simply doesn't bother to "make > a lot of common operations ..." concise. From tim.golden at viacom-outdoor.co.uk Wed Jan 12 10:50:31 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 12 Jan 2005 15:50:31 -0000 Subject: Excel module for Python Message-ID: <9A28C052FF32734DACB0A288A35339910359B1@vogbs009.gb.vo.local> [Simon Brunning] [sam ] wrote: | > No, I don't use MS windows. I need to generate Excel file | by printing | > data to it, just like Perl module Spreadsheet::WriteExcel. | | If you need to write out formulae, formratting, that kind of thing, | then I think you'll need to write a 'real' Excel file. I don't have a | clue how to do that - sorry. I think http://sourceforge.net/projects/pyxlwriter/ will do it; haven't used it myself, mind you. You need to know that the magic search term is "BIFF" which is -- for some reason -- the name of the Excel file format. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From fredrik at pythonware.com Mon Jan 24 11:21:24 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 17:21:24 +0100 Subject: Python 2.1 - 2.4 differences References: Message-ID: "BOOGIEMAN" wrote: >I found some e-book about Python 2.1, I want to print it but just to check > first if sintax of Python 2.1 is same as 2.4 ? almost everything that works under 2.1 works under 2.4. the opposite isn't always true, though. for more information on new stuff, see: http://www.python.org/doc/2.2.3/whatsnew/ http://www.python.org/doc/2.3.4/whatsnew/ http://www.python.org/doc/2.4/whatsnew/whatsnew24.html and http://effbot.org/zone/librarybook-py21.htm http://effbot.org/zone/librarybook-py22.htm http://effbot.org/zone/librarybook-py23.htm From jacek.generowicz at cern.ch Mon Jan 10 11:45:25 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Jan 2005 17:45:25 +0100 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> Message-ID: "Anna" writes: > Jacek Generowicz wrote: > > "Anna" writes: > > > > > With class and def, I at least have a *name* to start with - class > > > Square pretty obviously is going to have something to do with > > > geometric shapes, I would hope (or maybe with boring people...). > > > > Or maybe with multiplying something by itself. Or maybe the author > > made some changes in his program, and forgot to rename the class > > sensibly, and the class' functionality has nothing to do with squares > > of any sort any more. Or maybe he felt the name "Square" was very > > appropriate for something else in his program and inadvertently gave > > the same name to two different entities thereby clobbering the one > > whose use was intended at this point. > > Idjits abound. ;-) Yup ... which is one reason why lambda is so useful. Everything there is to know about it is right in front of your eyes. There is no chance that some idjit changed the meaning of lambda, or the code which appears within it (unless that refers to some external names, of course). > > So, IIUC, you consider > > > > def add_one(x): > > return x+1 > > > > map(add_one, seq) > > > > to be clearer than > > > > map(lambda x:x+1, seq) > > Completely, totally, and unambiguously: Curious. It's very much the other way around for me. > the version with the defined function is immediately clear to me; > the version with the lambda is decipherable, but requires > deciphering (even at 2nd and 3rd glance). But first, wouldn't > something like: > > [x+1 for x in seq] > > be even clearer? I'm glad you mentioned that. My next question was going to be something along the lines of what you think of the equivalent list comprehension, which is spectacularly devoid of any names to give you any hints whatsoever. As to whether it is clearer. That depends. I would venture to suggest that, given a pool of laboratory rats with no previous exposure to Python, more of them would understand the map-lambda than the list comprehension. There are no words in the list comprehension at all (besides the common "seq"): it's all syntax. Even if "map" and "lambda" ring no bells by association with anything you might have learned outside of Python, they sure are a lot easier to look up in the documentation. > Given an example more complex (which you must admit, lambdas usually > are) Well, they can't be _that_ much more complex in Python :-) But I'll grant you, they are often more complex that the one above. > - the name of the function is something my brain can hold on to to > represent the group of operations; where with the lambda, I need to > mentally go through each operation each time I try to read it. And the > more complex f is, the harder time I have holding it all in my head > while I figure out how to get from the beginning value x to the ending > value f(x). lambda is an O(N*N) problem for my brain. Fair enough. If I understand the code just by looking at it, then I prefer to see it inline. If its meaning isn't obvious immediately, then I'd go for the named function too. But I still value the ability to inline-define the function while developing ... even if the inline function will be outlined in the final product. But, how do you feel about the individual lines of code in the body of a multi-line function? They don't have individual names. > I could see someone more mathematically-minded being happier with > lambda. It's not, after all, the word "lambda" itself; Aaah ... you did suggest (upthread) that it was the word itself which gave you problems ... which is what piqued my interest. From invalidemail at aerojockey.com Fri Jan 21 12:57:24 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 21 Jan 2005 09:57:24 -0800 Subject: Funny Python error messages In-Reply-To: References: <1106315907.551660.276380@c13g2000cwb.googlegroups.com> Message-ID: <1106330244.724582.226020@z14g2000cwz.googlegroups.com> Peter Hansen wrote: > Will Stuyvesant wrote: > > Perhaps this will even be a useful thread, to brighten the > > life of the brave people doing the hard work of providing us > > with error messages. > > > > My first one (i'm learning, i'm learning) is > > > > TypeError: 'callable-iterator' object is not callable > > > > # >>> it = iter(lambda:0, 0) > > # >>> it() > > # TypeError: 'callable-iterator' object is not callable > > Given that the supposed humour depends on the *name* of > the object, which is "callable-iterator", I'd say it's > probably not hard to come up with lots of "funny" error > messages this way. The mildly amusing nature of this error message is due to Will's finding a name, "callable-iterator" (where callable is a name, not a description), appearing in a different context from where it was coined that causes us to parse it differently (where callable is a description, not a name), and accidentally stating an absurdity. I'd say it's actually a nice bit of subtlety. -- CARL BANKS From noreply at python.org Tue Jan 18 07:38:33 2005 From: noreply at python.org (Mail Administrator) Date: Tue, 18 Jan 2005 13:38:33 +0100 Subject: MDaemon Warning - virus found: Returned mail: Data format error Message-ID: <20050118123933.971AB1E4003@bag.python.org> ******************************* WARNING ****************************** Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado un fichero anexo(s) infectado(s). Por favor revise el reporte de abajo. Attachment Virus name Action taken ---------------------------------------------------------------------- instruction.zip I-Worm.Mydoom.m Removed ********************************************************************** Your message was undeliverable due to the following reason: Your message was not delivered because the destination server was unreachable within the allowed queue period. The amount of time a message is queued before it is returned depends on local configura- tion parameters. Most likely there is a network problem that prevented delivery, but it is also possible that the computer is turned off, or does not have a mail system running right now. Your message could not be delivered within 8 days: Mail server 169.58.69.124 is not responding. The following recipients did not receive this message: Please reply to postmaster at python.org if you feel this message to be in error. From Scott.Daniels at Acm.Org Wed Jan 12 10:04:38 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 12 Jan 2005 07:04:38 -0800 Subject: Help Optimizing Word Search In-Reply-To: <7xacrfl78y.fsf@ruckus.brouhaha.com> References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> <7xacrfl78y.fsf@ruckus.brouhaha.com> Message-ID: <41e53998$1@nntp0.pdx.net> Paul Rubin wrote: > "Case Nelson" writes: > >>Basically, the program needs to take in a random list of no more than >>10 letters, and find all possible mutations that match a word in my >>dictionary (80k words). However a wildcard letter '?' is also an >>acceptable character which increases the worst case time significantly. > > > For that size pattern and dictionary, simply compiling the pattern to > a regexp, joining the dictionary together into one big string ("abc > def ghijk..."), and matching the regexp against the big string, may > well be faster than using some fancy algorithm coded completely in > python. If these queries happen often, build a dictionary of sorted letters to lists-of-words. The setup will be slow, but use of such a secondary dictionary should be quite fast, with relatively easy dealing with ?s by iterations. --Scott David Daniels Scott.Daniels at Acm.Org From stephen.thorne at gmail.com Thu Jan 13 04:26:54 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 19:26:54 +1000 Subject: newbie q In-Reply-To: <34mku4F4c8bdkU1@individual.net> References: <34mgq0F4dq4buU1@individual.net> <34mku4F4c8bdkU1@individual.net> Message-ID: <3e8ca5c8050113012633ac6155@mail.gmail.com> On Thu, 13 Jan 2005 17:05:39 +1000, Egor Bolonev wrote: > > "Stephen Thorne" ???????/???????? ? ???????? > ?????????: news:mailman.611.1105598828.22381.python-list at python.org... > On Thu, 13 Jan 2005 15:55:10 +1000, Egor Bolonev wrote: > > how to get rid of 'for' operator in the code? > > > > import os, os.path > > > > def _test(): > > src = 'C:\\Documents and Settings\\????\\My Documents\\My Music\\' > > > > for i in [x for x in os.listdir(src) if > > os.path.isfile(os.path.join(src, > > x)) and len(x.split('.')) > 1 and x.split('.')[-1].lower() == 'm3u']: > > os.remove(os.path.join(src, i)) > > > > if __name__ == '__main__': > > _test() > > import glob > for x in glob.glob("*.m3u"): > os.remove(x) > > i want to wipe out 'for x in []: f(x)' using map, lambda, reduce, filter and > List > Comprehensions [x for x in []] > just don't get how to add string to all elements of list Here's a few ways, map(os.remove, glob.glob("*.m3u")) [os.remove(x) for x in glob.glob("*.m3u")] [os.remove(x) for x in os.listdir(src) if os.path.isfile(os.path.join(src, x)) and len(x.split('.')) > 1 and x.split('.')[-1].lower() == 'm3u'] def myfilter(x): return os.path.isfile(os.path.join(src, x)) and len(x.split('.')) > 1 and x.split('.')[-1].lower() == 'm3u' map(os.remove, filter(myfilter, os.listdir(src))) Regards, Stephen Thorne. From bulba at bulba.com Tue Jan 4 12:55:43 2005 From: bulba at bulba.com (Bulba!) Date: Tue, 04 Jan 2005 18:55:43 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <86ekh3qv1o.fsf@guru.mired.org> Message-ID: <03mlt0di3rcntvu7rlrk9k2m9bq8435bs5@4ax.com> On Sun, 02 Jan 2005 17:18:43 -0600, Mike Meyer wrote: >> This "free software" (not so much OSS) notion "but you can >> hire programmers to fix it" doesn't really happen in practice, >> at least not frequently: because this company/guy remains >> ALONE with this technology, the costs are unacceptable. > >Yes, but fixing python software - even sloppily written python >software - is pretty easy. I regularly see contracts to add a feature >to or fix a bug in some bit of OSS Python. That's remarkable, first time I see smth like this - out of curiosity, could you say a word where was that? -- Real world is perfectly indifferent to lies that are the foundation of leftist "thinking". From enleverlesO.OmcO at OmclaveauO.com Fri Jan 28 08:25:34 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Fri, 28 Jan 2005 14:25:34 +0100 Subject: How to post news articles with NNTPlib References: <1106911698.786860.109450@z14g2000cwz.googlegroups.com> Message-ID: <41fa577c$0$25809$8fcfb975@news.wanadoo.fr> Hi ! nntplib.NNTP(newsserver,port,user,passe) -- Michel Claveau From tchur at optushome.com.au Mon Jan 31 16:15:08 2005 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 01 Feb 2005 08:15:08 +1100 Subject: python and gpl In-Reply-To: References: Message-ID: <41FE9FDC.4080808@optushome.com.au> John Hunter wrote: >I have a question about what it takes to trigger GPL restrictions in >python code which conditionally uses a GPL library. > >Here is the context of my question. matplotlib, which I develop, is a >plotting module which is distributed under a PSF compatible license, >and hence we avoid using GPLd code so as to not trigger the GPL >requirements. matplotlib has rigid segregation between the front end >(plotting commands, figure objects, etc) and backends (gtk, wx, ps, >svg, etc). The backend is chosen dynamically at runtime -- eg the >same python script could trigger the import gtk, wx, or ps, depending >an some rc settings or command line opts. > >The question is: does shipping a backend which imports a module that >links with GPL code make some or all of the library GPL. > We sought formal legal advice on this issue from a lawyer with expertise in open source licensing - in our case, our application which is licensed under a (very slightly) modifided version of the Mozilla Public License v1.1 imports a GPLed Python module (RPy) which wraps a GPLed library (R). The answer was that the GPL does not apply to combination of code at run-time. Specifically, Section 0., Para 1 (assuming zero-based paragraph numbering...) says: "Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted,..." Furthermore, Section 2 para 1 says: "These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. ..." and Section 2 para 3 says: "In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License." On the basis of these clauses, the legal advice to us was that merely including "import rpy" and making calls to RPy-wrapped R functions does not invoke the provisions of the GPL because these calls only relate to run-time linking, which is not covered by the GPL. However, combining GPLed source code or static linking would invoke the GPL provisions. Additionally, we were advised to (re-)distribute any GPLed components required by our application in clearly separate packages i.e as separate tarballs or zip files, and not to bind them together in an omnibus distribution or installation file. However, putting them on the same CD-ROM or other media is fine. Note that the formal advice was specific to Australian law, and did mention some Australian case law regarding fair use under the Copyright Act with respect to making API calls - that relates to our application making API calls to the GPLed library which is imported at runtime. The opinion was that we were on safe ground here, but you might want to investigate this aspect wrt copyright laws in other countries. My understanding is that most copyright law provides for "fair use" which may cover use of parts of an API to a GPLed library (as distinct from complete incorporation of the entire API into another application - which would invoke the GPL). IANAL, and the above constitutes mangled paraphrasing of carefully worded formal legal advice, the scope of which was restricted to Australian law. However, the sections of the GPL quoted above are pretty unambiguous. The other, informal advice, was to ignore the FAQs and other opinions on the FSF web site regarding intepretation of the GPL - it's only the license text which counts. Tim C From invalidemail at aerojockey.com Sat Jan 8 19:25:50 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 8 Jan 2005 16:25:50 -0800 Subject: python3: 'where' keyword In-Reply-To: <7xk6qnzd3d.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> Message-ID: <1105230350.861683.265970@c13g2000cwb.googlegroups.com> Paul Rubin wrote: > "Carl Banks" writes: > > You misunderstand. BTW, Peter, I guess I should have said "I misunderstand, but it can be legal if you consider it part of the statements", since it appears the author did intend it to be part of an expression. > > There "where" is not part of the expression but the > > statement. The above example would be a modified print statement, a > > print...where statement, if you will. Under this suggestion, there > > would be modified versions of various simple statements. > > You mean I can't say > > # compute sqrt(2) + sqrt(3) > x = (sqrt(a) where: > a = 2.) \ > + sqrt (a) where: > a = 3. > > Hmmm. What would be the advantage of that over this? . x = sqrt(a) + sqrt(b) where: . a = 2.0 . b = 3.0 Where would making "where" part of an expression rather than part of the statement help? Can you think of a place? ("That it makes Python more like LISP" is not a good enough answer for me, BTW. But feel free to try. :) -- CARL BANKS From bokr at oz.net Fri Jan 21 20:29:09 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 22 Jan 2005 01:29:09 GMT Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> Message-ID: <41f1a3e6.1477492061@news.oz.net> On Fri, 21 Jan 2005 12:04:10 -0600, "A.M. Kuchling" wrote: >On Fri, 21 Jan 2005 18:30:47 +0100, > rm wrote: >> Nowadays, people are trying to create binary XML, XML databases, >> graphics in XML (btw, I'm quite impressed by SVG), you have XSLT, you >> have XSL-FO, ... . > >Which is an argument in favor of XML -- it's where the activity is, so it's >quite likely you'll encounter the need to know XML. Few projects use YAML, >so the chance of having to know its syntactic details is small. > I thought XML was a good idea, but IMO requiring quotes around even integer attribute values was an unfortunate decision. I don't buy their rationale of keeping parsing simple -- as if extracting a string with no embedded space from between an equal sign and terminating white space were that much harder than extracting the same delimited by double quotes. The result is cluttering SVG with needless cruft around numerical graphics parameters. OTOH, I think the HTML XML spec is very readable, and nicely designed. At least the version 1.0 spec I snagged from W3C a long time ago. ... I see the third edition at http://www.w3.org/TR/REC-xml/ is differently styled, (I guess new style sheets) but still pretty readable (glancing at it now). Regards, Bengt Richter From friedmud at gmail.com Mon Jan 31 13:13:00 2005 From: friedmud at gmail.com (friedmud at gmail.com) Date: 31 Jan 2005 10:13:00 -0800 Subject: Relocatable binary installs.... Message-ID: <1107195180.462949.222980@z14g2000cwz.googlegroups.com> Hello all, I'm currently working on a software package that is going to be distributed in binary form (with accompanying source) for lot of different unixes (Linux, AIX, HP-UX and others). Parts of the package are written in Python... so we are going to want to distribute our own version of python. Right now we are just distributing the Python tarball and building it at install time. This works ok, but we are running into some problems on some machines with weird default installs (DEC Alphas in particular).... some of them won't build all the python modules we want (although our in house machines will). What I want to do is compile python statically into binaries and then plop them wherever our customers choose to do an install (we will provide the source tarballs on a cd as well). The problem we are running into is that when we do this python continues to think it's still installed where it was initially compiled and not where it has been placed (which causes some problems with traceback and some other functions). Is there a way to make a relocateable python binary... that is... a python installation that won't care where it is on the machine... and won't care if it gets put somewhere else besides / ? Sorry for the long winded post... just want to make sure you understand my problem. Thanks in advance for any help! Derek From forestiero at qwest.net Tue Jan 11 23:04:20 2005 From: forestiero at qwest.net (DogWalker) Date: Tue, 11 Jan 2005 20:04:20 -0800 Subject: Python.org, Website of Satan In-Reply-To: <1105500724.648914.213880@z14g2000cwz.googlegroups.com> References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> <1105500724.648914.213880@z14g2000cwz.googlegroups.com> Message-ID: <20050112040212.8028.64816@linux.local> "Luis M. Gonzalez" said: >humblythegreat... at usa.com wrote: >> python.org = 194.109.137.226 >> >> 194 + 109 + 137 + 226 = 666 >> >> What is this website with such a demonic name and IP address? What >> evils are the programmers who use this language up to? >You dared to unveil our secret. >Now we'll have to kill you... > But is 194.109.137.226 the only one? What other sites are in league with the python? From josh at yucs.org Tue Jan 11 12:33:35 2005 From: josh at yucs.org (josh at yucs.org) Date: Tue, 11 Jan 2005 12:33:35 -0500 Subject: why not datetime.strptime() ? In-Reply-To: <16867.59681.423983.244528@montanaro.dyndns.org> References: <20050111021152.GA20127@yucs.org> <16867.59681.423983.244528@montanaro.dyndns.org> Message-ID: <20050111173335.GB26246@yucs.org> On Tue, Jan 11, 2005 at 08:56:33AM -0600, Skip Montanaro wrote: > * The seventh item returned from time.strptime() is the day of the week. > You're passing it into the microsecond arg of the datetime constructor Thanks! > and ignoring the timezone info (ninth item returned from > time.strptime(), eighth arg to the datetime constructor). > This is intentional. time.strptime() doesn't expose the timezone (only the daylight savings flag), so i'd have to duplicate its logic in order to distinguish between local time and utc. Since it's easy to explicitly call somedatetime.replace(tzinfo=sometzinfo), having strptime() always create "naive" datetimes seemed most sensible. > * It would be nice if the import happened only once and was cached: > > static PyObject *time_module; > ... > if (time_module == NULL && > (time_module = PyImport_ImportModule("time")) == NULL) > return NULL; > obj = PyObject_CallMethod(time_module, ...); The datetime is full of these calls. Would it make sense to make this a separate patch? (Or maybe the PyImport_ImportModule could implement such a cache :) ?) -------------- next part -------------- *** Modules/datetimemodule.c.orig 2003-10-20 10:34:46.000000000 -0400 --- Modules/datetimemodule.c 2005-01-11 12:19:36.839337336 -0500 *************** *** 3774,3779 **** --- 3774,3819 ---- return result; } + /* Return new datetime from time.strptime(). */ + static PyObject * + datetime_strptime(PyObject *cls, PyObject *args) + { + PyObject *result = NULL, *obj, *module; + const char *string, *format; + + if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format)) + return NULL; + + if ((module = PyImport_ImportModule("time")) == NULL) + return NULL; + obj = PyObject_CallMethod(module, "strptime", "ss", string, format); + Py_DECREF(module); + + if (obj != NULL) { + int i, good_timetuple = 1; + long int ia[6]; + if (PySequence_Check(obj) && PySequence_Size(obj) >= 6) + for (i=0; i < 6; i++) { + PyObject *p = PySequence_GetItem(obj, i); + if (PyInt_Check(p)) + ia[i] = PyInt_AsLong(p); + else + good_timetuple = 0; + Py_DECREF(p); + } + else + good_timetuple = 0; + if (good_timetuple) + result = PyObject_CallFunction(cls, "iiiiii", + ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]); + else + PyErr_SetString(PyExc_ValueError, + "unexpected value from time.strptime"); + Py_DECREF(obj); + } + return result; + } + /* Return new datetime from date/datetime and time arguments. */ static PyObject * datetime_combine(PyObject *cls, PyObject *args, PyObject *kw) *************** *** 4385,4390 **** --- 4425,4435 ---- PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp " "(like time.time()).")}, + {"strptime", (PyCFunction)datetime_strptime, + METH_VARARGS | METH_CLASS, + PyDoc_STR("strptime -> new datetime parsed from a string" + "(like time.strptime()).")}, + {"combine", (PyCFunction)datetime_combine, METH_VARARGS | METH_KEYWORDS | METH_CLASS, PyDoc_STR("date, time -> datetime with same date and time fields")}, *** Doc/lib/libdatetime.tex.orig 2003-09-06 01:36:56.000000000 -0400 --- Doc/lib/libdatetime.tex 2005-01-11 12:02:30.000000000 -0500 *************** *** 624,629 **** --- 624,636 ---- ignored. \end{methoddesc} + \begin{methoddesc}{strptime}{date_string, format} + Return the date corresponding to date_string, parsed according + to format. This is equivalent to \code{datetime(*(time.strptime( + date_string, format)[0:6]))}. \exception{ValueError} is raised if + \code{time.strptime()} returns a value which isn't a timetuple. + \end{methoddesc} + Class attributes: \begin{memberdesc}{min} *** Lib/test/test_datetime.py.orig 2005-01-11 11:56:36.000000000 -0500 --- Lib/test/test_datetime.py 2005-01-11 12:28:30.268243816 -0500 *************** *** 1351,1356 **** --- 1351,1365 ---- # Else try again a few times. self.failUnless(abs(from_timestamp - from_now) <= tolerance) + def test_strptime(self): + import time + + string = '2004-12-01' + format = '%Y-%m-%d' + expected = self.theclass(*(time.strptime(string, format)[0:6])) + got = self.theclass.strptime(string, format) + self.assertEqual(expected, got) + def test_more_timetuple(self): # This tests fields beyond those tested by the TestDate.test_timetuple. t = self.theclass(2004, 12, 31, 6, 22, 33) From gurpreet.sachdeva at gmail.com Thu Jan 6 02:47:11 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Thu, 6 Jan 2005 13:17:11 +0530 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: <2b7d8b42050105232546083758@mail.gmail.com> References: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> <003801c4f3b9$af17fa20$0800a8c0@vishnu> <2b7d8b42050105232546083758@mail.gmail.com> Message-ID: On Thu, 6 Jan 2005 12:55:22 +0530, Binu K S wrote: >>>The file's current position moves as you write into it. I concure and have figured out the solution BUT while reading from the file from the position where the file handler is, should return "Null/Blank/Anything in this world" BUT should not write into the file... The information written was that in the Buffer of the handler... Does that mean reading a file will actually release the buffer by throwing the contents in the file??? Please Comment... >>>You normally wouldn't read from the file that you are writing into. May be applicable in handling logs... Regards, Garry From wittempj at hotmail.com Mon Jan 17 11:07:04 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 17 Jan 2005 08:07:04 -0800 Subject: pychecker - sets.Set need to be overridden In-Reply-To: References: Message-ID: <1105978024.706237.304360@c13g2000cwb.googlegroups.com> mport sets class Foo: def __init__(self): self.x = sets.Set() x = Foo() print x, getattr(x, 'x') gives for me: <__main__.Foo instance at 0x00C578A0> Set([]) on 2.4. on WinXP. What environment do you run in? From mahs at telcopartners.com Tue Jan 25 15:05:53 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 25 Jan 2005 12:05:53 -0800 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: References: Message-ID: Steven Bethard wrote: > > I wish there was a way to, say, exec something with no builtins and > with import disabled, so you would have to specify all the available > bindings, e.g.: > > exec user_code in dict(ClassA=ClassA, ClassB=ClassB) > > but I suspect that even this wouldn't really solve the problem, > because you can do things like: > > py> class ClassA(object): > ... pass > ... > py> object, = ClassA.__bases__ > py> object > > py> int = object.__subclasses__()[2] > py> int > > > so you can retrieve a lot of the builtins. I don't know how to > retrieve __import__ this way, but as soon as you figure that out, you > can then do pretty much anything you want to. > > Steve Steve Safe eval recipe posted to cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 Couldn't safe exec be programmed similarly? 'import' and 'from' are syntax, so trivially avoided Likewise, function calls are easily intercepted As you say, attribute access to core functions appears to present the challenge. It is easy to intercept attribute access, harder to know what's safe. If there were a known set of 'dangerous' objects e.g., sys, file, os etc... then these could be checked by identity against any attribute returned Of course, execution would be painfully slow, due to double - interpretation. Michael From fumanchu at amor.org Thu Jan 20 11:46:26 2005 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 20 Jan 2005 08:46:26 -0800 Subject: QOTW from Ryan Tomayko Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339822D@exchange.hqamor.amorhq.net> http://naeblis.cx/rtomayko/2005/01/20/getters-setters-fuxors "...Many people coming to Python can't believe no one uses IDEs. The automatic assumption is that Python is for old grey beards who are comfortable with vi and Emacs and refuse to accept breakthroughs in programming productivity like IDEs. Then they write a little Python code and realize that an IDE would just get in their way." FuManChu From bokr at oz.net Sat Jan 22 08:32:37 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 22 Jan 2005 13:32:37 GMT Subject: default value in a list References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> <10v39ald6em3u6f@corp.supernews.com> Message-ID: <41f24e9a.1521192118@news.oz.net> On Fri, 21 Jan 2005 17:04:11 -0800, Jeff Shannon wrote: >TB wrote: > >> Hi, >> >> Is there an elegant way to assign to a list from a list of unknown >> size? For example, how could you do something like: >> >> >>>>> a, b, c = (line.split(':')) >> >> if line could have less than three fields? > >(Note that you're actually assigning to a group of local variables, >via tuple unpacking, not assigning to a list...) > >One could also do something like this: > > >>> l = "a:b:c".split(':') > >>> a, b, c, d, e = l + ([None] * (5 - len(l))) > >>> print (a, b, c, d, e) >('a', 'b', 'c', None, None) > >>> Or >>> a, b, c, d, e = ('a:b:c'.split(':')+[None]*4)[:5] >>> print (a, b, c, d, e) ('a', 'b', 'c', None, None) You could even be profligate and use *5 in place of that *4, if that makes an easier idiom ;-) Works if there's too many too: >>> a, b = ('a:b:c'.split(':')+[None]*2)[:2] >>> print (a, b) ('a', 'b') > >Personally, though, I can't help but think that, if you're not certain >how many fields are in a string, then splitting it into independent >variables (rather than, say, a list or dict) *cannot* be an elegant >solution. If the fields deserve independent names, then they must >have a definite (and distinct) meaning; if they have a distinct >meaning (as opposed to being a series of similar items, in which case >you should keep them in a list), then which field is it that's >missing? Are you sure it's *always* the last fields? This feels to >me like the wrong solution to any problem. > >Hm, speaking of fields makes me think of classes. > > >>> class LineObj: >... def __init__(self, a=None, b=None, c=None, d=None, e=None): >... self.a = a >... self.b = b >... self.c = c >... self.d = d >... self.e = e >... > >>> l = "a:b:c".split(':') > >>> o = LineObj(*l) > >>> o.__dict__ >{'a': 'a', 'c': 'c', 'b': 'b', 'e': None, 'd': None} > >>> > >This is a bit more likely to be meaningful, in that there's almost >certainly some logical connection between the fields of the line >you're splitting and keeping them as a class demonstrates that >connection, but it still seems a bit smelly to me. > That gives me an idea: >>> def foo(a=None, b=None, c=None, d=None, e=None, *ignore): ... return a, b, c, d, e ... >>> a, b, c, d, e = foo(*'a:b:c'.split(':')) >>> print (a, b, c, d, e) ('a', 'b', 'c', None, None) But then, might as well do: >>> def bar(nreq, *args): ... if nreq <= len(args): return args[:nreq] ... return args+ (nreq-len(args))*(None,) ... >>> a, b, c, d, e = bar(5, *'a:b:c'.split(':')) >>> print (a, b, c, d, e) ('a', 'b', 'c', None, None) >>> a, b = bar(2, *'a:b:c'.split(':')) >>> print (a, b) ('a', 'b') >>> a, b, c = bar(3, *'a:b:c'.split(':')) >>> print (a, b, c) ('a', 'b', 'c') But usually, I would like n + tail, where I know n is a safe bet, e.g., >>> def ntail(n, *args): ... return args[:n]+(args[n:],) ... >>> a, b, t = ntail(2, *'a:b:c:d:e'.split(':')) >>> print (a, b, t) ('a', 'b', ('c', 'd', 'e')) >>> a, b, t = ntail(2, *'a:b'.split(':')) >>> print (a, b, t) ('a', 'b', ()) People have asked to be able to spell that as a, b, *t = 'a:b:c:d:e'.split(':') Regards, Bengt Richter From gsakkis at rutgers.edu Mon Jan 24 11:47:24 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Mon, 24 Jan 2005 11:47:24 -0500 Subject: Tuple slices Message-ID: <35kn4mF4o44ufU1@individual.net> Why does slicing a tuple returns a new tuple instead of a view of the existing one, given that tuples are immutable ? I ended up writing a custom ImmutableSequence class that does this, but I wonder why it is not implemented for tuples. George From craig at postnewspapers.com.au Sat Jan 1 05:51:20 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 01 Jan 2005 18:51:20 +0800 Subject: exposing C array to python namespace: NumPy and array module. In-Reply-To: References: Message-ID: <1104576679.24895.41.camel@rasputin.localnet> On Sat, 2005-01-01 at 08:18, Bo Peng wrote: > Python's array module is built-in, easy to use, but *without* a > FromLenAndData function! Even the buffer interface provides only 'get > buffer' but no 'set buffer' functions. Could anyone tell me how I can > create an array object from existing data? Python has no array objects in the core language, only lists. The distinction is important when discussing numarray etc, because Python lists and NumPy etc arrays are very different. While you can build a Python list from a subsection of your C array, changes made in Python won't be pushed back to the C array it was created from. If this is OK, you can probably build the list using just a for loop - I'm not sure if there are any more efficient methods for variable length lists. If the Python user needs to be able to change the underlying array, I'd probably drop the use of the built-in list class entirely and write my own class that looks like a list (and smells like a list, and tastes like a list - lucky we didn't step in it!). It can be pretty simple, providing as few of the list protocol methods as: __getitem__ (a PyList_GetItem equivalent) __setitem__ (a PyList_SetItem equivalent) and preferably: __len__ __iter__ or as much of the list protocol as documented on the Python/C API page as you need. I'd probably implement the class in Python, and have my extension module provide a couple of simple functions to the underlying C array. These could be considered private to your list class. That'd make writing things like the __iter__ method much nicer, while still letting you implement __len__, __getitem__, __setitem__, etc in C. For example, I might write: class CArray(object): def __init__(self, ...): ... def __getitem__(self, index): _carray_getitem(self, index) def __len__(self): _carray_len(self, index) def __iter__(self): # build and return an interator using Python ... If you want to write part of your extension module in Python and part in C, there are two main ways to do it. The usual way is to write a 'wrapper' in Python that imports the C parts, wraps them where necessary or just pushes them into its own namespace, etc. The less common way is to import __builtins__ and __main__ into your C extension module's namespace then PyRun_String() python code in it to set things up. I find this approach MUCH more useful when embedding Python in an app and I only want to write small bits of my module in Python. The other alternative is to code your class entirely in C, implementing all the __methods__ as C functions. Unattractive as far as I'm concerned, but then I find constructing classes using Python's C API irritating and less clear than it could be. Here's the code -- hideously reformatted to avoid wrapping in the mail - in my initmodule() function that I use to set up the module so that Python code can execute in its namespace. You can ignore the const_cast<> stuff, chances are your compiler will ignore the const problems. ---- // 'd' is the dictionary of the extension module, as obtained // with PyModule_GetDict(module) PyObject* builtinModule = PyImport_ImportModuleEx( const_cast("__builtin__"), d, d, Py_BuildValue(const_cast("[]")) ); if (builtinModule == NULL) { // Error handling will not be shown; it'll depend on your module anyway. } PyDict_SetItemString(d, const_cast("__builtin__"), builtinModule); PyObject* exceptionsModule = PyImport_ImportModuleEx( const_cast("exceptions"), d, d, Py_BuildValue(const_cast("[]")) ); if (exceptionsModule == NULL) {} PyDict_SetItemString(d, const_cast("exceptions"), exceptionsModule); // We can now run Python code in the module's namespace. For // example (untested), as my real examples wouldn't do you any // good, they're too bound to the internal API of my module: QString python_code = ""; python_code += "def sample_function():\n"; python_code += " print \"See, it worked\"\n"; // My app sets sysdefaultencoding to utf-8, hence: char* python_code_cstring = python_code.utf8(); // Note that we pass our module dictionary as both // locals and globals. This makes the code effectively // run "in" the extension module, as if it was being // run during loading of a Python module after an // 'import' statement. PyObject* result = PyRun_String(python_code_cstring, Py_file_input, d,d); if (result == NULL) { qDebug("Python code to declare sample_function failed!"); PyErr_Print(); // also clears the exception } // Because 'result' may be NULL, not a PyObject*, we must call PyXDECREF not Py_DECREF Py_XDECREF(result); -- Ugh - I'd forgotten how ugly C code limited to 80 cols and without syntax highlighting really was. Especially when the reformatting is done as badly as I've done it. I hope you can make some sense out of that, anyway. Note that once the setup is done you can run as many python code snippets as you want, for declaring variables, functions, classes, etc. In my case, its easier to execute snippets as shown above than it is to worry about the module search path and wrapping things using a Python module. If you're doing substantial amounts of Python coding for your module, you'll almost certainly be better off writing a Python module that uses your C module internally (see PIL for a good example of this). -- Craig Ringer From wittempj at hotmail.com Mon Jan 17 12:19:47 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 17 Jan 2005 09:19:47 -0800 Subject: How to prevent the script from stopping before it should In-Reply-To: <1105981979.853318.269300@c13g2000cwb.googlegroups.com> References: <1105981979.853318.269300@c13g2000cwb.googlegroups.com> Message-ID: <1105982387.852448.298900@c13g2000cwb.googlegroups.com> #import urllib, sys #pages = ['http://www.python.org', 'http://xxx'] #for i in pages: # try: # u = urllib.urlopen(i) # print u.geturl() # except Exception, e: # print >> sys.stderr, '%s: %s' % (e.__class__.__name__, e) will print an error if a page fails opening, rest opens fine From steven.bethard at gmail.com Mon Jan 10 01:12:58 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 09 Jan 2005 23:12:58 -0700 Subject: Python3: on removing map, reduce, filter In-Reply-To: <1105314195.310792.163170@c13g2000cwb.googlegroups.com> References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> <-7mdndrwD_1qOHzcRVn-qQ@comcast.com> <1105314195.310792.163170@c13g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > Steven Bethard wrote: >> Note that list comprehensions are also C-implemented, AFAIK. > > Rather strange meaning attached to "C-implemented". The implementation > generates the code that would have been generated had you written out > the loop yourself, with a speed boost (compared with the fastest DIY > approach) from using a special-purpose opcode LIST_APPEND. See below. Fair enough. ;) So you basically replace the SETUP_LOOP, CALL_FUNCTION, POP_TOP and POP_BLOCK with a DUP_TOP and a LIST_APPEND. Steve From quentel.pierre at wanadoo.fr Sat Jan 8 05:22:19 2005 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Sat, 08 Jan 2005 11:22:19 +0100 Subject: Another look at language comparisons Message-ID: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> http://khason.biz/blog/2004/12/why-microsoft-can-blow-off-with-c.html From mesteve_bpleaseremovethis at hotmail.com Sun Jan 2 12:26:02 2005 From: mesteve_bpleaseremovethis at hotmail.com (StvB) Date: Sun, 02 Jan 2005 17:26:02 GMT Subject: Python! Is! Truly! Amazing! References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <1104657909.340055.283710@z14g2000cwz.googlegroups.com> <1104668455.691428.12670@c13g2000cwb.googlegroups.com> Message-ID: you did this with pygame!!?? "Erik Bethke" wrote in message news:1104668455.691428.12670 at c13g2000cwb.googlegroups.com... > somehow lost my j's: > > www.erikbethke.com/Python/screenshot02.jpg > www.erikbethke.com/Python/screenshot03.jpg > www.erikbethke.com/Python/screenshot04.jpg > www.erikbethke.com/Python/screenshot05.jpg > From quentel.pierre at wanadoo.fr Sat Jan 22 03:31:04 2005 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Sat, 22 Jan 2005 09:31:04 +0100 Subject: Comments in configuration files Message-ID: <41f20f4a$0$6599$8fcfb975@news.wanadoo.fr> Bonjour, I am developing an application and I have a configuration file with a lot of comments to help the application users understand what the options mean I would like it to be editable, through a web browser or a GUI application. With ConfigParser I can read the configuration file and edit the options, but when I write the result all the comments are lost Are there modules that work on the same kind of ini files (for the needs of my application, I prefer this format to XML or YAML) and don't remove the comments ? TIA, Pierre From martin at v.loewis.de Sun Jan 16 04:41:40 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 16 Jan 2005 10:41:40 +0100 Subject: deleting from tarfile In-Reply-To: References: Message-ID: <41EA36D4.6090409@v.loewis.de> Mark McEahern wrote: > It doesn't appear so. A workaround, of course, is to create a new file > with the subset of files from the old file: That is actually the *only* way to do that. tarfiles cannot be "sparse", in the sense that parts of the file can be marked as deleted. So in order to delete a file, you have to copy the entire tarfile, and skip the file you want to delete - whether you do this yourself, or whether tarfile.py does it for you. Regards, Martin From jcarlson at uci.edu Sat Jan 22 15:40:18 2005 From: jcarlson at uci.edu (Josiah Carlson) Date: Sat, 22 Jan 2005 12:40:18 -0800 Subject: IDLE Problem in Windows XP In-Reply-To: <41F03130.4080709@cc.gatech.edu> References: <41F03130.4080709@cc.gatech.edu> Message-ID: <20050122123747.F647.JCARLSON@uci.edu> Branden Smith wrote: > > Hi, > > I am a teaching assistant for an introductory course at Georgia Tech > which uses Python, and I have a student who has been unable to start > IDLE on her Windows XP Home Edition machine. Clicking on the shortcut > (or the program executable) causes the hourglass to appear momentarily > (and the process to momentarily appear in the process monitor), but > nothing happens thereafter. ... > Does anyone have any ideas as to what might cause this problem? It shows > up with both Python 2.4 and 2.3. Version 2.2 works as it should. It is probably the socket issue. To get past the socket issue, according to the idle docs: Running without a subprocess: If IDLE is started with the -n command line switch it will run in a single process and will not create the subprocess which runs the RPC Python execution server. This can be useful if Python cannot create the subprocess or the RPC socket interface on your platform. However, in this mode user code is not isolated from IDLE itself. Also, the environment is not restarted when Run/Run Module (F5) is selected. If your code has been modified, you must reload() the affected modules and re-import any specific items (e.g. from foo import baz) if the changes are to take effect. For these reasons, it is preferable to run IDLE with the default subprocess if at all possible. That is, have the student modify the shortcut to pass a '-n' argument (without the quotes) to the command. If it works, great, if it doesn't, a traceback would be helpful. - Josiah From irmen at -nospam-remove-this-xs4all.nl Mon Jan 3 18:39:41 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 04 Jan 2005 00:39:41 +0100 Subject: How to access database? In-Reply-To: References: Message-ID: <41d9d7bd$0$6219$e4fe514c@news.xs4all.nl> Florian Lindner wrote: > AFAIK python has a generic API for database access which adapters are > supposed to implement. How can I found API documentation on the API? http://www.python.org/topics/database/ --Irmen From mike.kreiner at gmail.com Tue Jan 25 00:45:07 2005 From: mike.kreiner at gmail.com (mike kreiner) Date: 24 Jan 2005 21:45:07 -0800 Subject: scipy.signal.convolve2d() clips off part of my image Message-ID: <1106631907.600618.324390@c13g2000cwb.googlegroups.com> I'm using the convolve2d(image, mask) function from scipy to blur an image. The image I'm using is 512 by 384. When I display the image that convolve2d returns, the the left-most square of pixels (388 by 388) turn out fine, blurred and everything, however the right side of the image is all black. I've uploaded the practice image to: http://tinypic.com/1g3iox The output image is: http://tinypic.com/1g3iv9 here's what I entered at the intereactive window: >>> import scipy >>> img = scipy.imread("c:\\practice.jpg",flatten=True) >>> img.shape (384, 512) >>> mask = (1.0/115)*scipy.array([[2,4,5,4,2],[4,9,12,9,4],[5,12,15,12,5],[4,9,12,9,4],[2,4,5,4,2]]) >>> blurredImg = scipy.signal.convolve2d(img, mask) >>> scipy.imsave("c:\\blurred.jpg",blurredImg) Also, I noticed that the shape attribute is (384, 512), even though windows and my image editor say the image is 512 by 384. Could this have something to do with the reason convolve2d() only works right on the left-most 388 by 388 pixels? Thanks for any help. -Mike Kreiner From fredrik at pythonware.com Sun Jan 23 14:10:27 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 20:10:27 +0100 Subject: on the way to find pi! References: <20050123184955.25121.qmail@web61005.mail.yahoo.com> Message-ID: Ali Polatel wrote: > write the code type str(pi(5)) and see what I mean it helps if you post the code you want help with in your first post, so people don't have to guess. the pi function doesn't return anything, it prints the value to stdout (that's what the stdout.write things are doing). if a function doesn't return anything, Python automagically inserts a "return None", which explains the "None" you're seeing (well, it prints 3.1415None after your modification, so you probably did something else to get "3.1415'None'"). if you want the digits, you have to change the stdout.write calls to something else. say: def pi(n=-1): output = "" printed_decimal = False r = f((1,0,1,1)) while n != 0: if len(r) == 5: output += str(r[4]) if not printed_decimal: output += '.' printed_decimal = True n -= 1 r = f(r[:4]) return output (this returns a string. to convert it to a Python float, use float(pi(x)). if x is large enough, that gives you the same thing as math.pi). From http Tue Jan 4 19:46:36 2005 From: http (Paul Rubin) Date: 04 Jan 2005 16:46:36 -0800 Subject: Embedding a restricted python interpreter References: Message-ID: <7xacrohfdf.fsf@ruckus.brouhaha.com> Rolf Magnus writes: > I would like to embed a python interpreter within a program, but since that > program would be able to automatically download scripts from the internet, > I'd like to run those in a restricted environment, which basically means > that I want to allow only a specific set of modules to be used by the > scripts, so that it wouldn't be possible for them to remove files from the > hard drive, kill processes or do other nasty stuff. > Is there any way to do that with the standard python interpreter? Don't count on it. From philippecmartin at sbcglobal.net Tue Jan 18 05:45:28 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Tue, 18 Jan 2005 11:45:28 +0100 Subject: Tkinter in thread hangs on windows but not on Linux Message-ID: <1106045128.6665.9.camel@localhost> Hi, I need to pop-up in a "modless" manner some windows from an existing Tkinter loop. The following code works OK under Linux: the second window opens, shows the information, and quits cleanly when destroyed. However, under windows, I get the second window without the content (so I hang in run I guess), and both the thread and the calling process hang. Any clue ? Thanks Philippe #******************************************************************************* class SC_DOCS(threading.Thread): __m_smg = None __m_title = None def __init__(self,p_msg,p_title): threading.Thread.__init__(self) self.__m_msg = p_msg self.__m_title = p_title #******************************************************************************* def run (self): l_r = Tk() l_r.title(self.__m_title) l_f = Frame(l_r) l_f.pack(side=TOP, expand=YES, fill=BOTH) l_st = ScrolledText(l_f) l_st.pack(side=TOP, expand=YES, fill=BOTH) l_st.insert(END,self.__m_msg) l_r.mainloop() . . . l_d = SC_DOCS('A MESSAGE', 'A TITLE') l_d.start() . . . -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From phr at localhost.localdomain Thu Jan 27 10:48:20 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Thu, 27 Jan 2005 15:48:20 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: Skip Montanaro writes: > phr> It is not a whizbang module. It is a stripped-down, basic > phr> implementation of a well-accepted set of standards that are being > phr> used in thousands of other applications in other languages. > > Then there should be a library already out there already. All you > should need to do is wrap it (manually, with SWIG, whatever). I'm currently using something wrapped with SWIG, but my understanding is that core modules are not supposed to depend on SWIG. So a core module will likely use some existing primitives wrapped by hand. That is what I've offered to do, along with providing a somewhat more Pythonic interface (though still a straightforward one) than directly wrapping a C library intended for use from C applications. > phr> There is demand for it. Look at how this thread started: some > phr> crypto user noticed that rotor was gone and wanted to know what to > phr> do instead. > > Yes, and putting rotor back would be the wrong thing to do. Correct. The right thing is to replace rotor with something reasonable that follows standards. > phr> The issue of whether there's enough desire for a crypto module to > phr> warrant including one in the stdlib was decided a long time ago. > phr> The proof of that somebody decided to accept the rotor module into > phr> the distro. > > No, rotor was added in Python's early days (July 1992). Times have changed. I don't see that. There's surely even more demand for crypto now than there was in 1992. > As long as we are discussing cryptography, what's wrong with m2crypto? > > http://sandbox.rulemaker.net/ngps/m2/ It's a good package but it's pretty heavyweight. It depends on both SWIG and OpenSSL. I think it's still under development--there's an occasional flurry of messages about it on python-crypto, but I haven't been following it closely. I'd have a hard time making a case for accepting it into the core given the difficulty I'm having making the case for something as simple as a block cipher wrapper. m2crypto+OpenSSL is at least 100 times as much code as the module I've proposed. I think the Python lib should someday have its own pure-Python SSL/TLS implementation sort of like the one Java has. But if m2crypto went into the lib, I'd use it. > Why not incorporate it into the standard distribution? I don't have the authority to incorporate anything into the standard distribution. All I can do is offer to contribute stuff that I write, and let the distro maintainers decide whether to incorporate it. I don't have the authority to offer m2crypto, since I'm not the author. Only the authors can do that. They haven't done so, as far as I know. > Or, what about Andrew Kuchling's crypto toolkit? > > http://www.amk.ca/python/code/crypto.html This is perhaps more suitable than m2crypto but as far as I know, Andrew hasn't offered to contribute it. Whatever his reasons are, I have to respect them. I think it has more stuff than a core crypto module really needs (e.g. numerous semi-obsolete algorithms that aren't in widespread use so aren't needed for interoperability) but the extra stuff doesn't really get in the way. If it were in the core, it would completely fulfill my desires and I would be transported with ecstacy. But I've never seen any indication that it's headed there. > I believe both have been around awhile. If crypto-in-the-core is > really what's needed why not see if one of them is ready to go? I don't think m2crypto is the answer, though maybe I'm wrong. And if Andrew's package is the answer, he would have submitted it already. > phr> Have you ever used a crypto library in a serious way? > > Nope, never directly. Don't make this about me. I'm interested in the > Python development process and how you'd like to turn it on its head. Either you're the one turning the actual process on its head, or else it's already on its head and needs to be turned rightside up. Either way, the existing process has certainly been a total failure so far at producing good crypto support in the lib. > phr> It's already the category king, because there are precisely zero > phr> other entrants in the category. > > See my above references. Note, I don't use crypto at all, yet I was aware > of both of these (no Googling required). The authors have not offered to contribute them, so they're not in the category. The category consists of crypto modules that have actually been offered. As I keep saying, I'd love it if someone else offered one. I'm not eager for this headache. I just saw that somebody really ought to do it, and nobody was doing it, so I decided I was elected. > My guess would be they are substantially more mature than your > proposed module. This may sound a little strange, since my module is not yet written, but if we take maturity to mean lower future maintenance needs, then I wouldn't say m2crypto is precisely more mature. m2crypto uses SWIG and is intimately connected to an immensely complex package (OpenSSL) anpd has to track new OpenSSL and SWIG releases. OpenSSL has all kinds of OS dependencies, has high performance math subsystems written in assembly code for various different cpu's, etc. So my guess is that m2crypto has a longer development curve and will always need significant amounts of maintenance. My module is more like a basic portable math library that computes square roots, cosines, etc. and is OS and CPU independent. Once written and tested, it's intended to be pretty solid and not need much attention. Andrew's package is along the same lines as mine, except Andrew's is already done, so Andrew's is definitely more mature. I like to think that my module's API incorporates some lessons from Andrew's and improves on it, but that's not that important in practice. > phr> I read those as saying that no crypto module will be > phr> considered for inclusion whether or not it's the category > phr> king, because any such module might conflict with crypto > phr> regulations in some countries. > > That may be a problem, sure. I'm not sure how the discussion here changes > that. That's just life as we know it. It doesn't change it. However, it does change my level of interest in writing a module, as is reasonable since the only important characteristics of my module that are different from existing ones is that mine is designed specifically to be suitable for the core and has been offered for distribution in the core. Outside the core, the existing modules work ok so I use them. > Why in the heck is inclusion in the standard library a requirement > for you to write this thing? There's no other reason to write it. Outside the stdlib, there are other modules that are already useable, like the ones you mentioned, so I use those. > If it's useful to you, write it and get on with your life. It's not worth doing unless it's intended for the stdlib. How many times do I have to explain this? > phr> Tell me again how rotor got into the distribution. > > Python's user community was probably a few hundred people. Guido > likely had no thoughts of world domination with the little language that > could. Times have changed. If Python is aiming for world domination, it needs to be able to compete with Java in security features. Java ships with the whole JSSE system and a much fancier low level crypto architecture than the one we've been discussing. So I think the Python folks should figure out how to incorporate crypto without getting crushed under the iron boot (or at least the wooden shoe) of the Dutch government or whatever it is that they're worried about. > You seem think there was a PEP process and distutils and Wikis. I > suspect some of the algorithms one might include in a robust crypto > toolkit today weren't even invented in 1992. AES wasn't invented then. DES became a US federal standard around 1977. > So throw away the rotor crutch and put your money where your mouth is. If you mean write yet another crypto module knowing ahead of time that it won't go into the stdlib, that would be more like throwing my money down the drain. From john at grulic.org.ar Tue Jan 18 13:33:10 2005 From: john at grulic.org.ar (John Lenton) Date: Tue, 18 Jan 2005 15:33:10 -0300 Subject: One-Shot Property? In-Reply-To: <20050118115456510-0500@braeburn.themorgue.org> References: <20050118115456510-0500@braeburn.themorgue.org> Message-ID: <20050118183245.GA13370@grulic.org.ar> On Tue, Jan 18, 2005 at 04:54:56PM +0000, Kevin Smith wrote: > > I have many cases in my code where I use a property for calculating a > value on-demand. Quite a few of these only need to be called once. > After that the value is always the same. In these properties, I set a > variable in the instance as a cached value and return that value on > subsequent calls. It would be nice if there was a descriptor that would > do this automatically. Actually, what would be really nice is if I > could replace the property altogether and put the calculated value in > its place after the first call, but the property itself prevents me from > doing that. Is this possible? consider this: 1 >>> class C: 2 ... x = property(str) 3 ... 4 >>> c = C() 5 >>> c.x 6 '<__main__.C instance at 0x4008d92c>' 7 >>> setattr(c, 'x', c.x) 8 >>> c.x 9 '<__main__.C instance at 0x4008d92c>' 10 >>> C.x 11 12 >>> c.x = 2 13 >>> in line 5 you see that the x property so defined works. In line 7 you remove it, replacing it with the computed value of the property. Line 9 shows that it worked, line 11 shows that it didn't break the class, and line 13 (through the absence of an exception) shows that it no longer is 'special' (as it shouldn't be). -- John Lenton (john at grulic.org.ar) -- Random fortune: You can tune a piano, but you can't tuna fish. You can tune a filesystem, but you can't tuna fish. -- from the tunefs(8) man page -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From xah at xahlee.org Fri Jan 14 22:34:41 2005 From: xah at xahlee.org (Xah Lee) Date: 14 Jan 2005 19:34:41 -0800 Subject: [perl-python] 20050114 if statement Message-ID: <1105760081.771782.140700@f14g2000cwb.googlegroups.com> . # here's an example of if statement in python. . . x=-1 . if x<0: . print 'neg' . elif x==0: . print 'zero' . elif x==1: . print 'one' . else: . print 'other' . . # the elif can be omitted. . ------------------------------ . # here's an example of if statement in perl . . $x=31; . if ($x<0) { . print 'neg' . } elsif ($x==0) { . print 'zero' . } elsif ($x==1) { . print 'one' . } else { . print 'other' . } . . . --------------------------- . . Note: this post is from the Perl-Python a-day mailing list at . http://groups.yahoo.com/group/perl-python/ . to subscribe, send an email to perl-python-subscribe at yahoogroups.com . if you are reading it on a web page, program examples may not run . because html conversion often breaks the code. . . Xah . xah at xahlee.org . http://xahlee.org/PageTwo_dir/more.html From klapotec at chello.at Wed Jan 5 01:44:30 2005 From: klapotec at chello.at (Christopher Koppler) Date: Wed, 05 Jan 2005 06:44:30 GMT Subject: % operation References: Message-ID: On Wed, 05 Jan 2005 15:36:30 +0900, Daewon YOON wrote: > ==== > Python 1.5.2 (#1, Jul 5 2001, 03:02:19) [GCC 2.96 20000731 (Red Hat > Linux 7.1 2 on linux-i386 > Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam > >>> x=9 > >>> y=4 > >>> x%y > 1 > >>> for z in range(44): > ... z%9 > File "", line 2 > z%9 > ^ > SyntaxError: invalid syntax > > ==== > What's wrong with the above operation and how can I get the correct > modulo result with Python? There's nothing wrong with the operation, but it looks like you forgot to indent your loop body (which the interactive shell doesn't automagically do for you): >>> for z in range(44): ... z%9 ... [result snipped] -- Christopher raise OutofSigError From daniel at bowettsolutions.com Wed Jan 26 03:27:34 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Wed, 26 Jan 2005 08:27:34 +0000 Subject: MySQLdb In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On Tue, 25 Jan 2005 20:43:54 +0000, Daniel Bowett > declaimed the following in > comp.lang.python: > > >>As a test I have written a script that executes 3000 insert statements >>on a table. The table contains 10 fields with a mix of text and numbers >>- its a product table for a website eg UPC, ProductName, Price etc. >> > > How many indices? > > >>The problem I have is that it takes just over two minuted to execute the >>3000 insert statements which seems really slow! I am running it on a > > > I recall reading that, for some RDBMs, when doing such batch > inserts, they recommend turning off the indices at the start, do the > inserts, then reactivate the indices -- apparently it is faster to > rebuild an index after the data has been inserted, then to continually > update the index. > UPC is my only index - its a varchar with 20 characters. I am only opening the connection once, then doing 3000 execute statements in a for loop. I do have two "TEXT" fields in the table which contain the long and short description. The average length of the long description is about 167 characters, the longest is 1800 characters. Is this whats making it slow? From asbach at ient.rwth-aachen.de Wed Jan 12 16:34:53 2005 From: asbach at ient.rwth-aachen.de (Mark Asbach) Date: Wed, 12 Jan 2005 22:34:53 +0100 Subject: GTK libs don't get events when wrapped for Python Message-ID: <1gqaqim.5ba4rn159bm4gN%asbach@ient.rwth-aachen.de> Hi list, I've got a crazy problem: an application fully written C and using a third-party library that itself uses GTK to draw some GUI widgets works as expected. But if I wrap the lib with SWIG and use it in Python, everythings works but the GUI parts. In fact, it looks like the library doesn't get events / messages from the window manager or these events have a significant delay. For example, I want to open a window and draw an image into it. This means two library calls. The first one should draw the window (but it only does when calling it from a C-only binary), the second one should resize the window and draw the image, but when called from python just draws the window. Occasionally, resize and in rare circumstances drawing of the image occur on subsequent calls of the library. Really strange and I don't have a clue where to look for a remedy. Is there anybody who could help me, please? FYI: the library used is Intel's OpenCV / HighGui, OS is debian/Sarge, python2.3 Thanks in advance, Mark -- Dipl.-Ing. Mark Asbach Tel +49 (0)241 80-27677 Institute of Communications Engineering RWTH Aachen University, Germany http://www.ient.rwth-aachen.de From bokr at oz.net Thu Jan 20 01:51:18 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 20 Jan 2005 06:51:18 GMT Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> <7xacr4ewjk.fsf@ruckus.brouhaha.com> Message-ID: <41ef4a7a.1323588509@news.oz.net> On 19 Jan 2005 17:09:19 -0800, Paul Rubin wrote: >Robin Becker writes: >> > Presumably he is talking about crypo-export rules. In the past strong >> > cryptography has been treated as munitions, and as such exporting it >> > (especially from the USA) could have got you into very serious >> > trouble. >> >> well since rotor is a german (1930's) invention it is a bit late for >> Amricans (Hollywood notwithstanding) to be worried about its export > >1. I think the concern was not about exporting from the US, but rather >importing into some countries that restrict the use of crypto. But >the cat is out of the bag on that one too. Just about every web >browser includes an SSL stack and those browsers are in use >everywhere. Isn't the SSL dependent on OS or at least shared lib support? Wasn't there a default 40-bit version that was ok (weak), but you had to declare yourself US resident to download 128-bit support? I dimly recall encountering this sort of thing installing Netscape a long time ago, I think. Is 128 just standard now? And now that 128 is wobbly(?), will the same thing be replayed with the ante upped? > >2. It's irrelevant for the purpose of export rules how old an >invention is or where it was invented. I don't know where machine >guns were invented, but they're at least 100 years old and you can't >export those without a license either. My gripe with the crypto rules >are not about the age or nationality of crypto rotor machines (rotor >is not a clone of the Enigma by the way; it just operates on related >principles) but rather on the control of information in general. I can easily conceive of information that I'd rather not see publicized without severe access controls. But in general I do believe in open sharing of free information as the most productive for everyone. >Exporting a machine gun is much different from publishing a >description of one. Software is just a precise type of description. Yeah, but ... ;-) Regards, Bengt Richter From grig.gheorghiu at gmail.com Mon Jan 10 13:42:22 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 10 Jan 2005 10:42:22 -0800 Subject: Importing Problem on Windows References: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> Message-ID: <1105382542.552797.125200@c13g2000cwb.googlegroups.com> What version of Python are you running on Linux vs. Windows? From richie at entrian.com Tue Jan 25 05:03:02 2005 From: richie at entrian.com (Richie Hindle) Date: Tue, 25 Jan 2005 10:03:02 +0000 Subject: Weakref.ref callbacks and eliminating __del__ methods In-Reply-To: <1f7befae05012411376821bb92@mail.gmail.com> References: <41F427EB.3000200@rogers.com> <1f7befae0501231720428ca3c@mail.gmail.com> <5lr9v0tg2i16irskb798f7rcti955j0c64@4ax.com> <1f7befae05012411376821bb92@mail.gmail.com> Message-ID: [Tim] > there's no 100% guarantee that a __del__ method will ever get called Can anyone point me to any definitive documentation on why this is the case? I was under the impression that __del__ would always be called: 1. for objects not in cycles and with no references 2. for objects whose only references are from cycles which themselves have no external references and no __del__methods, assuming that garbage collection runs. > __del__ methods (weakref callbacks too, for that matter) triggered > while Python is tearing itself down at exit may suffer bizarre > exceptions (due to trying to use facilities in partially-torn down > modules, including the module the __del__ method appears in). Good point. > In general, __del__ is a user-visible method like any other, and user > code may call it explicitly. For that reason, it's safest to write > __del__ methods in library objects such that they can be invoked > multiple times gracefully. Another good point - thanks. -- Richie Hindle richie at entrian.com From dmerrillq at usaq.netq Sat Jan 8 15:56:21 2005 From: dmerrillq at usaq.netq (Dave Merrill) Date: Sat, 8 Jan 2005 15:56:21 -0500 Subject: Installing IPython on win2k References: Message-ID: <4JqdnUwQgOFr1X3cRVn-gg@rcn.net> Fernando replied to a similar post of mine on the IPython list, and had a suggestion that for some unknown reason, worked. Or rather, what's unknown is why normal setup failed. For the benefit of anyone else who has this issue, I unzipped the files into C:\Program Files\ipython-0.6.6 ...then opened a DOS window, and did the following two cmds: cd C:\Program Files\ipython-0.6.6 "C:\Program Files\Python23\python.exe" setup.py install Tons of DOS cmds spat out, the shortcut was created, and launching it brought up the config wizard, then ipython. I'd really love it if ipython could be invoked in the current debugger context in PyDev under Eclipse. Is there any way to do that? Thanks again, Dave Merrill From fredrik at pythonware.com Sun Jan 23 17:52:29 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 23:52:29 +0100 Subject: Set parity of a string References: <1f060c4c050123140310e6f887@mail.gmail.com> Message-ID: "snacktime" wrote: > Is there a module that sets the parity of a string? I have an > application that needs to communicate with a host using even parity > So what I need is before sending the message, convert it from space to > even parity. And when I get the response I need to convert that from > even to space parity. umm. shouldn't the communication library do this for you? From bulba at bulba.com Wed Jan 5 21:27:25 2005 From: bulba at bulba.com (Bulba!) Date: Thu, 06 Jan 2005 03:27:25 +0100 Subject: No typical loops, and other crazy ideas Message-ID: OK. I have reworked this program (below) to use just the data manipulation capabilities of Python (training was largely the motivation). I've tried to manipulate the data just in Python and not in typical loops. One thing that may not be entirely crazy in this, IMHO, is the attempt to use built-in capabilities of the language as much as possible instead of doing it "manually". Anyway, Python is the only language I've seen (apart from functional languages probably, but I have yet to get unconventional enough to wet my feet there) where it is possible. Still, it was not as easy as I wish it were: I've had to use 3 types of data structures (dictionaries, sets, lists) and arguably 6 "stages" (marked in comments below) to get it done. And it still dies when the source terms are not unique. And I haven't figured out the way of producing a list of dictionaries that would have this particular key as unique across all the dictionaries in this list. [Also, for some reason the advice by another poster, to use: oldl=list(orig) instead of: oldl=[x for x in orig] ..somehow didn't work. The first instruction has produced only empty lists.] #---------Code follows----------- import sys import csv from sets import Set as set class excelpoldialect(csv.Dialect): delimiter=';' doublequote=True lineterminator='\r\n' quotechar='"' quoting=0 skipinitialspace=False epdialect=excelpoldialect() csv.register_dialect('excelpol',epdialect) try: ofile=open(sys.argv[1],'rb') except IOError: print "Old file %s could not be opened" % (sys.argv[1]) sys.exit(1) try: tfile=open(sys.argv[2],'rb') except IOError: print "New file %s could not be opened" % (sys.argv[2]) sys.exit(1) titles=csv.reader(ofile, dialect='excelpol').next() orig=csv.DictReader(ofile, titles, dialect='excelpol') transl=csv.DictReader(tfile, titles, dialect='excelpol') cfile=open('cmpfile.csv','wb') titles.append('New') titles.append('RowChanged') cm=csv.DictWriter(cfile,titles, dialect='excelpol') cm.writerow(dict(zip(titles,titles))) print titles print "-------------" # 1. creating lists of old & new translations #oldl=list(orig) #newl=list(orig) oldl=[x for x in orig] newl=[x for x in transl] # oldl is a list of dictionaries like: # [{'Polish': 'Zarzadzanie', 'TermID': '5', 'English': 'Administration'}, # {'Polish': 'Zarzadzanie systemem', 'TermID': '4', 'English': 'System Administration'}, # {'Polish': 'Testowanie', 'TermID': '5', 'English': 'Testing'}] # 2. creation of intersection of sets of old and new English strings to find the common source strings oldeng=set([item['English'] for item in oldl]) neweng=set([item['English'] for item in newl]) matcheng = list(oldeng & neweng) # 3. eliminating items not containing the common source strings oldl=[x for x in oldl if x['English'] in matcheng] newl=[x for x in newl if x['English'] in matcheng] # 4. sorting lists oldl.sort(lambda a, b: cmp(a['English'], b['English'])) newl.sort(lambda a, b: cmp(a['English'], b['English'])) # 5. defining comparison function def matchpol(old,new): retval={'TermID': old['TermID'], 'English': old['English'], 'Polish': old['Polish'], 'New': new['Polish'], 'RowChanged': ''} if old['Polish'] != new['Polish']: retval['RowChanged']='CHANGED' return retval # 6. Constructing list of target dictionaries chglist=map(matchpol, oldl, newl) # 7. Writing to a target file cm.writerows(chglist) # the end.. cfile.close() ofile.close() tfile.close() -- It's a man's life in a Python Programming Association. From alipolatel at yahoo.com Sat Jan 29 19:23:29 2005 From: alipolatel at yahoo.com (Ali Polatel) Date: Sat, 29 Jan 2005 16:23:29 -0800 (PST) Subject: Proxy Message-ID: <20050130002329.4200.qmail@web61003.mail.yahoo.com> is it possible to connect to somewhere through a proxy while using sockets module of Python to connect? If yes can you show me some basic examples? regards --------------------------------- Do you Yahoo!? Yahoo! Search presents - Jib Jab's 'Second Term' -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Sun Jan 23 18:29:55 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 24 Jan 2005 00:29:55 +0100 Subject: Alternative Ways to install Python 2.4? In-Reply-To: References: Message-ID: <41F43373.4020003@v.loewis.de> Michael Goettsche wrote: > I convinced my CS teacher to use Python in school. We currently have 2.2 > installed on a Windows 2000 Terminal server. I asked the system administrator > to upgrade to Python 2.4, but he didn't succeed in doing it. He used the > microsoft installer package, which according to him crashed when starting. > So my question is if there's an alternative way to install it(must be easy). > Would it be an option to remove 2.2 first and then try to install 2.4 again? That would be an option, but I doubt it helps. Please have a look at http://www.python.org/2.4/bugs.html Most likely, you need to upgrade Visual Basic on that machine. Of course, without a precise error description, it is hard to tell. Regards, Martin From sjmachin at lexicon.net Mon Jan 3 14:30:23 2005 From: sjmachin at lexicon.net (John Machin) Date: 3 Jan 2005 11:30:23 -0800 Subject: Py2exe and extension issues References: <1104763249.008031.100100@f14g2000cwb.googlegroups.com> Message-ID: <1104780623.038891.25810@z14g2000cwz.googlegroups.com> kdahlhaus at yahoo.com wrote: > Is anyone aware of issues with Py2exe and extensions compiled with > cygwin/mingw for Python 2.3? I have an extension that wraps access to > some C DLLs. The generated executable always segfaults at startup, > although things work fine when running through the normal python > interpreter. I had a guess that perhaps the issue stems from my > extension being compiled with cygwin and py2exe compiled with Visual > C++? Some questions: 1. Did it work before (e.g. with Python 2.2, or an earlier version of py2exe), or has it never worked? 2. Where at start-up does it "segfault"? Doesn't the "Dr Watson" log file tell you anything? You may need to sprinkle prints and printfs around your code. 3. Those C DLLs: supplied by whom -- you or an nth party? compiled with which compiler? 4. Which version(s) of which Windows are you using? Some hints: 1. Ask on the py2exe mailing list. 2. Your guess may be correct. The usual cause of such a problem is getting a run-time-library resource on one side of the chasm and trying to use it on the other side. When the resource is a pointer to a data structure whose contents are not defined by some standard, anything can go wrong, and usually does. Examples: (a) malloc() on one side and free() on the other (b) fopen() on one side and fanything() on the other. However I would expect these problems to show up under normal interpreter use. 3. Using py2exe instead of python may merely be exposing a bug in your code caused by e.g. an uninitialised variable. (-: When you say "things work fine" in normal interpreter mode, where does this lie in the continuum between "it ran regression tests and volume tests happily all night" and "I fired it up and it didn't fall over"? :-) HTH, John From removethis.kartic.krishnamurthy at gmail.com Mon Jan 31 20:38:19 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Tue, 01 Feb 2005 01:38:19 GMT Subject: "Mail receiver server" In-Reply-To: <41feb541$0$27942$636a15ce@news.free.fr> References: <41feaff2$0$2068$626a14ce@news.free.fr> <41feb541$0$27942$636a15ce@news.free.fr> Message-ID: manatlan said the following on 1/31/2005 5:46 PM: > > I like the idea, but how to connect the virtual smtp and a python script ? > > but ... There should be a way to be python only ... because i don't want > to be very complex, i just want to get the subject of the email, to run > some commands (and perhaps get a attachment file) ... but that's all > i am pretty sure that a recipe exists ... that a man has already done > that ! > But i don't know what to query on google ... Hi, What you are trying to do is what is called a mail filter. So google for python mail filter and see what you get. With this setup, lets say Computer B sends an email to user controluser on Computer A , the email is actually passed off to a script (in your case python script) to process the incoming email, instead of actually delivering the email to the user's inbox on "A". I don't have the faintest the idea how you would do this on IIS's virtual SMTP server; there is probably a setup user panel. In any case, on UNIXish systems, there are a few ways of doing it of which one way is to setup a user in a file called /etc/aliases and put an entry like this: controluser: | /usr/local/bin/mailprocessor.py which tells the SMTP server to pass off the email to script after the | (pipe) when controluser gets an email. So, see if the SMTP control panel provides you with some such feature. If IIS does not, my suggestion to you will be to install Cygwin from cygwin.com and use the Exim Mail transfer agent available with Cygwin (You will have to choose that when installing Cygwin, it is not automatically installed) or please google for Windows SMTP Server and see if something piques your interest. Now, coming to the Python related part. Your SMTP server will invoke your script by sending the incoming email data on your script's sysin. So, from python you will do... #!/usr/local/bin/python import sys, email, os em = email.message_from_file(sys.stdin) # Read message from Std Input subject = em.get('Subject') # Get the subject from em object if subject.startswith('reboot'): os.system('shutdown -r') # reboot the Server For more information, please read the email module in the Python Module Docs. Hope that will help you get started! Thanks, --Kartic From jlrodilla at gmail.com Sun Jan 30 14:19:30 2005 From: jlrodilla at gmail.com (jlrodilla at gmail.com) Date: 30 Jan 2005 11:19:30 -0800 Subject: search engine Message-ID: <1107112770.301449.49070@c13g2000cwb.googlegroups.com> hi all, i?m doing a search engine using python for the spider and php to make a web for the search. The Database i have choosen is postgreSQL. Do you think it is a good choosen? Any suggestion? if anybody in interested in colaborate please send an e-mail to jlrodilla at gmail.com In a few weeks i will upload all the code to one domain and so i can be able to send you information about this project. The idea is to build a search engine like "google", but my/our search engine only look for tech pages, i also wants that users can select if they want to search a web, faqs/howto, manuals/tutorials... Thanks. From fuzzyman at gmail.com Thu Jan 27 07:38:39 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 27 Jan 2005 04:38:39 -0800 Subject: Please suggest on the book to follow In-Reply-To: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> Message-ID: <1106829519.540737.164210@z14g2000cwz.googlegroups.com> We've only just had Python 2.4. Based on previous experience that means it will be about 18 months before python 2.5..... I learned to program from 'Programming Python'. Particularly the stuff on Tkinter is very helpful. I don't think you'll have much to 'unlearn', although obviously there is stuff it doesn't cover (like new style classes). Regards, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From __peter__ at web.de Mon Jan 17 16:04:41 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Jan 2005 22:04:41 +0100 Subject: Assigning to self References: <200501172055.33962.frans.englich@telia.com> Message-ID: Frans Englich wrote: >> > >>> class Foo(object): >> > >> > ... cache = {} >> > ... def __new__(cls, id): >> > ... try: >> > ... return cls.cache[id] >> > ... except KeyError: >> > ... pass >> > ... cls.cache[id] = result = object.__new__(cls, id) >> > ... return result >> > ... def __init__(self, id): >> > ... self.id = id >> > ... def __repr__(self): >> > ... return "Foo(id=%r)" % self.id >> > ... >> >> I'm not sure, but I think this code misses one thing: that __init__ is >> called each time __new__ returns it, as per the docs Peter posted. > > Ahem, John I ment :) You are right -- just put the initialization into the __new__() method, then. Peter From rkern at ucsd.edu Thu Jan 6 00:37:10 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 05 Jan 2005 21:37:10 -0800 Subject: Python evolution: Unease In-Reply-To: <41dcc35a$0$3872$afc38c87@news.optusnet.com.au> References: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> <41dcc35a$0$3872$afc38c87@news.optusnet.com.au> Message-ID: Mike Thompson wrote: > Alex Martelli wrote: > >> Carlos Ribeiro wrote: >> ... >> >>>> - IDE: Better than what? Than IDLE? Than Eclipse? Than SPE? Than >>>> Pythonwin? >>> >>> >>> I would like to seee Eric3, with some polish & opensourced on Win >>> (which means solving the Qt licensing problem). Perhaps someone could >>> convince Trolltech to release a special Qt Win version just for it >>> (Eric3). Eclipse is also an interesting approach. >> >> >> >> I love eric3, but if you're an eclipse fan, look at enthought's >> "envisage" IDE -- it seems to me that it has superb promise. >> > > I've tried both the SciPy and Enthought WWW sites and I can't find much > on "Envisage". At SciPy.org there is one set of powerpoint slides on it > but nothing more. > > Is it available for download somewhere? Alex is, I think, jumping the gun a bit. Envisage isn't quite ready for prime time as your day to day IDE. It might be useful to you right now as a platform to build a dynamic GUI application (Envisage's intended use) if you are willing to get your hands dirty and help us build Envisage. Hence, it is not being advertised widely. But Alex is right; Envisage does hold a lot of promise. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From ola.natvig at infosense.no Tue Jan 18 09:16:04 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Tue, 18 Jan 2005 15:16:04 +0100 Subject: generator expressions: performance anomaly? In-Reply-To: <354jhnF4gk8l6U1@individual.net> References: <377Hd.77904$Jk5.30235@lakeread01> <354gj7F4etgn8U1@individual.net> <354h9gF4fgsqgU1@individual.net> <354jhnF4gk8l6U1@individual.net> Message-ID: > > What makes the leftmost expression different from the iterable returning > expression inside the for? The same arguments apply there. > It's not different, but it's a requirement that the iterable returns the same data every time. I know that anyone can type range = fancyRange and make this return a random number of random items. But if that happens the expression cannot be transformed into a static list / tuple. Thats obvious. From ncoghlan at iinet.net.au Wed Jan 19 05:34:56 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 19 Jan 2005 20:34:56 +1000 Subject: Dictionary keys (again) (was Re: lambda) In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: <41EE37D0.70108@iinet.net.au> Antoon Pardon wrote: > A rule of thumb is context sensitive. If circumstances change, > so do the rules of thumb. Principles have a broader field > of application. > > IMO there is nothing principally wrong with using a mutable object > as a dictionary key. But avoiding doing so is a good rule of > thumb if you have a python-like implementation of a dictionary. For a 'mutable key' to make sense, the following: lst = [] dct = {l: "Hi!"} print dct[[]] print dct[lst] lst.append(1) print dct[[1]] print dct[lst] Should print: Hi Hi Hi Hi That's completely impractical though - for any sane implementation, at least one of the above print statements will throw a KeyError. Your example of a 'safe_dict' that copies mutable keys means that the final print statement is the one that fails. My suggestion of an "identity_dict" means that both of the same-value based lookups would fail. Notice that both of these approaches take a mutable key and make it immutable (either by holding the sole reference to a copy, or retrieving an immutable property of the mutable object). There's also your solution of "I promise not to mutate the key while it is in the dictionary". Workable, but opens the door to some entertaining bug hunts when the promise is broken. Which solution is the best default behaviour? Well, the Zen of Python states "In the face of ambiguity, refuse the temptation to guess". So that's the policy the builtin dict follows - it doesn't try to guess when to make a copy, or whether or not to use identity based semantics in the face of mutability. Instead, it raises an exception at key entry time, asking the programmer to clarify their intent. The principle is *certainly* that hash tables should contain immutable keys. Your own 'safe_dict' example implicitly concedes this point by making copies 'when required'. 'When required' for what? When required to preserve immutability, perhaps? In short, sane hash tables require immutable keys, and how mutable keys acquire the requisite immutability is going to be application dependent. Provision of a safe_dict or identity_dict would merely allow a programmer to state their intent at the time the container is created, rather than having to state it whenever keys are generated or referenced. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steve at holdenweb.com Mon Jan 31 13:55:34 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 13:55:34 -0500 Subject: Relocatable binary installs.... In-Reply-To: References: <1107195180.462949.222980@z14g2000cwz.googlegroups.com> Message-ID: <41FE7F26.1090209@holdenweb.com> Fredrik Lundh wrote: > friedmud at gmail.com wrote: > > >>Is there a way to make a relocateable python binary... that is... a >>python installation that won't care where it is on the machine... and >>won't care if it gets put somewhere else besides / ? > > > the standard CPython interpreter is 100% "relocatable". If you think > it isn't, you have to be a bit more specific. > Is it possible that you are using "relocatable" in the standard sense of "code can be located anywhere in physical memory", where the OP is using the same term to mean "can live anywhere in the filestore"? I suspect the problem the OP is seeing is because the --prefix configuration parameter will cause an interpreter to look in a specific place for standard libraries. Clearly if you "relocate" the libraries to another directory entirely then an interpreter without any further nouse (and no symbolic links to help it) is going to crap out badly. But I could be wrong. always-prepared-to-at-least-admit-the-possibility-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From http Sat Jan 22 07:32:30 2005 From: http (Paul Rubin) Date: 22 Jan 2005 04:32:30 -0800 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> Message-ID: <7xu0p9lk4h.fsf@ruckus.brouhaha.com> Dave Benjamin writes: > Can we get a show of hands for all of those who have written or are > currently maintaining code that uses the leaky listcomp "feature"? It's really irrelevant whether anyone is using a feature or not. If the feature is documented as being available, it means that removing it is an incompatible change that can break existing code which currently conforms to the spec. If the "feature" is described as the bug that it is, anything that relies on it is nonconformant. I do remember seeing some cute tricks (i.e. capable of becoming idioms) that depend on the leakage. From xah at xahlee.org Mon Jan 17 12:45:01 2005 From: xah at xahlee.org (Xah Lee) Date: 17 Jan 2005 09:45:01 -0800 Subject: [perl-python] 20050117, filter, map In-Reply-To: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> Message-ID: <1105983901.353590.83310@c13g2000cwb.googlegroups.com> erratum: the Mathematica Apply should've been Select. ... Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From godoy at ieee.org Wed Jan 19 12:17:55 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Wed, 19 Jan 2005 15:17:55 -0200 Subject: Accessing MDB files on Windows References: <1635068.ZTfiooUzB4@strongwill.g2ctech> <4262806.PViGKJWPeZ@strongwill.g2ctech> <57wHd.80954$Jk5.41342@lakeread01> Message-ID: <1116749.2eGh3JeIRy@strongwill.g2ctech> Steve Holden, Quarta 19 Janeiro 2005 14:38, wrote: > Note that DAO is a very old library, and nowadays ADO would probably be > the preferred method in the Windows environment (can DAO even *use* > oledb providers?). ADO libraries are available - see > > http://www.markcarter.me.uk/computing/python/ado.html > > for example, or Google for "python ado". Bottom line, there are many > ways to skin this particular cat. Hmmm... I see. I'm trying to avoid having to install external modules at my client's server. Should I use, given that both DAO and ODBC are available with the win32all extensions, DAO or ODBC? Or would ADO give me so much more performance that I should really use it? -- Godoy. From mauriceling at acm.org Sun Jan 2 16:34:58 2005 From: mauriceling at acm.org (Maurice LING) Date: Sun, 02 Jan 2005 21:34:58 GMT Subject: How to make executable file ? In-Reply-To: <33r5gcF449bt0U1@individual.net> References: <33r5gcF449bt0U1@individual.net> Message-ID: <41d868ff@news.unimelb.edu.au> Hi all, This may be OT but is there a way to do the same for *nix type of system? Like cast a python interpreter with scripts together? I'm running Mac OSX here. The only remote idea I have is to use jythonc to convert everything into .class files and package that as a .jar file but I can't do that with C bindings. Any suggestions? Thanks, Maurice From xah at xahlee.org Sat Jan 15 21:31:18 2005 From: xah at xahlee.org (Xah Lee) Date: 15 Jan 2005 18:31:18 -0800 Subject: python mode indentation problem In-Reply-To: <1105802644.939051.229990@f14g2000cwb.googlegroups.com> References: <1105802644.939051.229990@f14g2000cwb.googlegroups.com> Message-ID: <1105842678.044409.270450@z14g2000cwz.googlegroups.com> ? ok, here's the ordeal. ? ? for i in range(5): ? print i ? for i in range(2): ? print i, 'tt' ? for i in [3]: ? print i ? for i in [32]: ? print i ? ? # 1 level, 4 space ? # 2 level, 1 tab ? # 3 level, 1 tab, 4 spaces ? # 4 level, 2 tabs. ? ? who the fuck coded the python mode in emacs? fuckhead please peruse: ? http://xahlee.org/UnixResource_dir/writ/responsible_license.html ? ? PS Thanks for the tip on (setq-default indent-tabs-mode nil). ? ? Xah ? xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html From fredrik at pythonware.com Sat Jan 22 19:21:59 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 01:21:59 +0100 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com><41EE24F7.7030303@jessikat.fsnet.co.uk><7x1xchlpqv.fsf@ruckus.brouhaha.com><41efeb82$0$27807$9b622d9e@news.freenet.de><41f1a70b$0$25959$9b622d9e@news.freenet.de><7xbrbiqdhk.fsf@ruckus.brouhaha.com><7xllalljah.fsf@ruckus.brouhaha.com><7xekgdmpll.fsf@ruckus.brouhaha.com><7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >> you really don't have a fucking clue about anything, do you? > > You're not making any bloody sense. oh, I make perfect sense, and I think most people here understand why I found your little "lecture" so funny. if you still don't get it, maybe some- one can explain it to you. From orwin42 at mail.be Sun Jan 9 08:54:23 2005 From: orwin42 at mail.be (Nyx42) Date: Sun, 09 Jan 2005 08:54:23 -0500 Subject: Pygame and pyopengl with py2exe ? Message-ID: Hi, I have 2 programs which run without problems, but after building them with py2exe, they don't work (program opens the window and closed it immediately) First program (uses only pygame): screen = pygame.display.set_mode((W_WIDTH_F, W_HEIGHT)) This line refuses to be compiled correctly. Why ? Second program (pygame + pyopenGL): Py2exe can't import OpenGL.GL and OpenGL.GLU :( From apardon at forel.vub.ac.be Mon Jan 17 10:20:01 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Jan 2005 15:20:01 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-17, John Lenton schreef : > > > --vni90+aGYgRvsTuO > Content-Type: text/plain; charset=us-ascii > Content-Disposition: inline > Content-Transfer-Encoding: quoted-printable > > On Mon, Jan 17, 2005 at 11:41:20AM +0000, Antoon Pardon wrote: >> Op 2005-01-17, Steve Holden schreef : >> > Antoon Pardon wrote: >> > [...] >> >>>"A foolish consistency is the hobgoblin of little minds". Rules are ma= > de=20 >> >>>to be broken. >> >>=20 >> >>=20 >> >> Like only use immutables as dictionary keys. >> >>=20 >> > Fair enough, but don;t go advising newbies to do this. >>=20 >> How about something like this. >>=20 >> Because of the extra precautions one has to take when >> using mutables as hash keys, we advise newbies >> to stick with immutable keys until they have gathered >> enough knowledge and experience to adequatly weight >> the pro and cons of a mutable key solution against >> an immutable key solution. > > knowledgeable and experienced users know when to ignore the rules. Then why seems there to be so few acknowledgement that these rules may indeed be broken by users. My experience is that anyone who suggests so runs the risk of being branded a (python) heretic. -- Antoon Pardon From hans at zephyrfalcon.org Fri Jan 28 11:09:16 2005 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 28 Jan 2005 11:09:16 -0500 Subject: Dynamic class methods misunderstanding In-Reply-To: References: Message-ID: Bill Mill wrote: > Hello all, > > I have a misunderstanding about dynamic class methods. I don't expect > this behavior: > > In [2]: class test: > ...: def __init__(self, method): > ...: self.method = method > ...: self.method() > ...: > > In [3]: def m(self): print self > ...: [...] > > TypeError: m() takes exactly 1 argument (0 given) > ----------------------------------------------------------------------------- > > Why doesn't m get the implicit self parameter in the self.method() > call? How would I make it a proper member of the class, so that a > self.method() call would work with the above "m" function? m is a function. When you assign it to self.method, it's still a function. You don't create a new method that way; all you have is a new attribute called 'method' containing the function. To add m as a new method to the *class*, do this: >>> class test: ... def __init__(self, method): ... self.__class__.method = method ... self.method() ... >>> def m(self): print self ... >>> test(m) <__main__.test instance at 0x0192ED78> <__main__.test instance at 0x0192ED78> >>> To add m as a new method to the *instance*, use new.instancemethod, as Diez B. Roggisch already pointed out. HTH, -- Hans Nowak http://zephyrfalcon.org/ From theller at python.net Tue Jan 4 13:57:11 2005 From: theller at python.net (Thomas Heller) Date: Tue, 04 Jan 2005 19:57:11 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> <41dae3c3$0$228$edfadb0f@dread12.news.tele.dk> Message-ID: Max M writes: > Thomas Heller wrote: > >> It seems also the error messages aren't too helpful: >> >>>>>"?".encode("latin-1") >> Traceback (most recent call last): >> File "", line 1, in ? >> UnicodeDecodeError: 'ascii' codec can't decode byte 0x84 in position 0: ordinal not in range(128) >> Hm, why does the 'encode' call complain about decoding? > > Because it tries to print it out to your console and fail. While > writing to the console it tries to convert to ascii. Wrong, same error without trying to print something: >>> x = "?".encode("latin-1") Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0x84 in position 0: ordinal not in range(128) >>> > > Beside, you should write: > > u"?".encode("latin-1") to get a latin-1 encoded string. I know, but the question was: why does a unicode string has a encode method, and why does it complain about decoding (which has already been answered in the meantime). Thomas From jerf at jerf.org Tue Jan 4 21:12:40 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 04 Jan 2005 21:12:40 -0500 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> Message-ID: On Tue, 04 Jan 2005 17:12:04 -0800, Paul Rubin wrote: > Irrelevant, the issue isn't what docs can be written if someone wants to > do it, it's what docs are actually already there.... > I just see various other free software projects as > trying to live up to higher standards and I think Python should aspire to > the same thing. So, nobody should have to write the docs because they should already be there, but "somebody" should have to write the docs? You need to think more clearly about the pronouns you are slinging around. Who is this "they" that should write the docs? (Yes, I know you didn't use that exact word but the concept is clearly there.) And what right do you have to demand this action from "they"? Are you willing to pay me to do it? From jurgenex at hotmail.com Sun Jan 30 03:09:54 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sun, 30 Jan 2005 08:09:54 GMT Subject: [perl-python] sending email References: <1107041765.890014.112530@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: [...] > Here's how the situation stands as of 2001 March: ^^^^^^^^^^ Well, at least now we know why Mr. Lee is a little bit behind .... jue From oglycans at yahoo.com Thu Jan 13 17:49:41 2005 From: oglycans at yahoo.com (oglycans at yahoo.com) Date: 13 Jan 2005 14:49:41 -0800 Subject: how to control the mouse pointer with python? References: <1105650438.311153.167410@f14g2000cwb.googlegroups.com> <34o9npF4et4hiU1@individual.net> <1105654593.637145.321290@z14g2000cwz.googlegroups.com> <41e6f6db$0$5416$a1866201@visi.com> Message-ID: <1105656581.837894.142790@z14g2000cwz.googlegroups.com> >What environment? It's X. From jtr at ofb.net Sun Jan 2 22:38:04 2005 From: jtr at ofb.net (John Reese) Date: Mon, 3 Jan 2005 03:38:04 +0000 (UTC) Subject: using HTTP Digest auth with arbitrary HTTP methods? References: Message-ID: In comp.lang.python, [I] wrote: > Hello there. I've run into some missing functionality with HTTP Digest > authentication in the 2.3 library and I was wondering if I'm just > missing something. > > Missing functionality the first: urllib2 > > 1a. You can add "handlers" to your opener indicating that you want to > use HTTP Digest auth. This is nice way to handle it, but I don't > see any way to use a custom verb in your URLOpener -- it always > uses either GET or POST depending on whether you provided data. > Is there any way to specify an arbitrary method? This would allow > urllib2 to be used to write WebDAV clients. > > 1b. HTTPDigestAuthHandler is initialized with an HTTPPasswordMgr > object, which unfortunately deals in cleartext passwords. Digest > authentication can be computed using only a hash of username, > password, and realm; it would be nice if there was an alternate > version of HTTPPasswordMgr that let you deal in hashes instead of > or in addition to plaintext passwords. Well, I figured out a workaround, but it requires changing urllib2.py since the bugs are in base classes. I instead copied it (to urllib3.py) and made the following changes: a. in AbstractDigestAuthHandler.get_authorization, call req.get_method() instead of req.has_data() and 'POST' or 'GET' (python has a ternary operator, who knew) b. in AbstractHTTPHandler.do_open, call req.get_method instead of the hard-coded if-logic which is the same as that in req.get_method Both of these seem like bugs in urllib2. Then I overrode urllib2.Request and made it possibly to set the method, and then passed an instance of my custom Request class (the one that shouldn't have to exist, since Request should allow method to be set explicitly) to OpenerDirector.open(). I'd like to see these changes make it into the standard library -- after being vetted by whoever's in charge of urllib2. Anybody know who I should talk to? From gsakkis at rutgers.edu Tue Jan 25 19:25:55 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Tue, 25 Jan 2005 19:25:55 -0500 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> <1106669254.838248.317170@z14g2000cwz.googlegroups.com> <10vdj4s9ib19fe3@corp.supernews.com> Message-ID: <35o6cdF4qe45fU1@individual.net> "Jeff Shannon" wrote in message news:10vdj4s9ib19fe3 at corp.supernews.com... > George Sakkis wrote: > > > An iterator is perfectly ok if all you want is to iterate over the > > elements of a view, but as you noted, iterators are less flexible than > > the underlying sequence. The view should be (or at least appear) > > identical in functionality (i.e. public methods) with its underlying > > sequence. > > So, what problem is it, exactly, that you think you'd solve by making > tuple slices a view rather than a copy? > > As I see it, you get the *possibility* of saving a few bytes (which It all comes down on what you mean by "a few bytes". Since many (most?) slices are linear wrt to the original sequence's length, it is not hard to think of algorithms that involve the creation of *many* slices (e.g. most recursive divide-and-conquer algorithms). Implementing these using slices simply does not scale as the input sequence gets larger. Of course, you can always use the standard C/C++ approach and pass the original sequence along with the (start,stop,step) indices of the slice, as Terry Reedy mentioned, but then you lose in expressiveness. > may go in the other direction) at a cost of complexity and speed. You > have greater dependence of internal objects on each other, you can't > get rid of the original tuple while any slice views of it exist, you > gain nothing in the way of syntax/usage simplicity... so what's the > point? > > To my mind, one of the best things about Python is that (for the most > part) I don't have to worry about actual memory layout of objects. I > don't *care* how tuples are implemented, they just work. It seems to > me that you're saying that they work perfectly fine as-is, but that > you have a problem with the implementation that the language tries its > best to let you not care about. Is this purely abstract philosophy? No, it's called "scalability", and it's not purely abstract philosophy AFAIK. I fully agree that for the most part you don't have to care about it, and I'm grateful that python does all its magic trasparently. However if you do care about it, and at the same time you are unwilling to sacrifice the elegance of slices, the current implementation is not ideal. > Jeff Shannon > Technician/Programmer > Credit International George From ncoghlan at iinet.net.au Sun Jan 2 02:22:14 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 02 Jan 2005 17:22:14 +1000 Subject: PEP 288 ponderings In-Reply-To: <41D794BA.8090408@colorstudy.com> References: <41D794BA.8090408@colorstudy.com> Message-ID: <41D7A126.4060808@iinet.net.au> Ian Bicking wrote: > Using a one-element list is kind of annoying, because it isn't clear out > of context that it's just a way of creating shared state. But it's > okay, work right now, and provides the exact same functionality. Uh, isn't shared state what classes were invented for? Py> class mygen(object): ... def __init__(self, data): ... self.data = data ... def __iter__(self): ... while 1: ... print self.data ... yield None ... Py> g = mygen(0) Py> giter = iter(g) Py> giter.next() 0 Py> g.data = 1 Py> giter.next() 1 Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From peter at engcorp.com Sun Jan 9 09:50:51 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jan 2005 09:50:51 -0500 Subject: time module precision In-Reply-To: <1105268967.629064.154850@c13g2000cwb.googlegroups.com> References: <1105268967.629064.154850@c13g2000cwb.googlegroups.com> Message-ID: janeaustine50 at hotmail.com wrote: > So the problem (waiting tens to hundreds of us without busy looping) > still remains... That's actually not a "problem", it's your solution to a problem. Can you describe the _real_ problem, what you are trying to do? _Why_ do you want to wait such brief amounts of time? I ask as someone with fairly extensive background in realtime software (which is basically what it sounds like you are trying to write here), and I suspect that you are either trying to achieve something that's not really possible on Windows XP, or that you are simply doing something that is entirely unnecessary, probably for good reasons but with too little experience of the issues involved. Can you expand on your situation? -Peter From jelle.feringa at ezct.net Tue Jan 11 11:31:07 2005 From: jelle.feringa at ezct.net (Jelle Feringa // EZCT / Paris) Date: Tue, 11 Jan 2005 17:31:07 +0100 Subject: os.spawnv & stdin trouble Message-ID: <20050111163036.808E91C00CE9@mwinf0108.wanadoo.fr> ##I know I should be using 2.4 and os.Popen, I know, I know. ##However, since most modules I need, I'm using 2.3 for this script I'm having troubles executing a shell script. The thing is that I'm produing material and geometry files that need to be compiled to a binary description (for those familiar to Radiance, oconv) The trouble I'm having is that when python goes through my loop, files are overwritten before os.system was able to process these! (who ways complaining python is slow, well I'm not!! ;-) So the obvious thing to do is to swap os.system for os.spawnv. Here's where I run into trouble. In my os.system version, I'm perfectly able to pipe into another file, since the process has no real connection to python whatsoever. Would someone be able to explain me how to do this, all the tools I'm using for this script are unix-like tools and heavily rely on piping. program = 'xform.exe' path = 'c:\Radiance\bin\' args = ['-t 0 8 0', 'wall0.rad', '>', 'wall0.TRANS.rad'] os.spawnv(os.P_WAIT, path, ('xform', args)) here's the cmd error message: xform: cannot find file ">" ##for your info I'm on win/xp, python 2.3.4 Cheers, Jelle. -------------- next part -------------- An HTML attachment was scrubbed... URL: From foo at bar.com Sun Jan 23 22:48:27 2005 From: foo at bar.com (Steve Menard) Date: Sun, 23 Jan 2005 22:48:27 -0500 Subject: JPype and classpath (Was Re: embedding jython in CPython... ) In-Reply-To: <1106517122.552509.318400@f14g2000cwb.googlegroups.com> References: <1106446384.384110.25150@z14g2000cwz.googlegroups.com> <1106517122.552509.318400@f14g2000cwb.googlegroups.com> Message-ID: johng2001 at rediffmail.com wrote: > Thanks for the response. However, I continue to have problems. Allow me > to give some more detail. > > For simplicity of testing, I hard coded the classpath and JVM path > (BTW getDefaultJVMPath() returns None on my system) > > import os, os.path > from jpype import * > > startJVM("C:/jdk1.5.0/jre/bin/client/jvm.dll", > "-Djava.class.path=D:/Temp/classes") > ... > shutdownJVM() > > > I have setup a classes folder in the script folder (D:/Temp) and have > placed test.class in it. > I run the script from the script folder (working directory is the same > as script's root path in this case) > > Now how do I load the class test? I am afraid I cannot make that out > from the docs. > > The simple test class is > public class test > { > public int i = 100; > } > > > What do I have to do before I can write > test().i > ? > > Thank you for your time. > About the getDefaultJVMPath(), could you send me your system information? On windows, JPype uses the contents of the registry to find the JVM. Of course, the usefulness of this mechanism is limited byt he sample of configurations i can test (I have only one machine). So any info you can provide me on yours can only help. About the classpath. JPype 0.4 currently cannot import classes that are in the "default" package. The fix is easy, simply put your "test" class in a package. For exmaple, if you put the class in the package "test", the code to load it would be : test = jpype.JPackage("test").test -- Steve Menard -------------------- Maintainer of http://jpype.sourceforge.net From robin at SPAMREMOVEjessikat.fsnet.co.uk Wed Jan 19 19:12:44 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Thu, 20 Jan 2005 00:12:44 +0000 Subject: rotor replacement In-Reply-To: <41EEF691.20706@jessikat.fsnet.co.uk> References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> Message-ID: <41EEF77C.6030400@jessikat.fsnet.co.uk> Robin Becker wrote: >> Presumably he is talking about crypo-export rules. In the past strong >> cryptography has been treated as munitions, and as such exporting it >> (especially from the USA) could have got you into very serious >> trouble. > So Python is an American Language and must obey American Law. Luckily I seem to have escaped that fate. -- Robin Becker From steven.bethard at gmail.com Mon Jan 24 13:00:48 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 24 Jan 2005 11:00:48 -0700 Subject: Tuple slices In-Reply-To: References: <35kn4mF4o44ufU1@individual.net> Message-ID: Fredrik Lundh wrote: > George Sakkis wrote: > >>Why does slicing a tuple returns a new tuple instead of a view of the existing one, given that >>tuples are immutable ? > > really? > > >>>>a = 1, 2, 3 >>>>b = a[:] >>>>a is b > True My impression was that full tuple copies didn't actually copy, but that slicing a subset of a tuple might. Not exactly sure how to test this, but: py> a = 1, 2, 3 py> a[:2] is a[:2] False So _something_ at least is different between the two slices... Steve From pedro.werneck at terra.com.br Mon Jan 24 13:21:41 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Mon, 24 Jan 2005 16:21:41 -0200 Subject: Tuple slices In-Reply-To: References: <35kn4mF4o44ufU1@individual.net> Message-ID: <20050124162141.0903e6c6.pedro.werneck@terra.com.br> On Mon, 24 Jan 2005 18:45:46 +0100 "Fredrik Lundh" wrote: > George Sakkis wrote: > > > Why does slicing a tuple returns a new tuple instead of a view of > > the existing one, given that tuples are immutable ? > > really? Well... seems like this case (slicing the whole tuple) is optimized to return the original tuple just incrementing its reference count and returning tupleobject.c, 330-335 if (ilow == 0 && ihigh == a->ob_size && PyTuple_CheckExact(a)) { Py_INCREF(a); return (PyObject *)a; } > > >>> a = 1, 2, 3 > >>> b = a[:] > >>> a is b > True > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From peter at engcorp.com Wed Jan 5 15:05:27 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 05 Jan 2005 15:05:27 -0500 Subject: Python 2.4 on Windows XP In-Reply-To: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> References: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> Message-ID: DavidHolt wrote: > I have a problem that I see on two different machines, one running XP > SP1 and one XP SP 2. Works fine here. (First time I've run it though... don't use it.) > On both I installed Python 2.4. > > I can't seem to start IDLE. When I try to start it, I get an hourglass > cursor for a short time then nothing more happens. This happens whether > I click the IDLE shortcut or click the pythonw.exe directly, or attempt > to launch pythonw from a command line. Try python.exe instead of pythonw.exe, also from the command line. That should give you *some* kind of additional detail. > I don't have any trouble running the python command line version. Do you mean "python.exe" here? Are you saying that you can run IDLE using python.exe, but not using pythonw.exe? Or something else? It's not clear. -Peter From FBatista at uniFON.com.ar Wed Jan 5 13:12:43 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 5 Jan 2005 15:12:43 -0300 Subject: Python 2.4 on Windows XP Message-ID: [DavidHolt] #- I have a problem that I see on two different machines, one running XP #- SP1 and one XP SP 2. #- #- On both I installed Python 2.4. #- #- I can't seem to start IDLE. When I try to start it, I get an IDLE uses sockets to communicate its windows. Check if the integrated firewall in WinXP is not blocking you.... . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ncoghlan at iinet.net.au Sat Jan 8 00:13:10 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 15:13:10 +1000 Subject: Getting rid of "self." In-Reply-To: References: Message-ID: <41DF6BE6.1080807@iinet.net.au> Roy Smith wrote: > It's actually kind of neat, but boy does it play headgames with me when > I switch back and forth between that and Python. Switching back and forth betwen C++ and Python plays headgames *anyway* }:> Cheers, Nick. Hardware control with Python is nice. . . -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From kendall at monkeyfist.com Mon Jan 3 07:52:52 2005 From: kendall at monkeyfist.com (Kendall Clark) Date: Mon, 3 Jan 2005 07:52:52 -0500 Subject: Continuations Based Web Framework - Seaside. In-Reply-To: <41D8F86E.6030300@colorstudy.com> References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <7aTBd.11928$H%6.521997@twister1.libero.it> <20050102183402.GC8357@monkeyfist.com> <41D8F86E.6030300@colorstudy.com> Message-ID: <20050103125251.GA12713@monkeyfist.com> On Mon, Jan 03, 2005 at 01:46:54AM -0600, Ian Bicking wrote: > Kendall Clark wrote: > >Between this pressure (which isn't new, since as Steve points out, I > >was talking about this in Python community last year, and I wasn't > >nearly the first) and the growing popularity of Ruby on Rails, there's > >some small hint that Ruby is gaining on Python re: non-Java web app > >mind share. I think that's a v. important niche for Python and would > >like to see us remain strong there (though I've not *done* much about > >this, alas). > > I think that's probably true -- at least in terms of mindshare, even > though that might not reflect on actual work done. But, Rails is really > not a very experimental framework, and the existance of > continuation-based frameworks for Ruby is an aside. If such frameworks > happen at all for Python, I think they will be an aside as well. There's no sense whatever in which Rails is "experimental" -- who suggested such a thing? No, Rails hits a sweet spot, for a class (I suspect) of simple to mediumly-complex web app. Which is what most web apps *are*, after all. I don't begrudge Rails any popularity, I just want us to defend our turf. Sometimes that means ignoring what the other guy does, but sometimes it means aping him. I suspect in this case some aping would be a good thing. As for continuation-based frameworks, as you point out to Steve, that's largely an implementation technique and similar results may be achieved with other techniques (though I, unlike you, did *not* favor Steve's technique, as I recall). Continuations are certainly not experimental, nor are continuation-based modal web frameworks. The latter are *en vogue* and being seen to be *en vogue* is often an important technological virtue, especially for a perceived market niche leader. Kendall Clark -- Sometimes it's appropriate, even patriotic, to be ashamed of your country. -- James Howard Kunstler From janeaustine50 at hotmail.com Mon Jan 10 03:02:50 2005 From: janeaustine50 at hotmail.com (janeaustine50 at hotmail.com) Date: 10 Jan 2005 00:02:50 -0800 Subject: time module precision In-Reply-To: References: <1105268967.629064.154850@c13g2000cwb.googlegroups.com> Message-ID: <1105344170.575115.230820@c13g2000cwb.googlegroups.com> Peter Hansen wrote: > janeaustine50 at hotmail.com wrote: > > So the problem (waiting tens to hundreds of us without busy looping) > > still remains... > > That's actually not a "problem", it's your solution > to a problem. Can you describe the _real_ problem, what > you are trying to do? _Why_ do you want to wait such > brief amounts of time? > > I ask as someone with fairly extensive background in > realtime software (which is basically what it sounds like > you are trying to write here), and I suspect that you are > either trying to achieve something that's not really possible > on Windows XP, or that you are simply doing something that > is entirely unnecessary, probably for good reasons but > with too little experience of the issues involved. Can > you expand on your situation? > > -Peter What I am trying to do is sending binary data to a serial port. Since the device attached to the port cannot handle a continous in-flow of data, I need to make an artificial tiny delay in-between data chunks(a few hundreds of KBs). The delay might be a few tens to hundreds of us. I'd like to make the transmission as fast as possible, uh.. well.. reasonably fast. [I sort of posted this already but hasn't got it through so am reposting it now] Thanks From jello at comics.com Wed Jan 12 10:48:58 2005 From: jello at comics.com (rzed) Date: Wed, 12 Jan 2005 15:48:58 GMT Subject: ConfigParser - add a stop sentinel? Message-ID: I am working with PythonCard in one of my apps. For its purposes, it uses an .ini file that is passed to ConfigParser. For my app, I also need configuration information, but for various reasons, I'd rather use a syntax that ConfigParser can't handle. I know I can maintain two separate configuration files, and if I have to I will, but I'd rather avoid that, if possible, and a solution that suits my purposes is quite straightforward. I insert a sentinel in the ini file and modify my local ConfigParser's _read method to stop accepting input when it encounters that value. I handle my app's portion of the configuration myself. This all works fine, but I was wondering whether it might be worthwhile to add a standard stop flag in ConfigParser itself. Am I the only one with this sort of use case? If there were a standard way of doing this, I'd much rather use that, particularly if I ever have reason to distribute the app elsewhere. -- rzed From richardjones at optushome.com.au Fri Jan 28 19:34:30 2005 From: richardjones at optushome.com.au (richard) Date: Sat, 29 Jan 2005 11:34:30 +1100 Subject: move bugs from Zope BITS into Bugzilla? References: <1106956988.391329.320610@z14g2000cwz.googlegroups.com> Message-ID: <41fada16$0$25421$afc38c87@news.optusnet.com.au> lmhaskins at yahoo.com wrote: > I inherited a bug reporting system at work, and it's currently in Zope > BITS (Bug Information Tracking System). This version of BITS uses ZODB > -- not the RDBMS version. I would like to export all the incident > reports from BITS to later import into Bugzilla, but as of yet I > haven't quite figured it out. As soon as I'm done with this, that's it > for BITS and Zope, so I'd like to avoid writing a Zope app just for > this. > > Anyone solved this problem, or at least the part about exporting from > BITS? I'd hand-enter the open issues, but they also want the closed > ones for tracking & posterity. I'm not helping you with your problem, just plugging my own tracker ;) Use Roundup! It's Pure Python :) http://roundup.sf.net/ Richard From invalidemail at aerojockey.com Sun Jan 9 20:13:10 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 9 Jan 2005 17:13:10 -0800 Subject: python3: 'where' keyword In-Reply-To: <7xr7ku26zs.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> Message-ID: <1105319590.641211.191630@c13g2000cwb.googlegroups.com> Paul Rubin wrote: > Nick Coghlan writes: > > Trying to push it a level further (down to expressions) would, IMO, be > > a lot of effort for something which would hurt readability a lot. > > I think we should just try to do things in a simple and general way > and not try to enforce readability. For example, the > slightly-overcomplex code that I proposed might have been generated by > a macro, or even by a compiler from some other language. No human > would ever have to look at it, so it doesn't matter whether it's > easily readable. There's no reason to add needless constraints on the > language just to make writing ugly code difficult. The main goal > should be to make writing clear code easy, not to worry about whether > someone might also write ugly code. I couldn't disagree more. I belive in the Zen of Python. I believe the Zen of Python is the major factor responsible for Python's success. I believe that moving away from the Zen of Python will only diminish the language. And I think allowing a where statement inside in expression goes against the Zen in so many ways it isn't even funny. Beautiful is better than ugly. Simple is better than complex. (Note that simple means different things to different people: for me, and I believe, for the Zen of Python, it means simple for a human to understand.) Flat is better than nested. (Seems to be the official Zen if effect here.) Readability counts. (Yes, if something's unreadable enough, I hope it's not in the language, not merely that no one uses it.) Special cases aren't special enough to break the rules. (Heretofore, Python has never had a nested block inside an expression; doing that would make it a special case.) I don't want Python to be LISP. I don't think it's an admirable goal for Python to strive to be like LISP for the sake of being like LISP, or for the sake of being general or pure. If Python borrows something from LISP, it should be because that aspect of LISP supports the Zen of Python. If I wanted to use LISP, I'd be using LISP. But I like my statements and expressions distinct. I like things that belong in statements to stay in statements, and things that belong in expressions to stay in expressions. And a suite, be it a def statement, a where block, or whatever, belongs in a statement, not an expression. -- CARL BANKS From scott at hcsprogramming.com Mon Jan 17 10:56:51 2005 From: scott at hcsprogramming.com (Scott) Date: 17 Jan 2005 07:56:51 -0800 Subject: help with wxSlider & wxPython Message-ID: <1105977411.527188.198370@f14g2000cwb.googlegroups.com> I have the code below. I have changed the background of the frame to white, but I cannot get the wxSlider to not be the ugly gray color. Can someone tell me how to change it to a transparent background (I tried wxTRANSPARENT_WINDOW without success)? import os from wxPython.wx import * ID_ABOUT=101 ID_EXIT=110 class MainWindow(wxFrame): def __init__(self,parent,id,title): wxFrame.__init__(self,parent,wxID_ANY, title, size = ( 800,600),style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE) #self.control = wxTextCtrl(self, 1, style=wxTE_MULTILINE) wxStaticText(self, -1, "Distance to Move", (30, 40)) slider = wxSlider(self, 100, 25, 0, 3600, (30, 60), (400, -1),wxSL_HORIZONTAL | wxSL_TOP | wxSL_AUTOTICKS | wxSL_LABELS | wxTRANSPARENT_WINDOW) slider.SetTickFreq(1, 1) slider.SetValue(1800) self.CreateStatusBar() # A StatusBar in the bottom of the window # Setting up the menu. filemenu= wxMenu() filemenu.Append(ID_ABOUT, "&About"," Version 001") filemenu.AppendSeparator() filemenu.Append(ID_EXIT,"E&xit"," Terminate the program") # Creating the menubar. menuBar = wxMenuBar() menuBar.Append(filemenu,"&File") # Adding the "filemenu" to the MenuBar self.SetMenuBar(menuBar) # Adding the MenuBar to the Frame content. EVT_MENU(self, ID_ABOUT, self.OnAbout) # attach the menu-event ID_ABOUT to the EVT_MENU(self, ID_EXIT, self.OnExit) # attach the menu-event ID_EXIT to the self.SetBackgroundColour(wxWHITE) self.Show(true) self.Center(wxBOTH) def OnAbout(self,e): d= wxMessageDialog( self, "test","About test", wxOK) d.ShowModal() # Shows it d.Destroy() # finally destroy it when finished. def OnExit(self,e): self.Close(true) # Close the frame. app = wxPySimpleApp() frame = MainWindow(None, -1, "test") app.MainLoop() TIA, Scott From tchur at optushome.com.au Sat Jan 15 17:36:28 2005 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 16 Jan 2005 09:36:28 +1100 Subject: hash patent by AltNet; Python is prior art? In-Reply-To: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> References: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> Message-ID: <41E99AEC.1020008@optushome.com.au> GerritM wrote: > ZDnet features an article about the had patent at AltNet > http://news.zdnet.com/2100-9588_22-5534087.html . Apparantly this issue > plays already for some time, now the p2p companies are threatened, becuase > they use hashing to recognize files. I find it incredibly annoying when journalists reporting on patent issues don't bother to quote the patent numbers (or patent application numbers) concerned (failure to do so probably means they haven't bothered to examine the patent or patent application themselves). In this case, a search is made doubly difficult because the patent was purchased from someone else, so a name serach can't be done. A quick keyworfd search on the USPTO web site revealed some related patents issued to Apple and Sony, but hard to identify this particular patent. > As far as I know hasing is a very old technique used to quickly look up > information. The use of hashing always requires an idnetity check, because > the lookup is not unique (mapping a very big amount of possibilities on a > limited amount of entries). This is a fast and robust way of finding > information, if the right hashing function is used. > > How can this type of fundamental knowledge be patented? I am afraid this is > again an example of a total failure of the current patent system. > Unfortunately these ridiculous examples endanger smaller companies, open > software activities amd innovation in general. What you have to remember is that the US (and some countries which have been stupid enough to follow its lead, like Japan, Australia and now it seems India) permits patents not just on software algorithms and techniques, but also on business methods. Thus the "novel" application of a well-known and widely-used technique such as hashing to a particular field of endeavour (like file sharing on the Internet) can be patented (in the US). To be novel, there must be no published prior art - but the prior art needs to be specific to the claims of the patent. So if the patent says "use of hashing to uniquely identify files in a peer-to-peer network via IP over the Internet", then the prior art needs to describe exactly that. The Australian government recently passed legislation which tightened this test of novelty (thank goodness) by allowing separate bits of prior art which describe aspects of a patent claim to be combined to some degree when opposing a patent - but the test for novelty remains remarkably lax in the US, I beleive. And I agree 100% with Alex Martelli - Europe and other countries must reject software, algorithmic and business method patents and thus create a powerhouse of innovation. let the US and fellow-travellers stew in their own juice - they will become powerhouses of litigation instead. Provided other countries don't recognise software and business method patents, the litigation will be confined within US borders, where resources can be productivelt spent making television dramas about attractive young patent attorneys and plodding, tram-riding patent clerks who are really brilliant physicists if only someone would recognise their potential. So yes, please write to your MP and MEP and protest against the prospect of software and business method patents in Europe. Hopefully one day within my lifetime we'll have a governemt here in Australia which will roll back the damage done to our patent system by trying to make just like the US system, just so we can conclude an unbelieveably inequitable free trade agreement with the US. But that's our problem. Tim C From mensanator at aol.com Mon Jan 10 12:52:03 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 10 Jan 2005 09:52:03 -0800 Subject: Old Paranoia Game in Python In-Reply-To: References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> <1105318366.966577.107460@c13g2000cwb.googlegroups.com> Message-ID: <1105379523.253933.278550@f14g2000cwb.googlegroups.com> Lucas Raab wrote: > mensanator at aol.com wrote: > > Aahz wrote: > > > >>Trust the computer, the computer is your friend. > > > > > > However, the computer isn't a fuckin' mind reader. > > > > If you're going to post source code on the usenet, don't > > have lines longer than 72 characters. Otherwise you'll > > find your code has wrapped lines. This not only causes > > syntax errors in your choose and print statements but > > also fucks up the formatting of of printed paragraphs. > > > > Stupid human. > > > > Temper, temper... But if I hadn't thrown a temper tantrum, I never would have learned about pyparsing (which I downloaded and installed). From chrisdewinN0SPAM at yahoo.com.au Tue Jan 18 17:42:44 2005 From: chrisdewinN0SPAM at yahoo.com.au (Dfenestr8) Date: Wed, 19 Jan 2005 08:42:44 +1000 Subject: python/cgi/html bug Message-ID: Hi. I've written a cgi messageboard script in python, for an irc chan I happen to frequent. Bear with me, it's hard for me to describe what the bug is. So I've divided this post into two sections: HOW MY SCRIPTS WORKS, and WHAT THE BUG IS. HOW MY SCRIPT WORKS Basically, it's divided into two executable scripts...... One is the thread viewer, ppthread.py, which views threads. When someone posts a new topic, for instance called "Generic new topic", it creates a file called "Generic new topic.thread". It stores the post, and any subsequent posts under in the thread in that file. Nice and simple I figured. The other executable script is the topic viewer, pptopic.py. All that does is display the topics, by doing a "tops = os.popen('ls -c *.thread')" The "ls -c" part reads the threads in the order in which they've been modified, so the first item in the list is always the thread most recently posted in. It then creates an html link to each of the threads ... on the page the html looks like.... foo
WHAT THE BUG IS .... The problem is when someone posts a new topic, and that topic happens to have "" double quotes, or any other strange character, some strange glitches occur. Best way to describe is to demonstrate it is go to the forum and try it yourself. Try entering a topic with straight, ordindary characters, not that you can re enter the thread any time you want and make new posts under it. Then try entering a thread with new or whacky characters and see how far you get. http://funkmunch.net/~pirch/cgi-bin/alphaforum/pptopic.py BTW, if you want to download the script, here it is in gzipped form http://funkmunch.net/~pirch/pepperpot.tgz From klachemin at comcast.net Fri Jan 28 11:08:12 2005 From: klachemin at comcast.net (Kamilche) Date: 28 Jan 2005 08:08:12 -0800 Subject: Dynamic class methods misunderstanding References: Message-ID: <1106928492.114459.191320@c13g2000cwb.googlegroups.com> I see what you're attempting to do. However, your code, if it DID run, would result in a method being added to the object, not the object's class! Modify the class itself, not the object, as follows: |class Test: | def __init__(self): | self.method() | |def m(self): | print self | |setattr(Test, 'method', m) |Test() From deetsNOSPAM at web.de Tue Jan 18 09:29:06 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 18 Jan 2005 15:29:06 +0100 Subject: generator expressions: performance anomaly? References: <354esdF4fouh0U1@individual.net> Message-ID: <354kntF4g4crnU1@individual.net> > I don't see how generating byte code for a = 9; when seeing the > expression a = 3 + 6, would be a problem for non-functional > languages. Most probably. But I don't see much code of that type that it would be worth optimizing for, either. The cost for re-evaluation such an expression doesn't really account for any performance problems you hit - in python, of course. See this: deets at kumquat:/usr/lib/python2.3$ python timeit.py -c "[4*5 for i in xrange(10000)]" 100 loops, best of 3: 5.5e+03 usec per loop deets at kumquat:/usr/lib/python2.3$ python timeit.py -c "[20 for i in xrange(10000)]" 100 loops, best of 3: 4.3e+03 usec per loop Now of course the longer the expressions get, the more time it costs - but how many long arithmetical expression of constant evaluation value do you have? > > I agree that things like [time.time() for i in xrange(10)] shouldn't > be pregenerated and that the problem is more complicated as I thought. > > But during compilation the compilor could do an anlysis of the code > do determine whether there are side effects or not. If the compilor > then would store a code in the byte code for functions that are > guaranteed side-effect free and only pregenerated objects generated > by expressions with no side-effect, some common subexpression > elimination could be done even in a non-functional language. This analysis would only be possible for the most primitive of examples, the reason beeing that due to the dynamic features syntactically equivalent expressions can have totally different semantics. So its not really worth the effort. -- Regards, Diez B. Roggisch From jbperez808 at wahoo.com Wed Jan 12 20:26:29 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Thu, 13 Jan 2005 09:26:29 +0800 Subject: Another look at language comparisons In-Reply-To: References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> <34llf5F4apou6U2@individual.net> Message-ID: <34m12rF4cppjeU1@individual.net> Terry Reedy wrote: > It would hardly make more sense with the photos. The photos would be graphic evidence and would make it more entertaining to read through. > "Not the law is clear? There is a beard - there is a success. > There is no beard - you are guilty. " > > Terry J. Reedy And what about the moustache issue and Grace Hopper (COBOL is/was a very popular language but very much maligned and criticized like Perl and BASIC whose creators had moustaches instead of beards) ? Also, what about C#? AFAIK, Heljsberg has neither beard nor moustache, or is he sprouting one now (no pic to confirm...)? From eppstein at ics.uci.edu Wed Jan 19 13:19:55 2005 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 19 Jan 2005 10:19:55 -0800 Subject: Dictionary keys (again) (was Re: lambda) References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: In article , Nick Coghlan wrote: > For a 'mutable key' to make sense, the following: > > lst = [] > dct = {l: "Hi!"} > print dct[[]] > print dct[lst] > lst.append(1) > print dct[[1]] > print dct[lst] > > Should print: > Hi > Hi > Hi > Hi Yes, and what should the following do? lst1 = [1] lst2 = [2] dct = {lst1: "1", lst2: "2"} lst2[0]=1 lst1[0]=2 print dct[[1]] print dct[[2]] -- David Eppstein Computer Science Dept., Univ. of California, Irvine http://www.ics.uci.edu/~eppstein/ From steve at holdenweb.com Mon Jan 31 13:03:54 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 13:03:54 -0500 Subject: variable declaration In-Reply-To: <1gr9lyc.1rrm543162uefN%aleaxit@yahoo.com> References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1107188359.375703.110590@f14g2000cwb.googlegroups.com> <1gr9lyc.1rrm543162uefN%aleaxit@yahoo.com> Message-ID: <41FE730A.4030201@holdenweb.com> Alex Martelli wrote: > Michael Tobis wrote: > [...] >>Let me add that I remain unconvinced that a language cannot combine the >>best features of Python with very high performance, which is ultimately > > > I'm also unconvinced. Fortunately, so is the EU, so they have approved > very substantial financing for the pypy project, which aims in good part > exactly at probing this issue. If any single individual can be called > the ideator of pypy, I think it's Armin Rigo, well-known for his > excellent psyco specializing-compiler for Python: the key research > thesis behind both projects is that a higher-level, dynamic language > need not have performance inferior to a lower-level one and indeed may > well beat it. > I should be failing in my duty as Chairman if I didn't remind readers at this point that they can hear Armin Rigo's talk "PyPy and Type Inference" at PyCon at 5:30 on Wednesday March 23. http://www.python.org/pycon/dc2005/register.html While Alex is not necessarily too modest to mention it he might forget that he is also giving three talks to PyCon. I believe this is the first year he has been able to attend PyCon, so delegates are definitely in for a treat this year. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From ncoghlan at iinet.net.au Fri Jan 28 20:33:37 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 29 Jan 2005 11:33:37 +1000 Subject: Who should security issues be reported to? In-Reply-To: References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> <41FA22DA.2090402@iinet.net.au> Message-ID: <41FAE7F1.8060008@iinet.net.au> Fredrik Lundh wrote: > Nick Coghlan wrote: > > >>>I'm sorry, but this isn't really good enough. If Open Source wants to >>>say that they are better than these proprietary companies, they need >>>to deal with these sorts of things more professionally and establish >>>decent channels of communications for dealing with it. >> >>Is that the sound of a volunteer I hear? >> >>All you have to do is put your hand up, and the problem will be solved. If not you, who? > > > oh, please. this is a security issue. it needs a little more coordination > than an ordinary bug report. > > Well, a less facetious answer to the OP's question would be Anthony Baxter. As the current release manager, he's the best contact point I can think of. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From bokr at oz.net Sat Jan 22 23:28:27 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 23 Jan 2005 04:28:27 GMT Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) References: Message-ID: <41f325b5.1576259210@news.oz.net> On Sat, 22 Jan 2005 16:22:33 +1000, Nick Coghlan wrote: >Steven Bethard wrote: >> I wrote: >> > If you really want locals that don't contribute to arguments, I'd be >> > much happier with something like a decorator, e.g.[1]: >> > >> > @with_consts(i=1, deftime=time.ctime()) >> > def foo(x, y=123, *args, **kw): >> > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime >> > >> > Then you don't have to mix parameter declarations with locals >> > definitions. >> > >> > Steve >> > >> > [1] I have no idea how implementable such a decorator would be. I'd >> > just like to see function constants declared separate from arguments >> > since they mean such different things. >> >> I played around with this, and I think it's basically implementable: > >Raymond's constant binding decorator is probably a good model for how to do it: >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 > I thought so too. I modified it to accept **presets as a keyword argument and generate constants and assignments from its values matching assignment names when the rhs was __frompresets__, e.g., >>> from makeconstpre import make_constants as pre >>> import time >>> @pre(verbose=True, deftime=time.ctime(), a=1, b=2, c=3, pi=__import__('math').pi) ... def foo(): ... deftime = __frompresets__ ... b, a = __frompresets__ ... c = __frompresets__ ... pi = __frompresets__ ... return locals() ... __frompresets__ : deftime --> Sat Jan 22 20:18:09 2005 __frompresets__ : ('b', 'a') --> (2, 1) __frompresets__ : c --> 3 __frompresets__ : pi --> 3.14159265359 locals --> >>> import dis >>> dis.dis(foo) 3 0 LOAD_CONST 1 ('Sat Jan 22 20:18:09 2005') 3 STORE_FAST 3 (deftime) 4 6 LOAD_CONST 2 ((2, 1)) 9 UNPACK_SEQUENCE 2 12 STORE_FAST 2 (b) 15 STORE_FAST 0 (a) 5 18 LOAD_CONST 3 (3) 21 STORE_FAST 1 (c) 6 24 LOAD_CONST 4 (3.1415926535897931) 27 STORE_FAST 4 (pi) 7 30 LOAD_CONST 5 () 33 CALL_FUNCTION 0 36 RETURN_VALUE >>> foo() {'a': 1, 'c': 3, 'pi': 3.1415926535897931, 'b': 2, 'deftime': 'Sat Jan 22 20:18:09 2005'} Not vary tested as yet, but seems to work. I want to eliminate redundant constants if the same name is assigned = __frompresets__ more than once. Right now I brute force generate another constant. Regards, Bengt Richter From rupole at hotmail.com Fri Jan 28 02:04:57 2005 From: rupole at hotmail.com (Roger Upole) Date: Fri, 28 Jan 2005 02:04:57 -0500 Subject: PythonWin (build 203) for Python 2.3 causes Windows 2000 to grind to a halt? References: <3f233389.0501271147.43572416@posting.google.com> Message-ID: <41f9e4a9$1_1@127.0.0.1> These look like symptoms of sf bug #1017504 http://sourceforge.net/tracker/index.php?func=detail&aid=1017504&group_id=78018&atid=551954 What version of Pywin32 are you running ? There's a (semi) fix for this in the latest build. hth Roger "Chris P." wrote in message news:3f233389.0501271147.43572416 at posting.google.com... > I've been having a problem with PythonWin that seemed to start > completely spontaneously and I don't even know where to START to find > the answer. The only thing I can think of that marks the point > between "PythonWin works fine" and "PythonWin hardly every works fine" > was that I changed the size of my Virtual Paging file, noticing that > it was too small (I currently have a P4 with 1G of RAM). I tried > returning it to its original (smaller) size, but it didn't fix the > problems. > > The first time I noticed it, I was using PythonWin and then > right-clicked on My Computer to use "Explore". Instead of the usual > full listing (approx 10 items), I got a mini-listing of 4 items. > Then, after clicking "Explore", I either don't get a new window at all > OR I get a strange file explorer that won't let me look at files, > won't let me copy files, etc. The "mini-lising" thing also happens if > I click the "Start" button while PythonWin is open. > > Another problem is trying to open another program while PythonWin is > running - generally, the program will not start, but I also don't get > any kind of error popping up on the screen. My request is just > ignored (although I sometimes get a "system beep".) If I already have > other programs open and then open PythonWin, my menu bar might refuse > to function. Is it significant that, when the menu bar IS working, > the drop-down menu fades in quite slowly, instead of popping up > immediately? > > At the end of this message, I've pasted a screen dump of a message I > get when I try to open a file and I've got other apps open (note that > I can have very few, non-memory intensive apps open and I still get > it). > > Thanks for any help you can give, > > - Chris > > [SCREEN DUMP AFTER I TRY TO OPEN A .PY FILE] > File "C:\Python23\Lib\site-packages\pythonwin\pywin\mfc\docview.py", > line 91, in CreateNewFrame > wnd.LoadFrame(self.GetResourceID(), -1, None, context) # triggers > OnCreateClient... > win32ui: LoadFrame failed > > win32ui: CreateNewFrame() virtual handler ( SyntEditTemplate.CreateNewFrame of > 0x01193F30>>) raised an exception > TypeError: PyCTemplate::CreateNewFrame must return a PyCFrameWnd > object. ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From mfranklin1 at gatwick.westerngeco.slb.com Tue Jan 25 08:44:32 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Tue, 25 Jan 2005 13:44:32 +0000 Subject: tkinter socket client ? In-Reply-To: <1106659122.977876.234250@z14g2000cwz.googlegroups.com> References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> <1106311130.446259.30710@f14g2000cwb.googlegroups.com> <1106318469.311179.126140@c13g2000cwb.googlegroups.com> <1106319270.932204.180590@c13g2000cwb.googlegroups.com> <1106659122.977876.234250@z14g2000cwz.googlegroups.com> Message-ID: Tonino wrote: > Hi, > > thanks for this info - I had to abandon the createfilehandler() method > as it is not supported in windows and the GUI "might" be used there at > some time ... > > So - I went the threading route - works well - for now - so I will > stick to it ... > > BUT - the next question: > In the Text() widget - why - when the text scrolls off the screen - > does the window not follow it ? > > I have added a scrollbar to it : > > self.center_frame = Frame(self.top_frame, background="tan", > relief=RIDGE) > > self.text=Text(self.center_frame,background='white') > scroll=Scrollbar(self.center_frame) > self.text.configure(yscrollcommand=scroll.set) > > self.text.pack(side=LEFT, fill=BOTH, expand=YES) > scroll.pack(side=RIGHT,fill=Y) > self.center_frame.pack(side=RIGHT, expand=YES, fill=BOTH) > > > but the window does not scroll to follow the text ? > Any ideas ? > This is the default behavior of the Text widget. You have two options (as I see it) one, put the new text at the top of the Text widget textwidget.insert(0, "your new text") or two, use the yview_pickplace method to move the view down every time you insert text textwidget.yview_pickplace('end') I wrote a sub-class of the ScrolledText widget to do just this I gave it a write method - so I could re-direct stdout to it - and also called yview_pickplace in that method. HTH Martin. From fccoelho at gmail.com Tue Jan 11 06:32:01 2005 From: fccoelho at gmail.com (Flavio codeco coelho) Date: 11 Jan 2005 03:32:01 -0800 Subject: Checking for X availability Message-ID: I have a program that uses pythondialog for its UI. Pythondialog is a wrapper of the shell dialog and xdialog libs. But I would like for it to switch between using Dialog ( when X is not available ) and xdialog (when X is available) So my question is: how can I check for the availability of X? i.e., How will my program know if its running in a text only console or in console window over X? thanks, Fl?vio From rkern at ucsd.edu Mon Jan 31 00:29:51 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 30 Jan 2005 21:29:51 -0800 Subject: PyGame not working(?) In-Reply-To: <20050130152208505-0800@news.claremont.edu> References: <20050129232540162-0800@news.claremont.edu> <20050130152208505-0800@news.claremont.edu> Message-ID: Chris Weisiger wrote: > Thanks; I've now successfully installed Numeric, as well as all of the > other dependencies listed for PyGame. However, PyGame appears to still > not be working. When I try to run the program at the top of this page: > http://www.pygame.org/docs/tut/tom/games2.html > I get the following error: > > % python main.py > Fatal Python error: Interpreter not initialized (version mismatch?) > Abort A couple things: * Are you sure you are using the same python executable that you compiled the extension modules against? * If you aren't using the X11 versions of SDL et al., then you need to run your scripts with pythonw, which will run the framework's interpreter in such a way that it can communicate with the native window server. This shouldn't give you the error above, though. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From andre.roberge at gmail.com Fri Jan 21 20:57:48 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 21 Jan 2005 17:57:48 -0800 Subject: finding name of instances created References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> Message-ID: <1106359068.802501.35190@z14g2000cwz.googlegroups.com> Using the method suggested by Steven Bethard, I *almost* got it working the way I would like. Here's my program: === .class PrivateClass(object): . dict = {} . def not_so_simple_method(self): . for name in PrivateClass.dict.keys(): . if PrivateClass.dict[name] == self: . print "instance " + name + " called not so simple" . apparently_simple_method = not_so_simple_method . def __init__(self): . print "instance created" . for name, value in globals().iteritems(): . if isinstance(value, PrivateClass): . PrivateClass.dict[name] = value .def public_class(): . return PrivateClass() .print "=== start===" .alpha = public_class() .print "created alpha" .print PrivateClass.dict .print "### alpha is not there\n" .beta = public_class() .print "created beta" .print PrivateClass.dict .print "### we are always one behind in the dict content\n" .alpha.apparently_simple_method() .beta.apparently_simple_method() ================================= The output follows: === start=== instance created created alpha {} ### alpha is not there instance created created beta {'alpha': <__main__.PrivateClass object at 0x0117CDD0>} ### we are always one behind in the dict content instance alpha called not so simple ======= Note that instance beta was never recognized when it called "apparently simple method". I'm sure there must be a way to do this.... Andr? From jack at performancedrivers.com Wed Jan 26 12:03:01 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 26 Jan 2005 12:03:01 -0500 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: <1a72l6umj80r6.dlg@usenet.alexanderweb.de> References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> Message-ID: <20050126170301.GJ1607@performancedrivers.com> On Wed, Jan 26, 2005 at 05:18:59PM +0100, Alexander Schremmer wrote: > On Tue, 25 Jan 2005 22:08:01 +0100, I wrote: > > >>>> sys.safecall(func, maxcycles=1000) > > could enter the safe mode and call the func. > > This might be even enhanced like this: > > >>> import sys > >>> sys.safecall(func, maxcycles=1000, > allowed_domains=['file-IO', 'net-IO', 'devices', 'gui'], > allowed_modules=['_sre']) > > Any comments about this from someone who already hacked CPython? Yes, this comes up every couple months and there is only one answer: This is the job of the OS. Java largely succeeds at doing sandboxy things because it was written that way from the ground up (to behave both like a program interpreter and an OS). Python the language was not, and the CPython interpreter definitely was not. Search groups.google.com for previous discussions of this on c.l.py -Jack From ialbert at mailblocks.com Wed Jan 12 09:16:08 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 12 Jan 2005 09:16:08 -0500 Subject: shutil.move has a mind of its own In-Reply-To: References: Message-ID: Daniel Bickett wrote: > In my script, rather than a file being moved to the desired location, > it is, rather, moved to the current working directory (in this case, > my desktop -- without any exceptions, mind you). As it happens, the what is the output generated by the lines: fdir, fname = randFileInfo.new() debugMess( "Generated file information: %s, %s" % ( fdir, fname ) ) Istvan. From bob.ducharme at gmail.com Fri Jan 21 13:37:18 2005 From: bob.ducharme at gmail.com (bobdc) Date: 21 Jan 2005 10:37:18 -0800 Subject: short programming projects for kids Message-ID: <1106332638.595750.150590@c13g2000cwb.googlegroups.com> I will be teaching an "Introduction to Programming" class to some middle school aged children and will be using Python, obviously. Does anyone have suggestions for simple little programs to create and analyze with them after I get past turtle graphics? Turtle graphics will be plenty for the first session, and I will leave time to ask them what they'd like to do in later sessions, but I was curious if anyone on the list has experience picking pedagogical programming examples appropriate for twelve-year-olds' attention spans. thanks, Bob From tjreedy at udel.edu Sun Jan 30 03:37:08 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Jan 2005 03:37:08 -0500 Subject: Test of comp.lang.python to python-list to gmane pathway. References: <1107040729.535936.42230@c13g2000cwb.googlegroups.com> Message-ID: Feel free to ignore this. Some system falsely labeled this post (sent via gmane) as possible spam. I am sending it back in the opposite direction to see what transpires that way. Sorry for the disturbance. tjr "Terry Reedy" wrote in message news:cthdth$fp0$1 at sea.gmane.org... > > "Michael Tobis" wrote in message > news:1107040729.535936.42230 at c13g2000cwb.googlegroups.com... > >> I'd like to dynamically add a method to an instance at >> instantiation time. > > No can do. A method is function that is an attribute of a class, even if > accessed via an instance. A function added to an instance as an > attribute of the instance remains a function. It is instance-specific > data that methods and other code can use, just like other instance data, > for instance-specific effects. Two common examples: > > class composer: > # skip obvious init > def __call__(self, x): return self.outer(self.inner(x)) > > sincos = composer(math.sin, math.cos) > # yes, this can also be done with composer function with nested scope > > class memoizer: # posted several times > # skip init again > def __call__(self,x): > # return previously computed self.memodict[x] if it exists > # or calculate, store, and return self.func(x) > > \> PS - any idea how to get past google's stupid formatting these days? I >> thought they were supposed to like python, but they just ignore leading >> blanks. > > Don't use google to post on clp. Go to news.gmane.org instead. > > Terry J. Reedy > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From g.horvath at mx.at Tue Jan 4 14:40:25 2005 From: g.horvath at mx.at (Gregor Horvath) Date: Tue, 04 Jan 2005 19:40:25 GMT Subject: HTML table input data grid Message-ID: Hi, I googled for a possibilty to create a html table where the user can input data. I just found this site: http://www.codeproject.com/aspnet/I3HTree2.asp That is what I am looking for. Is there an existing solution for python? -- Greg From steve at holdenweb.com Mon Jan 17 07:21:16 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 07:21:16 -0500 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Antoon Pardon wrote: > Op 2005-01-17, Steve Holden schreef : > >>Antoon Pardon wrote: >>[...] >> >>>>"A foolish consistency is the hobgoblin of little minds". Rules are made >>>>to be broken. >>> >>> >>>Like only use immutables as dictionary keys. >>> >> >>Fair enough, but don;t go advising newbies to do this. > > > How about something like this. > > Because of the extra precautions one has to take when > using mutables as hash keys, we advise newbies > to stick with immutable keys until they have gathered > enough knowledge and experience to adequatly weight > the pro and cons of a mutable key solution against > an immutable key solution. > There you go with the minutiae again. How about: "Don't use mutables as hash keys"? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From jcribbs at twmi.rr.com Sun Jan 30 18:06:49 2005 From: jcribbs at twmi.rr.com (Jamey Cribbs) Date: Sun, 30 Jan 2005 23:06:49 GMT Subject: ANNOUNCE: KirbyBase 1.7 In-Reply-To: <7xy8ea1qgt.fsf@ruckus.brouhaha.com> References: <7xy8ea1qgt.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > That's cute, especially the part about using Python expressions > instead of SQL to express queries. I don't see anything in the info > page about what happens when you have multiple clients updating the db > concurrently. Do you make any attempt to handle that? Yep. There are two server scripts included with the distribution. One (kbsimpleserver.py) does serial, blocking requests, so there are no concurrent-access issues. The second server script (kbthreadedserver.py) is threaded and non-blocking. I have code in the script that manages read and write locks for each table. I'm no rocket scientist, but I have been using kbthreadedserver.py at work for several months with no issues so far, so I am beginning to trust the code. :) Jamey From fredrik at pythonware.com Fri Jan 28 08:29:34 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 28 Jan 2005 14:29:34 +0100 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com><1106911061.429966.303510@f14g2000cwb.googlegroups.com><7x3bwlsqnj.fsf@ruckus.brouhaha.com> Message-ID: Duncan Booth wrote: > I think its a bit borderline whether this really was a security bug in > Python rather than just a problem with the way some people used Python. It > was a standard library which if used in the wrong way opens a security hole > on your machine for SmartCookie, that should be "if used, opens a security hole" From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 14:32:59 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?UTF-8?B?TWFydGluIE1PS1JFSsWg?=) Date: Mon, 10 Jan 2005 20:32:59 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <1f7befae050110111239496b07@mail.gmail.com> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> Message-ID: <41E2D86B.5080909@ribosome.natur.cuni.cz> Tim Peters wrote: > [Martin MOKREJ?] > >> just imagine, you want to compare how many words are in English, German, >>Czech, Polish disctionary. You collect words from every language and record >>them in dict or Set, as you wish. > > > Call the set of all English words E; G, C, and P similarly. > > >> Once you have those Set's or dict's for those 4 languages, you ask >>for common words > > > This Python expression then gives the set of words common to all 4: > > E & G & C & P > > >>and for those unique to Polish. > > > P - E - G - C > > is a reasonably efficient way to compute that. Nice, is it equivalent to common / unique methods of Sets? > > >>I have no estimates >>of real-world numbers, but we might be in range of 1E6 or 1E8? >>I believe in any case, huge. > > > No matter how large, it's utterly tiny compared to the number of > character strings that *aren't* words in any of these languages. > English has a lot of words, but nobody estimates it at over 2 million > (including scientific jargon, like names for chemical compounds): > > http://www.worldwidewords.org/articles/howmany.htm As I've said, I analyze in real something else then languages. However, it can be described with the example of words in different languages. But nevertheless, imagine 1E6 words of size 15. That's maybe 1.5GB of raw data. Will sets be appropriate you think? >>My concern is actually purely scientific, not really related to analysis >>of these 4 languages, but I believe it describes my intent quite well. >> >> I wanted to be able to get a list of words NOT found in say Polish, >>and therefore wanted to have a list of all, theoretically existing words. >>In principle, I can drop this idea of having ideal, theoretical lexicon. >>But have to store those real-world dictionaries anyway to hard drive. > > > Real-word dictionaries shouldn't be a problem. I recommend you store > each as a plain text file, one word per line. Then, e.g., to convert > that into a set of words, do > > f = open('EnglishWords.txt') > set_of_English_words = set(f) I'm aware I can't keep set_of_English_words in memory. > f.close() M. From jeff at ccvcorp.com Mon Jan 17 19:50:21 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 17 Jan 2005 16:50:21 -0800 Subject: Fuzzy matching of postal addresses In-Reply-To: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <10uon0ir3n6b7ac@corp.supernews.com> Andrew McLean wrote: > The problem is looking for good matches. I currently normalise the > addresses to ignore some irrelevant issues like case and punctuation, > but there are other issues. I'd do a bit more extensive normalization. First, strip off the city through postal code (e.g. 'Beaminster, Dorset, DT8 3SS' in your examples). In the remaining string, remove any punctuation and words like "the", "flat", etc. > Here are just some examples where the software didn't declare a match: And how they'd look after the transformation I suggest above: > 1 Brantwood, BEAMINSTER, DORSET, DT8 3SS > THE BEECHES 1, BRANTWOOD, BEAMINSTER, DORSET DT8 3SS 1 Brantwood BEECHES 1 BRANTWOOD > Flat 2, Bethany House, Broadwindsor Road, BEAMINSTER, DORSET, DT8 3PP > 2, BETHANY HOUSE, BEAMINSTER, DORSET DT8 3PP 2 Bethany House Broadwindsor Road 2 BETHANY HOUSE > Penthouse,Old Vicarage, 1 Clay Lane, BEAMINSTER, DORSET, DT8 3BU > PENTHOUSE FLAT THE OLD VICARAGE 1, CLAY LANE, BEAMINSTER, DORSET DT8 3BU Penthouse Old Vicarage 1 Clay Lane PENTHOUSE OLD VICARAGE 1 CLAY LANE > St John's Presbytery, Shortmoor, BEAMINSTER, DORSET, DT8 3EL > THE PRESBYTERY, SHORTMOOR, BEAMINSTER, DORSET DT8 3EL St Johns Presbytery Shortmoor PRESBYTERY SHORTMOOR > The Pinnacles, White Sheet Hill, BEAMINSTER, DORSET, DT8 3SF > PINNACLES, WHITESHEET HILL, BEAMINSTER, DORSET DT8 3SF Pinnacles White Sheet Hill PINNACLES WHITESHEET HILL Obviously, this is not perfect, but it's closer. At this point, you could perhaps say that if either string is a substring of the other, you have a match. That should work with all of these examples except the last one. You could either do this munging for all address lookups, or you could do it only for those that don't find a match in the simplistic way. Either way, you can store the Database B's pre-munged address so that you don't need to constantly recompute those. I can't say for certain how this will perform in the false positives department, but I'd expect that it wouldn't be too bad. For a more-detailed matching, you might look into finding an algorithm to determine the "distance" between two strings and using that to score possible matches. Jeff Shannon Technician/Programmer Credit International From claird at lairds.us Thu Jan 6 18:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 06 Jan 2005 23:08:03 GMT Subject: Excluded and other middles in licensing (was: The Industry choice) References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> Message-ID: <75r0b2-ohg.ln1@lairds.us> In article <1gpz9qx.vmv8hav17z8qN%aleaxit at yahoo.com>, Alex Martelli wrote: . . . >One last reflection -- I believe there are or used to be some programs >written by people no doubt of very good will, distributed with all >sources and often with no profit motive at all, which are NOT open >source because they include in the license some restrictive clause, such >as "no military use", "no use by organizations which perform testing of >cosmetics on animals", or something of that kind. These would be >examples of closed-source software which DO allow ALMOST any kind of use >-- any EXCEPT the specific one the authors dislike so intensely. > >While most people may not think of such programs as "closed source", >they most definitely ARE: the definition of open source is very strict >about this aspect. > > >Alex With my mathematical background, I'm consistent about calling these "non-open" rather than "closed". I don't insist others adopt my nomenclature ... From ncoghlan at iinet.net.au Thu Jan 27 05:31:20 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 27 Jan 2005 20:31:20 +1000 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <41F8C2F8.8060203@iinet.net.au> Davor wrote: > data structures > and > functions that operate on these data structures Eh? What do you think a class is? Py> data = range(10) Py> list.extend(data, range(5)) Py> list.sort(data) Py> print data [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9] The fact that data.extend(range(5)) and data.sort() are alternative spellings for the second and third lines doesn't change the fact that a class is just a data structure grouped with a bunch of functions that operate on that data structure. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From grante at visi.com Mon Jan 17 14:50:13 2005 From: grante at visi.com (Grant Edwards) Date: 17 Jan 2005 19:50:13 GMT Subject: List problems in C code ported to Python References: <41ebed38$0$87063$a1866201@visi.com> <1105981814.317402.192940@f14g2000cwb.googlegroups.com> Message-ID: <41ec16f5$0$87076$a1866201@visi.com> On 2005-01-17, wittempj at hotmail.com wrote: >>>> l = [] >>>> for i in range(2): > for j in range(2): > l[i][j] = 'x' > > > > Traceback (most recent call last): > File "", line 3, in -toplevel- > l[i][j] = 'x' > IndexError: list index out of range > > So you still have to dimension the list before you can use it , eg like >>l = [] >>for i in range(2): >> l.append([]) >> for j in range(2): >> l[i].append(j) > > then you do not get the indexerror, but I feel a class is what you need > here to make life easier and the program more readable I'd probably numeric python (which I beleive is depricated, but it's what I have installed) or numarray. I think either would make it a lot easier. Using lists of lists when what you want is a matrix can be made to work, but there are a lot of non-obvious traps to fall into. -- Grant Edwards grante Yow! I always wanted a at NOSE JOB!! visi.com From aleaxit at yahoo.com Thu Jan 6 13:55:10 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 6 Jan 2005 19:55:10 +0100 Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> Message-ID: <1gpzgcv.1a4vagsqm9b69N%aleaxit@yahoo.com> Peter Hansen wrote: > Jacek Generowicz wrote: > > Peter Hansen writes: > >>Why the heck would I ever have to do "rectangle operations" on a > >>regular basis? ;-) > > > > Well, given that all editors are cat equivalent[*], you don't _have_ > > to use any of their features :-) > > This "cat equivalent" thing is a red-herring. I can rarely type more I tried offering a red herring to my cat to check this out, and, sure enough, she indignantly refused it and miaowed loudly for less smelly food. So, you may have a point here. Alex From mwm at mired.org Mon Jan 3 17:38:42 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 03 Jan 2005 16:38:42 -0600 Subject: Continuations Based Web Framework - Seaside. References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <7aTBd.11928$H%6.521997@twister1.libero.it> Message-ID: <861xd2qgst.fsf@guru.mired.org> Steve Holden writes: > It's the *ideas* that are important, though, rather than the > implementation, and my initial hope was to publicise the weakness of > statelessness on the web as applications become more complex. This needed publicity? Isn't it obvious to anyone who has ever written a non-trival web application? Enough so that people started referring to non-web applications as "stately" rather than "stateful". http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From martyn_quick at yahoo.co.uk Fri Jan 21 10:39:12 2005 From: martyn_quick at yahoo.co.uk (Martyn Quick) Date: 21 Jan 2005 07:39:12 -0800 Subject: Configuring Python for Tk on Mac Message-ID: On my desk here at work I have a Mac G4 running Mac OS X v10.2.8. When I go into a terminal and type "python" up comes a nice python interface and all seems great. However when I type "import Tkinter" I'm greeted by the following error. >>> import Tkinter Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 35, in ? import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter So I guess something about this implementation is not appropriately configured. I'm guessing this is the default behaviour since I don't think anyone did anything special about python when they set up my machine. What do I do to set it up so I can use Tkinter? Thanks... and sorry if this is an FAQ... but I couldn't find the info easily. Yours, Martyn From http Fri Jan 7 16:48:41 2005 From: http (Paul Rubin) Date: 07 Jan 2005 13:48:41 -0800 Subject: "A Fundamental Turn Toward Concurrency in Software" References: Message-ID: <7x4qhs52rq.fsf@ruckus.brouhaha.com> aurora writes: > Just gone though an article via Slashdot titled "The Free Lunch Is > Over: A Fundamental Turn Toward Concurrency in Software" > [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that > the continous CPU performance gain we've seen is finally over. And > that future gain would primary be in the area of software concurrency > taking advantage hyperthreading and multicore architectures. Well, another gain could be had in making the software less wasteful of cpu cycles. I'm a pretty experienced programmer by most people's standards but I see a lot of systems where I can't for the life of me figure out how they manage to be so slow. It might be caused by environmental pollutants emanating from Redmond. From jtr at ofb.net Fri Jan 21 16:52:59 2005 From: jtr at ofb.net (John Reese) Date: Fri, 21 Jan 2005 21:52:59 +0000 (UTC) Subject: Is there a library to parse Mozilla "mork" documents? References: <1rb1v0566bmkesg9mclsk28idkjopgofuc@4ax.com> Message-ID: On Thu, 20 Jan 2005 23:48:34 -0800, Tim Roberts wrote: > John Reese wrote: >> >>Mozilla, Firefox, Thunderbird, and so forth use this awful format >>called MORK to store all kinds of things: which messages you've read >>in a newsgroup, headers and indexes into the mbox file of messages in >>a mail folder, and address books. > > Yes. What a crock that is. The MORK format is a great way to compress > tabular information, IF the information consists of the same pieces of data > over and over. E-mail boxes do not fit into that class, so I have no doubt > that the typical Thunderbird MORK file is singificantly LARGER than the > same file would be in, say, INI format. > > I wrote a Python script to parse it, but it isn't terribly robust. I was > able to produce a dictionary, but I didn't do anything with the results. > You're welcome to take a look: > http://www.probo.com/timr/parsemsf.py Thanks, I'll work with this. I have to say that this has all been worth it just to read about Jamie Zawinski railing against this file format. I think your comment at the top sums it up well: # Why am I doing this? From tjreedy at udel.edu Thu Jan 13 15:08:16 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Jan 2005 15:08:16 -0500 Subject: lambda References: Message-ID: "Egor Bolonev" wrote in message news:opskje6vb7xejsk1 at theurs.octopusnet.lan... > why functions created with lambda forms cannot contain statements? Because lambda was only ever intended to be an inline abbreviation of simple one-use functions whose body consists of 'return '. It is clear to me that the word 'lambda' was a mistake since it engenders expectations of more than that from too many people, such as you. Terry J. Reedy From akineko at pacbell.net Fri Jan 14 01:00:10 2005 From: akineko at pacbell.net (Aki Niimura) Date: 13 Jan 2005 22:00:10 -0800 Subject: Pickled text file causing ValueError (dos/unix issue) Message-ID: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> Hello everyone, I started to use pickle to store the latest user settings for the tool I wrote. It writes out a pickled text file when it terminates and it restores the settings when it starts. It worked very nicely. However, I got a ValueError when I started the tool from Unix when I previously used the tool from Windows. File "/usr/local/lib/python2.3/pickle.py", line 980, in load_string raise ValueError, "insecure string pickle" ValueError: insecure string pickle If I do 'dos2unix ' to convert the file, then everything becomes fine. I found in the Python release note saying ... "pickle: Now raises ValueError when an invalid pickle that contains a non-string repr where a string repr was expected. This behavior matches cPickle." I guess DOS text format is creating this problem. My question is "Is there any elegant way to deal with this?". I certainly can catch ValueError and run 'dos2unix' explicitly. But I don't like such crude solution. Any suggestions would be highly appreciated. Best regards, Aki Niimura From duncan.booth at invalid.invalid Thu Jan 6 11:30:20 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 Jan 2005 16:30:20 GMT Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> <87pt0iegga.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: Nick Vargish wrote: > eeykay at gmail.com writes: > >> Can somebody there to point me any good commercial applications >> developed using python ? > > Python is used in several games, including Temple of Elemental Evil > and the forthcoming Civilization 4. Humungous Games, which makes > software for children, is also using Python. Sorry if games would give > your boss the wrong impression... Also "Startrek Bridge Commander", and "Uru: Ages beyond Myst". From amk at amk.ca Fri Jan 21 14:20:03 2005 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 21 Jan 2005 13:20:03 -0600 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> Message-ID: On Fri, 21 Jan 2005 18:54:50 +0100, Fredrik Lundh wrote: > judging from http://yaml.org/spec/current.html (750k), the YAML designers are > clearly insane. that's the most absurd software specification I've ever seen. they > need help, not users. IMHO that's a bit extreme. Specifications are written to be detailed, so consequently they're torture to read. Seen the ReStructured Text spec lately? The basic idea -- a data dumping format that's human-readable -- isn't a bad one. OTOH, I can't recall wanting such a thing -- when I want readable output I'm happy using unreadable pickle files, unpickling the object and calling a .dump() or .as_text() method.) But YAML seems to have started out with the goal of being human-writable, something you would write in Emacs, and that seems to have gotten lost; the format is now just as complicated as Restructured Text, but more cryptic (the URI namespacing for tags, for example), not really simpler than XML and in some ways weaker (e.g. only two encodings supported, more complicated escaping rules). For a pure Python application, I can't see a need for YAML; use pickle/cPickle instead, because they're already there. Exchanging serialized objects between Python/Perl/Ruby scripts might be a good use case for YAML, but XML has wider software support and S-expressions are simpler, so my inclination would be to use them instead of YAML. --amk From elephantum at dezcom.mephi.ru Sat Jan 8 06:43:36 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sat, 08 Jan 2005 14:43:36 +0300 Subject: python3: 'where' keyword In-Reply-To: <41dfc018.305122743@news.oz.net> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> Message-ID: <349vb9F45c9crU1@individual.net> Bengt Richter wrote: >>>It also allows the necessary but uninteresting setup for an expression >>>to be moved "out of the way", bringing the expression that does the real >>>work to prominence. >>Killer app for this keyword: >> >>class C(object): >> >> x = property(get, set) where: >> def get(self): >> return "Silly property" >> def set(self, val): >> self.x = "Told you it was silly" > Yes, that is cool and it _is_ an interesting idea. Are suites nestable? E.g., is this legal? ... > And, is the whole thing after the '=' an expression? E.g., > > x = ( foo(x) where: > x = math.pi/4.0 > ) where: > def foo(x): print 'just for illustration', x > > or is this legal? > > for y in ([foo(x) for x in bar] where: > bar = xrange(5) > ): baz(y) where: > def baz(arg): return arg*2 > > Not trying to sabotage the idea, really, just looking for clarification ;-) yes, all your examples are correct. And that's the way I'd like to use this feature. From lard at tardis.ed.ac.molar.uk Wed Jan 26 10:35:59 2005 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Wed, 26 Jan 2005 15:35:59 GMT Subject: cookielib and urllib2: thread-safe? Message-ID: I'm writing a test script in python for pulling web pages from a web server using urllib2 and cookielib. Since the main thing I am testing is what happens when concurrent requests are made to the web server, I need to make several requests concurrently, which I'll do from different threads in my python script. So the important question is: are cookielib and urllib2 thread safe? Are there any precautions that apply to using these libs in a multi-threaded context? thanks! alex From lkirsh at cs.ubc.ca Thu Jan 20 04:28:34 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Thu, 20 Jan 2005 01:28:34 -0800 Subject: why are these not the same? Message-ID: On a webpage (see link below) I read that the following 2 forms are not the same and that the second should be avoided. They look the same to me. What's the difference? Lowell ---- def functionF(argString="abc", argList = None): if argList is None: argList = [] ... def functionF(argString="abc", argList=None): argList = argList or [] ... http://www.ferg.org/projects/python_gotchas.html (number 5) From fperez.net at gmail.com Mon Jan 31 02:22:19 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Mon, 31 Jan 2005 00:22:19 -0700 Subject: Image stats - going from Matlab to Python References: <1107153660.431217.145160@f14g2000cwb.googlegroups.com> Message-ID: tjv at hotmail.com wrote: > Hi all, > I am working with images in python using PIL. I come from a MATLAB > background so I am finding it to be sometimes frustrating to do things > correctly and quickly. All I need to do is load an image and store a > list of pixel coordinates at which the alpha channel is set to 1. > In Matlab this would be easy...Lets say we have a 2x2x4 array that > represents the image. I would just type something like: > > indices = find(im(:,:,3)==1); > > then work with indices to get xy coords. Is there a similar way to > accomplish the same thing in python and PIL without having a nested for > loop and checking every pixel? > I would appreciate advice. Thanks very much for your attention! The kind of array functionality which you have in mind is implemented in python by the Numeric/Numarray libraries. You can (and should) use the PIL for the more image-specific tasks, but basic array things are done via those others. You may also want to look at matplotlib, for a high level, matlab-compatible plotting library. Regards, f From http Tue Jan 11 13:49:43 2005 From: http (Paul Rubin) Date: 11 Jan 2005 10:49:43 -0800 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <34h7m9F43vomsU1@individual.net> <7xsm58lcms.fsf@ruckus.brouhaha.com> Message-ID: <7xu0pn4x88.fsf@ruckus.brouhaha.com> Robin Becker writes: > A few months ago I tried and failed to get squirrelmail/php to run > with Apache2 and freeBSD 4.9. It seems that php prefers the old style > apache 1.3 work flow. I got some help from the php guys, but not > enough. I suppose I could have run a separate apache13 server, but > that seems like a cop out to me. We don't want to maintain an extra > set of configs etc etc. I think mod_php doesn't play nice with apache2 but am not aware of any cgi interoperability problems. I ran squirrelmail/php as an apache 1.3 cgi a while back (low enough traffic to not get killed by cgi overhead), if that helps. Note that squirrelmail itself has a bunch of security bugs that the maintainers refuse to acknowledge as bugs. Anyway, I'm still using apache 1.3 (haven't had a reason to modernize) so I can run mod_php if I need to. > Mailman, moinmoin and others work fine with apache2 maybe because they > use a cgi style interface. I would stick with a pythonic solution > unless there's a good reason not too. Yes, I certainly prefer Python to PHP. From jerf at jerf.org Fri Jan 21 18:07:24 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 21 Jan 2005 18:07:24 -0500 Subject: finding name of instances created References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> Message-ID: On Fri, 21 Jan 2005 21:01:00 -0400, Andr? Roberge wrote: > etc. Since I want the user to learn Python's syntax, I don't want to > require him/her to write > alex = CreateRobot(name = 'alex') > to then be able to do > alex.move() This is just my opinion, but I've been involved with teaching new programmers before so I think it is an informed one. I don't think you teach a language by hiding how the language works, no matter what the intentions. You should be *minimizing* the magic. You're going to train your students that Python objects have names (they don't) and that's going to mess them up later. Actually, it's going to mess them up almost right away, because how can they have a list of robots like this: for robot in robots: robot.turn_left() That can't work, right, the command inside the loop can only affect the robot named "robot", right? You can't teach Python if what you're actually teaching them is a variant that you have created that is used nowhere else on Earth, and is internally inconsistent to boot (see loop above, the *real* Python variable semantics conflict with the semantics you are teaching). Considering that not a month goes by where someone doesn't post a question related to this, and it has been a FAQ entry for as long as I've used Python, I think you are doing a major disservice to your "users" by training them that objects magically gets the name when assigned. I strongly urge you to do absolutely no pre-processing of any kind to the programs they generate. (By which I mean changes to the code; running pychecker on it would be OK; and I'd urge you to resist the temptation to process its output, either. Provide a "translation table" if you need to, but they need to learn to read the real output, too.) Programming is hard enough with burdening people with "pleasant falsehoods". Trust your students to handle the truth (and of course rationally minimize the truth they have to handle, and by using Python you're off to a great start there). If they can't handle the truth, with time, effort, and support, they *sure* as hell can't handle lies! From roy at panix.com Fri Jan 7 23:59:07 2005 From: roy at panix.com (Roy Smith) Date: Fri, 07 Jan 2005 23:59:07 -0500 Subject: Getting rid of "self." References: Message-ID: Jeremy Bowers wrote: > were I programming in C++ routinely now I'd prefix "this" and > dispense with that ugly "m_" garbage. (One of the things I ***hate*** > about C++ culture is its acceptance of hideously ugly variable names, > but now I'm two parentheticals deep so I probably ought to stop.)) I'm currently working in a C++ system where they have a wrapper class that provides some transaction locking functionality for member access. The colloquial name for the wrapped "this" pointer is self, i.e. they do "self = wrapper (this)" at the beginning of functions that need it. You can then do "member" to get the bare access or "self.member" to get the locking functionality. It's actually kind of neat, but boy does it play headgames with me when I switch back and forth between that and Python. From jeff at ccvcorp.com Mon Jan 10 12:53:13 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 10 Jan 2005 09:53:13 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> Message-ID: <10u5fu3o7v4h9e3@corp.supernews.com> Jacek Generowicz wrote: > "Anna" writes: > >>But first, wouldn't something like: >> >>[x+1 for x in seq] >> >>be even clearer? > > I'm glad you mentioned that. [...] > > As to whether it is clearer. That depends. I would venture to suggest > that, given a pool of laboratory rats with no previous exposure to > Python, more of them would understand the map-lambda than the list > comprehension. I would venture to suggest the exact opposite, that the syntax of a list comprehension is in itself suggestive of its meaning, while 'map' and 'lambda' are opaque until you've researched them. The verb 'to map', in this mathematical sense, is not part of standard usage among anyone that *I* know. Instead, they'd speak of doing something for (or to) each item in a group -- exactly what list comps express. Speaking for *this* laboratory rat, at least, map/lambda was always a nasty puzzle for me and difficult to sort out. But when list comps were introduced, after reading just a sentence or two on how they worked, they were completely clear and understandable -- much more so than map/lambda after many months of exposure. Jeff Shannon Technician/Programmer Credit International From vincent at visualtrans.de Tue Jan 25 14:32:11 2005 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 25 Jan 2005 20:32:11 +0100 Subject: module for 'po' files In-Reply-To: References: Message-ID: Sara Fwd wrote: > Hi all > Is there a module for processing & handling '.po' > files in python? Don't know exactly what you mean by "processing & handling". What do you want to do? -- Vincent Wehren > > > > __________________________________ > Do you Yahoo!? > Read only the mail you want - Yahoo! Mail SpamGuard. > http://promotions.yahoo.com/new_mail From http Tue Jan 4 20:12:04 2005 From: http (Paul Rubin) Date: 04 Jan 2005 17:12:04 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> Message-ID: <7x652che6z.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > Start writing (or reorganizing). Folks, this is open source. I'm > sure by the traffic on the list most people here know how to write. Irrelevant, the issue isn't what docs can be written if someone wants to do it, it's what docs are actually already there. I mean every shortcoming anyone could raise about Python or anything else could have the same answer, "it's open source, go fix it". The question is what does the existing stuff do. > In the case of Tkinter, you should probably get the okay of the > authors of various external docs before incorporating them into the > Python docs, If such permission is available then the external docs should just be dropped into the distro. > but note that several Tkinter-related documents are referenced > directly from the Tkinter module docs: Irrelevant, the Python docs mean the ones that are included, not the ones that are merely referenced. > This being the Internet and all, it's not clear that referencing external > documentation is somehow worse than incorporating it directly into the > distribution. The same thing could be said for software. So why not eliminate the Python library and let everyone download each module separately? Because it's bogus is why. It really does matter whether something is included or just referenced. That's what "batteries included" is supposed to be about--you get ONE package and it's supposed to have everything you need without having to go forage for additional components. It matters because most users shouldn't need to care about the Python distro at all, since they got Python through its inclusion in some bigger distro. E.g., I'm now running the Python that was included in Fedora Core 3 GNU/Linux, a complete OS distro on a DVD-ROM, containing about 3 gigabytes not including sources. And when a user installs 3 gigabytes of software from a DVD, they can reasonably expect that they've installed a complete system and shouldn't need to download anything additional to use all the features of the programs on the DVD. Now the Fedora maintainers aren't Python gurus--people ask for Python so they did the obvious thing: downloaded it, ran its installer, put the output into their distro, and said "ok, Fedora has Python". That's all they should need to do to incorporate Python into Fedora. So it's up to the Python maintainers, not the Fedora maintainers or the user, to make sure that the Python distro has everything that users need, without further downloading. And that was just about Tkinter, for which good docs exist but just don't happen to be in the distro. How about something like SocketServer, for which no reasonable docs exist at all? There's no way to figure out how to use it without reading the source. Or the socket library, whose docs say to go buy a book by W. Richard Stevens. The book is very good, but having to go buy a proprietary book is the opposite of what self-contained free software documentation is supposed to mean. I'm not trying to bash Python, which is excellent in many ways, or I wouldn't be using it. I just see various other free software projects as trying to live up to higher standards and I think Python should aspire to the same thing. > As for stuff that exists in PEPs and release notes, they should > already all have the necessary copyright (either they were placed in > the public domain or they are already part of the Python > distribution) to allow you do just check out a CVS tree, make the > necessary edits and either check the files back in or submit a patch > to SourceForge. And about that full featured Python web browser and native-code Python compiler, all you have to do is go write it. Come on. Having to piece together info from a dozen obscure and inconsistent PEP's and stuff in the CVS tree and source comments is not what most people think of as "documentation". Documentation means I can look in the manual and the info is right there, properly referenced in the table of contents and in the proper section for that type of language feature, unified with the rest of the docs. > In the documentation arena, I think more thought should probably be > given to producing online docs that can be directly annotated, thus > further reducing the barrier to more complete documentation (and > more updates). Take a look at latex2html, propose or implement > changes, or just rewrite the damn thing in Python. I think > latex2html is probably a recurring nightmare for Fred Drake. I've personally been happy with Texinfo for other kinds of docs and would consider it easier to deal with than latex2html. It might even be feasible to edit it in a wiki, so anyone could improve it easily. Another idea is web-based doc comments like PHP and MySQL have, so the doc editors can incorporate the info from the comments in subsequent doc releases. From deetsNOSPAM at web.de Mon Jan 3 08:10:15 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 03 Jan 2005 14:10:15 +0100 Subject: Async-signal safe functions in signal handlers (unix) References: <6942fc70.0501030347.29253110@posting.google.com> Message-ID: > So, is there a) any mechanism inside Python that can detect if the > current code is executed in a signal handler, or b) a list of > statements that must not be used in a Python signal handler in order > to avoid glibc function calls that are not async-signal safe? The execution of signal handlers in python is not done really asynchronous - instead, an incoming signal is noticed and flagged to the interpreters byte code loop - so the signal gets dealed with when the current bytecode instruction is termintated. Read section 7.1 in the docs about the signal module. In other words: Don't worry, be happy. -- Regards, Diez B. Roggisch From luismgz at gmail.com Mon Jan 10 10:49:53 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 10 Jan 2005 07:49:53 -0800 Subject: else condition in list comprehension In-Reply-To: References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> <1105305000.052714.188980@c13g2000cwb.googlegroups.com> Message-ID: <1105372193.185270.279290@c13g2000cwb.googlegroups.com> It's me wrote: > > z = [i + (2, -2)[i % 2] for i in range(10)] > > But then why would you want to use such feature? Wouldn't that make the > code much harder to understand then simply: > > z=[] > for i in range(10): > if i%2: > z.append(i-2) > else: > z.append(i+2) > > Or are we trying to write a book on "Puzzles in Python"? Once you get used to list comprehensions (and it doesn't take long), they are a more concise and compact way to express these operations. I think that writing 6 lines instead of 1 could be more readable of you are a beginner, but after playing a little bit with listcomps for the first time, you'll see they are very practical yet readable. From news at NOwillmcguganSPAM.com Wed Jan 26 11:25:43 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Wed, 26 Jan 2005 16:25:43 +0000 Subject: Help With Python In-Reply-To: <41f7c3a7$0$7777$db0fefd9@news.zen.co.uk> References: <41f7c3a7$0$7777$db0fefd9@news.zen.co.uk> Message-ID: <41f7c487$0$7777$db0fefd9@news.zen.co.uk> > > >>> print "Spam, " * 510 + "Spam" Or if you have 2.4.. >>> print ", ".join( "Spam" for _ in xrange( 511 ) ) Although, the replys with links will ultimately be more helpful! Will McGugan From deetsNOSPAM at web.de Mon Jan 24 16:33:27 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 24 Jan 2005 22:33:27 +0100 Subject: add indexes on the fly to lists References: Message-ID: The data structure you want to use is a dictionary - known as hashmap or hash or map in other languages. Lets say you have a few objects of type town that you want to access using their zip, then things could look like this: ------------ class Town(object): def __init__(self, zip, cool_clubs): self.zip = zip self.colo_clubs = cool_clubs towns = [Berlin(10439, ["Marietta", "ICON", "Bastart"]), Cologne(50000, ["Subway", "Stadtgarten", "Geb?ude 9"])] index = {} for town in towns: index[town.zip] = town ---------------- Hope that makes it clear to you - look into the tutorial for a chapter about python data structures. -- Regards, Diez B. Roggisch From ncoghlan at iinet.net.au Sat Jan 8 00:10:06 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 15:10:06 +1000 Subject: sorting on keys in a list of dicts In-Reply-To: <10ttukogfl43p62@corp.supernews.com> References: <10tr9ejf05pv660@corp.supernews.com> <10ttukogfl43p62@corp.supernews.com> Message-ID: <41DF6B2E.3030700@iinet.net.au> Jeff Shannon wrote: > Agreed. I'd started typing before I realized that it'd provide a stable > sort, which pretty much answered my own question, but decided to send it > anyhow in case I'd missed anything else... :) And it turns out we both missed the fact that it avoids comparing the dictionaries which could save a *lot* of number crunching (as well as making otherwise unsortable lists sortable). So it's a good thing you did decide to send it :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From fuzzyman at gmail.com Tue Jan 25 11:02:47 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Jan 2005 08:02:47 -0800 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: <1106643765.733317.27440@f14g2000cwb.googlegroups.com> Message-ID: <1106668967.677864.36690@f14g2000cwb.googlegroups.com> Nick Coghlan wrote: > Fuzzyman wrote: > > An implementation of the core language semantics - without any modules > > or file operations would be dead useful. > > > > It could replace some of the function of the long dead rexec modules as > > well as support projects like this. > > Securing a custom build of the CPython interpreter would probably be > significantly easier than designing a 'secure mode' that ran on top of the > standard version. The former might even be a stepping stone towards the latter. > > Still not easy though (the main task would be to prevent Python code from > accessing the OS, while still allowing module imports to work). Pure python imports only... no C extensions. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml > > Cheers, > Nick. > > -- > Nick Coghlan | ncoghlan at email.com | Brisbane, Australia > --------------------------------------------------------------- > http://boredomandlaziness.skystorm.net From sjmachin at lexicon.net Tue Jan 11 15:26:48 2005 From: sjmachin at lexicon.net (John Machin) Date: 11 Jan 2005 12:26:48 -0800 Subject: unicode mystery In-Reply-To: References: Message-ID: <1105475208.187957.282650@c13g2000cwb.googlegroups.com> Sean McIlroy wrote: > I recently found out that unicode("\347", "iso-8859-1") is the > lowercase c-with-cedilla, so I set out to round up the unicode numbers > of the extra characters you need for French, and I found them all just > fine EXCEPT for the o-e ligature (oeuvre, etc). I examined the unicode > characters from 0 to 900 without finding it; then I looked at > www.unicode.org but the numbers I got there (0152 and 0153) didn't > work. Can anybody put a help on me wrt this? (Do I need to give a > different value for the second parameter, maybe?) Characters that are in iso-8859-1 are mapped directly into Unicode. That is, the first 256 characters of Unicode are identical to iso-8859-1. Consider this: >>> c_cedilla = unicode("\347", "iso-8859-1") >>> c_cedilla u'\xe7' >>> ord(c_cedilla) 231 >>> ord("\347") 231 What you did with c_cedilla "worked" because it was effectively doing nothing. However if you do unicode(char, encoding) where char is not in encoding, it won't "work". As John Lenton has pointed out, if you find a character in the Unicode tables, you can just use it directly. There is no need in this circumstance to use unicode(). HTH, John From john at grulic.org.ar Sat Jan 15 00:11:58 2005 From: john at grulic.org.ar (John Lenton) Date: Sat, 15 Jan 2005 02:11:58 -0300 Subject: finding/replacing a long binary pattern in a .bin file In-Reply-To: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> Message-ID: <20050115051158.GA12018@grulic.org.ar> On Wed, Jan 12, 2005 at 10:36:54PM -0800, yaipa wrote: > What would be the common sense way of finding a binary pattern in a > .bin file, say some 200 bytes, and replacing it with an updated pattern > of the same length at the same offset? > > Also, the pattern can occur on any byte boundary in the file, so > chunking through the code at 16 bytes a frame maybe a problem. The > file itself isn't so large, maybe 32 kbytes is all and the need for > speed is not so great, but the need for accuracy in the > search/replacement is very important. ok, after having read the answers, I feel I must, once again, bring mmap into the discussion. It's not that I'm any kind of mmap expert, that I twirl mmaps for a living; in fact I barely have cause to use it in my work, but give me a break! this is the kind of thing mmap *shines* at! Let's say m is your mmap handle, a is the pattern you want to find, b is the pattern you want to replace, and n is the size of both a and b. You do this: p = m.find(a) m[p:p+n] = b and that is *it*. Ok, so getting m to be a mmap handle takes more work than open() (*) A *lot* more work, in fact, so maybe you're justified in not using it; some people can't afford the extra s = os.stat(fn).st_size m = mmap.mmap(f.fileno(), s) and now I'm all out of single-letter variables. *) why isn't mmap easier to use? I've never used it with something other than the file size as its second argument, and with its access argument in sync with open()'s second arg. -- John Lenton (john at grulic.org.ar) -- Random fortune: If the aborigine drafted an IQ test, all of Western civilization would presumably flunk it. -- Stanley Garn -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From peter at engcorp.com Sat Jan 29 23:12:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 29 Jan 2005 23:12:05 -0500 Subject: cx_freeze error In-Reply-To: <1107057808.297752.168780@z14g2000cwz.googlegroups.com> References: <1107048210.548048.152870@z14g2000cwz.googlegroups.com> <1107054796.999110.18380@c13g2000cwb.googlegroups.com> <1107057808.297752.168780@z14g2000cwz.googlegroups.com> Message-ID: <1Lqdnd44o_AOw2HcRVn-og@powergate.ca> zyqnews at 163.net wrote: > Thanks for your answer. > I tried it and the result is: > [cxfreeze]$ python > Python 2.2.3 (#1, Oct 15 2003, 23:33:35) > [GCC 3.3.1 20030930 (Red Hat Linux 3.3.1-6)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import re >>>>re.compile > > > >>>>re.__file__ > > '/usr/lib/python2.2/re.pyc' > > Is there any hint? "Hint", maybe. Clear answer, not for me. What it means is that your re module definitely has a "compile" function, as it is supposed to. What that suggests is that when the textwrap.py module is being imported by cx_freeze, it is not finding the correct "re" module when it imports it. I don't know anything about cx_freeze, and I don't have an appropriately configured Linux box to help troubleshoot, so I can't help further, but maybe somebody else could try compiling a simple "hello.py" like you did and offer some suggestions. -Peter From steven.bethard at gmail.com Fri Jan 21 19:30:08 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 17:30:08 -0700 Subject: default value in a list In-Reply-To: References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: Paul McGuire wrote: > expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen] Or if you're afraid of lambda like me: def expand(lst,default,minlen):return (lst + [default]*minlen)[0:minlen] or perhaps more readably: def expand(lst, default, minlen): return (lst + [default]*minlen)[0:minlen] No need for an anonymous function when you're naming it. ;) Steve From rschroev_nospam_ml at fastmail.fm Fri Jan 14 11:27:44 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 14 Jan 2005 16:27:44 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: <4qSFd.30758$Qv5.2842746@phobos.telenet-ops.be> Skip Montanaro wrote: > Fredrik> no, expressions CAN BE USED as statements. that doesn't mean > Fredrik> that they ARE statements, unless you're applying belgian logic. > > Hmmm... I'd never heard the term "belgian logic" before. Googling provided > a few uses, but no formal definition (maybe it's a European phrase so > searching for it in English is futile). I'm from Belgium, and I've never heard it before either. Probably a public secret, very carefully being kept hidden from us Belgians ;) -- "Codito ergo sum" Roel Schroeven From adonisv at DELETETHISTEXTearthlink.net Tue Jan 11 19:57:41 2005 From: adonisv at DELETETHISTEXTearthlink.net (Adonis) Date: Wed, 12 Jan 2005 00:57:41 GMT Subject: Newbie: Pythonwin In-Reply-To: References: Message-ID: <9C_Ed.4799$C52.960@newsread2.news.atl.earthlink.net> Brent W. Hughes wrote: > 1) I'm running a program within Pythonwin. It's taking too long and I want > to stop/kill it. What do I do (other than ctrl-alt-del)? > > 2) I'm running a long program and I want to minimize it to let it continue > to run in the background while I do something else in the foreground. I try > clicking on Pythonwin's minimize box but it doesn't respond until the Python > program finally quits Then it minimizes! Any way I can do what I want > here? > > Brent > > Try running your script using (from command prompt): \path\python.exe \path\script.py Alternatively go to its folder in explorer and double click it to run. pythonwin is just a developing enviroment, and the execution of scripts within it is just for debugging use. Hope this helps. Adonis From __peter__ at web.de Thu Jan 13 07:42:42 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 13 Jan 2005 13:42:42 +0100 Subject: from __future__ import decorators References: Message-ID: Jacek Generowicz wrote: > I have some code, which makes copious use of the @decorator syntax > which was introduced in Python2.4. Now I find myself in a situation > where I have to run the code under Python 2.3. However, I would like > to keep developing the code with the new syntax. > > How could I best automate the process of making the syntax digestible > by Python2.3 ? Have a look at Bill Mill's redecorate utility: http://llimllib.f2o.org/files/redecorate.py Peter From itsme at yahoo.com Fri Jan 7 11:26:55 2005 From: itsme at yahoo.com (It's me) Date: Fri, 07 Jan 2005 16:26:55 GMT Subject: sorting on keys in a list of dicts References: <10tr9ejf05pv660@corp.supernews.com> Message-ID: What does it mean by "stability in sorting"? Can somebody please give a sample for using the code posted? I am a little lost here and I like to know more about the use of keys.... Thanks, "Nick Coghlan" wrote in message news:mailman.298.1105112062.22381.python-list at python.org... > Jeff Shannon wrote: > > I suppose that your version has the virtue that, if the sortkey value is > > equal, items retain the order that they were in the original list, > > whereas my version will sort them into an essentially arbitrary order. > > Is there anything else that I'm missing here? > > Stability in sorting is a property not to be sneezed at - it means switching to > sorting by a second key gives the effect of "sort by key 1, then by key 2", > whereas that doesn't hold with an unstable sort algorithm. If you've ever used > an application with an unstable sorting process and that only allows sorting a > table on one column at a time, you'll appreciate the frustration that can cause :) > > Also, it's required to match the behaviour of the Python 2.4 version (which gets > to take advantage of the stability of the builtin sort). > > Cheers, > Nick. > > -- > Nick Coghlan | ncoghlan at email.com | Brisbane, Australia > --------------------------------------------------------------- > http://boredomandlaziness.skystorm.net From steven.bethard at gmail.com Mon Jan 24 02:31:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 24 Jan 2005 00:31:17 -0700 Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) In-Reply-To: <41f490e8.1669238027@news.oz.net> References: <41f325b5.1576259210@news.oz.net> <6I2dnYLoXdcTmGncRVn-vw@comcast.com> <41f490e8.1669238027@news.oz.net> Message-ID: Bengt Richter wrote: > So, e.g., for > > >>> presets = dict(a=1, b=2, deftime=__import__('time').ctime()) > > in the decorator args, the next version will act as if the decorated > function had the source code > > >>> print '%s = __frompresets__' % ', '.join(sorted(presets)) > a, b, deftime = __frompresets__ > > for the current version, except that it will be hidden. Cool! Keep us posted. I assume you'll put this into the Cookbook? Steve From uche at ogbuji.net Thu Jan 27 22:40:43 2005 From: uche at ogbuji.net (Uche Ogbuji) Date: 27 Jan 2005 19:40:43 -0800 Subject: 4suite XSLT thread safe ? In-Reply-To: <35praqF4p8vohU2@individual.net> References: <6lkkc2-fbd.ln1@pluto.i.infosense.no> <35pntaF4os76kU1@individual.net> <35ppqeF4nu516U1@individual.net> <35praqF4p8vohU2@individual.net> Message-ID: <1106883643.169034.74750@c13g2000cwb.googlegroups.com> Sorry I'm late to the whole thread. Diez B. Roggisch is pretty much right on the money in all his comments. 4XSLT *is* thread safe, but each individual processor instance is not thread safe. Yes, this is typical OO style: you encapsulate state in an instance so that as long as each thread has its own instance, there are no state clashes. Therefore, you should be creating at least one processor object per thread. Note: the 4Suite server is a multi-threaded architecture that uses 4XSLT heavily using processor-per-thread. -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://4Suite.org http://fourthought.com Use CSS to display XML - http://www.ibm.com/developerworks/edu/x-dw-x-xmlcss-i.html Introducing the Amara XML Toolkit - http://www.xml.com/pub/a/2005/01/19/amara.html Be humble, not imperial (in design) - http://www.adtmag.com/article.asp?id=10286UBL 1.0 - http://www-106.ibm.com/developerworks/xml/library/x-think28.html Manage XML collections with XAPI - http://www-106.ibm.com/developerworks/xml/library/x-xapi.html Default and error handling in XSLT lookup tables - http://www.ibm.com/developerworks/xml/library/x-tiplook.html Packaging XSLT lookup tables as EXSLT functions - http://www.ibm.com/developerworks/xml/library/x-tiplook2.html From harold.fellermann at upf.edu Thu Jan 13 11:26:11 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 13 Jan 2005 17:26:11 +0100 Subject: Using Tix and Tkinter In-Reply-To: References: Message-ID: On 31.12.2004, at 16:50, Harlin Seritt wrote: > import Tix > from Tkconstants import * > from Tkinter import * > > root = Tix.Tk() > > Label(root, text="Hello!").pack() > Tix.tixControl().pack() > > root.mainloop() > When I run this, I get the following error: > > Traceback (most recent call last): > File "TixTest.py", line 8, in ? > Tix.tixControl().pack() > AttributeError: 'module' object has no attribute 'tixControl' in the Tix module this widget is called Control. writing Tix.Control().pack() should work. - harold - -- Man will occasionally stumble over the truth, but most of the time he will pick himself up and continue on. -- Winston Churchill From steven.bethard at gmail.com Tue Jan 4 04:45:49 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 04 Jan 2005 09:45:49 GMT Subject: Hlelp clean up clumpsy code In-Reply-To: References: Message-ID: <7BtCd.276928$5K2.111655@attbi_s03> It's me wrote: > Another newbie question. > > There must be a cleaner way to do this in Python: > > #### section of C looking Python code #### > a = [[1,5,2], 8, 4] > a_list = {} > i = 0 > for x in a: > if isinstance(x, (int, long)): > x = [x,] > for w in [y for y in x]: > i = i + 1 > a_list[w] = i > print a_list > ##### > > The code prints what I want but it looks so "C-like". How can I make it > more Python like? Don't know what version of Python you're using, but if you're using 2.4 (or with a few slight modifications, with 2.3), you can write: py> dict((item, i+1) ... for i, item in enumerate( ... a_sub_item ... for a_item in a ... for a_sub_item ... in isinstance(a_item, (int, long)) and [a_item] or a_item)) {8: 4, 1: 1, 2: 3, 4: 5, 5: 2} Basically, I use a generator expression to flatten your list, and then use enumerate to count the indices instead of keeping the i variable. Steve From jan.dries at dcube-resource.be Sat Jan 1 01:46:12 2005 From: jan.dries at dcube-resource.be (Jan Dries) Date: Sat, 01 Jan 2005 07:46:12 +0100 Subject: Any Python XML Data Binding Utilities Avaiable? In-Reply-To: <41D61BB9.5030701@263.net> References: <41D61BB9.5030701@263.net> Message-ID: <41D64734.6090709@dcube-resource.be> SeSe wrote: > Hi, every one, happy new year! > > I am working on XML with Python. I wonder if there is any XML Schema<-> > Python Object mapping tools so that we can convert one to another. > Thanks. You may want to look at generateDS. It can generate Python data structures from an XML Schema document. It supports only a subset of the schema spec, but is nonetheless quite useful. See http://www.rexx.com/~dkuhlman/generateDS.html There's also minixsv, which does something similar. I've never used it myself though. See http://www.leuthe.homepage.t-online.de/minixsv/minixsv_overview.html The most complete Schema validator in Python is probably XSV. It doesn't have the ability to generate Python object mappings though. See http://www.ltg.ed.ac.uk/~ht/xsv-status.html Another extensive schema parser is part of (and well hidden in) the wsdl toolset from the pywebsvcs project. It does support Python object mapping generation, but the usefulness of the result is limited outside the context of web services. See http://pywebsvcs.sourceforge.net/ Regards, Jan From peter at engcorp.com Sat Jan 8 13:14:17 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Jan 2005 13:14:17 -0500 Subject: Recent infoworld column In-Reply-To: <41DEEF0F.5000300@nospamyahoo.com> References: <41DEEF0F.5000300@nospamyahoo.com> Message-ID: Dwarf Electrician wrote: > from a long time listener... > > http://www.infoworld.com/article/04/12/30/01OPstrategic_1.html Kudos for Roger Binns! From aleaxit at yahoo.com Mon Jan 31 08:16:39 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 31 Jan 2005 14:16:39 +0100 Subject: implicit conversion References: Message-ID: <1gr9bia.1nrrc8q1ny2zngN%aleaxit@yahoo.com> Benjamin Schmeling wrote: ... > I don't know how to achieve implicit conversion at this point, turning an > long automatically into an bigint. The other way round, turning an bigint > into long can be realized by defining __long__. Perhaps adding to your bigint class a constructor (not declared as ``explicit'', if you're coding C++) which accepts as its argument a python long might help...? Alex From G.Franzkowiak at web.de Sat Jan 15 12:22:16 2005 From: G.Franzkowiak at web.de (franzkowiak) Date: Sat, 15 Jan 2005 18:22:16 +0100 Subject: interpret 4 byte as 32-bit float (IEEE-754) Message-ID: <34t1p2F4foiplU1@individual.net> Hello, I've read some bytes from a file and just now I can't interpret 4 bytes in this dates like a real value. An extract from my program def l32(c): return ord(c[0]) + (ord(c[1])<<8) + (ord(c[2])<<16) + (ord(c[3])<<24) ... value = l32(f.read(4)) <--- 3F 8C CC CD should be 1.11 Anybody an answer ? regards gf From aleaxit at yahoo.com Tue Jan 4 04:10:00 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 4 Jan 2005 10:10:00 +0100 Subject: Frameworks for "Non-Content Oriented Web Apps" References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> <1104672631.884144.294730@c13g2000cwb.googlegroups.com> <1104771690.845547.264630@z14g2000cwz.googlegroups.com> Message-ID: <1gpv02y.1bwcbv218q4i02N%aleaxit@yahoo.com> wrote: > Moreover, I recently saw Dabo(http://www.dabodev.com/about), a > framework for developing 3 tier apps with Python and wxPython(and other > supported GUI toolkits). I have not tried it but I think something > similar, but for web-apps, is a close definition of "A Framework for > Non-Content Oriented Web Apps". Once you're on a multilayer track, whether the presentation is on the web or on some other UI should just be an issue for the very last layer (closest to the user). That's definitely how we did things at AB Strakt (www.strakt.com). Of course, the web-based presentation layer will be generally simpler/poorer than ones based on richer GUI toolkits -- as a compensation, it may more easily be "skinnable" by using CSS and the like, and it's way more easily _testable_ thanks to many good packages for webpage-generators testing. Alex From jeffrey at cunningham.net Fri Jan 21 21:30:22 2005 From: jeffrey at cunningham.net (Jeffrey Cunningham) Date: Fri, 21 Jan 2005 18:30:22 -0800 Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> Message-ID: On Fri, 21 Jan 2005 03:08:50 -0800, Xah Lee wrote: > i've started to read python tutorial recently. > http://python.org/doc/2.3.4/tut/tut.html > (snip rest of misleading filler) > > http://xahlee.org/PageTwo_dir/more.html The first line is solipsistic (..like..'so what?'). But I think its all misleading. The real purpose of his cross-post is to get people to visit his website, ooh-and-ahh at his unique and daring Bush-bashing at the top, and finally admire (along with Xah himself) the pictures he takes of himself. Vanity, vanity, all is vanity... The only remaining question is 'why does he restrict his cross-posting to this particular collection of groups?' I don't have an answer to that one. [incidentally, I'm still cracking up over k.t. and the soldier...] --Jeff From tonino.greco at gmail.com Thu Jan 27 03:16:21 2005 From: tonino.greco at gmail.com (Tonino) Date: 27 Jan 2005 00:16:21 -0800 Subject: tkinter socket client ? In-Reply-To: References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> <1106311130.446259.30710@f14g2000cwb.googlegroups.com> <1106318469.311179.126140@c13g2000cwb.googlegroups.com> <1106319270.932204.180590@c13g2000cwb.googlegroups.com> <1106659122.977876.234250@z14g2000cwz.googlegroups.com> Message-ID: <1106813781.056257.245180@f14g2000cwb.googlegroups.com> great - thanks ;) Tonino From lbates at syscononline.com Wed Jan 12 12:39:31 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 12 Jan 2005 11:39:31 -0600 Subject: ConfigParser - add a stop sentinel? In-Reply-To: References: Message-ID: You should probably consider NOT doing what you suggest. You would need to do some rather extensive work so you can support the .write method of ConfigParser. With a little ingenuity I've been able to user ConfigParser to support some very different and complex syntaxes on different projects. If this won't work, just have two different (separate) files. If you are dead set on combining these two, put your foreign syntax lines into the file as comments. ConfigParser will not process them, and you can have some other class extract only the comments and parse them independently. Regards, Larry Bates rzed wrote: > I am working with PythonCard in one of my apps. For its purposes, it > uses an .ini file that is passed to ConfigParser. For my app, I also > need configuration information, but for various reasons, I'd rather > use a syntax that ConfigParser can't handle. > > I know I can maintain two separate configuration files, and if I have > to I will, but I'd rather avoid that, if possible, and a solution > that suits my purposes is quite straightforward. I insert a sentinel > in the ini file and modify my local ConfigParser's _read method to > stop accepting input when it encounters that value. I handle my app's > portion of the configuration myself. > > This all works fine, but I was wondering whether it might be > worthwhile to add a standard stop flag in ConfigParser itself. Am I > the only one with this sort of use case? If there were a standard way > of doing this, I'd much rather use that, particularly if I ever have > reason to distribute the app elsewhere. From craig at postnewspapers.com.au Mon Jan 3 15:45:36 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Tue, 04 Jan 2005 04:45:36 +0800 Subject: Bad Interpreter In-Reply-To: <1104783849.754892.47560@c13g2000cwb.googlegroups.com> References: <1104783849.754892.47560@c13g2000cwb.googlegroups.com> Message-ID: <1104785136.4535.12.camel@albert.localnet> On Mon, 2005-01-03 at 12:24 -0800, RajaSrinivasan at hotmail.com wrote: > I have seen some previous messages about such a problem. I have this > problem but it is not clear what the solution really was. > > I am running FC2, python 2.3.3 > > the script i have sock.py runs if i say something like : > > python sock.py > > but ./sock.py results in a :bad interpreter error > how do i troubleshoot something like this? You probably have Windows-style line endings in the file. The kernel sees the ^M at the end of the line and gets all confused. -- Craig Ringer From google_groups_001 at yahoo.com Tue Jan 25 10:03:33 2005 From: google_groups_001 at yahoo.com (google_groups_001 at yahoo.com) Date: 25 Jan 2005 07:03:33 -0800 Subject: *IMPORTANT* Message for Google Group users! Message-ID: <1106665413.546265.22710@z14g2000cwz.googlegroups.com> Good News! Do you know how simple it is to go to Heaven after this life has ended? Some people believe that belonging to a local church, temple, mosque or synagogue will get them to Heaven. Others believe that water baptism, obeying the ten commandments or just being a good person will get them to Heaven. There are many other beliefs as well, but the good news about God's way to Heaven is found in the Holy Bible. The good news is that God came from Heaven to earth in the person of Jesus Christ over 2000 years ago and died for our sins(misdeeds). He was born in the land of Israel supernaturally to a virgin Jewish woman named Mary. He lived a sinless life for thirty-three years and then sacrificed His sinless blood and died on a cross to pay the death penalty for our sins. After Jesus was placed in a tomb He rose from the dead three days later as He said He would. The Holy Bible also tells us that Jesus Christ ascended into Heaven and that all who accept Him as their Lord and Saviour will live forever with Him in Heaven where there is no more death, sorrow, sickness and pain. The Bible says, "For the wages of sin is death, but the gift of God is eternal life through Christ Jesus our Lord." (Romans 6:23) This verse in the Bible says, "For ALL HAVE SINNED, and come short of the glory of God." (Romans 3:23) This verse says, "But God demonstrates his own love for us in this: While we were still sinners, Christ died for us." (Romans 5:8) In this passage the Bible clearly explains how simple it is to be saved and on your way to Heaven, "For if you confess with your mouth, "Jesus is Lord," and believe in your heart that God raised him from the dead, you WILL BE SAVED." (Romans 10:9) You can be saved right now and on your way to Heaven if you will open your heart to Jesus and pray the following prayer out loud: Dear Jesus Christ, I want to be saved so that I can have a home in Heaven when this life is over. I agree with You that I am a sinner. I believe You love me and want to save me. I believe that You bled and died on the cross to pay the penalty for my sins. I believe that You rose from the dead. Please forgive my sins and come into my heart and be my Lord and Saviour. Thank You Lord Jesus Christ for forgiving me and saving me through Your merciful grace. Amen. You are now a Christian if you said the prayer and allowed God to save you. Welcome to the family of God. Salvation is not a reward but a gift. The Bible says it this way, "For it is by GRACE you have been SAVED, through FAITH and this not from yourselves, it is the GIFT of God." (Ephesians 2:8) Nothing in the world is more important than your eternal destiny. The Bible says, "In Him(Jesus) we have redemption through His blood, the forgiveness of sins..." (Ephesians 1:7) If you have not yet made a decision to be saved, please do so now before it is too late. The reason why it is so important to be saved now is because you do not know exactly when you will die. You may die prematurely in a traffic accident, terrorist attack or some other way before you get another chance to be saved. The Bible tells us that we will spend eternity in Heaven or a place of eternal torment called Hell. It would be terrible to die and go to Hell when all you have to do is accept Jesus Christ as your personal Lord and Saviour. Some people that have already made Jesus Christ their Lord and Saviour worry about losing their salvation. The Bible teaches Christians that we can never lose our salvation no matter what happens. The Bible says it this way, "My dear children, I write this to you so that you will not sin. But if anybody does sin, we have one who speaks to the Father in our defense Jesus Christ, the Righteous One." Yes my friend, Jesus Christ is able to save you and keep you saved. Please tell your family and friends, thanks! Have a great day! Internet Evangelist R.L. Grossi 1. http://www.biblegateway.com << Free Online Bible 2. http://www.free-hoster.com/goodnews << Passion of the Christ 3. http://www.carm.org/cults/cultlist.htm << Beware Of Cults 4. http://www.equip.org/free/DH198.htm << About Hell 5. http://www.powertochange.com/questions/qna2.html << Is Jesus God? From __peter__ at web.de Wed Jan 26 04:06:50 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Jan 2005 10:06:50 +0100 Subject: need help on generator... (re) References: <63b5e209.0501241406.4fb5980b@posting.google.com> Message-ID: Joh wrote: >> def gen(iterable, start, end): >>it?=?iter(iterable) >>while?True: >>it,?a?=?tee(it) >>a?=?tuple(islice(a,?end-1)) >>for?sz?in?xrange(start,?len(a)+1): >>yield?a[:sz] >>it.next() >> >> if __name__ == "__main__": >>print?list(gen(range(1,?5),?2,?4)) > > please, this one looks interesting, could you explain a bit how it > works and why it "remain memory-efficient" ? If you have a generator of the form def gen1(iterable): for i in iterable: yield f(i) for i in iterable: yield g(i) and then use it for item in gen1(range(huge_number)): do_something_useful_with(item) it will only work when you feed it with something you can iterate over multiple times, e. g. a list, not a generator that reads data on every call of the next() method. That means you must store the data for (to keep it simple) the lifetime of gen1(). If you can modify the generator to def gen2(iterable): for i in iterable: yield f(i) yield g(i) for item in gen2(xrange(huge_number)): # switched from range() to xrange() do_something_useful_with(item) there is no such restriction to the iterable. All data can be read, processed and garbage-collected immediately. The gen() generator is a bit more complex in that it has to store a few adjacent items instead of only one and allows for an arbitrary number of functions (inlined as yield of an n-tuple) instead of always two functions, but the idea is the same. Peter From lbolognini at gmail.com Thu Jan 6 06:27:56 2005 From: lbolognini at gmail.com (lbolognini at gmail.com) Date: 6 Jan 2005 03:27:56 -0800 Subject: wxPython clipboard Message-ID: <1105010876.075011.261070@z14g2000cwz.googlegroups.com> Hi all, I'm thinking about coding a free version of this software: http://www.pitrinec.com/pkindex.htm I would use wxPython and wx.Clipboard class (hoping to be able to make it cross-platform) The software above detects macros you code in any Windows active window and replaces them with a text: something like you write "/ff" and he pastes "Feel free to call us back for whatever questions you might have". This kind of softwares are very usefull in a call-centre environment (where I'm currently working). The thing is I'm thinking about the best approach (in terms of CPU resources) to detect the macro. Not sure how keyloggers work but I suspect I could run a service that compares everything beign written in the active window with the macros I saved in the software configuration. Could you please give me some advice on the best approach to solve this problem? Thanks a lot, Lorenzo -- http://www.bolognini.net From usenet_spam at janc.invalid Fri Jan 7 19:26:33 2005 From: usenet_spam at janc.invalid (JanC) Date: Sat, 08 Jan 2005 00:26:33 GMT Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> <41DD5C6B.2070708@holdenweb.com> Message-ID: Peter Hansen schreef: > Steve Holden wrote: > >> Or even used cut(1) from the command line. > > Or myybe not :-) > > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > c:\>cut > 'cut' is not recognized as an internal or external command, > operable program or batch file. Microsoft Windows 2000 [versie 5.00.2195] (C) Copyright 1985-2000 Microsoft Corp. C:\>cut cut: u moet een lijst van bytes, tekens, of velden geven Probeer `cut --help' voor meer informatie. Seems to work just fine... :-P Have a look at: They have native win32 builds of many of the GNU commandline utilities... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From bo at systemhouse.dk Tue Jan 25 22:01:27 2005 From: bo at systemhouse.dk (Bo Jacobsen) Date: Wed, 26 Jan 2005 04:01:27 +0100 Subject: Can't load bytecode with execfile ? Message-ID: I have a number of files compiled to bytecode using py_compile.compile(). The .pyc files can be invoked by python directly ($python file.pyc), but "loading" them by execfile just throws an exception ? Any suggestions Bo. From aut_gbarros at uolinc.com Wed Jan 5 11:37:36 2005 From: aut_gbarros at uolinc.com (Gabriel Cosentino de Barros) Date: Wed, 5 Jan 2005 14:37:36 -0200 Subject: How to make executable file ? Message-ID: <2814F26DA6908F41927A81C410C4991A02079C33@siamun.server.bl.corp.intranet> > Also, you can try with py2exe. It's very easy. > Catalin. > > You may want to try cx_freeze. I brief experience with both. may be helpful 1. I did a little program on python/TK. Some 100 lines or less 2. executed cx_freeze 3. executed py2exe In the end, i had a dir with the name of the script: 03/12/04 18:08 . 03/12/04 18:08 .. 03/12/04 18:07 28.672 bugger.12.exe 25/05/04 21:19 45.117 datetime.pyd 03/12/04 18:07 563.528 library.zip 09/11/04 15:41 964 palavras.txt (this is data, i put here) 25/05/04 21:17 974.909 python23.dll 03/12/04 18:07 tcl 31/03/04 21:34 569.344 tcl84.dll 31/03/04 21:41 1.011.200 tk84.dll 25/05/04 21:18 16.384 w9xpopen.exe 25/05/04 21:18 57.401 _sre.pyd 25/05/04 21:19 36.925 _tkinter.pyd 10 File(s) 3.304.444 bytes 3 Dir(s) 2.143.559.680 bytes free Despite the fact that it got extremely big (but i wasn't expecting less when i started) it got pretty clumsy for what i had in mind. I was hoping for something like a 10Mb-single-exe-file kinda of result :) I belive cx_freeze didn't did much because i had no small includes. just the huge ones like Tk. Gabriel -------------- next part -------------- An HTML attachment was scrubbed... URL: From cabrera at wrc.xerox.com Mon Jan 31 20:47:41 2005 From: cabrera at wrc.xerox.com (jose isaias cabrera) Date: Mon, 31 Jan 2005 20:47:41 -0500 Subject: Java Integer.ParseInt translation to python References: <008d01c507f4$451d9b30$2820790d@stso.xcdg.xerox.com> <797fe3d405013116284ecfab68@mail.gmail.com> Message-ID: <003801c50800$04dea710$d6b8850d@jicman> Yes, that's my problem. I don't want to go through the java stuff. :-) Thanks. ----- Original Message ----- From: "Bill Mill" To: "jose isaias cabrera" Cc: Sent: Monday, January 31, 2005 7:28 PM Subject: Re: Java Integer.ParseInt translation to python > Jose, > > On Mon, 31 Jan 2005 19:23:35 -0500, jose isaias cabrera > wrote: >> >> Greetings! >> >> I've looked through the internet (not long, though) but I have not been >> able >> to find a python translation to >> >> buffer[0] = (byte)Integer.parseInt(string,16); > > Tell me what this does, give me an example or two, and I'll translate > it for you. I don't feel like going to read the java docs to figure it > out. > > You probably want to look at the built-in int() function though. Type > help(int) at the python prompt. > > Peace > Bill Mill > bill.mill at gmail.com > -- > http://mail.python.org/mailman/listinfo/python-list > From stephen.thorne at gmail.com Wed Jan 5 18:52:15 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 6 Jan 2005 09:52:15 +1000 Subject: Decorators and static typing. In-Reply-To: <41DC7893.2090707@oz.net> References: <41DC7893.2090707@oz.net> Message-ID: <3e8ca5c805010515525cddb69e@mail.gmail.com> On Wed, 05 Jan 2005 15:30:27 -0800, whisper at oz.net wrote: > Well, the decorator war is over (Python lost IMO!) and now we've got the > static typing war to fight! > > Both of these seem like syntax sugar to avoid writing good code! One has > already introduced ugly coding and the 2nd is likely to do the same! IMHO, the syntax is irrelevent. The goal of making it a core language feature is to remove the necessity of people writing their own type checkers and interface implementations. Essentially at the moment we have a situation with zope.interfaces that is causing many python projects that are completely unrelated to Zope (for instance, twisted) to depend on zope.interfaces, because its the most standard way of doing interfaces in Python. No one is going to like the syntax, and if anyone actually does, they're not going to speak up. Guido knows this. Thats why he's the BDFL, he can just dictate what the syntax SHALL be, and avoid 150 post threads over if '@' is better than 'dec' for decorators. Sure, we can implement type checking without language changes, but in doing so, we kill the entire point. Something standard is desired. Why don't we make it a language feature so that we don't have to waste even more lines of code and brain-cycles with obscure things like: def f(n): assert type(n) in (int, float) or subscribesToDuckType("number") using handwritten APIs that differ between every project. Regards Stephen Thorne From ariza at flexatone.com Thu Jan 13 04:43:19 2005 From: ariza at flexatone.com (ariza) Date: 13 Jan 2005 01:43:19 -0800 Subject: site.here on python 2.4 Message-ID: <1105609399.915874.71150@z14g2000cwz.googlegroups.com> greetings. it seems that the attribute site.here, of the site module, has vanished in python 2.4. up until python 2.3, site.here seemed (to me at least) a convenient way to get the complete path to the python library on any platform: >>> import site >>> site.here '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3' i do not see any information about this change save that in the new documentation it says: """ This module is automatically imported during initialization. The automatic import can be suppressed using the interpreter's -S option. Importing this module will append site-specific paths to the module search path. """ can anyone propose a similarly effective and cross-platform solution for easily discovering the the library path on any python installation? From bjourne at gmail.com Fri Jan 7 20:23:32 2005 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sat, 8 Jan 2005 02:23:32 +0100 Subject: Securing a future for anonymous functions in Python In-Reply-To: <10tu91mhv8mn89d@corp.supernews.com> References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <7xis6930ah.fsf@ruckus.brouhaha.com> <7xvfa90w6g.fsf@ruckus.brouhaha.com> <10tu91mhv8mn89d@corp.supernews.com> Message-ID: <740c3aec05010717232a784961@mail.gmail.com> The more features a language has, the harder it becomes to learn. An example of that is C++ which has almost everything. Classes, structs, templates, strange keywords that noone uses like auto, inline const, passing by reference/value, enum, union, lots of macros, multiple inheritance, namespaces etc. I'll bet that you could shave off 50% of C++'s features and it would still be 95% as usable[*]. Judging by the number of PEP proposals and syntax additions that appear on the mailing list every day Python could some day become as bloated. We don't want that, do we? So how do we avoid feature bloat?: 1. We stop adding features, either now or at some point in the future. 2. We remove some features. Either way we have to put a limit on the number of features we want Python to have. Let's call that number X where X is a number much smaller than infinity. With a set limit, the discussion becomes "which features should be selected for use in Python?" instead of "should this feature be added/removed?" Personally, I don't care either way if lambda is removed or retained, but I would much rather have the "with" keyword someone proposed, do-while loops or whatever. I think there are way too many good features out there just waiting to take lambdas place. * - Please don't ask me to make that bet. -- mvh Bj?rn From moma at example.net Fri Jan 28 15:41:05 2005 From: moma at example.net (moma) Date: Fri, 28 Jan 2005 21:41:05 +0100 Subject: Where can I find sample "beginner" programs to study? In-Reply-To: <_6CdnWIOB8AaA2fcRVn-rg@speakeasy.net> References: <_6CdnWIOB8AaA2fcRVn-rg@speakeasy.net> Message-ID: Todd_Calhoun wrote: > I'm trying to learn Python (and programming), and I'm wondering if there are > any places where I can find small, simple programs to study. > > Thanks. > Hello, http://www.python.org (docs -> tutorial) http://www.python.org/doc/ ! http://www.diveintopython.org http://www.byteofpython.info Eggs are here. Bring some bacon. http://www.python-eggs.org/links.html -------- Cross platform GUI-programs: http://www.wxPython.org Widgets documentation: http://www.wxPython.org -------- IDEs (programmers Python editors, if you want one): Eric http://www.die-offenbachs.de/detlev/eric3.html Dr.Python http://drpython.sourceforge.net/ ? // moma http://www.futuredesktop.org/OpenOffice.html http://www.futuredesktop.org/hpc_linux.html From pierre.barbier at cirad.fr Tue Jan 18 02:30:33 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Tue, 18 Jan 2005 08:30:33 +0100 Subject: extension module, thread safety? In-Reply-To: References: Message-ID: <41ecbaae$0$1046$626a14ce@news.free.fr> David Bolen a ?crit : > > If the threads under discussion are all Python threads, then by > default yes, the extension module C functions will appear to be atomic > from the perspective of the Python code. When the Python code calls > into the extension module, the GIL (global interpreter lock) is still > being held. Unless the extension module code explicitly releases the > GIL, no other Python threads can execute (even though those threads > are in fact implemented as native platform threads). Indeed, there is this (so annoying) GIL ... is there any project about extracting the (few ?) critical points of the python interpreter to put locks around them instead of choosing the opposite strategy (ie. locking anythime but when we know the section is not critical) ? Because it would made embedding a python interpreter in another language much more easy ! With the current CPython, it's very hard to mix Python and C in a multithreading application (with C-threads, not Python-threads). In fact I never really succeeded in that task because of that GIL ! I have a multi-thread application but every bit of Python code must be run into a Python thread. To be more precise, I wanted to be able to call Python code in response to some GUI events, and I didn't want to instanciate a new interpreter for I wanted to be able to access the environment of my main Python interpreter. By the way, if someone succeeded in a similar task, I'll be happy to hear about it :) Pierre PS: if the main code is in C (in fact C++ ...) and not Python it's for historical reasons of course ;) From peter at engcorp.com Thu Jan 6 10:59:07 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Jan 2005 10:59:07 -0500 Subject: OT: spacing of code in Google Groups In-Reply-To: <41DD5C6B.2070708@holdenweb.com> References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> <41DD5C6B.2070708@holdenweb.com> Message-ID: Steve Holden wrote: > Peter Hansen wrote: >> But the whole argument is fairly moot... I've needed a rectangle >> operation only once in the last ten years, and if I hadn't known at >> the time that my editor could do it (and spent about half an hour >> figuring out how it worked), I could have written a utility to >> do the job faster if I'd been using Python at the time... > > Or even used cut(1) from the command line. Or myybe not :-) Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. c:\>cut 'cut' is not recognized as an internal or external command, operable program or batch file. -Peter From hcslmf at texlife.com Mon Jan 10 14:56:44 2005 From: hcslmf at texlife.com (brolewis) Date: 10 Jan 2005 11:56:44 -0800 Subject: Importing Problem on Windows In-Reply-To: <1105382542.552797.125200@c13g2000cwb.googlegroups.com> References: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> <1105382542.552797.125200@c13g2000cwb.googlegroups.com> Message-ID: <1105387004.434581.194560@c13g2000cwb.googlegroups.com> Sorry. 2.4 in both locations From steve at holdenweb.com Fri Jan 14 16:51:44 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 16:51:44 -0500 Subject: why are people still using classic classes? In-Reply-To: References: <7x6522gegg.fsf@ruckus.brouhaha.com> Message-ID: <41E83EF0.2020402@holdenweb.com> Peter Hansen wrote: > Paul Rubin wrote: > >> Simon Wittber writes: >> >>>> Is there a reason NOT to use them? If a classic class works fine, what >>>> incentive is there to switch to new style classes? >>> >>> >>> Perhaps classic classes will eventually disappear? >> >> >> It just means that the formerly "classic" syntax will define a >> new-style class. Try to write code that works either way. > > > Unfortunately, if we should follow the recent advice about > always using "super()" in the __init__ method, it's hard > to do what you suggest (though it sounds like good advice) > without resorting to extreme ugliness: > > >>> class Classic: > .... def __init__(self): > .... super(Classic, self).__init__() > .... > >>> c = Classic() > Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in __init__ > TypeError: super() argument 1 must be type, not classobj > > Could classic classes ever be removed without us having manually > to fix all __init__ calls to the superclass? > That's not really an issue unless there's a diamond-shaped inheritance graph and linearisation of the the super classes is required to ensure that things stay sane. Remembering that the MO for classic classes and types are rather different, how many cases do you think it will matter? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From peter at engcorp.com Thu Jan 13 13:30:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 13:30:00 -0500 Subject: [perl-python] 20050112 while statement In-Reply-To: References: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> Message-ID: <-oSdnYnagrc_I3vcRVn-3Q@powergate.ca> Steven Bethard wrote: > Xah Lee wrote: [some Python code] > Because you're posting this to newsgroups, it would be advisable to use > only spaces for indentation -- tabs are removed by a lot of newsreaders, > which means your Python readers are going to complain about > IndentationErrors. Unfortunately, there are now two ways to post screwed up Python code, and using tabs is only one of them. The other is to post from Google Groups, and that's what Xah Lee is doing. (The rest of your advice, about going away, is pretty good though. ;-) -Peter From fredrik at pythonware.com Fri Jan 28 04:32:57 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 28 Jan 2005 10:32:57 +0100 Subject: unicode and data strings References: <41FA03C1.50404@geochemsource.com> Message-ID: Laszlo Zsolt Nagy wrote: > Now I installed Python 2.3.4 and wxPython 2.5.3 (with unicode support). I'm getting this > exception: > > exceptions.UnicodeDecodeError:'ascii' codec can't decode byte 0x91 in position 0: ordinal not in > range(128) >From where? Can you include a "print repr()" of the string you're trying to convert, and enough code from your script to be able to reproduce the problem? > The I tried this: > > >>>'\x91'.decode('utf8') > UnicodeDecodeError: 'utf8' codec can't decode byte 0x91 in position 0: unexpected code byte > >>>'\x91'.encode('utf8') > > Here is the question: I would like to use simple binary data strings (like an array of bytes). > I do not care about encodings. How do I do that? Unicode errors only appear if you're converting between "raw 8-bit data" and Unicode strings (which contain Unicode characters, not bytes or integers). You cannot do that without caring about encodings... From paolo_veronelli at yahoo.it Tue Jan 4 04:07:32 2005 From: paolo_veronelli at yahoo.it (paolo_veronelli) Date: Tue, 04 Jan 2005 09:07:32 +0000 Subject: Frameworks for "Non-Content Oriented Web Apps" In-Reply-To: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <41DA5CD4.8060900@yahoo.it> mirnazim at gmail.com wrote: >Hi, > >There are great Python Web Application Framework. But most of them are >meant for content oriented web apps. > >Is there something that can ease the development of application that >are not content oriented(I call them "NON CONTENT-ORIENTED WEB >APPLICATIONS" because I don't know what else to call them). I mean the >applications like, accounting, high volume data entry apps, where >normally GUI clients have ruled. I know very high quality ERP and >similar packages have been implemented in a web based environment. But >problem is that they have been developed with the tools that were >actually meant for content oriented apps like Zope, PHP, etc. > >But is there some sort of framework or something that is actually meant >for such web apps,application that make heavy use of forms, have very >high amount of user interaction etc. > >What I am asking here may sound off beat, but I think, in todays world >where web based solutions offers such a flexibility, we really need it. > >I also know that I am to ambiguous, but as is the characteristic of >this wonderful community, talks that start as most abigous, transform >in crystal clear. > >PS: I am a web developer, using PHP for living. I have been playing >with python for a while. I found python is really a cool language(do I >need to say that ;-)) with a really, really impressive collection of >modules and frameworks. While developing a school information system, I >felt the need of such a framework that makes developing of "Non-Content >Oriented Web-Apps" easy. > >I know I posted a similar message earlier, but this time I a bit more >general. > > > In pytypus everything is not content is metadata( a part from some of the code ,which part is useful for accessing informations) ,so my definition will simply be metadata oriented. From snail at objmedia.demon.co.uk Tue Jan 25 10:46:30 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Tue, 25 Jan 2005 15:46:30 +0000 Subject: is there better 32 clock() timing? References: <41f61372.1768192005@news.oz.net> <41f63d79.1778950866@news.oz.net> Message-ID: In message <41f63d79.1778950866 at news.oz.net>, Bengt Richter writes >I believe that is quite wrong as a general statement. Actually my initial statement should have been written "accessing a resource, the accuracy of which is no better than 10ms.". I was thinking of the 1ms multimedia timer but wrote about clock() instead. 10ms, coincidentally is the approx minimum scheduling granularity for threads unless you are in a multimedia thread (or real time thread - not sure about real time threads in NT). >If the "resource" only had ~1ms granularity, >the minimum would be zero, as it is if you call time.time() in a tight loop, Correct. Write your app in C and call clock(). Thats what you get. You can call clock 20000 times and still get a delta of zero. The next delta (on my system) is 10ms at about 22000 calls. >>There are various timers available, documented and undocumented, all of >>which end up at 1ms or 1.1ms, give or take. For anything shorter you Whoops here we go, same typo - should have been 10ms or 11ms. There is a 1ms timer in the multimedia timing group. >>need QueryPerformanceCounter() (but that *is* a slow call), or use the >Have you timed it, to make that claim? Yes. >What do you mean by "slow"? Slower than any other Win32, CRT or Undocumented NT function you can use to get timer information. Yes, I have timed them all, a few years ago. QueryPerformanceCounter is 47 times slower to call than clock() on my 1Ghz Athlon. QueryPerformanceCounter may have finer granularity, but called in a tight loop it'll crush your program. >>RDTSC instruction which is fast but gives a count of instruction cycles >>executed and is thus not totally accurate (multiple execution pipelines, >>plus multithreading considerations). >Accurate for what. See below - you haven't taken things into account, despite my comment in brackets above which gives a big hint. >A single clock AFAIK drives RDTSC Correct. >The main problem with a CPU clock based reading is that it's very stable unless >there's variable clock rate due to power management. Try running multiple apps at the same time you are doing your measurement, each of which has a variable loading. Each of these apps is contributing to the count returned by RDTSC. That is what I was referring to. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From http Fri Jan 7 16:49:44 2005 From: http (Paul Rubin) Date: 07 Jan 2005 13:49:44 -0800 Subject: how to extract columns like awk $1 $5 References: Message-ID: <7xzmzk3o5j.fsf@ruckus.brouhaha.com> roy at panix.com (Roy Smith) writes: > Something along the lines of: > > words = input.split() > print words[4], words[5] That throws an exception if there are fewer than 6 fields, which might or might not be what you want. From rschroev_nospam_ml at fastmail.fm Fri Jan 14 11:40:29 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 14 Jan 2005 16:40:29 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: <1CSFd.30772$Qv5.2842746@phobos.telenet-ops.be> Antoon Pardon wrote: > IMO we have a: dogs are mamals kind of relationship in Python. I see what you mean, but I don't think it's true. > Every expression can be used where a statement is expected. > (And this can be worded as: every expression is a statement.) Not really. An expression statement is a statement that looks like an expression, but actually it's more than that: not only does it calculate the value of the expression, it also prints the value. Note that it would be perfectly possible to modify the syntax into expression_stmt ::= "exprstmt" expression_list so that you would have to write exprstmt 6*9 instead of just 6*9 That makes it clearer to see the distinction: 6*9 is an expression, exprstmt 6*9 is a statement. An expression statement, more precisely. > Not every statement can be used where an expression is expected. AFAIK *no* statement can be used where an expression is expected. -- "Codito ergo sum" Roel Schroeven From air_jlin at yahoo.com Thu Jan 20 22:24:43 2005 From: air_jlin at yahoo.com (Johnny Lin) Date: 20 Jan 2005 19:24:43 -0800 Subject: Unbinding multiple variables Message-ID: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> Hi! Is there a way to automate the unbinding of multiple variables? Say I have a list of the names of all variables in the current scope via dir(). Is there a command using del or something like that that will iterate the list and unbind each of the variables? Thanks much! (If anyone posts an answer, if you could also cc your reply to my email air_jlin at yahoo.com, would be much obliged. Thanks again!) Best, -Johnny www.johnny-lin.com From grante at visi.com Mon Jan 31 23:29:13 2005 From: grante at visi.com (Grant Edwards) Date: 01 Feb 2005 04:29:13 GMT Subject: need for binary floats (except performance)? References: <81300027.0501312006.72454fd6@posting.google.com> Message-ID: <41ff0599$0$10746$a1866201@visi.com> On 2005-02-01, kartik wrote: > Since the Decimal type can represent any given fractional number > exactly, including all IEEE binary floating-point numbers, wouldn't it > be advisable to use Decimals for all floating point numbers (except > possibly for performance)? That's a pretty huge "except" for some applications. -- Grant Edwards grante Yow! HUGH BEAUMONT died at in 1982!! visi.com From rnd at onego.ru Wed Jan 19 15:45:15 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 19 Jan 2005 23:45:15 +0300 (MSK) Subject: RuntimeError: dictionary changed size during iteration Message-ID: I think, the behaviour below is misfeature: >>> [e for e in vars()] Traceback (most recent call last): File "", line 1, in ? RuntimeError: dictionary changed size during iteration >>> e = None >>> [e for e in vars()] ['e', '__builtins__', 'rlcompleter', '__file__', '_[1]', 'atexit', '__name__', 'readline', '__doc__'] Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From peter at engcorp.com Thu Jan 13 10:28:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 10:28:05 -0500 Subject: How to install pyparallel In-Reply-To: <41e689fc$0$15700$626a14ce@news.free.fr> References: <41e689fc$0$15700$626a14ce@news.free.fr> Message-ID: Michel LE VAN KIEM wrote: > > I'm trying to install the pyparallel module for my Python 2.3.4 (runs on > a FC3) but I do have some troubles. > > >>> p=parallel.Parallel() > ppdev0: failed to register device ! > ... > IOError: [No such device or address] > > Some help would be appreciated. Did you read the notes in the parallelppydev.py file's Parallel class? I suspect they may be of some help... (I don't see any other significant documentation of pyParallel, so I'm not sure where else one would look for assistance.) Also, perhaps one of these threads would be of help: http://groups.google.ca/groups?q=parallel+ppdev0+failed+to+register+device -Peter From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sun Jan 16 13:19:39 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Do Re Mi chel La Si Do) Date: Sun, 16 Jan 2005 19:19:39 +0100 Subject: Scriptomatic 2.0 Message-ID: <41eab05f$0$25799$8fcfb975@news.wanadoo.fr> Hi ! Scriptomatic 2.0 can, now, to generate scripts in Python. Download : http://www.microsoft.com/downloads/thankyou.aspx?FamilyID=09dfc342-648b-4119-b7eb-783b0f7d1178&displaylang=en Note : scriptomatic is a generator of WMI's scripts, for Windows, (and compatibles WBEM). Good night -- Michel Claveau From craig at postnewspapers.com.au Sat Jan 15 18:51:02 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sun, 16 Jan 2005 07:51:02 +0800 Subject: [Fwd: Re: Embedding Multiplr Python interpreter in C++] In-Reply-To: <41E7DA3B.9000005@holdenweb.com> References: <41E7DA3B.9000005@holdenweb.com> Message-ID: <1105833061.2858.1.camel@rasputin.localnet> On Fri, 2005-01-14 at 22:42, Steve Holden wrote: > Take a look at mod_python's code: that allows several independent > interpreters in the same Apache process using Py_NewInterpreter() I've never been entirely clear on whether mod_python does its magic by relying on having one thread per sub-interpreter, or if it can support multiple sub interpreters in a single thread. Any ideas? I'm pretty sure it's the former, but it'd be nice to be sure. -- Craig Ringer From robin at SPAMREMOVEjessikat.fsnet.co.uk Thu Jan 20 03:59:10 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Thu, 20 Jan 2005 08:59:10 +0000 Subject: rotor replacement In-Reply-To: References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> <7xacr4ewjk.fsf@ruckus.brouhaha.com> <41ef4a7a.1323588509@news.oz.net> <7xwtu8vb17.fsf@ruckus.brouhaha.com> Message-ID: <41EF72DE.5030305@jessikat.fsnet.co.uk> Peter Maas wrote: > Paul Rubin schrieb: > >>> Wasn't there a default 40-bit version that was ok (weak), but you had >>> to declare yourself US resident to download 128-bit support? >> >> >> >> That was years ago. The regulations changed since then, so they all >> have 128 bits now. > > > Perhaps the NSA has found a way to handle 128bit in the meantime. > But this is unlikely because there is no export regulation to ban > 512bit as far as I know :) > Apparently factorization based crypto is on the way out anyhow (as an article in Scientific American is reported to claim). http://www.sciam.com/article.cfm?chanID=sa006&articleID=000479CD-F58C-11BE-AD0683414B7F0000&ref=rdf -can't wait to get my quantum computer-ly yrs- Robin Becker From macrocosm at fastmail.fm Wed Jan 5 08:54:23 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Wed, 05 Jan 2005 08:54:23 -0500 Subject: project In-Reply-To: <20050104201100.73284.qmail@web80902.mail.scd.yahoo.com> References: <20050104201100.73284.qmail@web80902.mail.scd.yahoo.com> Message-ID: <41DBF18F.6040703@fastmail.fm> jerry wise wrote: >Please help me out! Your solution seems doable pretty easily, but I have very little experience in this so I need some help. At the very least respond, because I'm getting kind of desperate. Thank you so much. > > > "I'm getting kind of desperate", no kidding. Firstly, did you ask Jeff to help you understand the algorithm? Secondly, did you read up on the PyMedia docs? Thirdly, what do you have very little experience in exactly and why are you so desperate? Is this some sort of school project? You need to be able to answer yes to the first two questions if you want my and/or likely anyone else's help. I am very busy, but if you take the necessary preliminary steps, and do the work, there are many /very/ friendly and knowledgeable people here who would likely be willing to help you, given that you are willing to do some work/research yourself and ask good questions. Best regards, Arich From Rolf.Wester at t-online.de Sun Jan 2 11:52:52 2005 From: Rolf.Wester at t-online.de (Rolf Wester) Date: Sun, 02 Jan 2005 17:52:52 +0100 Subject: run region in IDLE Message-ID: <41D826E4.3020500@t-online.de> Hi, I would like to send a marked region of an IDLE editing window to the IDLE shell for evaluating, so that I can develop software incrementally. I know that I could type directly into the shell window (or copy and paste between an editing window and the shellwindow) but I'm looking for a way of doing it like it's possible with Emacs and Python. Is there any way of doing this? Regards Rolf Wester From tim at zeos.net Mon Jan 17 03:21:23 2005 From: tim at zeos.net (Timothy Babytch) Date: Mon, 17 Jan 2005 10:21:23 +0200 Subject: how to print unicode structures? Message-ID: Imagine you have some list that looks like ('unicode', 'not-acii', 'russian') and contains characters not from acsii. or list of dicts, or dict of dicts. how can I print it? not on by one, with "for" - but with just a simple print? My debugging would be MUCH simpler. Now when I try print or pprint that variable I get a page full of '\xe4\xeb\xa2\xa0\xe6\xe3\xaa\xe6\xe3\xaa' and so on. I use Python 2.4, Fedora Linux, UTF-8 locale From jgrahn-nntq at algonet.se Wed Jan 12 16:41:07 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 12 Jan 2005 21:41:07 GMT Subject: pulling info from website References: <41e2a556$0$14576$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: On 10 Jan 2005 16:06:33 GMT, Duncan Booth wrote: > bob wrote: > >> i am trying to write a script for Xbox media center that will pull >> information from the bbc news website and display the headlines , how >> do i pull this info into a list??? > > Google for "Python RSS reader" and read some of the results. And for the general (and fundamentally broken) approach, google for "web scraping". /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From sjmachin at lexicon.net Fri Jan 21 15:40:47 2005 From: sjmachin at lexicon.net (John Machin) Date: 21 Jan 2005 12:40:47 -0800 Subject: Simple (newbie) regular expression question References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> Message-ID: <1106340047.788392.74130@f14g2000cwb.googlegroups.com> Andr? Roberge wrote: > Sorry for the simple question, but I find regular > expressions rather intimidating. And I've never > needed them before ... > > How would I go about to 'define' a regular expression that > would identify strings like > __alphanumerical__ as in __init__ > (Just to spell things out, as I have seen underscores disappear > from messages before, that's 2 underscores immediately > followed by an alphanumerical string immediately followed > by 2 underscore; in other words, a python 'private' method). > > Simple one-liner would be good. > One-liner with explanation would be better. > > One-liner with explanation, and pointer to 'great tutorial' > (for future reference) would probably be ideal. > (I know, google is my friend for that last part. :-) > > Andre Firstly, some corrections: (1) google is your friend for _all_ parts of your question (2) Python has an initial P and doesn't have private methods. Read this: >>> pat1 = r'__[A-Za-z0-9_]*__' >>> pat2 = r'__\w*__' >>> import re >>> tests = ['x', '__', '____', '_____', '__!__', '__a__', '__Z__', '__8__', '__xyzzy__', '__plugh'] >>> [x for x in tests if re.search(pat1, x)] ['____', '_____', '__a__', '__Z__', '__8__', '__xyzzy__'] >>> [x for x in tests if re.search(pat2, x)] ['____', '_____', '__a__', '__Z__', '__8__', '__xyzzy__'] >>> I've interpreted your question as meaning "valid Python identifier that starts and ends with two [implicitly, or more] underscores". In the two alternative patterns, the part in the middle says "zero or more instances of a character that can appear in the middle of a Python identifier". The first pattern spells this out as "capital letters, small letters, digits, and underscore". The second pattern uses the \w shorthand to give the same effect. You should be able to follow that from the Python documentation. Now, read this: http://www.amk.ca/python/howto/regex/ HTH, John From invalidemail at aerojockey.com Wed Jan 12 13:53:29 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 12 Jan 2005 10:53:29 -0800 Subject: complex numbers In-Reply-To: References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: <1105556009.063965.145210@z14g2000cwz.googlegroups.com> It's me wrote: > The world would come to a halt if all of a sudden nobody understands complex > numbers anymore. :-) Actually, it would oscillate out of control. -- CARL BANKS From hans at zephyrfalcon.org Fri Jan 21 14:21:20 2005 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 21 Jan 2005 14:21:20 -0500 Subject: Funny Python error messages In-Reply-To: <1106315907.551660.276380@c13g2000cwb.googlegroups.com> References: <1106315907.551660.276380@c13g2000cwb.googlegroups.com> Message-ID: Will Stuyvesant wrote: > Add your funny or surprising Python error messages to this > thread. A requirement is that you should also show > (minimal) code that produces the message. Put the code > below, so people can think about how to generate the message > first, a little puzzle if you like. > > Perhaps this will even be a useful thread, to brighten the > life of the brave people doing the hard work of providing us > with error messages. I always liked: ValueError: insecure string pickle This error message is not strange if you think of "insecure", "string" and "pickle" as programming terms, but it's hugely mystifying to someone who isn't a programmer, since all of these words have different meanings in real life. Some code to produce it: >>> import cPickle >>> x = cPickle.dumps([1,2,3,"ratsj"]) >>> y = x[:18] + "?" + x[18:] >>> cPickle.loads(y) Traceback (most recent call last): File "", line 1, in ? ValueError: insecure string pickle -- Hans Nowak http://zephyrfalcon.org/ From steve at holdenweb.com Fri Jan 21 01:43:13 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Jan 2005 01:43:13 -0500 Subject: Does anyone want one? In-Reply-To: <20050120232749.14147.00000205@mb-m10.aol.com> References: <20050120232749.14147.00000205@mb-m10.aol.com> Message-ID: Drummmachine wrote: > http://www.freeiPods.com/?r=14249501 > > just go here to get started. It's very easy and very real. This is no scam. > Complete an offer, get 5 others to do the same and you'll receive a free Ipod > of your choice. > thanks for your time. Free ipods are real. > > As are pyramid scams. -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From maxm at mxm.dk Tue Jan 4 13:43:53 2005 From: maxm at mxm.dk (Max M) Date: Tue, 04 Jan 2005 19:43:53 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) In-Reply-To: References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> Message-ID: <41dae3c3$0$228$edfadb0f@dread12.news.tele.dk> Thomas Heller wrote: > It seems also the error messages aren't too helpful: > >>>>"?".encode("latin-1") > > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0x84 in position 0: ordinal not in range(128) > > Hm, why does the 'encode' call complain about decoding? Because it tries to print it out to your console and fail. While writing to the console it tries to convert to ascii. Beside, you should write: u"?".encode("latin-1") to get a latin-1 encoded string. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From usenet at horvath.com Tue Jan 4 01:42:46 2005 From: usenet at horvath.com (Bob Horvath) Date: Tue, 04 Jan 2005 00:42:46 -0600 Subject: Zope newsgroups? Need help with POSKeyError In-Reply-To: References: <41d5e51d$0$4095$afc38c87@news.optusnet.com.au> Message-ID: Dan Stromberg wrote: > On Sat, 01 Jan 2005 10:47:41 +1100, richard wrote: > > >>Bob Horvath wrote: >> >>>I have a Zope/Plone combination that I have been having POSKeyErrors >>>with for a while now. Are there any newsgroups that deal with Zope? >> >>No, but there is a mailing list - see zope.org >> >>Also, try google searching for POSKeyError. >> >> >> Richard > > > You could also see if the zeop mailing list is gatewayed to nntp on gmane. > They have a huge number of FLOSS development mailing lists on that nntp > server. Google should be able to find it easily. Hey thanks. That gmane tip will come in handy for many things! From anand at esi-india.com Thu Jan 6 05:34:16 2005 From: anand at esi-india.com (Anand K Rayudu) Date: Thu, 06 Jan 2005 16:04:16 +0530 Subject: Python C Object Comparison Message-ID: <41DD1428.1030503@esi-india.com> Dear All, I have some question regarding embedding and exposing of C pointers. We have embedded python and extended to expose our APIs and c objects to python. Every thing is working fine as far as customizing our application through python. How ever i am expecting following behavior but it failed. Can some oe suggest a work around!! Here is my python code import myModule a=myModule.myAPI1("1") b=myModule.myAPI2("name") # basically both above functions return same C pointer. # so i want to compare if(a==b): print "They are same" else : print "They are different" python always prints they are different, I guess this is because in python layer we create PythonCObject for every C pointer, and that is how it is exposed to python. Though both the APIs are returning the same C pointer, they are different instances of PythonCObject. So i guess that is the reason comparison is failing. How ever is it possible to make python to compare actual C pointer, rather than the PythonCObject Pointer. Can some one please suggest Regards, Anand From skip at pobox.com Mon Jan 17 12:10:35 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 17 Jan 2005 11:10:35 -0600 Subject: strange note in fcntl docs In-Reply-To: <16875.54085.712019.524951@montanaro.dyndns.org> References: <20050117053949.GA28456@grulic.org.ar> <16875.54085.712019.524951@montanaro.dyndns.org> Message-ID: <16875.61835.168746.328412@montanaro.dyndns.org> Skip> I could have sworn that os.open supported the O_SHLOCK and Skip> O_EXLOCK flags. I submitted a patch to posixmodule.c for these: http://python.org/sf/1103951 Skip From peter at somewhere.com Thu Jan 27 04:16:43 2005 From: peter at somewhere.com (Peter Maas) Date: Thu, 27 Jan 2005 10:16:43 +0100 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: Terry Reedy schrieb: > But if the class method syntax were > manditory, there would be class and/or class hierarchy bloat due to the > unlimited number of possible functions-of-a-float and large number of > actual such functions that have been written. You are right. I'm not an OO purist, I just wanted to convince Davor, that anti-OO purism can be harmful too. It's good for programmers to have a choice. > Your Four Steps to Python Object Oriented Programming - vars, lists, dicts, > and finally classes is great. I'm glad you like it :) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From http Wed Jan 12 23:06:39 2005 From: http (Paul Rubin) Date: 12 Jan 2005 20:06:39 -0800 Subject: why are people still using classic classes? References: Message-ID: <7x6522gegg.fsf@ruckus.brouhaha.com> Simon Wittber writes: > > Is there a reason NOT to use them? If a classic class works fine, what > > incentive is there to switch to new style classes? > > Perhaps classic classes will eventually disappear? It just means that the formerly "classic" syntax will define a new-style class. Try to write code that works either way. It would be nice if a __future__ directive were added right now (if it's not there already) that processes all class definitions as new-style. Otherwise there's no easy way to test for compatibility. From wittempj at hotmail.com Tue Jan 25 15:51:38 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 25 Jan 2005 12:51:38 -0800 Subject: __deepcopy__ without recursive copies? In-Reply-To: <1106677008.086803.76270@c13g2000cwb.googlegroups.com> References: <1106677008.086803.76270@c13g2000cwb.googlegroups.com> Message-ID: <1106686298.584607.116100@c13g2000cwb.googlegroups.com> In this thread a solution is given on how to work with __deepcopy__: http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/c34431c5fd3c223b/427866340239edd7?q=__deepcopy__+example&_done=%2Fgroups%3Fq%3D__deepcopy__+example+%26hl%3Den%26lr%3D%26safe%3Doff%26sa%3DN%26tab%3Dwg%26&_doneTitle=Back+to+Search&&d#427866340239edd7 For you this would give something like: -import copy -class DeviceManager(object): - def __init__(self,devFile): - DevFile = open(devFile) - devList = [Device(line) for line in DevFile] - #etc, etc... - - def __deepcopy__(self, memo): - x = DeviceManager.__new__(DeviceManager) - memo[id(self)] = x - for n, v in self.__dict__.iteritems(): - setattr(x, n, copy.deepcopy(v, memo)) - return x - -class Device(object): - def __init__(self,line): - self.copies = [] - #do something with line here - - def __deepcopy__(self, memo): - x = Device.__new__(Device) - memo[id(self)] = x - for n, v in self.__dict__.iteritems(): - setattr(x, n, copy.deepcopy(v, memo)) - return x - -DevMan1 = DeviceManager(r'c:\autoexec.bat') -DevMan2 = copy.deepcopy(DevMan1) - -print DevMan1 is DevMan2 From phr at localhost.localdomain Tue Jan 25 17:56:47 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Tue, 25 Jan 2005 22:56:47 GMT Subject: What's so funny? WAS Re: rotor replacement References: <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" writes: > There isn't. The interface might be beautifully designed, and you might > claim it is, and I would *still* require that the module gets field > testing before being incorporated into Python. Yes, of course, that's completely reasonable. > If other people start attesting that the module is beatifully > designed, and should be included in the Python core - *then* it is > worth looking into inclusion. You said something more than that. You said it's not worth even thinking about inclusion until the finished module is actually in distribution outside the core. That it's not appropriate for the distro maintainers to look at the spec and the reference (pure Python) implementatation and say "yes, we want this, go write the C version and we'll include it after it's had some testing". I think that's silly. (Anyway I don't think "beautifully designed" needs to be a requirement, and I don't claim to have done a beautiful design. "Gets the job done straightforwardly" is all that's needed and is all that I've aimed for). When the inestimable Alexbot went to O'Reilly to pitch "Python in a Nutshell", I'm sure they didn't tell him "go write the whole book from cover to cover, circulate it for at least a year and get it thoroughly reviewed, and if enough people recommend it, then and only then will we begin to think about distributing it ourselves". More normally, he'd have given them a proposal with an outline and maybe a sample chapter and they used that to decide to give him a go-ahead. Usually at that point, they'd even also pay him some money in advance to do the rest of the work with, and promise to pay him a cancellation fee if they changed their mind about the book. I certainly never asked for anything like that from the Python guys about the crypto module. I did ask for, and receive, a "this looks good, we want it". I later heard that they backed off because of legal concerns, so I put the task aside. Similarly, look at how the whole PEP process works. There are lots of times when a PEP has been accepted before any working code is distributed. To take your view to an extreme, no project should even have a task list of desired features that people are invited to implement. There's been numerous times when I've written something for the GNU project because it's been on a list like that, and it's been accepted after checking that it does what it's supposed to. > > I'm happy to have that kind of testing (and I requested it), given > > that the goal is inclusion in the core, and the core developers have > > told me (as they did) that the proposal looks good and they'd like to > > have the module, so I can reasonably expect it to go into the core if > > it meets its technical expectations. > > Not if I have a say in it. *Any* new module should see out-of-the-core > distribution first (unless there is BDFL pronouncement to include it, > of course). > > This really is a matter of development process, not of technical > quality. That's bizarre and abnormal as a development process. What kind of development process in industry doesn't decide whether to include a feature, until after the feature is completely implemented at a production scale? They figure out what the features should be, and write them into a specification. The specification defines what features will be included. Then they implement the features. (I'm talking specificially about straightforward, well-defined features, not blue-sky or experimental concepts). You see, they decide in advance what features they're going to include, because development consumes resources and they don't want to burn resources to develop something unless they're pretty sure they're going to use the result once it's done. (Of course it doesn't always work out that way. Everyone has worked on projects that have gotten cancelled before delivery. However that by definition means that something has gone wrong. No engineer likes it when that happens.) You seem to have the attitude that since volunteer development effort doesn't consume actual PSF funds, the volunteer effort is worth nothing and can be expended arbitrarily. The volunteers may not feel that way. > > If the developers instead say (as they seemed to somewhat later) that > > because of legal/political concerns, there's no way the module can > > possibly go into the core no matter how good it is technically, then > > my motivation for writing the module dries up quite a bit. > > I personally would not say that, although I can imagine that some people > do say that, and I would also defend an inclusion, and push compliance > the BXA requirements so we can legally export Python out of the U.S.A. The BXA notification on the US side is pretty easy to handle, as you know. If you look at those Python-dev messages, the concern was about importing Python-with-crypto into countries like Holland, not about exporting it from the USA. Those concerns are not necessarily something to sneeze at. Salman Rushdie had to go into hiding for years, after publishing a book in England whose contents were illegal in Iran. So, I can't get too upset with the Python maintainers for deciding to stay away from such political messes, even though I don't feel such strong concern myself. > In either case, the user would best use the pre-compiled binary that > somebody else provided for the platform. Who's the "somebody else"? The module author might also not have had a compiler for that platform. Are you suggesting that he maintain his own distribution of multiple binaries, duplicating the machinery of the Python distro for managing multi-platform builds? Do you do that with your own modules, and still say that it's easy? If you don't, then how does the end user know where to get the module for his platform? > No, I'm merely repeating myself, and rephrasing each time. > I have to, because apparently you don't see what my requirement is. Unless your requirement is different than what you say it is, I do see what it is, and I'm saying it's better to do what normal projects do and what Python has done in the past. That is, it's perfectly ok to decide to do something and then do it, rather than insisting, bizarrely, that it always be the other way around. > The original source code of the SHA-1 implementation is the NIST code > (Gutmann, then Hollerbach), so I guess that had hundreds of users before > the module was contributed to Python. Not terribly relevant, the NIST code was not a Python module. > The module itself (including the API) was written by Greg Stein and > Andrew Kuchling. I believe (without being able to verify) that they > distributed this module for quite some time, before contributing it > to Python. We would have to ask them how many users they had until > they felt confident to contribute the code. I think that question isn't the right one. We need to ask how many users the sha module was required to have, before Greg and Andrew could have reasonable confidence that the sha module would go into the core once it was tested enough and shown to be reliable. I suspect they were able to have that confidence long before testing was complete, and maybe before implementation even started. That is, they were likely able to decide that the core obviously needed a sha module, before setting off to write and test one for that purpose. If Andrew is reading this, maybe he can comment. From craig at postnewspapers.com.au Tue Jan 11 06:10:34 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Tue, 11 Jan 2005 19:10:34 +0800 Subject: here document In-Reply-To: <1166F26E-63BE-11D9-B3E0-003065FB7B26@upf.edu> References: <1166F26E-63BE-11D9-B3E0-003065FB7B26@upf.edu> Message-ID: <1105441834.3448.2.camel@rasputin.localnet> On Tue, 2005-01-11 at 18:46, harold fellermann wrote: > On 11.01.2005, at 11:34, Nader Emami wrote: > > Would somebody help me how i can write the 'here document' in > > Python script please? I have a csh script in which a program > > is invoked with some argument in the form of here document: > > > > /bin/exe.x << End_Here > > CategorY = GRIB > > etc. > > End_Here > > > > I translate this script to Python and i don't know how can I > > do this! > > f = open("/bin/exe.x","w") > print >>f , """CategoryY = GRIB > etc. > """ You mean "os.popen" not "open" I assume? The former opens a pipe to a command, the latter overwrites the file. I'd use: os.popen("/bin/exe.x", "w").write("""\ CategorY = GRIB etc. """) myself, but that's just taste (well, and performance I suspect). -- Craig Ringer From michele.simionato at gmail.com Tue Jan 4 03:26:54 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 4 Jan 2005 00:26:54 -0800 Subject: Frameworks for "Non-Content Oriented Web Apps" In-Reply-To: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <1104827214.733305.273410@z14g2000cwz.googlegroups.com> Well, with your first post you managed to get a very unclear picture of what you mean by "non-content oriented Web Application" ;-) Judging from your following posts, you want an easy way to construct Web interfaces, i.e. forms. This can be done with any Web framework, but a typical Web framework provides a lots of content-related functionality you don't want. For instance you could use Plone for your task, but you would waste 99% of its functionality and it would be absolutely overkill. If I had to write a Web application such as Webmin, for instance, i.e. one that use a Web interface to manage other applications, I would use Quixote as my Web framework of choice. Its key points are simplicity and the fact that it provides *very little*. Just the form library would be enough for you. Since the different part of Quixote are well separated, the learning curve is really really small. It also takes a little time to evaluate it. I suggest you to give a look at it. Michele Simionato From sean at buildingonline.com Wed Jan 19 22:38:22 2005 From: sean at buildingonline.com (Sean) Date: Wed, 19 Jan 2005 19:38:22 -0800 Subject: list item's position References: Message-ID: Not sure if this is what you are looking for but... >>> li = ['this','is','a','list','of','strings'] >>> li = [l for l in li if li.index(l) >= li.index('a')] >>> li ['a', 'list', 'of', 'strings'] >>> -- Sean Berry ~ Internet Systems Programmer BuildingOnline Inc. The Building Industry's Web Design and Marketing Agency Celebrating our 9th year in business, founded Aug. 1995 Ph: 888-496-6648 ~ Fax: 949-496-0036 --> Web Design Agency site: http://www.BuildingOnline.net --> Building Industry Portal: http://www.BuildingOnline.com --> Building Industry News: http://www.BuildingOnline.com/news/ --> Home Plans: http://www.eHomePlans.com "Bob Smith" wrote in message news:csn747$3fq$1 at solaris.cc.vt.edu... > Hi, > > I have a Python list. I can't figure out how to find an element's numeric > value (0,1,2,3...) in the list. Here's an example of what I'm doing: > > for bar in bars: > if 'str_1' in bar and 'str_2' in bar: > print bar > > This finds the right bar, but not its list position. The reason I need to > find its value is so I can remove every element in the list before it so > that the bar I found somewhere in the list becomes element 0... does that > make sense? > > Thanks, > > Bob From steven.bethard at gmail.com Thu Jan 27 16:07:40 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 14:07:40 -0700 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: Francis Girard wrote: > Le jeudi 27 Janvier 2005 21:29, Steven Bethard a ?crit : >> >>So None being smaller than anything (except itself) is hard-coded into >>Python's compare routine. My suspicion is that even if/when objects of >>different types are no longer comparable by default (as has been >>suggested for Python 3.0), None will still compare as smaller than >>anything... > > Well, here's python doesn't seem to confirm what you're saying : > > >>>>a = "10" >>>>b = 10 >>>>a > b > > True > >>>>b > a > > False > >>>>id(a) > > 1077467584 > >>>>id(b) > > 134536516 Actually, this code doesn't contradict what I said at all. I said that None (and only None) was special-cased. > It really looks like the addresses are compared when objects are of different > types if there is no __cmp__ or __lt__ user made specification to compare > objects of different types. Use the source Luke! ;) Download it from CVS and take a look. The end of default_3way_compare: static int default_3way_compare(PyObject *v, PyObject *w) { ... /* None is smaller than anything */ if (v == Py_None) return -1; if (w == Py_None) return 1; /* different type: compare type names; numbers are smaller */ if (PyNumber_Check(v)) vname = ""; else vname = v->ob_type->tp_name; if (PyNumber_Check(w)) wname = ""; else wname = w->ob_type->tp_name; c = strcmp(vname, wname); if (c < 0) return -1; if (c > 0) return 1; /* Same type name, or (more likely) incomparable numeric types */ return ((Py_uintptr_t)(v->ob_type) < ( Py_uintptr_t)(w->ob_type)) ? -1 : 1; } So it looks like Python uses the type name. Testing this: py> A = type('A', (object,), {}) py> Z = type('Z', (object,), {}) py> lst = [str('a'), dict(b=2), tuple(), Z(), A()] py> [type(o).__name__ for o in lst] ['str', 'dict', 'tuple', 'Z', 'A'] py> sorted(type(o).__name__ for o in lst) ['A', 'Z', 'dict', 'str', 'tuple'] py> sorted(lst) [<__main__.A object at 0x011E29D0>, <__main__.Z object at 0x011E29F0>, {'b': 2}, 'a', ()] Yup. Looks about right. (Note that the source code also special-cases numbers...) So, the order is consistent, but arbitrary, just as Fredrik Lundh pointed out in the documentation. Steve From francis.girard at free.fr Thu Jan 27 16:30:57 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 27 Jan 2005 22:30:57 +0100 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: <200501272230.57840.francis.girard@free.fr> Very complete explanation. Thank you Francis Girard Le jeudi 27 Janvier 2005 22:15, Steven Bethard a ?crit?: > Francis Girard wrote: > > I see. There is some rule stating that all the strings are greater than > > ints and smaller than lists, etc. > > Yes, that rule being to compare objects of different types by their type > names (falling back to the address of the type object if the type names > are the same, I believe). Of course, this is arbitrary, and Python does > not guarantee you this ordering -- it would not raise backwards > compatibility concerns to, say, change the ordering in Python 2.5. > > > What was the goal behind this rule ? > > I believe at the time, people thought that comparison should be defined > for all Python objects. Guido has since said that he wishes the > decision hadn't been made this way, and has suggested that in Python > 3.0, objects of unequal types will not have a default comparison. > > Probably this means ripping the end off of default_3way_compare and > raising an exception. As Fredrik Lundh pointed out, they could, if they > wanted to, also rip out the code that special-cases None too. > > Steve From steve at holdenweb.com Fri Jan 21 12:13:40 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Jan 2005 12:13:40 -0500 Subject: Zen of Python In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> Message-ID: Skip Montanaro wrote: > Steve> The fact that a bright bunch like the Python developers didn't > Steve> realize that it would be sensible to have a local scope for the > Steve> list comprehension variable is a perfect demonstration of that > Steve> point. > > Actually, I seem to recall that the topic came up, but at the time the goal > was that list comprehensions be semantically the same as for loops, so the > fact that the loop variable survived to pollute the namespace was deemed > okay. > > Skip > Thanks, Skip. I remember the discussions on python-dev, but I don't think that invalidates my point. I wasn't suggesting nobody realized there would be name-droppings, simply that nobody realized that a later goal of namespace purity would take priority over the initial one of for-loop compatibility. Similar issues surrounded nested scopes, if I remember, and even there the jury's still out. Which is why I "accused" Paul Rubin of requiring psychic powers from language developers when he said "So once we can see where it's going, why not proceed to the finish line immediately instead of bothering with the intermediate steps?" we-can't-always-see-where-we're-going-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From mcfletch at rogers.com Fri Jan 21 20:23:58 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 21 Jan 2005 20:23:58 -0500 Subject: Class introspection and dynamically determining function arguments In-Reply-To: <41f18d10.1471646806@news.oz.net> References: <41f18d10.1471646806@news.oz.net> Message-ID: <41F1AB2E.7080902@rogers.com> >On Thu, 20 Jan 2005 11:24:12 -0000, "Mark English" wrote: > > > >>I'd like to write a Tkinter app which, given a class, pops up a >>window(s) with fields for each "attribute" of that class. The user could >>enter values for the attributes and on closing the window would be >>returned an instance of the class. The actual application I'm interested >>in writing would either have simple type attributes (int, string, etc.), >>or attributes using types already defined in a c-extension, although I'd >>prefer not to restrict the functionality to these requirements. >> >> Hmm, I missed the original post, but I'll jump in anyway: This sounds a heck of a lot like a property-editing system. When creating a property-modeled system, the best approach is normally to use something that actually models the properties, rather than trying to guess at the metadata involved by poking around in an arbitrarily structured object. My BasicProperty system allows for this kind of interaction (property-sheets) using wxPython (rather than Tkinter) when using wxoo. You declare classes as having a set of data-properties (which can have defaults or not, constraints or not, restricted data-types or not, friendly names or not, documentation or not). Normally you create these classes as subclasses of a class that knows how to automatically assign __init__ parameters to properties, and knows how to tell (e.g.) wxoo about the properties of the class. Those same property classes also allow for editing properties of database rows in PyTable, but that isn't likely relevant to your case. We've also used them internally to create a rather large web-based property-editing mechanism (applied to such databases), but again, not really relevant to the case at hand. Anyway, if you aren't interested in BasicProperty for this task; another project on which I work, PyDispatcher provides fairly robust mechanism (called robustApply) for providing a set of possible arguments and using inspect to pick out which names match the parameters for a function in order to pass them in to the function/method/callable object. That said, doing this for __init__'s with attribute values from an object's dictionary doesn't really seem like the proper way to approach the problem. Good luck, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From macrocosm at fastmail.fm Sun Jan 9 23:13:04 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Sun, 09 Jan 2005 23:13:04 -0500 Subject: Python Operating System??? In-Reply-To: <7x6526otw3.fsf@ruckus.brouhaha.com> References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> Message-ID: <41E200D0.6010402@fastmail.fm> Paul Rubin wrote: >"Roose" writes: > > > ... > >>Upon reading back in the thread I see that you mean compiled Lisp, >>no? I was thinking that there would be a Lisp interpreter in a >>kernel, which afaik doesn't exist. >> >> > >Yes, compiled Lisp. There are Python compilers too.\ > > ??? You mean like Pyrex or some such? I wouldn't exactly call these "Python" compilers, as that kind of obscures some underlying (critical) facts. >>In any case, as I said before I don't think it is impossible, just a >>poor engineering decision and I don't see the rationale behind it. >> >> > >I don't see a convincing case against writing an OS even in >interpreted Python, though of course I'd want it to be compiled if >possible. > >What do you think OS's do, that Python wouldn't be suitable for? Your >examples of task switching and virtual memory are unconvincing. Those >just require setting up some suitable tables and then calling a >low-level routine to poke some CPU registers. File systems can be >more performance intensive, but again, in those, much of the cpu drain >can be relegated to low-level routines and the complexity can be >handled in Python. > > Correct. From rmemmons at member.fsf.org Sat Jan 8 11:31:05 2005 From: rmemmons at member.fsf.org (Rob Emmons) Date: Sat, 08 Jan 2005 10:31:05 -0600 Subject: The best way to do web apps with Python? References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: > > > > > > > >
What is Just FYI -- the post you posted was in HTML -- you might want to avoid this in the future. 99% of all posts to news groups are in text, not html. Html is hard for everyone to read with normal news readers and not usually of any extra value. It's also more of a security risk to read it -- because there is more potential for exploitation. Anyway, just thought I'd mention it if you didn't know. Take care, Rob From aorfanakos at gmail.com Sun Jan 30 21:58:10 2005 From: aorfanakos at gmail.com (Aggelos I. Orfanakos) Date: 30 Jan 2005 18:58:10 -0800 Subject: Regarding exception handling In-Reply-To: References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> Message-ID: <1107140290.363099.273690@c13g2000cwb.googlegroups.com> Good point, but with your way, if "s = ... # socket opens" fails, then nothing will catch it. What I usually do is what I wrote above (place it below the 2nd try), and when attempting to close it, first use an if like: "if locals().has_key('s'):". From kartic.krishnamurthy at gmail.com Tue Jan 25 15:05:54 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 25 Jan 2005 12:05:54 -0800 Subject: Import from database In-Reply-To: References: <1106587145.067483.14710@z14g2000cwz.googlegroups.com> Message-ID: <1106681053.863328.261670@f14g2000cwb.googlegroups.com> Steve, Hmmm... Yes, I see what you are saying. Could you post your create table statement so that I can create a db and play around with dbimport? Thanks, --Kartic From foo at bar.com Sun Jan 23 20:29:23 2005 From: foo at bar.com (Steve Menard) Date: Sun, 23 Jan 2005 20:29:23 -0500 Subject: Help on project, anyone? In-Reply-To: <35ienhF4lu88lU1@individual.net> References: <35ienhF4lu88lU1@individual.net> Message-ID: <5cYId.2514$zV3.523375@wagner.videotron.net> Georg Brandl wrote: > Hello, > > to train my Python skills I am looking for some project I can contribute > to. I learned Python about one year ago, and had already some > programming background behind (I contributed to SharpDevelop for > instance), so I'm not the complete newbie. > > About myself: I'm a 20 year old German with strong interests in > programming and, of course, especially in Python (I love it...). > > Does anyone run, or participate in, a project looking for fellow > programmers? I don't have a special area of interest, well, perhaps web > programming... > > Thanks, > Georg You know what I would do? I would go on Sourceforge. Try to find a project that seems interestingto you. and then contact the Maintainer see if you can help. Many project also advertise the kind of help they need. -- Steve Menard -------------------- Maintainer of http://jpype.sourceforge.net From bokr at oz.net Sat Jan 8 06:31:08 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 08 Jan 2005 11:31:08 GMT Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> Message-ID: <41dfc018.305122743@news.oz.net> On Sat, 08 Jan 2005 16:42:16 +1000, Nick Coghlan wrote: >Nick Coghlan wrote: >> It also allows the necessary but uninteresting setup for an expression >> to be moved "out of the way", bringing the expression that does the real >> work to prominence. > >Killer app for this keyword: > >class C(object): > > x = property(get, set) where: > def get(self): > return "Silly property" > def set(self, val): > self.x = "Told you it was silly" > Yes, that is cool and it _is_ an interesting idea. Are suites nestable? E.g., is this legal? x = term1 + term2 where: term1 = a*b where: a = 123 b = 456 term2 = math.pi Reminds me of some kind of weird let ;-) And, is the whole thing after the '=' an expression? E.g., x = ( foo(x) where: x = math.pi/4.0 ) where: def foo(x): print 'just for illustration', x or is this legal? for y in ([foo(x) for x in bar] where: bar = xrange(5) ): baz(y) where: def baz(arg): return arg*2 Not trying to sabotage the idea, really, just looking for clarification ;-) Regards, Bengt Richter From http Sun Jan 9 01:48:27 2005 From: http (Paul Rubin) Date: 08 Jan 2005 22:48:27 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> Message-ID: <7xr7kvm72c.fsf@ruckus.brouhaha.com> "Roose" writes: > But are you really going to write a virtual memory system in Python? Are > you going to write a file system, and a task scheduler in Python? Are you > going to have people write device drivers in Python? Do you know how virtual memory systems, file systems, task schedulers, and device drivers actually work? Have you ever written any of them? What exactly do you think the obstacles are to writing them in Python? I've written file systems in Python, and task schedulers in Javascript, and they were fine for their purposes. Virtual memory and device drivers are just more of the same. > > It doesn't prove anything of the sort. The Lisp hardware was needed > > for performance reasons, back in the day. > > OK, then give me an example of Lisp OS that runs on a PC. I would like to > install it on my PC tomorrow. Or maybe my Mac. That was your whole point, > originally, that since it could be done in Lisp, why not Python? Huh? That's a non-sequitur, nothing prevents you from running Lisp on your PC or Mac. The same issues issues that apply to OS code, also apply to user code. The Lisp machine hardware wasn't needed only to make the OS run fast. The Lisp machine was developed so that people could deploy large user-level applications written in Lisp, and the hardware was there to support those applications. And given such a good Lisp environment, there was no reason to think of writing the OS in anything other than Lisp. In fact, the reason the Lisp machine died off was because general purpose workstation hardware (and later, PC-class hardware) became fast enough to run Lisp applications without needing special purpose CPU's. That same PC hardware speed is what makes it possible to run user applications in Python. From cam.ac.uk at mh391.invalid Sun Jan 23 09:57:42 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 23 Jan 2005 14:57:42 +0000 Subject: is there better 32 clock() timing? In-Reply-To: References: Message-ID: Ray Schumacher wrote: > I have a need for a time.clock() with >0.000016 second (16us) accuracy. > The sleep() (on Python 2.3, Win32, at least) has a .001s limit. > > Are they lower/better on other's platforms? The meaning of time.clock() is entirely different on other platforms. See the documentation. You could probably get a slight speedup by using "from time import clock" and then just clock(). -- Michael Hoffman From http Mon Jan 10 20:13:17 2005 From: http (Paul Rubin) Date: 10 Jan 2005 17:13:17 -0800 Subject: Writing huge Sets() to disk References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <7xmzvgren6.fsf@ruckus.brouhaha.com> <7xis64ree5.fsf@ruckus.brouhaha.com> Message-ID: <7xr7ks3h02.fsf@ruckus.brouhaha.com> =?windows-1252?Q?Martin_MOKREJ=8A?= writes: > Yes, I'm. I still don't get what that acronym CLRS stands for ... :( CLRS = the names of the authors, Cormen, Leiserson, Rivest, and Stein, if I spelled those correctly. :) From golux at comcast.net Sat Jan 22 16:40:16 2005 From: golux at comcast.net (Stephen Waterbury) Date: Sat, 22 Jan 2005 16:40:16 -0500 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> Message-ID: <41F2C840.2050304@comcast.net> Steve Holden wrote: > It seems to me the misunderstanding here is that XML was ever intended > to be generated directly by typing in a text editor. It was rather > intended (unless I'm mistaken) as a process-to-process data interchange > metalanguage that would be *human_readable*. The premise that XML had a coherent design intent stetches my credulity beyond its elastic limit. From aaronwmail-usenet at yahoo.com Sat Jan 8 06:53:26 2005 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 8 Jan 2005 03:53:26 -0800 Subject: OT: google groups bug, or worse? In-Reply-To: <41df13b7.260993058@news.oz.net> References: <1105127965.616198.302710@z14g2000cwz.googlegroups.com> <41df13b7.260993058@news.oz.net> Message-ID: <1105185206.674806.155330@c13g2000cwb.googlegroups.com> Bengt Richter wrote: > What did you google with? Is this it? > http://groups-beta.google.com/groups?hl=en&ie=UTF-8&q=%22The+xsdbXML+framework+provides+a+flexible+and+well+defined+infrastructure%22&qt_s=Search+Groups That was my *reply* to one of the original posts using Google, which I faked up when I couldn't find it (posted using google). The two originals aren't there. hmmm. -- Aaron Watters === You'd be paranoid too, if everyone was out to get you! From steve at holdenweb.com Mon Jan 31 17:49:53 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 17:49:53 -0500 Subject: Want to meet any of these people? They are registered for PyCon In-Reply-To: References: Message-ID: Aahz wrote: > In article , > Steve Holden wrote: > >>Note that the sort order isn't perfect - I just sorted on the second >>"word" in each name. PyCon is a *great* place to meet people and discuss >>ideas. Hope to see you there. > > > Good thing I'm not coming this year, eh? ;-) If you mean specifically for sorting purposes, it would have put the null second name at the beginning just like you'd expect. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From bearophileHUGS at lycos.com Wed Jan 5 19:40:47 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 5 Jan 2005 16:40:47 -0800 Subject: Other notes References: <86r7l7sczp.fsf@guru.mired.org> Message-ID: <1104972047.050366.211670@f14g2000cwb.googlegroups.com> Thank you to all the gentle people that has given me some comments, and sorry for bothering you... Doug Holton: >This will also likely never appear in Python. I know, that's why I've defined it "wild". >Also, you might request the NetLogo and StarLogo developers to support Jython (in addition to Logo) scripting in their next version< I was suggesting the idea of adding the complex data structures of NetLogo (patches, etc) to the normal Python. ------------- Andrew Dalke: >(BTW, it needs to be 1 .. 12 not 1..12 because 1. will be interpreted as the floating point value "1.0".)< Uhm, I have to fix my ignorance about parsers. Cannot a second "." after the first tell that the first "." isn't in the middle of a floating point number? >In Pascal it works because you also specify the type and Pascal has an incr while Python doesn't.< The Pascal succ function (that works on chars and all integer types) is often useful (it's easy to define it in Python too). >>This may allow: assert 5 interval 9 == interval(5,9) >Maybe you could give an example of when you need this in real life?< Every time you have a function with 2 parameters, you can choose to use it infix. >Does this only work for binary or is there a way to allow unary or other n-ary (including 0-ary?) functions?< It's for binary functions only. For unary the normal fun(x) syntax is good enough, and for n-ary the sintax becomes unnecessary complex, and you can use the normal function syntax again. >But to someone with C experience or any language which derives its formatting string from C, Python's is easier to understand than your Pascal one.< You can be right, but "understanding" and "being already used to something" are still two different things :-) >A Python view is that there should be only one obvious way to do a task. Supporting both C and Pascal style format strings breaks that.< Okay. >I don't think Pascal is IEEE enough.< Well, if you assign that FP number inside the program (and not as a constant) Delphi 4 too gives a more "correct" answer ^_^ (I don't know/remember why there are such differences inside Delphi between constants and variables). >note also that the Pascal-style formatting strings are less capable than Python's,< I know... >though few people use features like< Right. >A real-life example would also be helpful here.< (I was parsing trees for Genetic Programming). People here can probably suggest me 10 alternative ways to do what I was trying to do :-) As list comprehensions, that suggestion of mine cannot solve new kinds of problems, it's just another way of doing things. >What does map(len, "Blah", level = 200) return?< Well: "c" == "c"[0][0][0][0][0][0] map(len, "blah") == [1, 1, 1, 1] So I think that answer is still [1, 1, 1, 1]. >You need to learn more about the Pythonic way of thinking of things. The usual solution for this is to have "level = None".< To Steven Bethard I've suggested an alternative syntax (using a level-ed flatten with a standard map command). >There's also tmPython.< Thank you, the screenshoots are quite nice :-) http://dkbza.org/11.0.html -------------- Steven Bethard: >Since I can't figure it out intuitively (even with examples), I don't think this syntax is any less inscrutable than '%.f'.< Well, I haven't given a textual explanation, but just few examples. >My suspicion is that you're just biased by your previous use of Pascal.< This is possible. >This packs two things into map -- the true mapping behaviour (applying a function to a list) and the flattening of a list.< Okay, then this is my suggestion for the syntax of an iterable xflatten: xflatten(sequence, level=-1, monadtuple=False, monadstr=True, safe=False]) - level allows to specify the mapping level: level=0 no flattening. level=1 the flattening is applied to the first and second level. Etc. And like in the indexing of lists: level=-1 (default) means the flattening is applied up to the leaves. level=-2 flattens up to pre-leaves. Etc. - monadtuple (default False) if True tuples are monads. - monadstr (default True) if False then strings with len>1 are sequences too. - safe (default False) if True it cheeks (with something like an iterative isrecursive) for recursive references inside the sequence. >(Also, Google for flatten in the python-list -- you should find a recent thread about it.)< I've discussed it too in the past :-) http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d0ba195d98f35f66/ >and that your second example gains nothing over< Right, but maybe with that you can unify the def and lambda into just one thing ^_^ >def foo(x): > globals()['y'] = globals()['y'] + 2 >Not exactly the same syntax, but pretty close. Thank you for this idea. >I'll second that. Please, "Bearophile", do us the courtesy of checking [...] before posting another such set of questions. While most of the people on this list are nice enough to answer your questions anyway, the answers are already out there for at least half of your questions, if you would do us the courtesy of checking first.< I've read many documents, articles and PEPs and, but I'm still new, so I've missed many things. I'm sorry... I'm doing my best. ----------- Terry J. Reedy >I also suggest perusing the archived PyDev (Python Development mailing list) summaries for the last couple of years (see python.org). Every two weeks, Brett Cannon has condensed everything down to a few pages.< Okay, thank you. Bear hugs, Bearophile From steve at holdenweb.com Sat Jan 22 10:34:08 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 22 Jan 2005 10:34:08 -0500 Subject: What YAML engine do you use? In-Reply-To: <41f1a3e6.1477492061@news.oz.net> References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> Message-ID: Bengt Richter wrote: > On Fri, 21 Jan 2005 12:04:10 -0600, "A.M. Kuchling" wrote: > > >>On Fri, 21 Jan 2005 18:30:47 +0100, >> rm wrote: >> >>>Nowadays, people are trying to create binary XML, XML databases, >>>graphics in XML (btw, I'm quite impressed by SVG), you have XSLT, you >>>have XSL-FO, ... . >> >>Which is an argument in favor of XML -- it's where the activity is, so it's >>quite likely you'll encounter the need to know XML. Few projects use YAML, >>so the chance of having to know its syntactic details is small. >> > > > I thought XML was a good idea, but IMO requiring quotes around > even integer attribute values was an unfortunate decision. I don't buy > their rationale of keeping parsing simple -- as if extracting a string > with no embedded space from between an equal sign and terminating white > space were that much harder than extracting the same delimited by double quotes. It isn't that much harder, but if there are two ways to do the same thing then effectively one of them has to become a special case, thereby complicating the code that has to handle it (in this case the parser). "There should be one (and preferably only one) ..." should be a familiar mantra around here :-) > The result is cluttering SVG with needless cruft around numerical graphics parameters. > > It seems to me the misunderstanding here is that XML was ever intended to be generated directly by typing in a text editor. It was rather intended (unless I'm mistaken) as a process-to-process data interchange metalanguage that would be *human_readable*. Tools that *create* XML are perfectly at liberty not to require quotes around integer values. > OTOH, I think the HTML XML spec is very readable, and nicely designed. > At least the version 1.0 spec I snagged from W3C a long time ago. > .... I see the third edition at http://www.w3.org/TR/REC-xml/ is differently styled, > (I guess new style sheets) but still pretty readable (glancing at it now). > > Regards, > Bengt Richter regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From max at alcyone.com Fri Jan 7 16:43:14 2005 From: max at alcyone.com (Erik Max Francis) Date: Fri, 07 Jan 2005 13:43:14 -0800 Subject: Notification of PEP Updates In-Reply-To: References: Message-ID: Nick Coghlan wrote: > I can't recall which thread this came up in, so I'm starting a new one. . . > > Barry Warsaw has kindly added a "peps" topic to the python-checkins mailing > list. If you want to be notified only when PEP's get updated, then subscribe to > python-checkins and edit your settings to select just the 'peps' topic. Maybe someone could roll this into an RSS feed? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis There's a reason why we / Keep chasing morning -- Sandra St. Victor From jepler at unpythonic.net Thu Jan 27 22:29:59 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 27 Jan 2005 21:29:59 -0600 Subject: tkinter: Can You Underline More Than 1 Char In A Menu Title In-Reply-To: References: Message-ID: <20050128032958.GA17445@unpythonic.net> On Thu, Jan 27, 2005 at 06:38:22AM -0500, Tim Daneliuk wrote: > Is it possible to underline more than a single character as I am doing > with the 'underline=0' above. I tried 'underline=(0,2)' but that didn't > work. No. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From gandalf at geochemsource.com Mon Jan 24 07:45:15 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Mon, 24 Jan 2005 13:45:15 +0100 Subject: wx.BoxSizer problem In-Reply-To: <48F31575-6BD2-11D9-9482-003065B11E84@leafe.com> References: <41F11AC1.6040108@geochemsource.com> <48F31575-6BD2-11D9-9482-003065B11E84@leafe.com> Message-ID: <41F4EDDB.3080807@geochemsource.com> >> My problem is that only one of the buttons is visible and that one is >> not expanded. (System: Windows, Python 2.3.4, wxPython 2.5.3) > > > Works as expected on Mac OS X 10.3.7, python 2.3.4, wxPython 2.5.2.8. Thanks. Probably the problem is with my bitmap (I used a bitmap instead of a button). Please do not spend more time on it - I'll handle. Best, Laci 2.0 From claird at lairds.us Mon Jan 17 15:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Mon, 17 Jan 2005 20:08:04 GMT Subject: PyChecker messages References: <1105983271.574296.37740@c13g2000cwb.googlegroups.com> Message-ID: In article <1105983271.574296.37740 at c13g2000cwb.googlegroups.com>, Ben Sizer wrote: >But you could use a dict of return values, or even just assigning a >different return value in each if clause. The end result is that you >have a single well-defined exit point from the function, which is >generally considered to be preferable. > Well, no; I'm trying to say exactly that there are times when "a dict of return values" only adds complexity. Or perhaps I'm missing a bet- way to code: def condition_label(): if x13.fluid_level() > lower_threshhold: return "OK" if user in restricted_list: return "Ask for help" if not current_time.in_range(beginning, end): return "Uncorrectable exception reported" ... When conditions live in a space with higher dimensionality than any handy immutable range, no dict-ification is a benefit. From mcfletch at rogers.com Mon Jan 24 10:35:58 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 24 Jan 2005 10:35:58 -0500 Subject: Weakref.ref callbacks and eliminating __del__ methods In-Reply-To: <1f7befae0501231720428ca3c@mail.gmail.com> References: <41F427EB.3000200@rogers.com> <1f7befae0501231720428ca3c@mail.gmail.com> Message-ID: <41F515DE.8000600@rogers.com> Tim Peters wrote: >[Mike C. Fletcher] > > >>I'm looking at rewriting parts of Twisted and TwistedSNMP to eliminate >>__del__ methods (and the memory leaks they create). >> >> >A worthy goal! > > Well, as of now it seems to have eliminated the last leaks in TwistedSNMP, and that's likely going to eliminate the last of our leaks in our products, so yes, I suppose it was :) . >A callback is strongly referenced from the weakref(s) containing it. > > Thanks. >It would really help to give a minimal example of self-contained >executable code. I'm not sure how you're using this code, and >guessing takes too long. > > Sorry about that. I was expecting a theoretical problem, not a practical one, so didn't think to provide a practical example. >The "2" there is important, just because this is an interactive >session. The point of it was to stop `_` from holding a reference to >the created weakref. In your code > > weakref.ref( self, self.close ) > >the weakref itself becomes trash immediately after it's created, so >the weakref is thrown away entirely (including its strong reference to >self.close, and its weak reference to self) right after that line >ends. Of course callbacks aren't *supposed* to be called when the >weakref itself goes away, they're supposed to be called when the thing >being weakly referenced goes away. So this all looks vanilla and >inevitable to me -- the callback is never invoked because the weakref >itself goes away long before self goes away. > > Alex already scooped you on this "smack yourself on the head, Mikey". I was assuming the weakref object was a proxy for a reference in an internal structure; I was expecting a list of weak references that was nothing but a series of functions to call after finalising the object. My bad. >I'm pretty sure it's just because there's nothing here to keep the >weakref itself alive after it's created. You could try, e.g., > > self.wr = weakref.ref( self, self.close ) > >to keep it alive, but things get fuzzy then if self becomes part of >cyclic trash. > > Yes, so it requires an external storage mechanism and code to clean that up... ick. __del__ looks cleaner and cleaner by comparison. You'd think I would have noticed the huge tables of weakref objects in PyDispatcher as I was working in there... >>I can work around it in this particular case by defining a __del__ on >>the Closer, but that just fixes this particular instance (and leaves >>just as many __del__'s hanging around). I'm wondering if there's a >>ready recipe that can *always* replace a __del__'s operation? >> >> > >In the presence of cycles it gets tricky; there's a lot of >more-or-less recent words (less than a year old ) about that on >python-dev. It gets complicated quickly, and it seems nobody can make >more time to think about it. > > Sigh, guess I should stop listening to rumours just because they are saying something about that for which I yearn. >>I know I heard a rumour somewhere about Uncle Timmy wanting to eliminate >>__del__ in 2.5 or thereabouts, >> >> > >Python 3 at the earliest. That's the earliest everything nobody can >make time for lands <0.5 wink>. > > Well, we darn well better solve it by then! Don't want memory leaks when we're hard-wired into someone's brain. >There are unresolved issues about how to get all this stuff to work >sanely. The driving principle behind cyclic-trash weakref endcases >right now is "do anything defensible that won't segfault". > >I'll note that one fairly obvious pattern works very well for weakrefs >and __del__ methods (mutatis mutandis): don't put the __del__ method >in self, put it in a dead-simple object hanging *off* of self. Like >the simple: > >class BTreeCloser: > def __init__(self, btree): > self.btree = btree > > def __del__(self): > if self.btree: > self.btree.close() > self.btree = None > > Yes, this was the "work around" I'd implemented (well, with __call__ instead and del just calling it). Of course, that didn't actually eliminate any __del__ methods, but oh well, if we're not losing those until 3.x it doesn't really matter :) . The fix for the Deferred in Twisted got a little hideous (there the __del__ is poking around into lots of different attributes of the Deferred. To hack that I created a descriptor class that forwards a variable to the held object and wrapped each of the needed variables in one of those... I'm going to have to find something a little less baroque if I'm going to get it into Twisted... really, it doesn't look like any of it's necessary, it's just logging an error if the Deferred ended on a Failure. Something should be done though, leaking memory from a core object in the framework is just a PITA. >When a weakref and its weak referent are both in cyclic trash, Python >currently says "the order in which they die is undefined, so we'll >pretend the weakref dies first", and then, as at the start of this >msg, the callback is never invoked. > So external storage of a weakref is basically a requirement to make it useful. Hmm. >The problem this avoids is that >the callback may itself be part of cyclic trash too, in which case >it's possible for the callback to resurrect anything else in cyclic >trash, including the weakly-referenced object associated with the >callback. But by hypothesis in this case, that object is also in >cyclic trash, and horrible things can happen if a partially destructed >object gets resurrected. > > Reasonable I suppose. >So the real rule right now is that, if you want a guarantee that a >callback on a weakly referenced object gets invoked, you have to write >your code to guarantee that the referent becomes trash before its >weakref becomes trash. (And note that if you do, the callback >necessarily will be alive too, because a weakref does in fact hold a >strong reference to its callback.) > > Guess I'll go back to the sub-object approach for all things and merely dream of a far off weakref utopia free of all __del__ methods. Thanks, Tim, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From fredrik at pythonware.com Sat Jan 22 05:25:08 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 11:25:08 +0100 Subject: list unpack trick? References: <1gqsalx.4ip95k18168r0N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: >> or (readable): >> >> if len(list) < n: >> list.extend((n - len(list)) * [item]) > > I find it just as readable without the redundant if guard -- just: > > alist.extend((n - len(alist)) * [item]) the guard makes it obvious what's going on, also for a reader that doesn't know exactly how "*" behaves for negative counts. once you've seen the "compare length to limit" and "extend", you don't have to parse the rest of the statement. From a at b.c Tue Jan 4 15:19:44 2005 From: a at b.c (Doug Holton) Date: Tue, 04 Jan 2005 14:19:44 -0600 Subject: Python evolution: Unease In-Reply-To: <98WdnVGqi-yaUkfcRVn-tw@giganews.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> Message-ID: Istvan Albert wrote: > Doug Holton wrote: > >> application is so important that I expect Python 3000 will have >> optional type declarations integrated into the argument list." > > > I think that *optional* part of the "optional type declaration" > is a myth. > > It may be optional in the sense that the language will > accept missing declarations but as soon as the feature > is available it will become "mandatory" to use it > (peer pressure, workplace practices). I didn't write that, Guido did. I agree with you, and others who have made the same point you made. I would have to think Guido is already aware of this issue (keep python simple). I'm not sure what his motivations are for wanting to add static typing to python, not that I'm against it. It doesn't matter a whole lot either way since Python 3000 is still years away and you can already do static typing now with Pyrex or boo, as well as many other things that people have requested for python from little things like ++i to bigger features like multi-line anonymous methods/closures. From roy at panix.com Sat Jan 1 09:27:30 2005 From: roy at panix.com (Roy Smith) Date: Sat, 01 Jan 2005 09:27:30 -0500 Subject: what is lambda used for in real code? References: Message-ID: In article , Adam DePrince wrote: > We can operate on every other class without having to involve the > namespace, why should functions be any different? def is a weird beast. It does more than just bind a lambda to a name, it also alters the function so it knows its own name. For example, the following: -------------- def foo (): print "I am foo" bar = foo def foo (): print "I am foo's evil twin" foo() print foo bar() print bar baz = lambda : "I am lambda" print baz print baz() -------------- will print: I am foo's evil twin I am foo at 0x363770> I am lambda From Jared.Cohen at noaa.gov Wed Jan 5 17:22:21 2005 From: Jared.Cohen at noaa.gov (Jared Cohen) Date: Wed, 05 Jan 2005 17:22:21 -0500 Subject: Please help -- Pmw PanedWidget inside ScrolledFrame Message-ID: <41DC689D.5010305@noaa.gov> I'm trying to use a Pmw.ScrolledFrame which contains a PanedWidget. But I can't get the PanedWidget to expand to fill the interior frame. It expands fine if I just grid it into the toplevel window; and when I tried gridding DIFFERENT widgets into the ScrolledFrame, they expanded just fine. So both the ScrolledFrame and PanedWidget seem to work OK on their own, but when I try to put one inside the other, something goes haywire. Can anyone help please? -------------- next part -------------- An HTML attachment was scrubbed... URL: From daranrife at yahoo.com Fri Jan 28 19:13:18 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 16:13:18 -0800 Subject: LinearAlgebra incredibly slow for eigenvalue problems In-Reply-To: References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> <1106952951.834888.65430@f14g2000cwb.googlegroups.com> Message-ID: <1106957598.136667.45430@z14g2000cwz.googlegroups.com> Hi David, Yes, when Numeric compiles it does look like the linking is being done properly. I captured the build to a file and see a few lines similar to: gcc -pthread -shared build/temp.linux-i686-2.4/Src/lapack_litemodule.o -L/d2/lib/atlas -llapack -lptcblas -lptf77blas -latlas -lg2c -o build/lib.linux-i686-2.4/lapack_lite.so I checked the files in build/lib.linux-i686-2.4 and none have dependencies on ATLAS. When I run Python interpreter with: >>> import Numeric >>> Numeric.__file__ I get the answer I expect. I am totall baffled. Any other ideas? Thanks for your help, Daran From peter at engcorp.com Sun Jan 23 19:00:18 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jan 2005 19:00:18 -0500 Subject: OT: problems mirroring python-list to c.l.py? In-Reply-To: References: <1d6cdae305012310535980e82d@mail.gmail.com> <20050123190637.GA4820@grulic.org.ar> Message-ID: Daniel Bickett wrote: > John Lenton wrote: >>>On Sun, Jan 23, 2005 at 01:53:52PM -0500, Daniel Bickett wrote: >>>>Is there a reason that Google Groups isn't mirroring python-list >>>>exactly like it used to, or is it simply a conspiracy I'm not in on? >>> >>>You should not ask this kind of question in a public forum, >> >>and *you* should know better than to go around flapping your mouth >>like that. > > Now I'm further confused, because I don't know what you quoted, but it > isn't on the mailing list and it isn't on c.l.py :) Maybe I should > give up trying to figure these things out. For what it's worth, I'm seeing the same behaviour as what you (Daniel) are seeing, and I read the group through comp.lang.python via NTTP, not via the mail-based python-list or Google Groups. > You didn't include a name at the beginning of your citation... Who had > the audacity to take my joke seriously? ;-) Apparently somebody who doesn't understand that unlike most other public fora, comp.lang.python is "special" in that it is mirrored to and from the mailing list, and that there is no other more appropriate place to ask such a question (at least until it's apparent that it is a problem with a specific part of this system, rather than being entirely unclear just _what_ the problem is). -Peter From iddwb at moroni.pp.asu.edu Thu Jan 13 20:26:09 2005 From: iddwb at moroni.pp.asu.edu (David Bear) Date: Fri, 14 Jan 2005 01:26:09 +0000 (UTC) Subject: query python env Message-ID: How does one query the python environment, ie pythonhome, pythonpath, etc. also, are there any HOWTO's on keeping multiple versions of python happy? From jdhunter at ace.bsd.uchicago.edu Mon Jan 31 11:01:15 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 31 Jan 2005 10:01:15 -0600 Subject: barchart for webpage needed In-Reply-To: (dimitri pater's message of "Mon, 31 Jan 2005 16:54:52 +0100") References: Message-ID: >>>>> "dimitri" == dimitri pater writes: dimitri> Hello, I am looking for a Python tool to create graphs dimitri> and charts on a webpage. Chartdirector is too expensive dimitri> for me. A simple script for creating a barchart should be dimitri> sufficient as a starting point. matplotlib does barcharts, errorbars, stacked bars, and more (and its free). See the following links # matplotlib with web app servers: http://matplotlib.sourceforge.net/faq.html#APPSERVER # a barchart screenshot with example code http://matplotlib.sourceforge.net/screenshots.html#barchart_demo # the bar command for making bar charts http://matplotlib.sourceforge.net/matplotlib.pylab.html#-bar JDH From jzgoda at gazeta.usun.pl Tue Jan 25 16:06:21 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Tue, 25 Jan 2005 22:06:21 +0100 Subject: snakespell and myspell In-Reply-To: <1106657932.301181.150050@z14g2000cwz.googlegroups.com> References: <1106657932.301181.150050@z14g2000cwz.googlegroups.com> Message-ID: Fuzzyman wrote: > I'm looking to implement a plugin spell checker. > > I'm probably going to go with PyEnchant, as it looks to be the most > promising currently maintained spell checker. > > I just wondered if anyone knew what happened to snakespell and myspell. > Both seem to have dissapeared from the net. People have reported good > results from both - and it seems a shame to lose them. Well, myspell-python is no longer maintained, original author resigned some time ago and I didn't found anybody who would like to take responsibility on this package. I provide myspell-1.0 download from my project page at BerliOS (http://developer.berlios.de/projects/jpa/), but I do not maintain this package. If you look for spell-checking library, I'd consider using python binding for aspell, available at http://www.republika.pl/wmula/proj/aspell-python/ (currently I'm rewriting my program to use python-aspell). This library is actively maintained and Wojtek Mula is active member of Polish Python community. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From aut_gbarros at uolinc.com Thu Jan 27 09:04:41 2005 From: aut_gbarros at uolinc.com (Gabriel Cosentino de Barros) Date: Thu, 27 Jan 2005 12:04:41 -0200 Subject: Point of Sale Message-ID: <2814F26DA6908F41927A81C410C4991A02079C72@siamun.server.bl.corp.intranet> Hi, i'm curently doing a POS. But mine is a small scale and stand alone. Are you planing on developing in house and then opening? develop at open or simple use open source tools and keep it closed? I'm going to post my progress at source forge next week when i finish proof reading the design docs. i'm curently focused in the HCI layer (primarily using only plain tk) and haven't gave much tought to the 'external' stuff, like integrating wire money cards and such Gabriel -----Original Message----- From: Andreas Pauley [mailto:andreasp at qbcon.com] Sent: quinta-feira, 27 de janeiro de 2005 11:08 To: python-list at python.org Subject: Point of Sale Hi, My company has given me a rather cool project: I have to provide them with an open-source python-based point-of-sale / cash register system that can integrate with their existing ERP backend. The project will include development to ensure that the features they require are included in the open-source POS system. Can you recommend anything that I can use? Regards, Andreas -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From ola.natvig at infosense.no Wed Jan 26 11:06:27 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Wed, 26 Jan 2005 17:06:27 +0100 Subject: access private field in python 2.4 In-Reply-To: <1106754371.637295.82160@z14g2000cwz.googlegroups.com> References: <1106754371.637295.82160@z14g2000cwz.googlegroups.com> Message-ID: <4prkc2-ini.ln1@pluto.i.infosense.no> ajikoe at gmail.com wrote: > Hello, > I'm new to python, > How can I access private field in python. > > thanks > In python there realy are not private fields. There are those fields that you start with a double underline (__) theese are translated to ___ Withouth the < and > markers, but there are not good practice to access theese through that name. -- -------------------------------------- Ola Natvig infoSense AS / development From aurora00 at gmail.com Sat Jan 22 13:03:27 2005 From: aurora00 at gmail.com (aurora) Date: Sat, 22 Jan 2005 10:03:27 -0800 Subject: list unpack trick? References: Message-ID: Thanks. I'm just trying to see if there is some concise syntax available without getting into obscurity. As for my purpose Siegmund's suggestion works quite well. The few forms you have suggested works. But as they refer to list multiple times, it need a separate assignment statement like list = s.split('=',1) I am think more in the line of string.ljust(). So if we have a list.ljust(length, filler), we can do something like name, value = s.split('=',1).ljust(2,'') I can always break it down into multiple lines. The good thing about list unpacking is its a really compact and obvious syntax. On Sat, 22 Jan 2005 08:34:27 +0100, Fredrik Lundh wrote: ... >> So more generally, is there an easy way to pad a list into length of n >> with filler items appended >> at the end? > > some variants (with varying semantics): > > list = (list + n*[item])[:n] > > or > > list += (n - len(list)) * [item] > > or (readable): > > if len(list) < n: > list.extend((n - len(list)) * [item]) > > etc. > > From benn at cenix-bioscience.com Wed Jan 12 04:48:58 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Wed, 12 Jan 2005 10:48:58 +0100 Subject: Game programming in Python In-Reply-To: References: Message-ID: <41E4F28A.3000806@cenix-bioscience.com> Baza wrote: >I'm looking for any books or on-line resources on game programming using >Python. Does anyone have any advice? >-- >Computer says, 'no' > > > > Like the end quote : eh, eh, eeehhhhhh!! -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From steven.bethard at gmail.com Wed Jan 26 18:02:47 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 16:02:47 -0700 Subject: inherit without calling parent class constructor? In-Reply-To: References: Message-ID: Christian Dieterich wrote: > On D? C?adaoin, Ean 26, 2005, at 13:45 America/Chicago, Steven Bethard > wrote: > >> Note that: >> @deco >> def func(...): >> ... >> is basically just syntactic sugar for: >> def func(...): >> ... >> func = deco(func) > > > Oh, I learned something new today :-) Nice thing to know, these > descriptors. Just a note of clarification: The @deco syntax is called *decorator* syntax. Classes with a __get__ method are called *descriptors*. But yes, they're both nice things to know. ;) Steve From mb at muenster.de Thu Jan 13 16:35:51 2005 From: mb at muenster.de (Martin Bless) Date: Thu, 13 Jan 2005 21:35:51 GMT Subject: Pyrex-0.9.3: definition mismatch with distutils of Python24 Message-ID: <41e6e1c5.8718906@news.muenster.de> Now that I've got my extension building machine using the VC++ Toolkit 2003 up and running I'm keen on using Pyrex (Pyrex-0.9.3, Python-2.4.0). But the definition of the swig_sources() method seems to have changed. When I try to build the examples from Pyrex I get a TypeError: c:\Pyrex-0.9.3\Demos> python Setup.py build_ext --inplace running build_ext building 'primes' extension [...] File "C:\Python24\lib\distutils\command\build_ext.py", line 442, in build_extension sources = self.swig_sources(sources, ext) TypeError: swig_sources() takes exactly 2 arguments (3 given) I can see that Pyrex.Distutils.build_ext.py subclasses distutils.command.build_ext.build_ext, and the number of arguments of the swig_sources method seems to have changed. Pyrex uses: def swig_sources (self, sources): whereas the distutils use: def swig_sources (self, sources, extension): If I just add the "extension" arg to the Pyrex definitions everything seems to work. But I have to admit that I don't really know what I'm doing here and I feel sorry I can't contribute more than just reporting the error. mb - Martin Bless From aleaxit at yahoo.com Sat Jan 22 08:10:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 14:10:36 +0100 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> <7xu0p9lk4h.fsf@ruckus.brouhaha.com> Message-ID: <1gqsn7o.qyazai1nh7smmN%aleaxit@yahoo.com> Paul Rubin wrote: > Dave Benjamin writes: > > Can we get a show of hands for all of those who have written or are > > currently maintaining code that uses the leaky listcomp "feature"? > > It's really irrelevant whether anyone is using a feature or not. If > the feature is documented as being available, it means that removing > it is an incompatible change that can break existing code which > currently conforms to the spec. If the "feature" is described as the > bug that it is, anything that relies on it is nonconformant. > > I do remember seeing some cute tricks (i.e. capable of becoming > idioms) that depend on the leakage. Sure, ``if [mo for mo in [myre.search(line)] if mo]: use(mo)`` and the like, used to simulate assign-and-test. No doubt maintaining backwards compat with this kind of horrors means listcomps need to keep leaking until Python 3.0, alas. But hopefully no farther... Alex From daranrife at yahoo.com Fri Jan 28 14:31:44 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 11:31:44 -0800 Subject: Installing Numeric with ATLAS and LAPACK In-Reply-To: References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> Message-ID: <1106940704.164253.134630@c13g2000cwb.googlegroups.com> Thanks John. Those are the steps I followed, and to no avail. Interestingly, I downloaded and installed SciPy, and ran the same eigenvector problem. SciPy greatly speeds up the calculation...was 1.5 hours using Numeric, now only 15 min with SciPy. Unfortunately, SciPy only solves ordinary and generalized eigenvalue problems of a square matrix. They do not test to see if the matrix is symmetric, then call the appropriate routine from LAPACK. Daran From littlejohn.75NOSPAM at news.free.fr.invalid Mon Jan 31 11:41:44 2005 From: littlejohn.75NOSPAM at news.free.fr.invalid (F. Petitjean) Date: 31 Jan 2005 16:41:44 GMT Subject: Crude statistics on the standard library Message-ID: <41fe5fc7$0$29873$636a15ce@news.free.fr> I have written a script to find the modules which export the largest number of names. The gc.getreferrers(*objs) function gives also an idea of the dependencies between the modules. The code (statsmod.py) : #!/usr/bin/env python # -*- coding: latin-1 -*- """ statsmod.py module rudimentaire de statistiques des noms export?s par les modules de la biblioth?que standard """ import sys import gc from glob import glob import os, os.path from os.path import basename def browse_stdlib(): """browse the standard library returns list of names of modules """ pyver = 'python%s' % (sys.version[:3],) pyglob = os.path.join(sys.prefix, 'lib', pyver, '*.py') # lpys = glob(pyglob) if os.path.exists(os.path.join(sys.prefix, 'Lib', 'os.pyc')): pyglob = os.path.join(sys.prefix, 'Lib', '*.py') lpys = map(basename, glob(pyglob)) names = [ name[:-3] for name in lpys ] # remove some obsolete modules ('this' + DeprecationWarning) for dontparse in ("this", "tzparse", 'FCNTL', 'posixfile', 'pre', 'regsub', 'statcache', 'TERMIOS', 'xmllib'): try: names.remove(dontparse) except ValueError: continue return names def exports(names, with_modules=False): """imports all the modules in names returns a 2-tuple : - list of tuples : NumberOfExternalNames len(dir(module)) nodname - list of modules (if with_modules is true) """ res = [] add = res.append _all = [] modules = [] # this simple minded method (__import__) doesn't include sys ? for name in names: print name, " ", try: module = __import__(name, globals(), locals(), _all) ldir = len(dir(module)) if hasattr(module, '__all__'): nexports = len(module.__all__) else: nexports = ldir add((nexports, ldir, name)) if with_modules: modules.append(module) # del sys.modules[name] except ImportError, msg: print "cannot import module", name, msg return res, modules def pm_histo(values, nbins=20): """a poor man histogram Return a list of nbins tuples (left, right) such that the union of the consecutive ranges(left, right) is range(len(values)+1) values[k] """ vlo, vhi = values[0], values[-1]+1 nbins = min(nbins, vhi-vlo) deltax = int((vhi - vlo)/nbins) assert deltax > 0 ranges = [] add = ranges.append left = 0 # left index first bin val = vlo + deltax while val < vhi: for right in range(left, len(values)): if values[right] > val: break add((left, right)) left = right val = val + deltax return ranges def basic_stat(seq): """basic statistics on the values in seq Returns NumberOfItems, MeanValue, StandardDeviation, variance """ s0, s1, s2 = 0, 0, 0 for indx, item in enumerate(seq): s0 = s0 + 1 # seq may be an iterable without len Xi = float(item) if not indx: Xmin = Xi s1 = s1 + Xi s2 = s2 + Xi*Xi # s0 = len(seq) # sum of 0 order Xm = s1/s0 # mean value Xmax = Xi median = (Xmin + Xmax)*0.5 variance = (s2 - s0*Xm*Xm)/s0 # ecart-type ** 2 import math stddev = math.sqrt(variance) # ecart-type return s0, Xmin, Xmax, median, Xm, stddev # , variance if __name__ == '__main__': names = ['cStringIO', 'sys', 'gc' ] names.extend(browse_stdlib()) freqs, modules = exports(names, True) print # exports() prints without new line print "%d imported modules and %d in sys.modules" % ( len(freqs), len(sys.modules)) print "number of unreachable objects", gc.collect() simples = [] while modules: module = modules.pop() # print module.__name__, sys.getrefcount(module) items = gc.get_referrers(module) litems = len(items) if litems <= 2: simples.append(module.__name__) del sys.modules[module.__name__], module, items else: print "referrers of %s" % (module.__name__,) for item in items[2:]: name = item.get('__file__', 'unknown') if name.endswith('__init__.pyc'): pslash = name.rfind(os.sep) pslash = name[:pslash].rfind(os.sep) name = name[pslash+1:][:-4] # strip .pyc elif name.endswith('__init__.py'): pslash = name.rfind(os.sep) pslash = name[:pslash].rfind(os.sep) name = name[pslash+1:][:-3] # strip .py elif name.endswith('.pyc'): pslash = name.rfind(os.sep) name = name[pslash+1:][:-4] # strip .pyc elif name.endswith('.py'): pslash = name.rfind(os.sep) name = name[pslash+1:][:-3] # strip .py print name, del module, items print print "number of unreachable objects", gc.collect() print "new length of sys.modules %d" % (len(sys.modules),) print "%d simple modules" % (len(simples),) freqs.sort() values = [item[0] for item in freqs ] # print freqs[-2:] # supprim?s # del values[-2:] ranges = pm_histo(values) ranges2 = [ item for item in ranges if item[1] > item[0]] limite = ranges[0][1] + 1 # first bin rangesbas = pm_histo(values[:95], 6) print rangesbas lbin = 11 start = 0 print "St Nb. min max median average stddev" fmt = "%3d%3d%6.1f%6.1f%8.3f%8.3f%8.3f" while start < len(values): res = (start,) + basic_stat(values[start:start+lbin]) print fmt % res start = start + lbin print "modules with a lot of external names :" for item in freqs[140:]: print item Parts of output of python -i statsmod.py (python2.4 windows) repr rexec rfc822 rlcompleter cannot import module rlcompleter No module named readline robotparser sched ... etc ... whrandom C:\Python24\lib\whrandom.py:38: DeprecationWarning: the whrandom module is deprecated; please use the random module DeprecationWarning) xdrlib xmlrpclib zipfile ... etc ... _threading_local __future__ __phello__.foo Hello world... cannot import module __phello__.foo No module named foo cannot import module __phello__.foo No module named foo number of unreachable objects 0 referrers of __future__ referrers of __future__ ... etc ... referrers of socket asynchat asyncore BaseHTTPServer SocketServer urllib httplib ftplib imaplib nntplib poplib smtpd smtplib Utils ... etc ... referrers of cStringIO logging\__init__ xmlrpclib number of unreachable objects 564 new length of sys.modules 154 121 simple modules [(0, 39), (39, 58), (58, 74), (74, 79), (79, 91), (91, 94)] St Nb. min max median average stddev 0 11 1.0 1.0 1.000 1.000 0.000 11 11 1.0 2.0 1.500 1.545 0.498 22 11 2.0 2.0 2.000 2.000 0.000 33 11 2.0 3.0 2.500 2.455 0.498 44 11 3.0 3.0 3.000 3.000 0.000 55 11 3.0 4.0 3.500 3.727 0.445 66 11 4.0 5.0 4.500 4.273 0.445 77 11 5.0 6.0 5.500 5.818 0.386 88 11 6.0 8.0 7.000 6.909 0.668 99 11 9.0 10.0 9.500 9.545 0.498 110 11 10.0 12.0 11.000 11.182 0.716 121 11 12.0 16.0 14.000 13.818 1.113 132 11 16.0 21.0 18.500 17.636 1.367 143 11 21.0 29.0 25.000 24.818 2.367 154 11 31.0 51.0 41.000 38.364 7.413 165 11 55.0 92.0 73.500 70.636 10.764 176 5 97.0 136.0 116.500 111.400 13.865 modules with a lot of external names : (18, 40, 'cgi') (19, 19, 'cgitb') ... etc ... (72, 72, 'pydoc') (74, 74, 'cookielib') (78, 78, 'urllib2') (86, 86, 'symbol') (92, 92, 'sre_constants') (97, 97, 'xmlrpclib') (101, 118, 'os') (107, 107, 'sre_compile') (116, 116, 'sre_parse') (136, 151, 'socket') Output with python 2.3.3 Linux gives a greater number for socket as the OpenSSL library is wrapped. gc.collect() at the interactive prompt gives 0. (good) Conclusion : sre_compile and sre_parse should be coded with a __all__ attribute The standard library contains a module 'tzparse' which cannot be imported ! Most library modules do not begin with #!/usr/bin/env python and a coding cookie. Regards From just.starting at gmail.com Tue Jan 25 03:38:05 2005 From: just.starting at gmail.com (just starting) Date: Tue, 25 Jan 2005 14:08:05 +0530 Subject: how to call python code from C# In-Reply-To: <41F54FF6.30209@pythonapocrypha.com> References: <8LGdneLOysys1WjcRVn-1Q@powergate.ca> <41F54FF6.30209@pythonapocrypha.com> Message-ID: <3898fa73050125003838dc376c@mail.gmail.com> Thanks for all your kind information. I haven't used COM objects so far.I think now I have to learn it.Anyway thanks a lot again. paritosh. On Mon, 24 Jan 2005 12:43:50 -0700, Dave Brueck wrote: > Peter Hansen wrote: > > paritosh mahana wrote: > > > >> How can I call python code from my C# code. > [snip] > > You could use ctypes or the pywin32 package to provide your > > Python code with an ActiveX interface. Then you could just > > use it via COM, like any other COM object. Lots of references > > available via Google if you want to learn more about this > > approach... > > Lemme add my two cents and say that this approach works well. > > We have a component that uses ctypes and runs as a COM local server (its own > .exe) and we currently use it both from Internet Explorer and from a C# > application. COM can be hairy initially, but if you have any experience with COM > then this approach is pretty straightforward. > > -Dave > -- > http://mail.python.org/mailman/listinfo/python-list > From aleaxit at yahoo.com Sat Jan 22 06:30:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 12:30:36 +0100 Subject: Class introspection and dynamically determining function arguments References: <359lfnF4hd6e3U1@individual.net> <359nmoF4koiepU1@individual.net> Message-ID: <1gqsidn.1n13vyo85fvd7N%aleaxit@yahoo.com> Diez B. Roggisch wrote: > Nick Coghlan wrote: > > > > If this only has to work for classes created for the purpose (rather than > > for an arbitrary class): > > Certainly a step into the direction I meant - but still missing type > declarations. And that's what at least I'd like to see - as otherwise you > don't know what kind of editing widget to use for a property. Though it may be overkill for your needs, you'll be interested in Enthought's "Traits", I think; see, for example, . Facilitating such presentation tasks (no doubt including editing) appears to be a major driving force for Traits. Alex From detlev at die-offenbachs.de Sat Jan 29 12:12:41 2005 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 29 Jan 2005 18:12:41 +0100 Subject: ANN: eric3 3.6.1 released Message-ID: Hi, this is to let all of you know, that eric3 3.6.1 has just been released. It fixes a few nasty bugs, which were reported since the last release. It is available via http://www.die-offenbachs.de/detlev/eric3.html Eric3 is an Integrated Development Environment for Python. For details please see the above mentioned URL. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From oceanwavecn at gmail.com Sun Jan 2 10:03:41 2005 From: oceanwavecn at gmail.com (oceanwave) Date: 2 Jan 2005 07:03:41 -0800 Subject: Gate Oxide thickness of CMOS In-Reply-To: <69fbfcd3.0108291911.76f12106@posting.google.com> References: <69fbfcd3.0108291911.76f12106@posting.google.com> Message-ID: <1104678221.272720.73830@c13g2000cwb.googlegroups.com> it's depend on the various product, 200 Angstrom or 30 Angstrom is possible. the number of mask:15 or 30 ^^^^^^ From jeff at ccvcorp.com Thu Jan 27 20:38:49 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 27 Jan 2005 17:38:49 -0800 Subject: Question about 'None' In-Reply-To: <1106873904.761513.153710@z14g2000cwz.googlegroups.com> References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> <2fCdnYr1l-CZwmTcRVn-ig@comcast.com> <1106873904.761513.153710@z14g2000cwz.googlegroups.com> Message-ID: <10vj5hv8hcn3k9f@corp.supernews.com> flamesrock wrote: > I should also mention that I'm using > version 2.0.1 (schools retro solaris machines :( ) > At home (version 2.3.4) it prints out 'True' for the above code block. That would explain it -- as /F mentioned previously, the special case for None was added in 2.1. Jeff Shannon Technician/Programmer Credit International From spam at nospam.org Thu Jan 27 17:59:45 2005 From: spam at nospam.org (Erik Johnson) Date: Thu, 27 Jan 2005 15:59:45 -0700 Subject: building Python: up arrow broken on SuSE Linux 8.2 References: <41f6c3f7$1@nntp.zianet.com> <41f85dd8@nntp.zianet.com> Message-ID: <41f97058$1@nntp.zianet.com> "Peter Otten" <__peter__ at web.de> wrote... > Have you ensured (with yast) that readline-devel is actually installed? I had not previously, but (not surprisingly) version 4.3 is installed. :) Good idea - I thought maybe I would be able to do an online update (YOU) to it, but it is taking forever to get a patch list. I don't understand it, we have a pretty decent internet connection (DSL). I now have the readline version 5.0 library built locally. Can someone give me some clues about how to get it statically linked? Thanks, -ej From john at grulic.org.ar Tue Jan 18 18:28:14 2005 From: john at grulic.org.ar (John Lenton) Date: Tue, 18 Jan 2005 20:28:14 -0300 Subject: simultaneous multiple requests to very simple database In-Reply-To: References: Message-ID: <20050118232814.GA15780@grulic.org.ar> On Tue, Jan 18, 2005 at 11:26:46AM -0500, Eric S. Johansson wrote: > I have an application where I need a very simple database, effectively a > very large dictionary. The very large dictionary must be accessed from > multiple processes simultaneously. I need to be able to lock records > within the very large dictionary when records are written to. Estimated > number of records will be in the ballpark of 50,000 to 100,000 in his > early phase and 10 times that in the future. Each record will run about > 100 to 150 bytes. > > speed is not a huge concern although I must complete processing in less > than 90 seconds. The longer the delay however the greater number of > processes must be running parallel in order to keep the throughput up. > It's the usual trade-off we have all come to know and love. > > it is not necessary for the dictionary to persist beyond the life of the > parent process although I have another project coming up in which this > would be a good idea. > > at this point, I know they will be some kind souls suggesting various > SQL solutions. While I appreciate the idea, unfortunately I do not have > time to puzzle out yet another component. Someday I will figure it out > because I really liked what I see with SQL lite but unfortunately, today > is not that day (unless they will give me their work, home and cell > phone numbers so I can call when I am stuck. ;-) I'm sure we could agree on a fee for me to do so :) > So the solutions that come to mind are some form of dictionary in shared > memory with locking semaphore scoreboard or a multithreaded process > containing a single database (Python native dictionary, metakit, gdbm??) > and have all of my processes speak to it using xmlrpc which leaves me > with the question of how to make a multithreaded server using stock xmlrpc. berkley db (at least version 3, http://pybsddb.sourceforge.net/) supports multiple readers and writers, with fine-grained locking, it looks like a dictionary, and it isn't sql. The use you have in mind is a bit more complicated than the simple create-me-a-dictionary-in-a-file, but is pretty straightforward. The documentation mostly refers you to the C API, but fortunately it (the C API) is clear and well written. HTH -- John Lenton (john at grulic.org.ar) -- Random fortune: Today is National Existential Ennui Awareness Day. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From irmen at -nospam-remove-this-xs4all.nl Sun Jan 30 09:57:50 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 30 Jan 2005 15:57:50 +0100 Subject: ANN: Frog 1.3 released (python 'blog' application) Message-ID: <41fcf53b$0$28986$e4fe514c@news.xs4all.nl> I've just uploaded the Frog 1.3 release. Frog is a blog (web log) system written in 100% Python. It is a web application written for Snakelets. It outputs XHTML, is fully unicode compatible, small, and doesn't require a database. You can read about it and download it here: http://snakelets.sourceforge.net/frog/ It's 60Kb if you already have Snakelets, otherwise 122Kb. Frog 1.3 uses the same storage format as 1.2 so no conversion is required. If you encounter bugs or problems, or want to give some feedback, please let me know. Enjoy, --Irmen de Jong. PS I'm running Frog for my personal blog, so if you want to see it in action, please visit: http://www.razorvine.net/snake/frog/user/irmen/ (still somewhat experimental and most is in Dutch) From http Wed Jan 12 09:16:48 2005 From: http (Paul Rubin) Date: 12 Jan 2005 06:16:48 -0800 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <1105509379.301556.178130@z14g2000cwz.googlegroups.com> Message-ID: <7xoefuenqn.fsf@ruckus.brouhaha.com> michele.simionato at gmail.com writes: > > I can't imagine how it could be worse than the learning curve of > > __metaclass__, which we already have. > > To me, learning macros *and their subtilities* was much more difficult > than learning metaclasses. I guess I've only used Lisp macros in pretty straightforward ways, that weren't hard to understand. That's enough for anything I've needed. But we don't hear much about __metaclass__ because almost nobody understands it. > Go to comp.lang.scheme and google for "macros and module system"; > you will get everything you want to know and much more! OK, I might do this. > Well, I see this as a positive fact. If a syntax is contrived (such > as a ternary operator, for instance) it is better *not* to have it > than to have one hundred custom made syntaxes. At the end, we are > just talking about syntax sugar here, not about lack of > functionality. I think the idea is there would be some experimentation and then one of the versions would make it into the standard library. > > [compiling Lisp to Python bytecode] > This is a bizarre idea if you want to make Python run faster. It is > not so bizarre if what you want is to have access to Python from > Lisp/Scheme in the same sense Jython has access to Java. Why not just use a foreign function interface? From tim.golden at viacom-outdoor.co.uk Thu Jan 20 13:58:25 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 20 Jan 2005 18:58:25 -0000 Subject: Print to Windows default Printer Message-ID: <9A28C052FF32734DACB0A288A35339910359D9@vogbs009.gb.vo.local> [Samantha] | The printer is on LPT1, but I sure can't get the temp file to | print for some | reason. | I am using Windows XP SP2. | S i'm afraid I have to step out here (metaphorically speaking): I'm using Win2K and have no access to XP boxes. The technique works fine here; it may be that either they've removed the functionality under XP, or that there's some security context which is preventing you from accessing the port. Can anyone else try a "PRINT blah" or a "COPY blah LPT1:" on XP SP2? TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From steven.bethard at gmail.com Sun Jan 2 04:22:59 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 02 Jan 2005 09:22:59 GMT Subject: PEP 288 ponderings In-Reply-To: References: Message-ID: Raymond Hettinger wrote: > [Steven Bethard] >>(2) Since in all the examples there's a one-to-one correlation between >>setting a generator attribute and calling the generator's next function, >>aren't these generator attribute assignments basically just trying to >>define the 'next' parameter list? > > They are not the same. The generator needs some way to receive the values. The > function arguments cannot be used because they are needed to create the > generator-iterator. The yield statements likewise won't work because the first > yield is not encountered until well after the first next() call. Yeah, I wasn't trying to claim that passing the arguments to .next() is equivalent to generator attributes, only that the point at which new values for the generator state variables are provided correspond with calls to .next(). So if there was a means within a generator of getting access to the arguments passed to .next(), generator attributes would be unnecessary for the examples provided. > The given examples are minimal and are intended only to demonstrate the idea. Do you have an example where the generator state isn't updated in lock-step with .next() calls? I'd be interested to look at an example of this... >>I definitely don't like the >>idea of a magical __self__ variable that isn't declared anywhere. > > It is no more magical than f.__name__ or f.__doc__ for functions. I'm not sure this is quite a fair parallel. The difference here is that f.__name__ and f.__doc__ are accessed as attributes of the f object, and the __name__ and __doc__ attributes are created as a result of function creation. The proposed __self__ is (1) not an attribute that becomes available, rather, a new binding local to the function, and (2) not created as a result of generator object creation but created as a result of calling .next() on the generator object. > Also, the __self__ argument is a non-issue because there are other alternate > approaches such as providing a function that retrieves the currently > running generator. Is there a discussion of some of these alternate suggested approaches somewhere you could point me to? > The more important part of the PEP is the idea for generator exceptions. The > need arises in the context of flushing/closing resources upon generator > termination. I wonder if maybe it would be worth moving this part to a separate PEP. It seems like it could probably stand on its own merit, and having it in with the generator attributes PEP means it isn't likely to be accepted separately. Of course, I would probably declare a class and provide a .close() method. =) Steve From tim.peters at gmail.com Wed Jan 19 23:54:58 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 19 Jan 2005 23:54:58 -0500 Subject: Zen of Python In-Reply-To: <7xis5szpdj.fsf@ruckus.brouhaha.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> Message-ID: <1f7befae05011920543bb58720@mail.gmail.com> [Paul Rubin] > Huh? [1,2,[3,4,5],[6,[[[[7]],8]]]] is a perfectly valid Python list. You're claiming not to know any relevant difference between Python lists and Lisp lists? Heh. > And you can break out of a containing loop from a nested loop > with try/raise. Heh heh. Yes, you can. I've never seen a real Python program that did, but there's nothing to stop you. What did you think the "direct" in "direct way" might have been intended to mean? > More troublesome is not being able to see a variable in a > containing scope from a nested scope, unless the containing > scope is the global one. Why bother debating lexical scope for > years before deciding to add it, only to stop halfway? I'd call it 80% of the way, but suit yourself. The debates are all easily found, if you really want to know. From devries at idolstarastronomer.com Sun Jan 23 14:43:06 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: Sun, 23 Jan 2005 14:43:06 -0500 Subject: make install with python In-Reply-To: References: <35d4i9F4makucU1@individual.net> Message-ID: <20050123194306.GA1296@miyu.cjas.org> On Sat, Jan 22, 2005 at 01:54:17AM +0100, Uwe Mayer wrote: > Any suggestions how I handle uninstallation? This was provided by automake > rather mechanically. I didn't find a section on that in the distutils > documentation... :( I've been using distutils for a couple of projects I've written for work. Overall I love it as I rarely have to consult documentation (I always need to look at documentation to use autoconf, though I must admit I have only used autoconf/automake on two projects). On the distutils2.0 Wiki page (http://www.python.org/moin/DistUtils20) I found the quote: "Uninstallation is solved as soon as we have an installation database, which is part of what we're trying to do here." -- BobIppolito So it looks like they are working on it. Chris From removethis.kartic.krishnamurthy at gmail.com Thu Jan 20 20:34:17 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Fri, 21 Jan 2005 01:34:17 GMT Subject: Print a string in binary format In-Reply-To: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> Message-ID: neutrino said the following on 1/20/2005 7:53 PM: > Greetings to the Python gurus, > > I have a binary file and wish to see the "raw" content of it. So I open > it in binary mode, and read one byte at a time to a variable, which > will be of the string type. Now the problem is how to print the binary > format of that charater to the standard output. It seems a common task > but I just cannot find the appropriate method from the documentation. > Thanks a lot. Not a guru, but I will try to help out :-) how about this: >>> import binhex >>> binhex.binhex('C:/windows/system32/telnet.exe', 'C:/TEMP/telnet.hex') >>> Now this is what telnet.hex looks like: (This file must be converted with BinHex 4.0) :#R4PE'jPG#jPH'8!2j!)!!!!!4B!N!@9[deDN!!!!`!!!!3!!!$rr`!!Z!#3"d! !N#2J!!!!$Kqk$J#d#FdKZ!&-c5&8D'Pc)("bEfGbB at dJBf&ZEQpd)'*P)(*eEL" TEL"%6e-JE at pNC5i0$3SN!*!(Q$X`mpaDAU$F at PkJh&THS#Cj(U$G at PkJh&TIS'P DAU!QH8HJceTHS%Yj'k$G at PkJ"RP#S-TDAU!'H81Jh9THS#CjBk$G at PkJ8QPMD0a DAU!!N""343!!6!%$!&VGE6d!N!MJ!!m"#`%(!!$!!!!!"J)!N!AQ[3!!!"!!!!$ 3!*!&!3!3!!!!!J!!"3!"!!8!!3!%!*!)i!)!!!3!!&Hl!3!$!!#!!!!%!!!3!*! %%!!!%!#3"K!!N!Z3!-%!!-J!N!5J!J"B1!#3'[!5!!!F!*!M8!)!!-`!N!33!!$ F!J#3'LjdCAKd!!!!rVm!!!!3!!!!`!!!!!3!N!iJ!!"J,Q4KG'%!!!"mb`%!!0! (... Big Snip ...) Or how about this? >>> f = open('C:/windows/system32/telnet.exe', 'rb') >>> fcontents = f.read() >>> import binhex >>> print binhex.binascii.hexlify(fcontents[0:10]) '4d5a9000030000000400' >>> Is this what you want??? Thanks, --Kartic From tzot at sil-tec.gr Mon Jan 3 14:11:10 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 03 Jan 2005 21:11:10 +0200 Subject: BASIC vs Python References: <1103327631.570908.321770@c13g2000cwb.googlegroups.com> Message-ID: <9q5jt09llq0ak9h587d2ctvq29r2ag85t9@4ax.com> On 17 Dec 2004 15:53:51 -0800, rumours say that "ladasky at my-deja.com" might have written: >> The BASICs of my youth also supported graphics and sounds. >> >> PLAY "CGFED>CC >Now wait a minute, shouldn't that be... > >PLAY "CGFED>CC': 2.0} # octave modifier def play(sequence): """Play a sequence of notes.""" octave=1.0 for note in sequence: try: # to play a note winsound.Beep(int(round(notes[note]*octave)), 200) except KeyError: # well, it wasn't octave *= modifiers[note] if __name__ == "__main__": play("CGFED>CC" and "<" for example if I got them correctly). [1] and then I "inherited" a Stride with an 68010 from a student friend who finished studies and got drafted, who himself had it borrowed from the company of a friend of his so that he would develop code that could be used by the company, and in general all my troubles seem to come from exposure to Unix in my puberty, but that's another story :) -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From rkern at ucsd.edu Fri Jan 28 20:29:22 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 28 Jan 2005 17:29:22 -0800 Subject: LinearAlgebra incredibly slow for eigenvalue problems In-Reply-To: <1106960619.700424.278180@z14g2000cwz.googlegroups.com> References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> <1106952951.834888.65430@f14g2000cwb.googlegroups.com> <1106957598.136667.45430@z14g2000cwz.googlegroups.com> <1106957760.485860.104760@f14g2000cwb.googlegroups.com> <1106960619.700424.278180@z14g2000cwz.googlegroups.com> Message-ID: drife wrote: > David, > > I noticed that the libraries that ATLAS builds are not shared > objects (e.g., liblapack.a). Should these be shared objects? > I see nothing in the ATLAS documentation about building > things as shared objects. > Wondering if this is why the Numeric install is failing. No, they should work just fine as static libraries. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From peter at engcorp.com Wed Jan 26 10:33:08 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 Jan 2005 10:33:08 -0500 Subject: is there better 32 clock() timing? In-Reply-To: References: <41f61372.1768192005@news.oz.net> Message-ID: Stephen Kellett wrote: >>> that time.clock() is inaccurate. The problem is that the "time.clock()" >>> statement takes several hundred microseconds to execute. > > The statement is incorrect. clock() itself isn't slow, but it is > accessing a resource, the accuracy of which is no better than 1ms. > > There are various timers available, documented and undocumented, all of > which end up at 1ms or 1.1ms, give or take. For anything shorter you > need QueryPerformanceCounter() (but that *is* a slow call), or use the > RDTSC instruction which is fast but gives a count of instruction cycles > executed and is thus not totally accurate (multiple execution pipelines, > plus multithreading considerations). (I've read the five or so following messages you and Bengt have posted, but not in detail so I'm not sure where you're going with all this, but... ) According to the docs for time.clock(), "On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond." Depending on whether you really meant "accuracy" above, and on other things, this is either irrelevant, or contradicts your first statement... -Peter From ncoghlan at iinet.net.au Thu Jan 6 06:58:46 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 06 Jan 2005 21:58:46 +1000 Subject: Deferred expressions (was Re: Lambda as declarative idiom) In-Reply-To: <41dc4099.75876003@news.oz.net> References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> <41dc4099.75876003@news.oz.net> Message-ID: <41DD27F6.6040700@iinet.net.au> Bengt Richter wrote: > I like the fact that 'def' can serve as a mnemonic for 'defer' or 'deferred' ;-) Yeah, me too. I didn't actually notice that until after I'd thought of the phrase. > OTOH, I like concise notation for expressions, and the def and from aren't > really necessary if you can tag the first expression with some syntax marker. > I suggested (: rather than (def since (: is illegal now and won't break anything. True, but I've always liked Python's preference for keywords over punctuation. And 'def' is only 2 characters longer than ':', too. > That is an advantage of having it inside the outer parens, which my (:expr)(params) > couldn't benefit from -- unless I just take your format and substitute ':' for > both def and from: But where does that leave "Python is executable pseudocode"? Compare: (lambda (a, b, c) : f(a) + o(b) - o(c)) (: f(a) + o(b) - o(c) : (a, b, c)) (def f(a) + o(b) - o(c) from (a, b, c)) Which of the above most clearly expresses "defer a functional expression taking arguments a, b, and c"? For comparison, named syntax requires 3 lines, since Guido also wants to remove suite one-liners in Py3k: def f1(a, b, c): return f(a) + o(b) - o(c) f1 Not so bad for a single deferred expression (particularly a not-completely-trivial one like this), but fares significantly worse for simple zero-argument functions, or if you are just setting up a couple of deferred expressions in a function call. There's no more virtue in completely squandering vertical screen real estate than there is in being overly conservative with it. > What was the point of all this again? Pretending lambda goes away without really killing it? ;-) Actually, it was started by the "please don't take our lamdbas!" comments regarding Python 3k. I suggested that one of the problems with lambda is that it is an expression but looks like a one-liner statement ("it's ugly as sin" may have been closer to my actual phrasing), that the syntax would be deservedly rejected if proposed as a new addition to the language, and a more productive response might be to consider nicer alternative syntax that Guido would consider retaining in Python 3k (since it would make sense to try out such a syntax in the Python 2.x series before committing to it for 3.0). Of course, after making that suggestion, my brain decided to start working on its *own* ideas for a more Pythonic syntax (trying to learn from generator expressions), which seemed to set off a few other people :) The name 'deferred expression' is intended to emphasise what I see as the most appropriate application for anonymous functions - using an entire named function statement to defer a simple expression is serious overkill. Recognising this use case was what switched me from "I won't miss lambdas" to "You know, I'd really regret it if they disappeared completely". Basically, I think lambda has a PR problem - its usefulness as a way to defer expression evaluation is obscured by its ugly syntax and its current explanation as "a neutered form of function definition, but at least you can use it in an expression". On backticks, they have a major problem in that many fonts make ` and ' virtually indistinguishable. A secondary problem is that printed text often renders an opening single quote like a backtick. Guido has already mentioned this in one of Python Regrets talks (in the context of the backtick repr syntax). So I don't expect any syntax involving backticks to even be looked at by the BDFL. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From gstoyanoff at gmail.com Thu Jan 27 19:39:01 2005 From: gstoyanoff at gmail.com (g_xo) Date: Thu, 27 Jan 2005 19:39:01 -0500 Subject: Hello Message-ID: Hello everyone, I am a python beginner and look forward to learning the language and working on some interesting projects using it. I was wondering if anybody may help me get access to the news group comp.lang.python I am trying to access it using KNode but I get an "unable to resolve host name" error. Thank you. George +------------------------------------------------+ Linux - the future is free +------------------------------------------------+ From bulba at bulba.com Tue Jan 4 13:13:52 2005 From: bulba at bulba.com (Bulba!) Date: Tue, 04 Jan 2005 19:13:52 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> Message-ID: On Sun, 2 Jan 2005 23:59:53 -0800, "Eric Pederson" wrote: >I'm decades behind on economics research, but I remember >modeling clustering based on mass and distance (the gravity model). >On a decision making basis there seems to be an aspect of it that is >binary: (0) either give in to gravity and gain shared advantage as >part of a massive object, or (1) choose an alternate "location" far >enough away not to be much affected by the force of the massive >objects, and try to build "mass" there. I suspect Python is a (1) in >that regard, but I may be wrong. Frankly, I find such models to be built on over-stretched analogies to physics - how _exactly_ is gravity supposed to be an analogy equivalent to economic "forces"? Sure such model can be built - but is it adequate in explaining real-world phenomenons? Analogy tends to be the weakest form of reasoning. I'd be wary of making such analogies. Models like this probably tend to be built by French engineers from this joke: The American and French engineers work together on some product (that would look strange nowadays but it's not impossible in principle). The Americans show the French engineers a working prototype. The French engineers scratch their heads and ask warily: "OK, it works in practice; but will it work in theory?" -- Real world is perfectly indifferent to lies that are the foundation of leftist "thinking". From tjreedy at udel.edu Sat Jan 22 18:36:12 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 22 Jan 2005 18:36:12 -0500 Subject: need help on need help on generator... References: <63b5e209.0501210558.686f5c10@posting.google.com><1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> <200501221106.49241.francis.girard@free.fr> Message-ID: "Francis Girard" wrote in message news:200501221106.49241.francis.girard at free.fr... >If I understand correctly, Almost... > a "generator" produce something over which you can > iterate with the help of an "iterator". To be exact, the producer is a generator function, a function whose body contains 'yield'. In CPython, the difference after executing the def is that a generator function has a particular flag set. People sometimes shorten 'generator function' to 'generator' as you did, but calling both a factory and its products by the same name is confusing. (For instance, try calling an automobile factory an automobile). >>> def genf(): yield 1 ... >>> genf The result of calling a generator function is a generator, which is one but only one type of iterator. >>> gen = genf() >>> gen >>> dir(gen) [, '__iter__', ' gi_frame', 'gi_running', 'next'] The .__iter__ and .next methods make this an iterator. The two data attributes are for internal use. > Can you iterate (in the strict sense >of an "iterator") over something not generated by a "generator" ? Of course. Again, a generator is one specific type of iterator, where an iterator is anything with the appropriate .__iter__ and .next methods. Terry J. Reedy From jean.rossier at epfl.ch Wed Jan 19 04:40:55 2005 From: jean.rossier at epfl.ch (jean.rossier at epfl.ch) Date: Wed, 19 Jan 2005 10:40:55 +0100 Subject: problem with import pylab from a website Message-ID: <1106127655.41ee2b2758a9a@imapwww.epfl.ch> Hello All, I am facing a problem while importing pylab library(in a .py program file) via web browser however the same program works when I execute it from the command prompt. my configuration : Fedora Core 3 Apache 2.0 python 2.3.4 postgresql 7.3.4 mod_python-3.1.3-5 Error message we get: [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] Traceback (most recent call last):, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/var/www/html/sensor_data/get_graph.py", line 15, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] import pylab, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/usr/lib/python2.3/site-packages/pylab.py", line 1, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] from matplotlib.pylab import *, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/usr/lib/python2.3/site-packages/matplotlib/pylab.py", line 184, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] from axes import Axes, PolarAxes, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/usr/lib/python2.3/site-packages/matplotlib/axes.py", line 14, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] from axis import XAxis, YAxis, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/usr/lib/python2.3/site-packages/matplotlib/axis.py", line 20, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] from font_manager import FontProperties, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/usr/lib/python2.3/site-packages/matplotlib/font_manager.py", line 942, in ?, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] fontManager = FontManager(), referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/usr/lib/python2.3/site-packages/matplotlib/font_manager.py", line 786, in __init__, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] rebuild(), referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] File "/usr/lib/python2.3/site-packages/matplotlib/font_manager.py", line 780, in rebuild, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] pickle.dump(self.ttfdict, file(ttfcache, 'w')), referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] IOError, referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] : , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] [Errno 13] Permission denied: '/usr/share/matplotlib/.ttffont.cache', referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] , referer: http://128.178.156.101/sensor_data/readings.php [Wed Jan 19 09:43:58 2005] [error] [client 128.178.156.101] Premature end of script headers: get_graph.py, referer: http://128.178.156.101/sensor_data/readings.php Thanks in advance. Regards, jean From kartic.krishnamurthy at gmail.com Thu Jan 6 07:10:45 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 6 Jan 2005 04:10:45 -0800 Subject: navigating/changing directories In-Reply-To: References: Message-ID: <1105013445.219752.99060@z14g2000cwz.googlegroups.com> > /this/directory when I exit the script. Is it possible to have a script > that can drop me off into a different directory than where I initiated it > from? Use os.chdir(newpath) So, you can code os.chdir(r'/a/totally/different/directory') and find yourself in /a/totally/different/directory after the script completes. Thanks, --Kartic From steven.bethard at gmail.com Wed Jan 26 15:41:20 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 13:41:20 -0700 Subject: can not use __methods__ In-Reply-To: <1106769790.604491.290680@c13g2000cwb.googlegroups.com> References: <1106769790.604491.290680@c13g2000cwb.googlegroups.com> Message-ID: ajikoe at gmail.com wrote: > I try to use __methods__ in python 2.4 and 2.2 it always fail. > Can some one tell me if I want to itterate the methods in a class and > print it in a string format ( it is possible using __methods__ ). > Is there any replacement? py> class C(object): ... a = 1 ... b = 2 ... def f(self): ... pass ... def g(self): ... pass ... py> import inspect py> for attr, value in C.__dict__.iteritems(): ... if inspect.isroutine(value): ... print attr, value ... g f or: py> for attr, value in vars(C).iteritems(): ... if inspect.isroutine(value): ... print attr, value ... g f or if you want to include special methods: py> for attr in dir(C): ... value = getattr(C, attr) ... if inspect.isroutine(value): ... print attr, value ... __delattr__ __getattribute__ __hash__ __init__ __new__ __reduce__ __reduce_ex__ __repr__ __setattr__ __str__ f g This is probably useful for introspection at the Python prompt, but if you're planning on doing this in your code somewhere, you might present the problem you're trying to solve to the list, because this is likely not the best way to approach it... Steve From john.thingstad at chello.no Fri Jan 14 06:03:15 2005 From: john.thingstad at chello.no (John Thingstad) Date: Fri, 14 Jan 2005 12:03:15 +0100 Subject: huygens lands on titan Message-ID: -- Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ From lee at example.com Wed Jan 5 17:41:15 2005 From: lee at example.com (Lee Harr) Date: Wed, 05 Jan 2005 22:41:15 GMT Subject: get the IP address of a host References: Message-ID: On 2005-01-05, none <""> wrote: > I want to determine the outside (non local, a.k.a. 127.0.0.x) ip > addresses of my host. It seems that the socket module provides me with > some nifty tools for that but I cannot get it to work correctly it seems. > > Can someone enlightened show a light on this: > > import socket > def getipaddr(hostname='default'): > """Given a hostname, perform a standard (forward) lookup and return > a list of IP addresses for that host.""" > if hostname == 'default': > hostname = socket.gethostname() > ips = socket.gethostbyname_ex(hostname)[2] > return [i for i in ips if i.split('.')[0] != '127'][0] > > It does not seem to work on all hosts. Sometimes socket.gethostbyname_ex > only retrieves the 127.0.0.x ip adresses of the local loopback. Does > someone has a more robust solution? > > Targetted OS'es are Windows AND linux/unix. I found that the socket solutions only work if your DNS entries are correct ... which in my case was not true. So I came up with this: import commands ifconfig = '/sbin/ifconfig' # name of ethernet interface iface = 'eth0' # text just before inet address in ifconfig output telltale = 'inet addr:' def my_addr(): cmd = '%s %s' % (ifconfig, iface) output = commands.getoutput(cmd) inet = output.find(telltale) if inet >= 0: start = inet + len(telltale) end = output.find(' ', start) addr = output[start:end] else: addr = '' return addr Basically, it scrapes the output from ifconfig for the actual address assigned to the interface. Works perfectly on FreeBSD and Linux (given the correct configuration). From jjl at pobox.com Sun Jan 30 17:19:23 2005 From: jjl at pobox.com (John J Lee) Date: Sun, 30 Jan 2005 22:19:23 +0000 (GMT) Subject: RFC 2965 cookies, cookielib, and mailman. Message-ID: Just noticed your c.l.py post quoted below. Nobody but me knows or cares about this obscure stuff ;-) so I'm not surprised you got no answer... C. Titus Brown Dec 27 2004, 12:41 pm wrote: [...] > The issue turned out to be that mailman sends out RFC 2965 [1] cookies, > which are by default rejected by cookielib. I don't remotely pretend to > understand the issues involved; hence my post ;). > > A few questions for those more clued in than me: > > * what is the difference between RFC 2965 cookies and others? See "Where can I find out more about the HTTP cookie protocol?" here: http://wwwsearch.sourceforge.net/ClientCookie/ For both very short, slightly longer (first link in that section, to a section of the ClientCookie docs on the cookie standards), and insanely detailed (Kristol's paper) explanations. > * why would mailman implement RFC 2965 cookies over the old format? > (I'm guessing simply because it's the latest/best/format?) Because Barry didn't realise that almost no browsers implement it (and never will), I guess. > * why would cookielib NOT accept RFC 2965 cookies by default? See above: browsers don't implement it. It's essentially dead as an internet standard. The only real standard is "what IE and Mozilla do", plus some wisdom from RFCs 2109, 2965 and (more readably!) 2964. [...] > In any case, the way to make the cookielib example work for mailman is > like so: > > policy = cookielib.DefaultCookiePolicy(rfc2965=True) > cj = cookielib.LWPCookieJar('cookies.lwp', policy=policy) Hmm, cookielib should work if IE and Mozilla do, so that's a bug :( You shouldn't need to turn on 2965 handling. Do you have a script that demonstrates the problem, so I can fix it? Thanks John From mambuhl at earthlink.net Fri Jan 28 19:02:07 2005 From: mambuhl at earthlink.net (Martin Ambuhl) Date: Fri, 28 Jan 2005 19:02:07 -0500 Subject: what's OOP's jargons and complexities? In-Reply-To: References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> Message-ID: <360244F4lolueU1@individual.net> Dan Perl wrote: > Actually, it can be as simple as: > public class test { There is no "public" or "class" in C. Please don't post such trash to comp.lang.c. In fact, C++ is not topical in any of the five newsgroups you posted to. I don't know where you're posting from, so I apologize to the perl, python, lisp, scheme, and C people who see this in their newsgroups. Followup-To set to comp.lang.c++ where you can play with your bloated language all you wish. From jeff at ccvcorp.com Fri Jan 7 14:33:42 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 07 Jan 2005 11:33:42 -0800 Subject: The Industry choice In-Reply-To: <7xhdluuq3k.fsf@ruckus.brouhaha.com> References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <10trej2fl8dip65@corp.supernews.com> <7xhdluuq3k.fsf@ruckus.brouhaha.com> Message-ID: <10ttomdd6mp7711@corp.supernews.com> Paul Rubin wrote: > Jeff Shannon writes: > >>Note that the so-called 'viral' nature of GPL code only applies to >>*modifications you make* to the GPL software. > > > Well, only under an unusually broad notion of "modification". True enough. It can be difficult, in software development, to define a distiction between a situation where two software products are distinct but cooperative, and a situation where one software product is derivative of another. Stallman has chosen a particular definition for use in the GPL; one may debate the value of using this definition over any other possible definition, but the line had to be drawn *somewhere*. (And given Stallman's philosophies, it shouldn't be too surprising that he's drawn it about as broadly as he reasonably could.) >>(Problems may come if someone licenses a library under the GPL; that's >>what the LGPL was invented for. But the issue here is not that the >>GPL is bad, it's that the author used the wrong form of it.) > > > The "problem" is not a problem except that in the case of some > libraries, simply being able to use a library module is often not > enough incentive to GPL a large application if the library module's > functionality is available some other way (including by > reimplemntation). If the library does something really unique and > difficult, there's more reason to GPL it instead of LGPL'ing it. To my mind, the intent of the GPL is "use it, but if you change it or make a derivative, share the changes". With libraries, though, you *can't* use it without hitting the FSF-specified definition of a derivative. The LGPL exists to make it clear that, for libraries, the common meaning of "using" and "changing" are different than they are for applications. Of course, there's nothing that stops people from insisting that, if you *use* their libraries, anything you use them for must be free-as-in-speech (which is the effect of using the GPL instead of the LGPL); it's the author's choice what restrictions should be put on the software. But the usage-restrictions on a library under GPL are more severe than they are on an application under GPL. The unfortunate thing, in my opinion, is that a fair number of library authors don't think about that when they GPL their code. Jeff Shannon Technician/Programmer Credit International From cartermark46 at ukmail.com Mon Jan 10 06:22:57 2005 From: cartermark46 at ukmail.com (Mark Carter) Date: Mon, 10 Jan 2005 11:22:57 +0000 Subject: Port blocking Message-ID: <34f6sgF4asjm7U1@individual.net> Supposing I decide to write a server-side application using something like corba or pyro. What's the chance that in big corporations, the client's ports (in both senses of the word: fee-paying, and application) will be blocked, thereby immediately scuppering whatever I have written? Has this problem ever arisen for anyone? Also, is there a good tool for writing database UIs? From dhwild at argonet.co.uk Fri Jan 28 15:41:36 2005 From: dhwild at argonet.co.uk (David H Wild) Date: Fri, 28 Jan 2005 20:41:36 +0000 (GMT) Subject: Talking to the wind References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> <1106875259.426213.252030@z14g2000cwz.googlegroups.com> Message-ID: <4d3481485adhwild@argonet.co.uk> In article , Terry Reedy wrote: > > Xah Lee, > > > > Do you want to be taken seriously? > > First, stop posting. > > Second, learn perl. > > Third, learn python. > Hey all, I have seen no evidence that XL even reads the responses that > have been directed thereto. The above is like > /dev/null, > Why don't you ever answer the messages I keep sending to you? He's been in my killfile for quite some time. If **everyone** ignored him, this newsgroup would be a better place. :-)) -- __ __ __ __ __ ___ _____________________________________________ |__||__)/ __/ \|\ ||_ | / Acorn StrongArm Risc_PC | || \\__/\__/| \||__ | /...Internet access for all Acorn RISC machines ___________________________/ dhwild at argonet.co.uk From apardon at forel.vub.ac.be Fri Jan 14 03:24:17 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Jan 2005 08:24:17 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-01-13, Terry Reedy schreef : > > "Antoon Pardon" wrote in message > news:slrncucmeo.5qu.apardon at rcpc42.vub.ac.be... >> Op 2005-01-13, Fredrik Lundh schreef : >>> Antoon Pardon wrote: >>> >>>> Well, it seems that Guido is wrong then. The documentation clearly >>>> states that an expression is a statement. >>> >>> no, it says that an expression statement is a statement. if you don't >>> understand the difference, please *plonk* yourself. >> >> And what else is an expression statement but an expression (list) used >> as a statement. > > Whereas an expression used within a statement is not a statement, and that > is the difference. > > And of course, statements, in general, are not expressions and are not used > within statements (except within compound statements). Here you are stating the opposite of what Guido is supposed to have said. IMO we have a: dogs are mamals kind of relationship in Python. Every expression can be used where a statement is expected. (And this can be worded as: every expression is a statement.) Not every statement can be used where an expression is expected. -- Antoon Pardon From max at alcyone.com Mon Jan 24 17:01:39 2005 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Jan 2005 14:01:39 -0800 Subject: Looking for Form Feeds In-Reply-To: References: Message-ID: Greg Lindstrom wrote: > I have a file generated by an HP-9000 running Unix containing form feeds > signified by ^M^L. I am trying to scan for the linefeed to signal > certain processing to be performed but can not get the regex to "see" > it. Suppose I read my input line into a variable named "input" > > The following does not seem to work... > input = input_file.readline() > if re.match('\f', input): print 'Found a formfeed!' > else: print 'No linefeed!' > > I also tried to create a ^M^L (typed in as Q M L) but that > gives me a syntax error when I try to run the program (re does not like > the control characters, I guess). Is it possible for me to pull out the > formfeeds in a straightforward manner? What's happening is that you're using .match, so you're only checking for matches at the _start_ of the string, not anywhere within it. It's easier than you think actually; you're just looking for substrings, so searching with .find on strings is probably sufficient: if line.find('\f') >= 0: ... If you want to look for ^M^L, that'd be '\r\f': if line.find('\r\f') >= 0: ... If you want to keep a running count, you can use .count, which will count the number of substrings in the line. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis I would have liked to have seen Montana. -- Capt. Vasily Borodin From http Mon Jan 10 00:29:26 2005 From: http (Paul Rubin) Date: 09 Jan 2005 21:29:26 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> <7xvfa53obd.fsf@ruckus.brouhaha.com> Message-ID: <7x3bx9c0nd.fsf@ruckus.brouhaha.com> Arich Chanachai writes: > > And I think Pypy is currently set up to compile Python > >into Pyrex and then run the Pyrex results through GCC. > > > But of course, who's going to argue that Pyrex produces "compiled > Python"? Pyrex produces compiled Python in the same sense that asm produces "compiled C". PyPy contains a Python compiler which reads Python source and produces Pyrex output. The Pyrex output then gets compiled by the Pyrex compiler and then the C compiler before ending up with machine code. There is nothing terribly bizarre about this kind of compiler. For example, Gnu Common Lisp compiles Lisp code into C, then runs the C code through gcc. For that matter, the Yacc/Bison parser generators do something similiar. From timr at probo.com Sun Jan 9 03:05:51 2005 From: timr at probo.com (Tim Roberts) Date: Sun, 09 Jan 2005 00:05:51 -0800 Subject: Getting rid of "self." References: Message-ID: BJ?rn Lindqvist wrote: >I think it would be cool if you could refer to instance variables >without prefixing with "self." I know noone else thinks like me so >Python will never be changed, but maybe you can already do it with >Python today? > >.import sys >. >.def magic(): >. s = "" >. for var in sys._getframe(1).f_locals["self"].__dict__: >. s += var + " = self." + var + "\n" >. return s >. >.class A: >. def __init__(self): >. self.hi = "yo" >. >. def meth(self): >. exec(magic()) >. print hi >. >.a = A() >.a.meth() > >It works! exec(magic()) does the needed hi = self.hi. Does it? class A: def __init__(self): self.hi = "yo" def meth(self): exec(magic()) print hi hi = "baby" print hi def other(self): exec(magic()) print hi a = A() a.meth() a.other() That's way too fragile to be useful. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dan.gass at gmail.com Sun Jan 30 21:04:58 2005 From: dan.gass at gmail.com (Dan Gass) Date: Sun, 30 Jan 2005 20:04:58 -0600 Subject: [Python-Announce] cfgparse v01_00 released Message-ID: I'm pleased to announce the initial release of cfgparse (V01_00) Background ------------------------------------------------------------- cfgparse is a more convenient, flexible, and powerful module for parsing configuration files than the standard library ConfigParser module. cfgparse uses a more declarative style modelled after the popular optparse standard library module. cfgparse can optionally cooperate with the optparse module to provide coordination between command line and configuration file options. In addition, the cooperation can be used to allow the user to control features of the parser from the command line. URLs ------------------------------------------------------------- Docs/home page: http://cfgparse.sourceforge.net/ Download: http://sourceforge.net/projects/cfgparse/ Feature Summary ------------------------------------------------------------- + Simple ini style configuration syntax + Type checking with error handling and help messages + Help summary modelled after that in optparse + Round trip - read, modify, write configuration files with comment retention + Cooperates with optparse for configuration file options that should be overridden by command line options + Supports heirarchically organized option settings * User may store multiple option settings in a arbitrarily deep keyed dictionary. * Application uses a key list to walk into the dictionary to obtain a setting. * User controls key list with setting in configuration file. * Supports adding keys to the list through a command line option or from environment variables. + Supports allowing user control of configuration files used. * Environment variables may be used to allow user to specify a default configuration file. * Command line options to specify configuration file supported. * Configuration files may include other configuration files where where sections are read in parallel. * Configuration files may be nested heirarchically by including configuration files from within a section or subsection. + Configuration files may alternatively be written in Python. * full power and flexibility of Python available for creation of option settings * allows options settings to be real Python objects * this feature is NOT enabled by default + May be extended to support syntax such as XML. Enjoy, Dan Gass From fredrik at pythonware.com Mon Jan 24 02:22:53 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 08:22:53 +0100 Subject: Asynchronous event handling...? References: Message-ID: Chris Line wrote: > When the 'stop' button is selected after 'count', it does > not execute until the count command finishes at 500. > Instead, it is desired to stop counting immediately and > execute the 'stop' method. > > Is there a simple way to handle this situation? calling self.update() at regular intervals inside the loop (at least a couple of times per second, if you can arrange that) will give Tkinter a chance to process incoming events. another possibility is to use a thread to do the processing, but that involves other tricky issues (especially if you want to update the UI from the thread). From fredrik at pythonware.com Wed Jan 12 18:19:49 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 13 Jan 2005 00:19:49 +0100 Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: Chris Lasher wrote: > Since the file I'm working with contains tens of thousands of these > records, I believe I need to find a way to hash this file such that I > can retrieve the respective sequence more quickly than I could by > parsing through the file request-by-request. However, I'm very new to > Python and am still very low on the learning curve for programming and > algorithms in general; while I'm certain there are ubiquitous > algorithms for this type of problem, I don't know what they are or > where to look for them. So I turn to the gurus and accost you for help > once again. :-) If you could help me figure out how to code a solution > that won't be a resource whore, I'd be _very_ grateful. (I'd prefer to > keep it in Python only, even though I know interaction with a > relational database would provide the fastest method--the group I'm > trying to write this for does not have access to a RDBMS.) keeping an index in memory might be reasonable. the following class creates an index file by scanning the FASTA file, and uses the "marshal" module to save it to disk. if the index file already exists, it's used as is. to regenerate the index, just remove the index file, and run the program again. import os, marshal class FASTA: def __init__(self, file): self.file = open(file) self.checkindex() def __getitem__(self, key): try: pos = self.index[key] except KeyError: raise IndexError("no such item") else: f = self.file f.seek(pos) header = f.readline() assert ">" + header + "\n" data = [] while 1: line = f.readline() if not line or line[0] == ">": break data.append(line) return data def checkindex(self): indexfile = self.file.name + ".index" try: self.index = marshal.load(open(indexfile, "rb")) except IOError: print "building index..." index = {} # scan the file f = self.file f.seek(0) while 1: pos = f.tell() line = f.readline() if not line: break if line[0] == ">": # save offset to header line header = line[1:].strip() index[header] = pos # save index to disk f = open(indexfile, "wb") marshal.dump(index, f) f.close() self.index = index db = FASTA("myfastafile.dat") print db["CW127_A02"] ['TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAG... tweak as necessary. From vincent at visualtrans.de Mon Jan 3 15:10:43 2005 From: vincent at visualtrans.de (vincent wehren) Date: Mon, 03 Jan 2005 21:10:43 +0100 Subject: Developing Commercial Applications in Python In-Reply-To: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: eeykay at gmail.com wrote: > Hello All, > I am trying to convince my client to use Python in his new product. He > is worried about the license issues. Can somebody there to point me any > good commercial applications developed using python ?. The licence > clearly says Python can be used for commercial applications. Is there > any other implications like that of GPL to make the source open ? > Thanks for any help. > eeykay At CSB-System AG, we use Python extensively as embedded scripting language throughout the ERP system we develop (fields of application: system automation, GUI scripting, programmable user exits, reporting, data access/replication, autotests, and apart from that, everywhere we need something done fast ;-). I'm sure that its liberal license was among the main drivers to use it in the first place! -- Vincent Wehren From simon.alexandre at cetic.be Tue Jan 11 08:17:42 2005 From: simon.alexandre at cetic.be (simon.alexandre) Date: Tue, 11 Jan 2005 14:17:42 +0100 Subject: [csv module] duplication of end of line character in output file generated References: <41e3ceb6$1_3@newspeer2.tds.net> Message-ID: ok thanks it works S. "Kent Johnson" a ?crit dans le message de news:41e3ceb6$1_3 at newspeer2.tds.net... > simon.alexandre wrote: > > Hi all, > > > > I use csv module included in python 2.3. I use the writer and encouter the > > following problem: in my output file (.csv) there is a duplication of the > > end of line character, so when I open the csv file in Ms-Excel a blank line > > is inserted between each data line. > > From the docs for csv.writer(): > writer( csvfile[, dialect='excel'[, fmtparam]]) > ...If csvfile is a file object, it must be opened with the 'b' flag on platforms where that > makes a difference. > > Windows is a "platform where that makes a difference." So try > self.writer = csv.writer(file("Test.csv", "wb")) > > Kent > > > > > OS: W2k > > > > Someone has an idea ? > > > > thanks in advance > > > > the source code is the following: > > > > --------------------------------------------------> > > import csv > > > > class CsvDumper: > > > > def __init__(self): > > self.object = > > [['la','mb','mc','md'],['ma','mb','mc','md'],['ma','mb','mc','md']] > > self.writer = csv.writer(file("Test.csv", "w")) > > > > def DumpCsvFile(self): > > for row in self.object: > > self.writer.writerow(row) > > > > c = CsvDumper() > > c.DumpCsvFile() > > > > From daranrife at yahoo.com Fri Jan 28 17:55:51 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 14:55:51 -0800 Subject: LinearAlgebra incredibly slow for eigenvalue problems In-Reply-To: References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> Message-ID: <1106952951.834888.65430@f14g2000cwb.googlegroups.com> Hi David, I performed the above check, and sure enough, Numeric is --not-- linked to the ATLAS libraries. I followed each of your steps outlined above, and Numeric still is not linking to the ATLAS libraries. My setup.py file is attached below. Thanks , Daran --#!/usr/bin/env python # To use: # python setup.py install # or: # python setup.py bdist_rpm (you'll end up with RPMs in dist) # import os, sys, string, re from glob import glob if not hasattr(sys, 'version_info') or sys.version_info < (2,0,0,'alpha',0): raise SystemExit, "Python 2.0 or later required to build Numeric." import distutils from distutils.core import setup, Extension # Get all version numbers execfile(os.path.join('Lib','numeric_version.py')) numeric_version = version execfile(os.path.join('Packages', 'MA', 'Lib', 'MA_version.py')) MA_version = version headers = glob (os.path.join ("Include","Numeric","*.h")) extra_compile_args = [] # You could put "-O4" etc. here. mathlibs = ['m'] define_macros = [('HAVE_INVERSE_HYPERBOLIC',None)] undef_macros = [] # You might need to add a case here for your system if sys.platform in ['win32']: mathlibs = [] define_macros = [] undef_macros = ['HAVE_INVERSE_HYPERBOLIC'] elif sys.platform in ['mac', 'beos5']: mathlibs = [] # delete all but the first one in this list if using your own LAPACK/BLAS sourcelist = [os.path.join('Src', 'lapack_litemodule.c')] # set these to use your own BLAS; library_dirs_list = ['/d2/lib/atlas'] libraries_list = ['lapack', 'ptcblas', 'ptf77blas', 'atlas', 'g2c'] # set to true (1), if you also want BLAS optimized matrixmultiply/dot/innerproduct use_dotblas = 1 include_dirs = ['/d2/include'] # You may need to set this to find cblas.h # e.g. on UNIX using ATLAS this should be ['/usr/include/atlas'] extra_link_args = [] # for MacOS X to link against vecLib if present VECLIB_PATH = '/System/Library/Frameworks/vecLib.framework' if os.path.exists(VECLIB_PATH): extra_link_args = ['-framework', 'vecLib'] include_dirs = [os.path.join(VECLIB_PATH, 'Headers')] # The packages are split in this way to allow future optional inclusion # Numeric package packages = [''] package_dir = {'': 'Lib'} include_dirs.append('Include') ext_modules = [ Extension('_numpy', [os.path.join('Src', '_numpymodule.c'), os.path.join('Src', 'arrayobject.c'), os.path.join('Src', 'ufuncobject.c')], extra_compile_args = extra_compile_args), Extension('multiarray', [os.path.join('Src', 'multiarraymodule.c')], extra_compile_args = extra_compile_args), Extension('umath', [os.path.join('Src', 'umathmodule.c')], libraries = mathlibs, define_macros = define_macros, undef_macros = undef_macros, extra_compile_args = extra_compile_args), Extension('arrayfns', [os.path.join('Src', 'arrayfnsmodule.c')], extra_compile_args = extra_compile_args), Extension('ranlib', [os.path.join('Src', 'ranlibmodule.c'), os.path.join('Src', 'ranlib.c'), os.path.join('Src', 'com.c'), os.path.join('Src', 'linpack.c')], extra_compile_args = extra_compile_args), Extension('lapack_lite', sourcelist, library_dirs = library_dirs_list, libraries = libraries_list, extra_link_args = extra_link_args, extra_compile_args = extra_compile_args) ] # add FFT package (optional) packages.append('FFT') package_dir['FFT'] = os.path.join('Packages','FFT','Lib') include_dirs.append(os.path.join('Packages','FFT','Include')) ext_modules.append(Extension('FFT.fftpack', [os.path.join('Packages','FFT','Src', 'fftpackmodule.c'), os.path.join('Packages', 'FFT', 'Src', 'fftpack.c')], extra_compile_args = extra_compile_args)) # add MA package (optional) packages.append('MA') package_dir['MA'] = os.path.join('Packages', 'MA', 'Lib') # add RNG package (optional) packages.append('RNG') packages.append('RNG') package_dir['RNG'] = os.path.join('Packages', 'RNG', 'Lib') include_dirs.append(os.path.join('Packages', 'RNG', 'Include')) ext_modules.append(Extension('RNG.RNG', [os.path.join('Packages', 'RNG', 'Src', 'RNGmodule.c'), os.path.join('Packages', 'RNG', 'Src', 'ranf.c'), os.path.join('Packages', 'RNG', 'Src', 'pmath_rng.c')], extra_compile_args = extra_compile_args)) # add dotblas package (optional) if use_dotblas: packages.append('dotblas') package_dir['dotblas'] = os.path.join('Packages', 'dotblas', 'dotblas') ext_modules.append(Extension('_dotblas', [os.path.join('Packages', 'dotblas', 'dotblas', '_dotblas.c')], library_dirs = library_dirs_list, libraries = libraries_list, extra_compile_args=extra_compile_args)) long_description = """ Numerical Extension to Python with subpackages. The authors and maintainers of the subpackages are: FFTPACK-3.1 maintainer = "Numerical Python Developers" maintainer_email = "numpy-discussion at lists.sourceforge.net" description = "Fast Fourier Transforms" url = "http://numpy.sourceforge.net" MA-%s author = "Paul F. Dubois" description = "Masked Array facility" maintainer = "Paul F. Dubois" maintainer_email = "dubois at users.sf.net" url = "http://sourceforge.net/projects/numpy" RNG-3.1 author = "Lee Busby, Paul F. Dubois, Fred Fritsch" maintainer = "Paul F. Dubois" maintainer_email = "dubois at users.sf.net" description = "Cray-like Random number package." """ % (MA_version, ) # Oops, another bug in Distutils!? # Write rpm_build.sh pointing to this python rpm_build_text="""env CFLAGS="$RPM_OPT_FLAGS" %setup.py build\n""" % sys.executable rpm_script = open("rpm_build.sh", "w") rpm_script.write(rpm_build_text) rpm_script.close() # Write rpm_install.sh pointing to this python rpm_install_text=sys.executable +""" setup.py install --root=$RPM_BUILD_ROOT cat >INSTALLED_FILES <>INSTALLED_FILES """ rpm_script = open("rpm_install.sh", "w") rpm_script.write(rpm_install_text) rpm_script.close() setup (name = "Numeric", version = numeric_version, maintainer = "Numerical Python Developers", maintainer_email = "numpy-developers at lists.sourceforge.net", description = "Numerical Extension to Python", long_description = long_description, url = "http://numpy.sourceforge.net", # distutils allows you to fix or fudge anything :-) extra_path = 'Numeric', packages = packages, package_dir = package_dir, headers = headers, include_dirs = include_dirs, ext_modules = ext_modules ) print 'MA Version', MA_version print 'Numeric Version', numeric_version From peter at engcorp.com Tue Jan 18 01:00:18 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Jan 2005 01:00:18 -0500 Subject: python execution path In-Reply-To: <1106027652.064860.12650@z14g2000cwz.googlegroups.com> References: <1106027652.064860.12650@z14g2000cwz.googlegroups.com> Message-ID: qhfgva at gmail.com wrote: > Peter Hansen wrote: >>The best approach, if it's really intended to be a debugging >>aid, might be to learn about "pdb" .... > > This is more of a what if-ish question I guess. I use pdb fairly > regularly, I'm just looking to extend my debugging toolkit. I saw an > article recently about how perl has the sh -x type functionality and I > was curious if anything like that was possible in python. Not entirely > sure how it would make my life better, but it seems intriguing. Ah. In that case, investigate sys.settrace(). There are doubtless a variety of recipes and snippets available in either the Cookbook or in the mailing list archives, after you do the basic reading in http://www.python.org/doc/2.4/lib/module-sys.html . -Peter From skip at pobox.com Thu Jan 6 21:02:44 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 6 Jan 2005 20:02:44 -0600 Subject: Please Contribute Python Documentation! In-Reply-To: <10to8qulnc3vke1@news.supernews.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> Message-ID: <16861.60868.409947.889215@montanaro.dyndns.org> I'm changing the subject so that hopefully people who have long ago tuned out the "Python evolution: Unease" subject will read this note. John> I would like to contribute some documentation to Python. I've got John> the time, I write quite a bit, etc. I've got fairly strong John> opinions about some things that need to be documented, (such as John> all the new style class descriptor stuff from 2.2) and I have John> relatively little difficulty matching the existing style. John> However, I don't know TEX, Latex, CVS or Sourceforge. (The latter John> two are on my "learn sometime soon so I can put PyFIT where it John> belongs" list.) John> I have no desire to install Perl to run the documentation John> toolchain. I also have no particular desire to write up a bunch John> of final format stuff and drop it on someone else to put into the John> latex format so it can be included. I'm really not picking on John. I just happen to be replying to his message. Others have echoed sentiments similar to his. Let me emphasize this. You do not (repeat, *do not*) need to install any tools to contribute content to the documentation. Just whip out your favorite text editor and type plain old text. There are plenty of us around who know enough LaTeX to markup anything you contribute. Don't let lack of a specific set of tools be a barrier to contribution! The preferred way to submit documentation changes is by submitting a patch to the Python project on SourceForge: http://sourceforge.net/projects/python If you discover an error that requires little more than calling attention to the problem (or if you don't know how to fix it), just submit a bug report instead of a patch. In either case, select "Documentation" as the category. There is no need to assign it to anyone. It will get seen shortly. The correctness of a documentation fix is generally easier to verify than that for a code fix, so they tend to get applied pretty quickly. The only (small) barrier to submitting bug reports and patches via SourceForge is that you must register first. We used to allow anonymous reports but found that too often they were incomplete and required further input. With no way to contact the submitter of an anonymous report we had no choice but to hope they returned to check for progress. That only happened rarely, so the usual resolution was simply to delete the report. Fred Drake releases new development versions of the docs frequently (typically once every month or two). I normally use the development docs instead of the regular ones for my day-to-day work. They are available here: http://www.python.org/dev/doc/devel/ It's useful to check to see the most current status of the docs. The only thing more current is the source in CVS. Skip From rparnes at megalink.net Sat Jan 29 07:58:57 2005 From: rparnes at megalink.net (Bob Parnes) Date: Sat, 29 Jan 2005 12:58:57 -0000 Subject: Maximum Number of Class Attributes References: Message-ID: On Wed, 26 Jan 2005 10:03:47 +0100, Sylvain Thenault wrote: > On Wed, 26 Jan 2005 02:03:12 +0000, Bob Parnes wrote: > >> In its default configuration, my version of pylint (0.5.0) sets the >> maximum number of class attributes at 7. This seems low to me, but I can >> see how an excessive number might make maintenance more difficult. Is this >> indeed the best value for a maximum under ordinary conditions? If not, can >> anyone suggest a more reasonable value? > > well, this value is very subjective, and may change from one context to > another... For instance at some point I hope that pylint will detect "GUI" > classes and allow more attributes (and methods?) to those. > Anyway that's just an indicator, not a rule of thumb (and pylint itself > has some class with more than 7 attributes...). > > And FYI, this value has been taken from a post to the > testdrivendevelopment at yahoogroups (as most others default values in the > "design analysis" checker). Hum, well... After checking it seems that the > post said 20 attributes. I don't remember why did i get this number down > to 7. If this discussion leads to an agreement for a better number, I > can change the default value. > > -- > Sylvain Th?nault LOGILAB, Paris (France). > > http://www.logilab.com http://www.logilab.fr http://www.logilab.org > > Thanks for the information. I *am* using gui classes. -- Bob Parnes rparnes at megalink.net From martin at v.loewis.de Tue Jan 4 03:44:49 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 04 Jan 2005 09:44:49 +0100 Subject: Using ICL to compile C extensions In-Reply-To: <1104815892.984903.182190@f14g2000cwb.googlegroups.com> References: <1104815892.984903.182190@f14g2000cwb.googlegroups.com> Message-ID: <41da5779$0$1652$9b622d9e@news.freenet.de> dayzman at hotmail.com wrote: > Does anyone know how I can use "icl" (Intel C++) to compile C > extensions? I'm on Windows, and my Python is compiled using VS7.1 > (binary distribution). Right now, when I run setup.py install, it uses > cl.exe (MSVC++ Toolkit 2003), and I would like to use icl because > MSVC++ 2003 does not support C99. It should be possible to use this compiler, as long as you can link to msvcr71.dll (i.e. as long as you have header files of the MS C library, and an import library that links to msvcr71). Whether you can use distutils to run the build process is a different issue - you might need to extend distutils. Regards, Martin From aahz at pythoncraft.com Tue Jan 4 10:12:05 2005 From: aahz at pythoncraft.com (Aahz) Date: 4 Jan 2005 10:12:05 -0500 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1104830276.579755.133870@f14g2000cwb.googlegroups.com> <7x652dk0gh.fsf@ruckus.brouhaha.com> <1104831798.408560.228940@c13g2000cwb.googlegroups.com> Message-ID: In article <1104831798.408560.228940 at c13g2000cwb.googlegroups.com>, wrote: > >Maybe a PSF grant would help? I guess this has been considered ... The first three PSF grants were all in some way not directly related to changing the core language. One was for a library, one for improving Jython, and one for improving docs. Giving the PSF more money increases the chances for additional work. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From steve at holdenweb.com Mon Jan 31 09:37:04 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 09:37:04 -0500 Subject: Want to meet any of these people? They are registered for PyCon Message-ID: In accordance with PyCon's privacy policy, there are currently 29 PyCon registrants who have asked that their names not be published. The remainder, however, are listed here just in case you've ever wanted to meet any of them, and could do so by registering for PyCon at http://www.python.org/pycon/2005/register.html Note that the sort order isn't perfect - I just sorted on the second "word" in each name. PyCon is a *great* place to meet people and discuss ideas. Hope to see you there. regards Steve Chris Akre Brad Allen Kevin Altis Ummesalma Amil Stephen Apiki Dan Arico Larry Austin Suresh Babu Eddala Jim Baker Amir Bakhtiar Greg Barr Facundo Batista Anton Benard Thomas Bennett Bill Bergmann Ian Bicking Brian Bilbrey David Binger Zachery Bir Matthew Blecker Chris Blunck Ben Bodner Jonah Bossewitch Ivo Busko Theodore C. Pollari Matthew Cahn JP Calderone Brett Cannon Katie Capps Parlante Vern Ceder Michael Chermside Martin Chilvers Anders Chrigstrom Daniel Chudnov Tom Cocagne Eric Coffman Kevin Cole Tim Couper Matt Croydon Kevin Cully Andrew Dalke R. David Murray Zoltan Deak Stephan Deibel Catherine Devlin Cory Dodt Bruce Donald Campbell Brian Dorsey Scott Downie Fred Drake Matt Drew Michael Droettboom Reggie Dugard Donovan Eastman Bruce Eckel John Ehresman Alan Elkner Jeffrey Elkner Richard Emslie Mathieu Fenniak Robert Ferguson Abe Fettig Russell Finn Timothy Fitz Mike Fletcher Alec Flett Paul Flint Mitchell Foral Doug Fort Robin Friedrich Phil Frost Jim Fulton Patrick Garrett Philip Gaudette David Geller Grig Gheorghiu Christopher Gillett John Goebel Matthew Good David Goodger Nat Goodspeed Perry Greenfield Joe Grossberg David Grumm Walter H. Rauser Warren Hack Walker Hale IV Jacob Hallen David Hancock Andrew Harrington Travis Hartwell Randy Heiland Mark Hertel Raymond Hettinger Rob Hill Tom Hoffman Steve Holden Jim Hugunin John Hunter Jeremy Hylton Bob Ippolito Joseph J. Pamer Kevin Jacobs Vineet Jain Michael Johnson Eric Jones Evan Jones Ian Jones Richard Jones Francisco Juarez Patrick K. O'Brien Jacob Kaplan-Moss Don Kauffman David Keeney Peter Kessler Shahthureen Khan Brian Kirsch Sally Kleinfeldt Josheph Kocherhans Jeff Kowalczyk Daniel Krech Kartic Krishnamurthy Peter Kropf Andrew Kuchling Bob Kuehne Jeff Kunce Lloyd Kvam Jason L Asbahr MAN-YONG LEE Cameron Laird LD Landis Jukka Laurila Aaron Lav Phil Lawrence Edward Leafe Charles Leake Glyph Lefkowitz Ted Leung Michelle Levesque Bailing Li Greg Lindstrom Yihsiang Liow Peter Lyons John M. Camara Matthew MacInnes Andrew MacKeith Bryan MacRae Brian Mahoney Alex Martelli Andrej Masiar Peter Masiar Roger Masse Mark McClain Alan McIntyre Michael McLay Paul McNett Simon Michael Charles Moad Andrew Moore David Morrill David Muffley Edward Muller Robin Munn Eric Newton Edward Ng Rob Nichols Nestor Nissen Greg Noble Neal Norwitz Peter Olsen Mike Orr Brad Palmquist Guy Pardoe Bob Parks Thomas Parsli Anders Pearson Joel Pearson Samuele Pedroni Dave Perkins Tim Peters Carl Phillips Charles Phillips John Pinner Mike Pirnat Patrick Power Mark Pratt Kashif Qureshi James R Hall-Morrison Michael R. Bernstein Douglas R. Caldwell Andrew R. Gross Robert R. Knight Christian R. Simms Anna Ravenscroft Jimmy Retzlaff John Rhodes Anthony Rhudd Armin Rigo Nicholas Riley Arnaldo Riquelme Tracy Ruggles Jeff Rush Ollie Rutherfurd Dr. S. Candelaria de Ram Mike Salib Prasan Samtani Michel Sanner Phil Schumm Bill Sconce Chris Shenton Allen Short Jim Sizelove Brian Skahan Erik Smartt Garrett Smith Jason Smith Jacob Smullyan Jeff Sprandel David Stanek William Stein Yusei TAHARA Geoff Talvola Lee Taylor Mike Taylor Christian Theune Rick Thomas Andy Trice George Trojan Jamie Turner Karl Ulbrich Kirby Urner Eric V. Smith Andi Vajda Hernando Vera Thomas Verghese Martin Walsh Barry Warsaw Steve Waterbury Michael Weigend Chad Whitacre Kendall Whitesell Frank Wilder Derek Willis Simon Willison Mark Wittner Russ Woodman Andy Wright Linden Wright Peter Wu Yahong Wu James Y Knight Ka-Ping Yee Nathan Yergler Wai Yip Tung Rici Yu Peter Zhang Brian Zimmer matthew daiprai holger krekel clint malone Martin v. Loewis Guido van Rossum Tom von Schwerdtner -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From ebbaalm at uiuc.edu Fri Jan 7 16:00:54 2005 From: ebbaalm at uiuc.edu (Ebba Cecilia Ovesdotter Alm) Date: Fri, 7 Jan 2005 15:00:54 -0600 Subject: Tkinter: using a Listbox Message-ID: <6fb0c302.bb18916d.865c900@expms2.cites.uiuc.edu> Hello, I'm learning how to use the Tkinter module. I would like to use an element similar to a drop-down form, where the user can select one option out of many. I thought that a Listbox item could do just this. The following extract from my code (with the listbox part basically mirroring http://effbot.org/books/tkinterbook/listbox.htm), does, however, not create a visable Listbox. Am I interpreting the Listbox incorrectly? Ideas or suggestions are appreciated. #Frame & label for the listbox self.selectFrame = Frame(self.root) self.selectFrame.pack(side=TOP, fill=X, padx=10) Label(self.selectFrame, text='Primary choice').pack(side=LEFT) #Listbox self.listbox = Listbox(self.selectFrame) self.listbox.insert(END, "a list entry") for item in ["A","B","C"]: self.listbox.insert(END, item) Thanks, Cecilia From tim.golden at viacom-outdoor.co.uk Thu Jan 20 04:03:17 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 20 Jan 2005 09:03:17 -0000 Subject: Print to Windows default Printer Message-ID: <9A28C052FF32734DACB0A288A35339910359D1@vogbs009.gb.vo.local> [Samantha] | Thanks Tim. I didn't realize it would be so difficult. | S Strictly, if all you want to do is print text and you have mapped LPTx: to some printer (local or network) then the venerable "PRINT " or "COPY LPTx:" may well be what you want. You can issue these via an os.system call from within Python, and if that serves the purpose, well... import os f = open ("temp.txt", "w") f.write ("""I must go down to the sea again, To the lonely sea and the sky. And all I ask is a tall ship And a star to steer her by. """) f.close () os.system ("print temp.txt") TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From http Fri Jan 7 21:54:26 2005 From: http (Paul Rubin) Date: 07 Jan 2005 18:54:26 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> Message-ID: <7xk6qoeil9.fsf@ruckus.brouhaha.com> Arich Chanachai writes: > >But I thought Python was an all-purpose language. After all, OS's > >have been written in Lisp before too. > > > Pure Lisp? Or a Lisp/C/Asm combo? Lisp has a compiled flavor by the way. Compiled flavor? Lisp has been compiled since the 1950's. No, there was no C code on Lisp machines. There was some low-level code at the bottom whose capabilities were such that you could accurately call it asm, but it was Lisp too, just a very restricted form. From peter at engcorp.com Tue Jan 18 14:53:10 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Jan 2005 14:53:10 -0500 Subject: hex notation funtion In-Reply-To: <41ed66d5$0$92053$a1866201@visi.com> References: <41ed60f9$0$29427$a1866201@visi.com> <41ed66d5$0$92053$a1866201@visi.com> Message-ID: Grant Edwards wrote: > On 2005-01-18, Grant Edwards wrote: > >>On 2005-01-18, tertius wrote: >> >> >>>Is there a builtin function that will enable me to display the hex >>>notation of a given binary string? (example below) >> >>' '.join('%02x' % ord(b) for b in s) > > > Oops. Should be: > > ' '.join(['%02x' % ord(b) for b in s]) The first works fine under Python 2.4, actually... you need the list comprehension only on previous versions. -Peter From aahz at pythoncraft.com Thu Jan 6 19:01:46 2005 From: aahz at pythoncraft.com (Aahz) Date: 6 Jan 2005 19:01:46 -0500 Subject: The Industry choice References: <10trej2fl8dip65@corp.supernews.com> Message-ID: In article <10trej2fl8dip65 at corp.supernews.com>, Jeff Shannon wrote: > >Note that the so-called 'viral' nature of GPL code only applies to >*modifications you make* to the GPL software. The *only* way in which >your code can be 'infected' by the GPL is if you copy GPL source. That's not true -- consider linking to a GPL library. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From steven.bethard at gmail.com Sun Jan 23 15:08:11 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 23 Jan 2005 13:08:11 -0700 Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) In-Reply-To: References: Message-ID: Nick Coghlan wrote: > Steven Bethard wrote: > >> I wrote: >> > If you really want locals that don't contribute to arguments, I'd be >> > much happier with something like a decorator, e.g.[1]: >> > >> > @with_consts(i=1, deftime=time.ctime()) >> > def foo(x, y=123, *args, **kw): >> > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime >> > >> > Then you don't have to mix parameter declarations with locals >> > definitions. >> > >> > Steve >> > >> > [1] I have no idea how implementable such a decorator would be. I'd >> > just like to see function constants declared separate from arguments >> > since they mean such different things. >> >> I played around with this, and I think it's basically implementable: > > > Raymond's constant binding decorator is probably a good model for how to > do it: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 Yeah, I thought about this recipe, but opcodes always scare me too much. ;) Steve From jeff at ccvcorp.com Thu Jan 6 16:00:18 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 06 Jan 2005 13:00:18 -0800 Subject: sorting on keys in a list of dicts In-Reply-To: References: Message-ID: <10tr9ejf05pv660@corp.supernews.com> Jp Calderone wrote: > L2 = [(d[key], i, d) for (i, d) in enumerate(L)] > L2.sort() > L = [d for (v, i, d) in L2] Out of curiosity, any reason that you're including the index? I'd have expected to just do L2 = [(d[key], d) for d in L] L2.sort() L = [d for (v, d) in L2] I suppose that your version has the virtue that, if the sortkey value is equal, items retain the order that they were in the original list, whereas my version will sort them into an essentially arbitrary order. Is there anything else that I'm missing here? Jeff Shannon Technician/Programmer Credit International From holbertr at dma.org Wed Jan 5 10:37:53 2005 From: holbertr at dma.org (Rick Holbert) Date: Wed, 05 Jan 2005 10:37:53 -0500 Subject: % operation References: Message-ID: It also looks like you are using an old version of Python running on an old version of Linux. Time to upgrade? Christopher Koppler wrote: > On Wed, 05 Jan 2005 15:36:30 +0900, Daewon YOON wrote: > >> ==== >> Python 1.5.2 (#1, Jul 5 2001, 03:02:19) [GCC 2.96 20000731 (Red Hat >> Linux 7.1 2 on linux-i386 >> Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >> >>> x=9 >> >>> y=4 >> >>> x%y >> 1 >> >>> for z in range(44): >> ... z%9 >> File "", line 2 >> z%9 >> ^ >> SyntaxError: invalid syntax >> >> ==== >> What's wrong with the above operation and how can I get the correct >> modulo result with Python? > > There's nothing wrong with the operation, but it looks like you forgot to > indent your loop body (which the interactive shell doesn't automagically > do for you): > >>>> for z in range(44): > ... z%9 > ... > > [result snipped] > From case.nelson at gmail.com Wed Jan 12 21:47:50 2005 From: case.nelson at gmail.com (snoe) Date: 12 Jan 2005 18:47:50 -0800 Subject: Help Optimizing Word Search In-Reply-To: References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Message-ID: <1105584470.524744.324640@z14g2000cwz.googlegroups.com> With a list of letters: 'ABAE?S?' your implementation ran 3.5 times faster than the one from http://blog.vrplumber.com/427 (in 0.437 seconds vs 1.515) Without wildcards yours runs slightly quicker as well. I guess with the wildcards, using an re as a quick filter against each word, versus the translate method is much faster. From macrocosm at fastmail.fm Sun Jan 9 10:01:08 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Sun, 09 Jan 2005 10:01:08 -0500 Subject: Python Operating System??? In-Reply-To: <7xr7kvm72c.fsf@ruckus.brouhaha.com> References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> Message-ID: <41E14734.5050908@fastmail.fm> Paul Rubin wrote: > ... > >>OK, then give me an example of Lisp OS that runs on a PC. I would like to >>install it on my PC tomorrow. Or maybe my Mac. That was your whole point, >>originally, that since it could be done in Lisp, why not Python? >> >> > >Huh? That's a non-sequitur, nothing prevents you from running Lisp on >your PC or Mac. The same issues issues that apply to OS code, also >apply to user code. The Lisp machine hardware wasn't needed only to >make the OS run fast. The Lisp machine was developed so that people >could deploy large user-level applications written in Lisp, and the >hardware was there to support those applications. And given such a >good Lisp environment, there was no reason to think of writing the OS >in anything other than Lisp. > >In fact, the reason the Lisp machine died off was because general >purpose workstation hardware (and later, PC-class hardware) became >fast enough to run Lisp applications without needing special purpose >CPU's. That same PC hardware speed is what makes it possible to run >user applications in Python. > > So true, there was indeed a contextual reason for special hardware, and the context has since changed (dramatically). From uche at ogbuji.net Sat Jan 15 01:07:06 2005 From: uche at ogbuji.net (Uche Ogbuji) Date: 14 Jan 2005 22:07:06 -0800 Subject: XPath and XQuery in Python? In-Reply-To: References: Message-ID: <1105769226.435105.19310@c13g2000cwb.googlegroups.com> Interesting discussion. My own thoughts: http://www.oreillynet.com/pub/wlg/6224 http://www.oreillynet.com/pub/wlg/6225 Meanwhile, please don't make the mistake of bothering with XQuery. It's despicable crap. And a huge impedance mismatch with Python. --Uche From hpk at trillke.net Fri Jan 7 19:14:11 2005 From: hpk at trillke.net (holger krekel) Date: Sat, 8 Jan 2005 01:14:11 +0100 Subject: AttributeError of a module instance In-Reply-To: <43B02B32.6010805@yahoo.it> References: <43B02B32.6010805@yahoo.it> Message-ID: <20050108001411.GC7646@solar.trillke.net> On Mon, Dec 26, 2005 at 17:41 +0000, Paolino wrote: > I'd like to catch AttributeError on the module level,so that I can > declare default bindings for useds defore definition.How is this to be > done?Thanks for help. It cannot be done directly but with a small hack. This is the idea: import sys class A: def __getattr__(self,name): if name[:1] != '_': return name raise AttributeError(name) sys.modules['a'] = A() import a print a.helloworld # will print "helloworld" Note, that subsequently you can "import a" also from other modules because the import statement consults sys.modules. This is all a bit bothersome and thus it's often easier to just do "from somemod import a" directly and forget about the above magic. cheers, holger From tmohr at s.netic.de Wed Jan 26 00:44:51 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Wed, 26 Jan 2005 06:44:51 +0100 Subject: import hook, overwrite import? Message-ID: Hi, is there some description available to overwrite the import hook? By googling i found out so far that i need to overwrite __builtins__.__import__ with something else. Can i also do this with a C function that is provided when using an embedded python interpreter? So my own C program provides this and when linking with python.lib the function is overwritten? Or is there some extension hook? Does this also handle "from module import *" not only the normal "import module"? Thanks for any hints, Torsten. From nick at craig-wood.com Sat Jan 22 05:30:22 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 22 Jan 2005 10:30:22 GMT Subject: default value in a list References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: TB wrote: > Is there an elegant way to assign to a list from a list of unknown > size? For example, how could you do something like: > > >>> a, b, c = (line.split(':')) > if line could have less than three fields? You could use this old trick... a, b, c = (line+"::").split(':')[:3] Or this version if you want something other than "" as the default a, b, b = (line.split(':') + 3*[None])[:3] BTW This is a feature I miss from perl... -- Nick Craig-Wood -- http://www.craig-wood.com/nick From list.adam at twardoch.com Sat Jan 29 23:15:34 2005 From: list.adam at twardoch.com (Adam Twardoch) Date: Sun, 30 Jan 2005 05:15:34 +0100 Subject: [Plone] Detailed poll results? Message-ID: Hello, Is there a method, or an alternative module that could be used, to have "polls" in Plone that display detailed results of the poll, i.e. all users and the votes they have given? Adam From jdhunter at ace.bsd.uchicago.edu Thu Jan 20 15:27:56 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 20 Jan 2005 14:27:56 -0600 Subject: problem with import pylab from a website In-Reply-To: <1106127655.41ee2b2758a9a@imapwww.epfl.ch> (jean.rossier@epfl.ch's message of "Wed, 19 Jan 2005 10:40:55 +0100") References: <1106127655.41ee2b2758a9a@imapwww.epfl.ch> Message-ID: >>>>> "jean" == jean rossier writes: jean> Hello All, I am facing a problem while importing pylab jean> library(in a .py program file) via web browser however the jean> same program works when I execute it from the command jean> prompt. jean> Error message we get: Permission denied: '/usr/share/matplotlib/.ttffont.cache', referer: One solution is to give yourself write permission to /usr/share/matplotlib. If this is not possible or in unpalatable for sysadmin reasons, you have a couple of options. matplotlib creates a font cache .ttffont.cache of the ttf files it finds on your system. If the HOME environment variable is set, it places the cache file in the HOME dir. So if setting HOME is a viable option for you, simply set this to a writable directory on your system and you are good to go. This is the approach I recommend. If HOME does not exist, matplotlib falls back on its data path: this is where fonts, icons and other goodies live. You can also customize this directory by setting the MATPLOTLIBDATA environment variable. If you go this route, more all the files currently in /usr/share/matplotlib to some other directory, say /my/dir, and make sure it is writable, and then set MATPLOTLIBDATA to point to it. Note matplotlib has a configuration file that controls all of the default settings for the plot. If you want to edit these, the edited file can also be placed in the HOME directory. See http://matplotlib.sf.net/.matplotlibrc . Hope this helps, JDH From a at b.c Sat Jan 15 10:55:41 2005 From: a at b.c (Doug Holton) Date: Sat, 15 Jan 2005 09:55:41 -0600 Subject: java 5 could like python? In-Reply-To: References: Message-ID: vegetax wrote: > In the other hand, with the recent changes in java 5 i can pythonize > java, Have you seen Jython? http://www.jython.org/ It may be the best option for you. It will run just as fast as a regular java program. Also there is groovy: http://groovy.codehaus.org/ From TheDolphin at ivonet.nl Wed Jan 26 16:56:12 2005 From: TheDolphin at ivonet.nl (Ivo Woltring) Date: Wed, 26 Jan 2005 22:56:12 +0100 Subject: subprocess.Popen() redirecting to TKinter or WXPython textwidget??? References: <41f80b1b$0$148$3a628fcd@reader1.nntp.hccnet.nl> <1106775371.049857.36360@z14g2000cwz.googlegroups.com> Message-ID: <41f811fe$0$148$3a628fcd@reader1.nntp.hccnet.nl> wrote in message news:1106775371.049857.36360 at z14g2000cwz.googlegroups.com... > Ivo, my initial thought would be, you need to know how much text you > will get back from popen. My Python reference has the following > example: > > import os > dir = os.popen('ls -al', 'r') > while (1): > line = dir.readline() > if line: > print line, > else: > break > > that example shows how to capture the process output in a file-type > object, then bring it into a string with readline(). > >[.... snip ....] > cheers > S > Thanx for trying Stewart, but that is not what I need The output of mencoder is not readable with readlines (i tried it) because after the initial informational lines You don't get lines anymore (you get a linefeed but no newline) The prints are all on the same line (like a status line) something like Pos: 3,1s 96f ( 0%) 42fps Trem: 0min 0mb A-V:0,038 [171:63] which is coninually updated while the process runs... > in your app, you could create a Tkinter stringVar, say myOutput, for > the process output. In your Tkinter widget, you could then set a > textvariable=myOutput. also use the wait_variable and watch options How does this work? wait?? anyone? > (hope I recall these correctly, don't have my Tkinter ref. at hand) to > detect when there's been a change to the contents of the StringVar and > update the contents of the label. > Hope this helps, if not, write back. I really like to know how I can catch the output of a subproces.Popen() command and redirect it to something else (like a textwidget ) and I really like to use the subprocess module (standard in v2.4) to get to know it. Another reason to use the subprocess module is I can stop the process because I know the handle of the thread. The subprocess module knows all this. cheerz, Ivo. From starbuck_ms at yahoo.com Fri Jan 21 17:56:31 2005 From: starbuck_ms at yahoo.com (PyStarbuck) Date: 21 Jan 2005 14:56:31 -0800 Subject: PyXML problem between python 2.3 and python 2.4 Message-ID: <1106348191.156451.282180@c13g2000cwb.googlegroups.com> Hi All, Has anybody had an issue with compatiblity between XML files between python 2.3 and python 2.4. I have PyXML 0.8.3 installed in ClearCase and it is shared between Solaris and Windows. Here is an example on my system: ActivePython 2.3.4 Build 233 (ActiveState Corp.) based on Python 2.3.4 (#53, Oct 18 2004, 20:35:07) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path.insert(0, r"C:\cc\sweeneym_atf\reuse_python") >>> import xml >>> xml.__file__ 'C:\\cc\\sweeneym_atf\\reuse_python\\xml\\__init__.py' >>> import xml.marshal.generic as m >>> f = open(r"C:\test.xml", "w+") >>> m.dump_format(sys.path, f) >>> f.close() ActivePython 2.4 Build 243 (ActiveState Corp.) based on Python 2.4 (#60, Nov 30 2004, 09:34:21) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path.insert(0, r"C:\cc\sweeneym_atf\reuse_python") >>> import xml >>> import xml.marshal.generic as m >>> fd = open(r"C:\test.xml", "r") >>> l = m.load(fd) Traceback (most recent call last): File "", line 1, in ? File "C:\cc\sweeneym_atf\reuse_python\xml\marshal\generic.py", line 377, in load return m._load(file) File "C:\cc\sweeneym_atf\reuse_python\xml\marshal\generic.py", line 396, in _load p.parseFile(file) File "C:\cc\sweeneym_atf\reuse_python\xml\sax\drivers\drv_pyexpat.py", line 74, in parseFile self.close() File "C:\cc\sweeneym_atf\reuse_python\xml\sax\drivers\drv_pyexpat.py", line 132, in close if self.parser.Parse("", 0) != 1: xml.parsers.expat.ExpatError: parsing finished: line 17, column 0 I then performed a test by doing the following: 1) From python 2.4, marshal sys.path into a test24.xml file. 2) From python 2.3 un-marshal the test24.xml file, it workes. 3) From python 2.3 re-marshal the just un-marshaled list into test23.xml 4) Back in python24, un-marshal test23.xml, it failed. 5) Perform a diff on the new files, identical. Any Ideas? From francis.girard at free.fr Wed Jan 26 16:18:30 2005 From: francis.girard at free.fr (Francis Girard) Date: Wed, 26 Jan 2005 22:18:30 +0100 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <200501262135.30872.francis.girard@free.fr> Message-ID: <200501262218.31133.francis.girard@free.fr> Le mercredi 26 Janvier 2005 21:44, PA a ?crit?: > On Jan 26, 2005, at 21:35, Francis Girard wrote: > >> Project fails for many reasons but seldomly because one language is > >> "better" or "worst" than another one. > > > > I think you're right. But you have to choose the right tools that fit > > your > > needs. But I think that's what you meant anyway. > > Yes. But even with the "best" tool and the "best" intents, projects > still fail. In fact, most IT projects are considered failures: > > http://www.economist.com/business/PrinterFriendly.cfm?Story_ID=3423238 Well, let's go back home for some gardening. My wife will be happy. > > Cheers > > -- > PA > http://alt.textdrive.com/ From genezhang at gmail.com Sun Jan 9 20:21:24 2005 From: genezhang at gmail.com (Gene) Date: 9 Jan 2005 17:21:24 -0800 Subject: path to python file given module In-Reply-To: <1105319404.902746.179690@c13g2000cwb.googlegroups.com> References: <1105315568.887724.260370@c13g2000cwb.googlegroups.com> <1105315923.520581.280580@c13g2000cwb.googlegroups.com> <1105317971.205487.82770@c13g2000cwb.googlegroups.com> <1105319404.902746.179690@c13g2000cwb.googlegroups.com> Message-ID: <1105320084.044360.221800@c13g2000cwb.googlegroups.com> It works now. Thanks. From steven.bethard at gmail.com Tue Jan 25 15:24:03 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Jan 2005 13:24:03 -0700 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: References: Message-ID: Michael Spencer wrote: > Safe eval recipe posted to cookbook: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 This recipe only evaluates constant expressions: "Description: Evaluate constant expressions, including list, dict and tuple using the abstract syntax tree created by compiler.parse" It means you can't eval arbitrary Python code -- it's basically just a data parser. Handy in some situations, but not the equivalent of a limited Python virtual machine. > Likewise, function calls are easily intercepted I'm not sure I follow this... How do you intend to intercept all function calls? > As you say, attribute access to core functions appears to present the > challenge. It is easy to intercept attribute access, harder to know > what's safe. If there were a known set of 'dangerous' objects e.g., > sys, file, os etc... then these could be checked by identity against any > attribute returned It sounds like you're suggesting overriding the global attribute access mechanism. Is that right? So that every time Python encountered an attribute access, you would verify that the attribute being accessed is not on the 'dangerous' list? I don't know how to do that without basically rewriting some of Python's C code, though certainly I'm no expert in the area... Also, I'm not sure identity is sufficient: py> import sys py> import new py> new.module('newsys') py> newsys = new.module('newsys') py> newsys.__dict__.update(sys.__dict__) py> newsys is sys False py> newsys == sys False Steve From PeterMayne at ap.spherion.com Mon Jan 3 22:25:02 2005 From: PeterMayne at ap.spherion.com (PJDM) Date: 3 Jan 2005 19:25:02 -0800 Subject: [Hack] Import binary extensions from zipfiles, windows only References: Message-ID: <1104809102.966779.18480@f14g2000cwb.googlegroups.com> I'm trying to make ZopeX3 start faster by zipping up the "zope" directory. (Because this will be stored on a CD, having less data to read will make it quicker to start.) The standard python zipimporter won't work with the ZopeX3 .pyd files, so zipextimporter came along at just the right time. However, it doesn't seem to work for me (Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32, Windows XP SP2). Sample script: ---- import zipextimporter zipextimporter.install() import sys print 'Hooks:\n', sys.path_hooks sys.path.append(r'C:\tmp\zope.zip') print 'Path:\n', sys.path # Try an innocuous import first to make sure we have the path correct. import zope.server print 'Server file:\n', zope.server.__file__ # Now try a .pyd import. import zope.thread._zope_thread print 'Thread file:\n', zope.thread._zope_thread.__file__ ---- Output: ---- Hooks: [, ] Path: ['C:\\tmp', 'C:\\WINDOWS\\system32\\python23.zip', 'C:\\tmp', 'C:\\opt\\Python23\\DLLs', 'C:\\opt\\Python23\\lib', 'C:\\opt\\Python23\\lib\\plat-win', 'C:\\opt\\Python23\\lib\\lib-tk', 'C:\\opt\\Python23', 'C:\\opt\\Python23\\lib\\site-packages', 'C:\\tmp\\zope.zip'] Server file: C:\tmp\zope.zip\zope\server\__init__.py Traceback (most recent call last): File "zei.py", line 15, in ? import zope.thread._zope_thread ImportError: No module named _zope_thread ---- The zope.zip file contains zope.thread: ---- $ unzip -l zope.zip |grep zope/thread 0 11-08-04 11:00 zope/thread/ 0 07-03-04 04:34 zope/thread/DEPENDENCIES.cfg 65 07-28-04 22:52 zope/thread/SETUP.cfg 994 07-03-04 04:34 zope/thread/tests.py 748 11-08-04 11:00 zope/thread/tests.pyc 748 11-08-04 11:00 zope/thread/tests.pyo 20480 11-07-04 00:54 zope/thread/_zope_thread.pyd 7838 08-17-04 17:20 zope/thread/__init__.py 7808 11-08-04 11:00 zope/thread/__init__.pyc 7808 11-08-04 11:00 zope/thread/__init__.pyo ---- What am I missing? Thanks. PJDM From michele.simionato at gmail.com Wed Jan 26 08:27:48 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 26 Jan 2005 05:27:48 -0800 Subject: FTP Server In-Reply-To: References: <1106743852.600769.72820@c13g2000cwb.googlegroups.com> Message-ID: <1106746068.798541.219240@c13g2000cwb.googlegroups.com> > If you're after a simple FTP server, have a look at medusa. Uhm ... Medusa does not seem actively maintained nowadays. M.S. From as006d4848 at blueyonder.co.uk Fri Jan 28 23:41:57 2005 From: as006d4848 at blueyonder.co.uk (Philip Smith) Date: Sat, 29 Jan 2005 04:41:57 GMT Subject: Elliptic Code References: <7x3bwl9n40.fsf@ruckus.brouhaha.com> Message-ID: Quite so - but thanks for your help in any case "Paul Rubin" wrote in message news:7x3bwl9n40.fsf at ruckus.brouhaha.com... > Nick Craig-Wood writes: >> > I understand the algorithm quite well but how to code the >> > multiplication >> > stage most efficiently in python eludes me. >> >> You might want to look at >> >> http://gmpy.sourceforge.net/ >> >> It has very fast multiplication up to any size you like! > > I think he's talking about point multiplication on the elliptic curve > group, not integer multiplication. From reinhold-birkenfeld-nospam at wolke7.net Sat Jan 1 16:25:53 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 01 Jan 2005 22:25:53 +0100 Subject: What can I do with Python ?? In-Reply-To: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> Message-ID: <33oir1F40vpumU2@individual.net> BOOGIEMAN wrote: > Beginners question, but really what can you do with it ? > How hard is Python to learn compared with other languages > (let's say C#). Can you make fullscreen game with it (for example) ? > I've looked at http://www.python.org but nothing concrete there For fullscreen games, see PyGame (www.pygame.org). BTW, I don't know of a way to write fullscreen games in C#... Reinhold From itsme at yahoo.com Tue Jan 4 13:16:39 2005 From: itsme at yahoo.com (It's me) Date: Tue, 04 Jan 2005 18:16:39 GMT Subject: Hlelp clean up clumpsy code References: Message-ID: What's "LBYL"? Oh...Look-before-you-leap. OK. I think I understand what's going on now (I read up on generator and iterators and my head still hurts). I knew there must be a cleaner way of "walking" around in Python. I will experiment with generator more. Thanks everybody. "Jp Calderone" wrote in message news:mailman.140.1104857018.22381.python-list at python.org... > > > On Tue, 04 Jan 2005 08:18:58 -0800, Scott David Daniels wrote: > >Nick Coghlan wrote: > > > A custom generator will do nicely: > > > > > > Py> def flatten(seq): > > > ... for x in seq: > > > ... if hasattr(x, "__iter__"): > > > ... for y in flatten(x): > > > ... yield y > > > ... else: > > > ... yield x > > > > Avoiding LBYL gives you: > > def flatten(seq): > > for x in seq: > > try: > > for y in flatten(x): > > yield y > > except TypeError: > > yield x > > But totally messes up on error handling. Instead: > > def flatten(seq): > for x in seq: > try: > subseq = iter(x) > except TypeError: > yield x > else: > for subx in flatten(subseq): > yield subx > > to avoid catching TypeErrors from .next(). > > Jp From bokr at oz.net Thu Jan 13 18:04:21 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 23:04:21 GMT Subject: Octal notation: severe deprecation References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> <39ednWfqlrgB6HvcRVn-iA@powergate.ca> Message-ID: <41e6f606.777680996@news.oz.net> On Thu, 13 Jan 2005 08:18:25 -0500, Peter Hansen wrote: >and-google at doxdesk.com wrote: >> In Mythical Future Python I would like to be able to use any base in >> integer literals, which would be better. Example random syntax: >> >> flags= 2x00011010101001 >> umask= 8x664 >> answer= 10x42 >> addr= 16x0E800004 # 16x == 0x >> gunk= 36x8H6Z9A0X > >I think I kinda like this idea. Allowing arbitrary values, >however, would probably be pointless, as there are very >few bases in common enough use that a language should make >it easy to write literals in any of them. So I think "36x" >is silly, and would suggest limiting this to 2, 8, 10, and >16. At the very least, a range of 2-16 should be used. >(It would be cute but pointless to allow 1x000000000. :-) > My concern is negative numbers when you are interested in the bits of a typical twos-complement number. (BTW, please don't tell me that's platform-specific hardware oriented stuff: Two's complement is a fine abstraction for interpreting a bit vector, which is another fine abstraction ;-) One way to do it consistently is to have a sign digit as the first digit after the x, which is either 0 or base-1 -- e.g., +3 and -3 would be 2x011 2x101 8x03 8x75 16x03 16xfd 10x03 10x97 Then the "sign digit" can be extended indefinitely to the left without changing the value, noting that -3 == 97-100 == 997-1000) and similarly for other bases: -3 == binary 101-1000 == 111101-1000000 etc. IOW, you just subtract base** if the first digit is base-1, to get the negative value. This would let us have a %.b format to generate the digits part and would get around the ugly hack for writing hex literals of negative numbers. def __repr__(self): return '<%s object at %08.16b>' %(type(self).__name__, id(self)) and you could write based literals in the above formats with e.g., with '16x%.16b' % number or '2x%.2b' % number etc. Regards, Bengt Richter From mhartl at post.harvard.edu Thu Jan 6 15:40:49 2005 From: mhartl at post.harvard.edu (mhartl at post.harvard.edu) Date: 6 Jan 2005 12:40:49 -0800 Subject: File Handling Problems Python I/O References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> <1105034789.700445.291380@z14g2000cwz.googlegroups.com> <1105043692.497106.315270@z14g2000cwz.googlegroups.com> Message-ID: <1105044049.815913.17830@z14g2000cwz.googlegroups.com> Sorry, the BASE variable should be 'C:\\' on Windows: >>> BASE = 'C:\\' >>> import os >>> os.path.join(BASE, 'foo', 'bar', 'baz') 'C:\\foo\\bar\\baz' From vze4rx4y at verizon.net Sun Jan 16 07:18:23 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 16 Jan 2005 12:18:23 GMT Subject: generator expressions: performance anomaly? References: <1105854381.117059.59940@c13g2000cwb.googlegroups.com> Message-ID: "John Machin" wrote in message news:1105854381.117059.59940 at c13g2000cwb.googlegroups.com... > Please consider the timings below, where a generator expression starts > out slower than the equivalent list comprehension, and gets worse: > > >python -m timeit -s "orig=range(100000)" "lst=orig[:];lst[:]=(x for x > in orig)" . . . > >python -m timeit -s "orig=range(200000)" "lst=orig[:];lst[:]=(x for x > in orig)" This has nothing to do with genexps and everything to do with list slice assignment. List slice assignment is an example of a tool with a special case optimization for inputs that know their own length -- that enables the tool to pre-allocate its result rather than growing and resizing in spurts. Other such tools include tuple(), map() and zip(). The incredulous tone of the posting suggests a presumption that genexps always outperform list comps. That is not the case. Sometimes you want a list instead of a generator because you want more than just iteration; perhaps the consumer function may be able to take advantage of length reporting, indexing, slicing, re-iterability or other useful list behaviors. Also, the timing jig bites. Use xrange() instead of range(). Otherwise, there's an immediate forfeit of the memory savings normally being sought by the use of generators and iterators. > Background: There was/is a very recent thread about ways of removing > all instances of x from a list. /F proposed a list comprehension to > build the result list. FWIW, deques have a natural idiom for this kind of situation: for i in xrange(len(mydeque)): x = mydeque.popleft() if some_condition(x): mydeque.append(x) > Given a requirement to mutate the original list, > this necessitates the assignment to lst[:]. Sometimes people introduce arbitrary requirements and twist themselves in knots when real applications tend to allow a wider range of alternative solutions. There is a funky code smell emanating from any code resembling a[:]=some_iterator. It would make me examine how 'a' is being used and check whether the surrounding code can use the iterator or an new object. > Comments, clues, ... please. As a point of interest, note that Py2.4 improved some of its built-in iterators to report their length if requested. Now you now why. >>> d = dict(a=1, b=2, c=3, d=4) >>> len(d.iteritems()) 4 Raymond Hettinger From gene.tani at gmail.com Sun Jan 30 20:40:08 2005 From: gene.tani at gmail.com (gene.tani at gmail.com) Date: 30 Jan 2005 17:40:08 -0800 Subject: Help! Host is reluctant to install Python In-Reply-To: References: Message-ID: <1107135608.548166.243620@f14g2000cwb.googlegroups.com> Based on discusses with these guys, who know LAMP, python, ruby inside and out, and support it well: http://textdrive.com/ I'm guessing you'd have a hard time finding mod_python / apache hosting unless you get a dedicated server. It's pretty labor-intensive setup and admin-wise. linux shell / python / SSH shdn't be a big deal, tho. From tim.peters at gmail.com Wed Jan 26 22:51:02 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 26 Jan 2005 22:51:02 -0500 Subject: threading.py Condition wait overflow error In-Reply-To: <40E605146701DE428FAF21286A97D309174516@wphexa02.corp.lh.int> References: <40E605146701DE428FAF21286A97D309174516@wphexa02.corp.lh.int> Message-ID: <1f7befae050126195119b1ba9@mail.gmail.com> [Tim Peters] ... >> The most common cause for "impossible exceptions" > is flawed C code in an extension that fails to >> check a Python C API call for an error return. [Mark English] > Yes, I use a lot of C modules which I wrote. Then you know where to start looking . > It could certainly be one of them (although which one could be an > interesting challenge to find out). It may even have something to do > with moving to the VC7.1 compiler. Hard to say in advance. Since you have VC7.1, that opens a world of possiblities if you recompile Python. There are extra checks in ceval.c in a debug build, trying to catch "a call lied about whether it raised an exception" soon(er) after it happens. Rebuilding all your extensions in debug mode too could be a PITA, so you could get the same effect by #define'ing CHECKEXC in a release build. But a debug build has all sorts of extra checks that can help, and you could get into the debugger then and set a breakpoint on the unexpected OverflowError ... a quick check of the source shows that "long int too large to convert to int" is produced only by longobject.c's PyLong_AsLong() function. There's no way we _should_ be getting into that function by applying min() to floats, of course. > Thank you very much for your suggestion. Without it I would never have > thought to look at that code. Nobody ever does . From steve at holdenweb.com Fri Jan 14 16:55:56 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 16:55:56 -0500 Subject: Refactoring; arbitrary expression in lists In-Reply-To: References: Message-ID: <_hXFd.75450$Jk5.55685@lakeread01> Peter Maas wrote: > Steven Bethard schrieb: > >> BJ?rn Lindqvist wrote: > > [...] > >>> I believe this can be nicelier written as: >>> >>> if "Makefile" in basename: >>> >> >> +1 for "nicelier" as VOTW (Vocabulation of the week) =) > > > Me too, because nicelier is nicer than more nicely. :) > Is that really the niceliest way to express that thought? regards-li-er y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From limodou at gmail.com Wed Jan 19 02:46:36 2005 From: limodou at gmail.com (limodou) Date: Wed, 19 Jan 2005 15:46:36 +0800 Subject: safest way to kill a thread In-Reply-To: <1106115159.200989.60870@c13g2000cwb.googlegroups.com> References: <1106106497.429643.307440@f14g2000cwb.googlegroups.com> <1106115159.200989.60870@c13g2000cwb.googlegroups.com> Message-ID: <41EE105C.6060407@gmail.com> I think only those threads which invoked with setDaemon() method will exit, and others will not, as the main program exit. martinnitram at excite.com wrote: > limodou wrote: > >>Using Thread's method setDaemon() before you call the start() method. >>Just like : >>t.setDaemon(True) >>t.start() > > thank for fast reply. > from python.org doc, said that setDaemon() function as > "The entire Python program exits when no active non-daemon threads > are left." > is it mean that when the main program exit (normally/abnormally), all > threads created will also exit? > Thank again. > -- I love python! My Blog: http://www.donews.net/limodou From gdr at integrable-solutions.net Sat Jan 29 00:57:11 2005 From: gdr at integrable-solutions.net (Gabriel Dos Reis) Date: 29 Jan 2005 06:57:11 +0100 Subject: what's OOP's jargons and complexities? References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> <360244F4lolueU1@individual.net> Message-ID: Martin Ambuhl writes: | Dan Perl wrote: | | > Actually, it can be as simple as: | > public class test { | | There is no "public" or "class" in C. Please don't post such trash to | comp.lang.c. In fact, C++ is not topical in any of the five But, it was anything but C++. Maybe Java. -- Gabriel Dos Reis gdr at integrable-solutions.net From richie at entrian.com Tue Jan 4 05:55:29 2005 From: richie at entrian.com (Richie Hindle) Date: Tue, 04 Jan 2005 10:55:29 +0000 Subject: Python! Is! Truly! Amazing! In-Reply-To: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: <2etkt0pstn12l5d4l2o28ivei9np7cl3a2@4ax.com> [Erik] > I am now a super gushing fan-boy. +1 Quote of the Week! -- Richie Hindle From bokr at oz.net Tue Jan 18 23:55:53 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 19 Jan 2005 04:55:53 GMT Subject: Has apparent 2.4b1 bug been fixed? flatten in Lib\compiler\ast.py overloads 'list' name Message-ID: <41ede67e.1232456679@news.oz.net> What am I missing? (this is from 2.4b1, so probably it has been fixed?) def flatten(list): l = [] for elt in list: ^^^^--must be expecting list instance or other sequence t = type(elt) if t is tuple or t is list: ^^^^--looks like it expects to refer to the type, not the arg for elt2 in flatten(elt): l.append(elt2) else: l.append(elt) return l Regards, Bengt Richter From fredrik at pythonware.com Thu Jan 27 15:44:50 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 27 Jan 2005 21:44:50 +0100 Subject: Question about 'None' References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: Steven Bethard wrote: > So None being smaller than anything (except itself) is hard-coded into Python's compare routine. > My suspicion is that even if/when objects of different types are no longer comparable by default > (as has been suggested for Python 3.0), None will still compare as smaller than anything... from the change log for Python 2.1: "An implementation detail changed in 2.1a1 such that None now compares less than any other object. Code relying on this new behavior (like code that relied on the previous behavior) does so at its own risk." the documentation (which I quoted earlier) still applies. From ncoghlan at iinet.net.au Fri Jan 14 02:15:02 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 14 Jan 2005 17:15:02 +1000 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: <41e6dc9b.771173178@news.oz.net> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> <41e6dc9b.771173178@news.oz.net> Message-ID: <41E77176.9070002@iinet.net.au> Bengt Richter wrote: > Problems? (Besides NIH, which I struggle with regularly, and had to overcome to accept Tim's > starting point in this ;-) The ideas regarding creating blocks whose name bindings affect a different scope are certainly interesting (and relevant to the 'using' out-of-order execution syntax as well). Out-of-order execution appeals to me, but the ability to flag 'hey, this is just setup for something I'm doing later' might be a reasonable alternative (particularly with the affected names highlighted on the first line). As Jeff pointed out, it would be significantly less surprising for those encountering the construct for the first time. Folding code editors would be able to keep the setup clause out of the way if you really wanted to hide it. On the other hand, it might be feasible to construct a virtually identical out-of-order two suite syntax, similar to the mathematical phrasing "let f = c/lambda where f is the frequency, c is the speed of light and lambda is the wavelength". Either way, you've convinced me that two suites (and a new compound statement), as well as specifying which names can be rebound in the containing scope, is a better way to go than trying to mess with the definition of Python statements. On keywords, while 'let' is nice for assignments, I find it just doesn't parse properly when I put function or class definitions in the clause. So, I'll swap it for 'use' in the examples below. The statement could then be read "use these outer bindable names, and this additional code, in this suite". YMMV, naturally. Let's consider some of the examples given for 'where' using an in-order let/in type syntax (the examples only bind one name at a time, but would allow multiple names): # Anonymous functions use res: def f(x): d = {} exec x in d return d in: res = [f(i) for i in executable] # Declaring properties class C(object): use x: def get(self): print "Demo default" def set(self, value): print "Demo default set" in: x = property(get, set) # Design by contract use foo: def pre(): pass def post(): pass in: @dbc(pre, post) def foo(): pass # Singleton classes use C: class _C: pass in: C = _C() # Complex default values use f: def default(): return "Demo default" in: def f(x=default()): pass They actually read better than I expected. Nicely, the semantics of this form of the syntax *can* be articulated cleanly with current Python: use : in: as equivalent to: def __use_stmt(): def _in_clause(): return return _in_clause() __use_stmt_args = {} = __use_stmt() del __use_stmt Those semantics don't allow your switch statement example, though, since it doesn't use any magic to write to the outer scope - it's just a normal return and assign. However, I don't think starting with these semantics would *preclude* adding the ability to name the second block at a later date, and make the name rebinding part of executing that block - the standard usage doesn't really care *how* the names in the outer scope get bound, just so long as they do. Whether I think that's a good idea or not is an entirely different question :) Another aspect to consider is whether augmented assignment operations in the inner-scopes should work normally - if so, it would be possible to alter the semantics to include passing the existing values as arguments to the inner scopes. Moving on to considering a two-suite out-of-order syntax, this would have identical semantics to the above, but a syntax that might look something like: as : using: # Anonymous functions as res: res = [f(i) for i in executable] using: def f(x): d = {} exec x in d return d # Declaring properties class C(object): as x: x = property(get, set) using: def get(self): print "Demo default" def set(self, value): print "Demo default set" # Design by contract as foo: @dbc(pre, post) def foo(): pass using: def pre(): pass def post(): pass # Singleton classes as C: C = _C() using: class _C: pass # Complex default values as f: def f(x=default()): pass using: def default(): return "Demo default" Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From http Fri Jan 7 02:20:40 2005 From: http (Paul Rubin) Date: 06 Jan 2005 23:20:40 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41dcf582.122188317@news.oz.net> <7xd5wh7qdf.fsf@ruckus.brouhaha.com> Message-ID: <7xpt0h66yf.fsf@ruckus.brouhaha.com> Roman Suzi writes: > I do not like the idea of having stubs. Once I had an experience working with > CPAN (I tried to install SpamAssassin and it required some specific modules.) > "Magic" install shell, provided by Perl, upgraded half the Perl distro, > including newer version of Perl! > > So, I do like Python distutils better. it is not a major problem to > install something even if it required something else. Of course, > this depends on the package authors. But distutils don't help the problem that the module requires stuff that's missing. That's what happened with the thing I downloaded last week, that needed wxPython. I don't understand why the author felt he had to use wxPython instead of tkinter, since it wasn't a really fancy gui, but after already-described hassles trying to instead wxPython, I just used the application's command line interface instead, which worked fine. But if wxPython is so much better, maybe it's time for Python to include it. I want to start using Audacity pretty soon, which I think really does depend on wxPython, so I'm going to have to deal with this wxPython installation problem which is definitely not completely trivial. What a pain. > Yes, probably there could be a no-brainer script to run install > directly from zip and/or tar.gz/bz2 file, but I usually check > md5, pgp sigs and look inside anyway before running something. I thought distutils doesn't have any code-signing features. From kartic.krishnamurthy at gmail.com Thu Jan 13 11:01:52 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 13 Jan 2005 08:01:52 -0800 Subject: Free python server. In-Reply-To: <1105631360.938494.286750@c13g2000cwb.googlegroups.com> References: <1105631360.938494.286750@c13g2000cwb.googlegroups.com> Message-ID: <1105632112.104412.183870@f14g2000cwb.googlegroups.com> And yes, they have python installed... From richie at entrian.com Tue Jan 4 06:06:50 2005 From: richie at entrian.com (Richie Hindle) Date: Tue, 04 Jan 2005 11:06:50 +0000 Subject: hidding the "console" window + system global shortcut keys In-Reply-To: <2814F26DA6908F41927A81C410C4991A02079C19@siamun.server.bl.corp.intranet> References: <2814F26DA6908F41927A81C410C4991A02079C19@siamun.server.bl.corp.intranet> Message-ID: [Gabriel] > 2. Set global key biddings. You can do this using ctypes: http://groups.google.co.uk/groups?selm=mailman.929.1069345408.702.python-list%40python.org -- Richie Hindle richie at entrian.com From craig at postnewspapers.com.au Mon Jan 3 10:28:32 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Mon, 03 Jan 2005 23:28:32 +0800 Subject: removing comments form a file In-Reply-To: References: Message-ID: <1104766112.4535.5.camel@albert.localnet> On Mon, 2005-01-03 at 11:46 -0300, Batista, Facundo wrote: > - Used file instead of open, to don't read the whole file in memory. [craig at albert ~]$ python Python 2.3.4 (#1, Oct 26 2004, 16:42:40) .>>> file is open True .>>> print repr(file), repr(open) I'd be interested if you could clarify what you mean there. As far as I know, the whole file will only be read into memory if you use file.read () or file.readlines(). If you use an iterator it does internal readahead, but won't read the lot at once. If you use read() it reads only what you say. -- Craig Ringer From pedro.werneck at terra.com.br Mon Jan 24 10:04:11 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Mon, 24 Jan 2005 13:04:11 -0200 Subject: TCP server In-Reply-To: <1106576718.263709.280380@c13g2000cwb.googlegroups.com> References: <1106576718.263709.280380@c13g2000cwb.googlegroups.com> Message-ID: <20050124130411.1a91fa65.pedro.werneck@terra.com.br> A quick example for you: ### import SocketServer class EchoRequestHandler(SocketServer.BaseRequestHandler): def setup(self): print self.client_address, 'connected!' self.request.send('hi ' + str(self.client_address) + '\n') def handle(self): while 1: data = self.request.recv(1024) self.request.send(data) if data.strip() == 'bye': return def finish(self): print self.client_address, 'disconnected!' self.request.send('bye ' + str(self.client_address) + '\n') #server host is a tuple ('host', port) server = SocketServer.ThreadingTCPServer(('', 5000), EchoRequestHandler) server.serve_forever() ### Telnet to localhost 5000 and any data you sent will be echoed back to you... send 'bye' and the connection is closed On 24 Jan 2005 06:25:18 -0800 "assaf" wrote: > i am try to create a server > what am i suppose to send to SocketServer.TCPServer > what is the client_address ("127.0.0.1:80" ?) > and BaseRequestHandler = ? > > thanks > > -- > http://mail.python.org/mailman/listinfo/python-list From tjreedy at udel.edu Fri Jan 28 14:48:24 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Jan 2005 14:48:24 -0500 Subject: py.dll for version 2.2.1 (Windows) References: <1106937199.667357.42040@z14g2000cwz.googlegroups.com> Message-ID: "mike" wrote in message news:1106937199.667357.42040 at z14g2000cwz.googlegroups.com... > Just recently, my virus checker detected what it called a Trojan Horse > in the py.dll file in the python22 folder. Installation is version > 2.2.1 and I think that it came installed when I bought the PC in > October 2002. My HP came with 2.2 also, but nothing caught by McAfee > Does anyone know where I can get a copy of the py.dll file from version > 2.2.1 for Windows (XP) ? > > I looked at www.python.org and do not see a py.dll file in the > self-installation or .tgz versions of 2.2.1 that are posted. If the installer is not a selectively extractable archive, delete and reinstall fresh might be easiest. Terry J. Reedy From deetsNOSPAM at web.de Thu Jan 20 12:20:33 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 20 Jan 2005 18:20:33 +0100 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> Message-ID: <35a7grF4jjrcsU1@individual.net> > I know that there are different YAML engines for Python out there (Syck, > PyYaml, more?). > > Which one do you use, and why? I first used yaml, tried to migrate to syck. What I like about syck is that it is faster and doesn't try to create objects but only dicts - but it crashed if the number of yaml objects grew larger. So I still use yaml. > > For those of you who don't know what YAML is: visit http://yaml.org/! > You will be amazed, and never think of XML again. Well, almost. It is certainly nice. -- Regards, Diez B. Roggisch From fredrik at pythonware.com Mon Jan 24 17:19:06 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 23:19:06 +0100 Subject: What's so funny? WAS Re: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com><41EE24F7.7030303@jessikat.fsnet.co.uk><7x1xchlpqv.fsf@ruckus.brouhaha.com><41efeb82$0$27807$9b622d9e@news.freenet.de><41f1a70b$0$25959$9b622d9e@news.freenet.de><7xbrbiqdhk.fsf@ruckus.brouhaha.com><7xllalljah.fsf@ruckus.brouhaha.com><7xekgdmpll.fsf@ruckus.brouhaha.com><7xpszxcnfa.fsf@ruckus.brouhaha.com><7xllalcmqc.fsf@ruckus.brouhaha.com><7xbrbhosh7.fsf@ruckus.brouhaha.com><7xzmz0lw6h.fsf@ruckus.bro Message-ID: wrote > As an app writer I want to publish code that runs on multiple > platforms without needing special attention from the end user, and > preferably without needing special platform-specific attention from > me. please answer the question: have you done this? what kind of programs have you successfully delivered as "self-contained apps" for use on arbi- trary platforms? From klachemin at comcast.net Fri Jan 7 11:02:23 2005 From: klachemin at comcast.net (Kamilche) Date: 7 Jan 2005 08:02:23 -0800 Subject: Calling Function Without Parentheses! In-Reply-To: <41D8B5F4.1010903@mxm.dk> References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> <41D8B5F4.1010903@mxm.dk> Message-ID: <1105113743.189469.115440@f14g2000cwb.googlegroups.com> Yeah, but still. If they even had the most basic check, like 'an object is being referred to on this line, but you're not doing anything with it' would be handy in catching that. When you use an object like that, usually you're doing something with it, like assigning it to a variable. From sean_mcilroy at yahoo.com Fri Jan 14 15:28:37 2005 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 14 Jan 2005 12:28:37 -0800 Subject: reusing Tkinter Canvases Message-ID: I'd like to save one Tkinter Canvas in order to use it on another Canvas later. The problem is that it gets saved as EPS but it needs to be GIF to be reuseable. How can I convert that format? Peace, STM From aleaxit at yahoo.com Fri Jan 28 04:20:17 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 28 Jan 2005 10:20:17 +0100 Subject: Question about 'None' References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: <1gr3gdr.15hwalixjl91xN%aleaxit@yahoo.com> flamesrock wrote: ... > (The reason I ask is sortof unrelated. I wanted to use None as a > variable for which any integer, including negative ones have a greater > value so that I wouldn't need to implement any tests or initializations > for a loop that finds the maximum of a polynomial between certain x > values. Anything is greater than nothing, no?) To have this work reliably across versions of Python (and you mentioned you need it to work on 2.0 as well as 2.3...) you have to make your own sentinel class, such as: class MinusInfinity: def __cmp__(self, other): if isinstance(other, MinusInfinity): return 0 else: return -1 minusInfinity = MinusInfinity() Now, you should be able to use this 'minusInfinity" as ``a variable for which any integer ... has a greater value'', as you wished to use None. (Untested code, as I don't have any 2.0 on which to test it anyway). Alex From peter at engcorp.com Sun Jan 9 13:51:59 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jan 2005 13:51:59 -0500 Subject: read numbers from file and covert to integer In-Reply-To: References: Message-ID: ?ystein Western wrote: > I got a file with a lot blocks of numbers that are strings. I'd like to read > all > this numbers and convert them to numbers for futher compareation. How can I > convert all this numbers to integer? Do I have to put all numbers into a > list? It would help immensely if you could post some kind of example of the sorts of data you are talking about, perhaps a hex representation of the bytes (if it's a binary file). Otherwise we are just guessing how you are using the terms "block", "number", "string", and even "integer". -Peter From itsme at yahoo.com Mon Jan 10 19:11:01 2005 From: itsme at yahoo.com (It's me) Date: Tue, 11 Jan 2005 00:11:01 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: For those of us that works with complex numbers, having complex number as a natively supported data type is a big advantage. Non-native add-ons are not sufficient and lead to very awkward program code. "J?rgen Exner" wrote in message news:Fm6Ed.3556$u47.321 at trnddc09... > xah at xahlee.org wrote: > > #python supports complex numbers. > [...] > > So? > The world would come to a halt if all of a sudden nobody understands complex numbers anymore. :-) > > # Perl doesn't support complex numbers. But there are packages that > > supports it. > > The Math::Complex module is part of the standard installation already, no > need for any "packages" (whatever that might be). > Did you check "perldoc Math::Complex" > > NAME > Math::Complex - complex numbers and associated mathematical functions > [...] > > jue > > From http Sun Jan 9 20:49:19 2005 From: http (Paul Rubin) Date: 09 Jan 2005 17:49:19 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> Message-ID: <7xllb2f3z4.fsf@ruckus.brouhaha.com> "Carl Banks" writes: > And a suite, be it a def statement, a where block, or whatever, belongs > in a statement, not an expression. So do you approve of the movement to get rid of the print statement? From db3l at fitlinxx.com Mon Jan 17 17:34:35 2005 From: db3l at fitlinxx.com (David Bolen) Date: 17 Jan 2005 17:34:35 -0500 Subject: extension module, thread safety? References: Message-ID: Torsten Mohr writes: > The question came up if this is by itself thread safe, > if some two or more threads try to change these data types, > are the C functions by themselves are "atomic" or can they > be interrupted be the perl interpreter and then (data types > are in some inconsistent half-changed state) another function > that works on these data is called? I presume you mean "Python" and not "perl"... If the threads under discussion are all Python threads, then by default yes, the extension module C functions will appear to be atomic from the perspective of the Python code. When the Python code calls into the extension module, the GIL (global interpreter lock) is still being held. Unless the extension module code explicitly releases the GIL, no other Python threads can execute (even though those threads are in fact implemented as native platform threads). So in general, if you write an extension module where none of its functions ever release the GIL, there's no way for two of its functions to be run from different Python threads simultaneously. Note that this restriction won't necessarily hold if there are other ways (at the C level, or from other extension modules) to trigger code in the extension module, since that's outside of the control of the Python GIL. Nor will it necessarily hold true if your extension module calls back out into Python (as a callback, or whatever) since once the interpreter is back in Python code the interpreter itself will periodically release the GIL, or some other extension code that the callback code runs may release it. To the extent possible, it's considered good practice to release the GIL in an extension module whenever you are doing lengthy processing so as to permit other Python threads (that may have nothing to do with using your extension module) to execute. For short routines this really isn't an issue, but if your extension module will be spending some time managing its data, you may wish to add some internal thread protection around that data, so that you can use your own locks rather than depending on the GIL. -- David From boomberschloss at yahoo.com Fri Jan 14 10:46:48 2005 From: boomberschloss at yahoo.com (Joachim Boomberschloss) Date: Fri, 14 Jan 2005 07:46:48 -0800 (PST) Subject: Integration with java In-Reply-To: Message-ID: <20050114154648.70925.qmail@web53103.mail.yahoo.com> Hello, I am working on a project in Python, and I"m currently looking into the possibiliy of writing some of the project"s modules in Java. Given that a large part of the code is already written in Python, using the standard libraries and several extension modules, I am trying to gauge the viability of integration with Java via Jython with minimal impact on present code, on the complexity of future code, and on deadlines! I need to know in general how dirty it will be to combine the two languages, and what the costs I should take into account are. I"m also interested to know if there are any commonly accepted strategies to fully switch project languages (I"m considering, in the extreme case, to change it all into Java), and if writing some modules in Java and replacing the rest gradually makes sense. Three more specific questions I thought of: 1. Is is possible to pack a Jython/Java program in a py2exe-like fashion? Is it possible to pack in such a way both Python, Jython and Java code? 2. Does transferring large data structures between Java and Python code running by Jython have a significant effect on memory? For example, would passing the result of a large database query from Java to Jython, for further processing, cause the entire data to be duplicated or something similar? 3. Did I miss anything fundemental? Thanks! Joe. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From reinhold-birkenfeld-nospam at wolke7.net Fri Jan 21 14:26:36 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 21 Jan 2005 20:26:36 +0100 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> Message-ID: <35d3bcF4k9t5mU1@individual.net> A.M. Kuchling wrote: > On Fri, 21 Jan 2005 18:54:50 +0100, > Fredrik Lundh wrote: >> judging from http://yaml.org/spec/current.html (750k), the YAML designers are >> clearly insane. that's the most absurd software specification I've ever seen. they >> need help, not users. > > IMHO that's a bit extreme. Specifications are written to be detailed, so > consequently they're torture to read. Seen the ReStructured Text spec > lately? Agreed. If you just want to use it, you don't need the spec anyway. > The basic idea -- a data dumping format that's human-readable -- isn't a bad > one. OTOH, I can't recall wanting such a thing -- when I want readable > output I'm happy using > unreadable pickle files, unpickling the object and calling a .dump() or > .as_text() method.) > > But YAML seems to have started out with the goal of being human-writable, > something you would write in Emacs, Exactly. I use it as a format for config files the user can edit directly without much thinking (the explanation on top of the file are 3 lines). > and that seems to have gotten lost; the > format is now just as complicated as Restructured Text, but more cryptic > (the URI namespacing for tags, for example), not really simpler than > XML and in some ways weaker (e.g. only two encodings supported, more > complicated escaping rules). In most cases you don't need the complicated things, and the http://www.yaml.org/refcard.html isn't very complex either. Reinhold From pierre.barbier at cirad.fr Fri Jan 14 02:36:46 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri, 14 Jan 2005 08:36:46 +0100 Subject: Unclear On Class Variables In-Reply-To: References: Message-ID: <41e77621$0$19576$636a15ce@news.free.fr> Antoon Pardon a ?crit : >>Well I find this a confusing behaviour on python's part. The fact >>that instance.field can mean something different, depending on >>where in a statement you find it, makes the behaviour inconsistent. >> >>I know people in general here are against declarations, but declarations >>could IMO provide more consistency here and thus more obvious behaviour. > > > Well just to show how confusing python can be, the following piece of > code. > > | class Spam: > | eggs = [2, 3] > | > | > | sp1 = Spam() > | sp2 = Spam() > | > | print sp1.eggs, id(sp1.eggs) > | print sp2.eggs, id(sp2.eggs) > | print '--------------------' > | > | sp1.eggs += [4,] > | > | print sp1.eggs, id(sp1.eggs) > | print sp2.eggs, id(sp2.eggs) > | print '--------------------' > | > | Spam.eggs = [3,5] > | > | print sp1.eggs, id(sp1.eggs) > | print sp2.eggs, id(sp2.eggs) > | print '--------------------' > > Which produces: > > [2, 3] 1075958860 > [2, 3] 1075958860 > -------------------- > [2, 3, 4] 1075958860 > [2, 3, 4] 1075958860 > -------------------- > [2, 3, 4] 1075958860 > [3, 5] 1075959084 > -------------------- > Well ... and could someone explain this behaviour ? I don't catch it ! Pierre From invalidemail at aerojockey.com Sun Jan 9 00:44:47 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 8 Jan 2005 21:44:47 -0800 Subject: python3: accessing the result of 'if' In-Reply-To: References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> <1105236383.521393.40680@c13g2000cwb.googlegroups.com> Message-ID: <1105249487.644698.309100@c13g2000cwb.googlegroups.com> Nick Coghlan wrote: > Carl Banks wrote: > > What if the condition you wanted to test wasn't the same as the thing > > you want to save? In other words, how would you convert this? > > > > . where: > > . m = something() > > . if m > 20: > > . do_something_with(m) > > Yeah, this problem eventually occurred to me as well. However, I think a little > utility function can help solve it: > > def test(val, condition): > if condition(val): > return val > else: > return None > > if test(something(), lambda x: x < 10) as m: > print "Case 1:", m > elif test(something(), lambda x: x > 20) as m: > print "Case 2:", m > else: > print "No case at all!" I'm sorry, I really can't agree that this helper function "solves" it. IMO, it's a workaround, not a solution. And, if I may be frank, it's a pretty ugly one. Not only that, but it still doesn't work. What if the object itself is false? -- CARL BANKS From tjreedy at udel.edu Tue Jan 4 16:53:08 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 4 Jan 2005 16:53:08 -0500 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl><1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> Message-ID: "Bulba!" wrote in message > E.g. right now I would kill for a standard, built-in matrix > type The array types of Numerical Python (NumPy) and now Numarray are, defacto, Python's standard 1 to n dimensional array types. Once installed, they are as builtin as anything else. Several other packages build on top of them. > that would be as flexible as lists and dictionaries are > in Python, so that I could slurp the whole CSV file or some > other table in one instruction into a matrix that could > accomodate data types likes strings and floats (just like > dictionaries do - just, say, declare, "column 1 of matrix > contains strings, and please convert the values in column 2 > into floats"), and then easily do some fancy matrix > transformations. Numarray has a record array type. If there is not one publicly available, perhaps you could write a CSV file to record-array slurper and contribute it to the Recipes site or maybe even the CSV module. Terry J. Reedy From hodmann at lycos.nl Wed Jan 26 07:56:10 2005 From: hodmann at lycos.nl (robert) Date: 26 Jan 2005 04:56:10 -0800 Subject: execute python code from db Message-ID: Hello, Anybody knows if it's possible to execute python code from an db. db=MySQLdb.connect(host="localhost",user="r",passwd="j",db="v") c=db.cursor() c.execute("""SELECT * FROM table WHERE id = %s""", (id,)) for python_code in c.fetchall(): execute (python_code) Maybe feed python with stdin??. robert. From xah at xahlee.org Thu Jan 13 07:41:38 2005 From: xah at xahlee.org (Xah Lee) Date: 13 Jan 2005 04:41:38 -0800 Subject: how to stop google from messing Python code Message-ID: <1105620098.878376.110250@z14g2000cwz.googlegroups.com> i'm using groups-beta.google.com to post python code. Is there a way to stop google from messing with my format? it seems to have eaten the spaces in my python code. thanks. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From dbickett at gmail.com Sun Jan 16 13:27:57 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 16 Jan 2005 13:27:57 -0500 Subject: threading and sockets ? In-Reply-To: References: Message-ID: <1d6cdae3050116102711c5c041@mail.gmail.com> http://www.twistedmatrix.com/ Daniel Bickett From harold.fellermann at upf.edu Tue Jan 18 14:54:42 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 18 Jan 2005 20:54:42 +0100 Subject: pickling extension class In-Reply-To: <1gqlpxp.g66j8sl6zkutN%aleaxit@yahoo.com> References: <1gqlpxp.g66j8sl6zkutN%aleaxit@yahoo.com> Message-ID: On 18.01.2005, at 20:31, Alex Martelli wrote: > harold fellermann wrote: > >> File "/sw/lib/python2.4/pickle.py", line 760, in save_global >> raise PicklingError( >> pickle.PicklingError: Can't pickle : it's >> not found as hyper.PeriodicGrid >>>>> dir(hyper) >> ['Dir', 'Neighbors', 'PeriodicGrid', 'PeriodicPos', '__doc__', >> '__file__', '__name__', 'refcount'] >>>>> hyper.PeriodicGrid >> >> >> So pickle complains about the class PeriodicGrid not being found in >> the >> module hyper, but a dir() >> proves that python can find it. Has anyone an idea what's going wrong >> here? > > These symptomps are pretty weird -- let's try to pin things down a bit > more. The relevant few lines of pickle.py are: > > try: > __import__(module) > mod = sys.modules[module] > klass = getattr(mod, name) > except (ImportError, KeyError, AttributeError): > raise PicklingError( > > so, could you please edit your pickle.py to provide VASTLY more info, [...] > and let us know exactly what his modified pickle.py outputs...? Here it goes...: OOPS, error (exceptions.ImportError): No module named hyper Traceback (most recent call last): File "pickle_test.py", line 5, in ? pickle.dump(g,file("test","w")) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 1387, in dump Pickler(file, protocol, bin).dump(obj) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 231, in dump self.save(obj) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 338, in save self.save_reduce(obj=obj, *rv) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 414, in save_reduce save(func) File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 293, in save f(self, obj) # Call unbound method with explicit self File "/Volumes/space/Users/harold/uni/pace/ono/pickle.py", line 765, in save_global raise PicklingError( pickle.PicklingError: Can't pickle : it's not found as hyper.PeriodicGrid I have noticed that the error does not occur, when the imported module ('hyper') is in the same directory as the script that pickles. When it is imported from a subpackage (like in the code I sent you) it goes wrong. - harold - -- Reality is for people who lack imagination. From http Sun Jan 2 00:08:58 2005 From: http (Paul Rubin) Date: 01 Jan 2005 21:08:58 -0800 Subject: Frameworks for "Non-Content Oriented Web Apps" References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <7xd5woa045.fsf@ruckus.brouhaha.com> Tim Churches writes: > Can you give some URL for publicly accessible examples of what you > mean by a "NON CONTENT-ORIENTED WEB APPLICATIONS", so we can get a > better idea of what you mean? I don't think there was anything unclear about it. A spreadsheet might be a good example. From ianb at colorstudy.com Fri Jan 7 15:39:01 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Fri, 07 Jan 2005 14:39:01 -0600 Subject: Exception report library Message-ID: <41DEF365.4030209@colorstudy.com> I've been using one of several systems to catch unexpected exceptions and log them (e.g., write to a file, display on web page, email me, etc). But many are built into a particular system, or have an interesting but incomplete set of features. E.g., many web frameworks have exception reporters (and the stdlib includes cgitb), but I want to handle non-web exceptions in the same way as exceptions from web requests, and that's not generally easy. So, I'm figuring there should be some generic library that does this. Does anyone have experience with one they could recommend? PyCrash comes to mind: http://pycrash.sourceforge.net/, though the XML output doesn't excite me (but the post-mortem debugging data is nice). py.test makes nice tracebacks with extra data as well, and cgitb is another option, though I've found the code to be poorly factored for reusability when I've looked at it in the past. Zope includes an otherwise-Zope-neutral ExceptionFormatter, which isn't terribly exciting, except that it does look for __traceback_info__ local variables and create reports with those inlined. Maybe there's something better that's packaged as part of a larger framework? Does anyone have good or bad experience with PyCrash? Localized application extensibility is really useful to me as well; for instance, in a web application I like to know who the logged-in user is, and all sorts of environment information, and there's no way to do that that is common to all the environments I'd like this to work in. On the reporting end configuration and hooks are also really useful; e.g., there's no general way to display an exception report on a web page, so a web framework would have to hook into it in some way as well. I feel like there must be something out there, since every Python programmer has to deal with this sort of thing to some degree...? -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From macrocosm at fastmail.fm Thu Jan 6 18:37:29 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Thu, 06 Jan 2005 18:37:29 -0500 Subject: Python Operating System??? In-Reply-To: <10trb0mgiflcj4f@corp.supernews.com> References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: <41DDCBB9.9020202@fastmail.fm> David Brown wrote: >Hello. I recently came across a free operating system called Unununium (or >something like that) and it was developed in Python and Assembly. > >Now, I have been looking for a way to make an operating system for a long >long time and the only possibilities I could find were C++ and assembly. I >don't mind assembly so much if I don't have to use it very often. But C++ is >so complicated and errors are pretty much impossible to find in the code for >me. > >So, I was wondering if it would be possible to find a bootloader that loads >a python file at startup or something... > >Is there an example somewhere of a Python OS? > >Thanks! > > > > People don't make Python OSs because it's a serious pain in the Deng-Xiao-ping. J/k, I am half kidding. Go to google groups, and search for Python OS. You will find that this topic has been discussed numerous times. There was another project other than Unununium which was Python based, but it is not being developed any longer and I fail to remember what it was called. So search away, you will find many results! Alternatively you could contact the Unununium folks for help. Note also that there are Java OSs as well (and probably others). But then again, if you don't like C++, you probably won't like Java. They can be very different languages, but in my experience, the reasons why one does not like C++ is usually due to a quality/flaw that can also be found in Java. From jbperez808 at wahoo.com Wed Jan 12 17:06:30 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Thu, 13 Jan 2005 06:06:30 +0800 Subject: "Architecture of Python" was removed ? In-Reply-To: References: <004801c4f7cb$f62d1d30$1d02a8c0@cr> Message-ID: <34llb0F4apou6U1@individual.net> Skip Montanaro wrote: > Yes, perhaps. Note that it doesn't appear that the Wayback Machine contains > the meat of the essay, just the front page. It came from a wiki. Perhaps Most of the text seems to be there, but there are some critical diagrams (images) which the Wayback Machine did not archive. From stephen.thorne at gmail.com Wed Jan 12 22:07:12 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 13:07:12 +1000 Subject: Octal notation: severe deprecation In-Reply-To: <1105575689.335040.174490@c13g2000cwb.googlegroups.com> References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105575689.335040.174490@c13g2000cwb.googlegroups.com> Message-ID: <3e8ca5c805011219073b98cb64@mail.gmail.com> On 12 Jan 2005 16:21:29 -0800, PJDM wrote: > Maybe P3K will have an integer literal like "n_b" for "the integer n in > base b". I would actually like to see pychecker pick up conceptual errors like this: import datetime datetime.datetime(2005, 04,04) Regards, Stephen Thorne From jeff at ccvcorp.com Fri Jan 7 15:06:42 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 07 Jan 2005 12:06:42 -0800 Subject: The Industry choice In-Reply-To: References: <10trej2fl8dip65@corp.supernews.com> Message-ID: <10ttqk8k1e64495@corp.supernews.com> Bulba! wrote: > On 6 Jan 2005 19:01:46 -0500, aahz at pythoncraft.com (Aahz) wrote: > > >>>Note that the so-called 'viral' nature of GPL code only applies to >>>*modifications you make* to the GPL software. The *only* way in which >>>your code can be 'infected' by the GPL is if you copy GPL source. > > >>That's not true -- consider linking to a GPL library. > > > Will someone please explain to me in simple terms what's > the difference between linking to LGPLed library and linking > to GPLed library - obviously in terms of consequences of > what happens to _your_ source code? > > Because if there isn't any, why bother with distinguishing > between the two? Releasing a product in which your code is linked together with GPL'ed code requires that your code also be GPL'ed. The GPL goes to some lengths to define what exactly "linked together" means. Releasing a product in which your code is linked together with LGPL'ed code does *not* require that your code also be (L)GPL'ed. Changes to the core library must still be released under (L)GPL, but application code which merely *uses* the library does not. (I've forgotten, now, exactly how LGPL defines this distinction...) Jeff Shannon Technician/Programmer Credit International From jstroud at mbi.ucla.edu Mon Jan 24 19:31:13 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 24 Jan 2005 16:31:13 -0800 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <41f589f9$0$3357$9b622d9e@news.freenet.de> References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> Message-ID: <1106613073.2400.104.camel@lipscomb.mbi.ucla.edu> Martin v. L?wi said > Hmm. Most applications don't have any crypto needs. Any program where one stores data would have crypto needs. Here are some examples: Database, wordprocessor, spreadsheet, address book, mail program, (should I go on?). What would be the alternative to encryption to satisfy the functionality encryption provides...memorization? But I believe this may be a case of things being so obvious people forget their importance (e.g. breathing). I have written a class that goes something like this (highly simplified) class encryptFilter: def __init__(acipher): self.mycipher = acipher def open(self, filename): self.myfile = open(filename,"w") def write(data): encrypted_data = self.encrypt(data) self.myfile.write(encrypted_data) etc... Now what if acipher and this class could be made from part of the core distro? Any application could have the option of encryption with only a few lines of code: import std_crypt # other code here if get_user_pref("do_encryption"): password = my_get_password() acipher = std_crypt.AES(password) outfile = std_crypt.encryptFilter(acipher) outfile.open(filename) else: outfile = open(filename,"w") # all other code doesn't change... outfile.write(buncha_data) This could be even more simpler, but that's the general idea. The usefulness would be tremendous. From me at yahoo.com Sun Jan 2 18:02:26 2005 From: me at yahoo.com (it's me) Date: Sun, 2 Jan 2005 15:02:26 -0800 Subject: arbitrary number of arguments in a function declaration References: Message-ID: And in case it's not obvious already, you get the number of arguments that got passed down from: len(args) "Nick Coghlan" wrote in message news:mailman.65.1104694009.22381.python-list at python.org... > rbt wrote: > > How do I set up a function so that it can take an arbitrary number of > > arguments? For example, I have a bunch of expenses which may grow or > > shrink depending on the client's circumstance and a function that sums > > them up... hard coding them is tedious. How might I make this dynamic so > > that it can handle any amount of expenses? > > > > def tot_expenses(self, e0, e1, e2, e3): > > pass > > The Python Tutorial is a wonderful thing. . . > > Anyway, you can either set up your function to take a proper list, and then > discover that the sum function already exists to add up the contents of a list: > > def tot_expenses(self, expenses): > self.total_expenses = sum(expenses) > > Or, have the function take a variable number of arguments, and do the same thing: > > def tot_expenses(self, *args): > self.total_expenses = sum(args) > > Cheers, > Nick. > > -- > Nick Coghlan | ncoghlan at email.com | Brisbane, Australia > --------------------------------------------------------------- > http://boredomandlaziness.skystorm.net From sesquile at gmail.com Mon Jan 31 16:17:39 2005 From: sesquile at gmail.com (mh) Date: 31 Jan 2005 13:17:39 -0800 Subject: [ANN] Spike Asset Manager release 0.13 In-Reply-To: References: <1107196878.026930.154270@c13g2000cwb.googlegroups.com> <16894.36152.345508.583247@montanaro.dyndns.org> Message-ID: <1107206259.910842.111840@f14g2000cwb.googlegroups.com> Fredrik- This is a known issue. The tool currently only looks in certain locations or hints rather then spidering the whole hard drive (which could take a bit of time). If you have installed in a non-standard location (or are using a platform or version of software that hasn't been tested against) the tool won't find the component. One way around this is manually enter more "hints" but this doesn't scale. I'm open to suggestions for handling this in a better way. matt ps-I assume you are running on windows. Where is python installed on your machine? From ncoghlan at iinet.net.au Sat Jan 8 01:38:04 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 16:38:04 +1000 Subject: switching an instance variable between a property and a normal value In-Reply-To: References: Message-ID: <41DF7FCC.8070503@iinet.net.au> Steven Bethard wrote: > I'd like to be able to have an instance variable that can sometimes be > accessed as a property, and sometimes as a regular value, e.g. something > like: If you want the behaviour to be switchable per-instance, you have to go the route of always running through the property machinery, since property() creates a descriptor on the class, not the instance. On the other hand, if you want to switch the behaviour of every instance, then making usevalue and usefunc class methods may give you some mileage. I'm rather curious about your use case, though. . . Here's a different way of using the property machinery, too: Py> class C(object): ... def __init__(self): ... self._use_val = None ... def useval(self, x): ... self._val = x ... self._use_val = True ... def usefunc(self, func, *args, **kwds): ... self._func, self._args, self._kwds = (func, args, kwds) ... def _get(self): ... use_val = self._use_val ... if use_val is None: ... raise AttributeError('x') ... if use_val: ... return self._val ... else: ... return self._func(*self._args, **self._kwds) ... x = property(_get) ... Py> c = C() Py> c.useval(4) Py> c.x 4 Py> c.usefunc(list) Py> c.x [] -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From janeaustine50 at hotmail.com Sat Jan 8 23:13:49 2005 From: janeaustine50 at hotmail.com (Jane Austine) Date: 8 Jan 2005 20:13:49 -0800 Subject: time module precision Message-ID: What is the precision (and accuracy) of time module on a Windows XP machine? threading module depends on time module so it's precision(and accuracy) is up to time module's. | for i in xrange(1000): | time.sleep(0.001) This sleeps for awhile, which means 0.001 sec is not ignored. On the other hand, | for i in xrange(10000): | time.sleep(0.0001) This returns right away. 0.0001 sec is ignored and lost in the air. So can I tell the time.sleep's precision is 1ms? Any other way to increase the precision? (Using busy waiting -- spinning loop -- is not a good option, it makes over 90% cpu usage) Jane From ptmcg at austin.rr._bogus_.com Tue Jan 11 18:28:54 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 11 Jan 2005 23:28:54 GMT Subject: Time script help sought! References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> <1105477084.525279.312970@f14g2000cwb.googlegroups.com> <1105479292.689762.155510@f14g2000cwb.googlegroups.com> <1105480151.431987.327080@c13g2000cwb.googlegroups.com> <1105485509.346577.292130@f14g2000cwb.googlegroups.com> Message-ID: wrote in message news:1105485509.346577.292130 at f14g2000cwb.googlegroups.com... > man, now that is beautifully done. Paul, I wish I knew about pyparsing > a while ago. I could have used it in a few projects. :) > Thanks for the compliment! I'll be the first to admit that pyparsing can be a bit persnickety in some applications, especially when you have to trap on end-of-line, or have some columnar-dependent syntax. pyparsing really works best with data that has some syntactic structure to it, but is not whitespace sensitive (pyparsing's default behavior is to skip over whitespace). I don't recommend it when the data is well-formed - regexp's or even just string.split() will blow it away from a performance (and simplicity) standpoint. For instance, if the OP knew that all his data was itemId, tapeId, recordNum, startTime, endTime, comment, he could have most easily parsed it with item, tape, recordNum, startTime, endTime, comment = dataline.split(None,5) It's just those optional and variable-formatted fields that getcha. :) -- Paul pyparsing can be downloaded at http://pyparsing.sourceforge.net. From jerf at jerf.org Mon Jan 31 00:00:22 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 31 Jan 2005 00:00:22 -0500 Subject: python and gpl References: Message-ID: On Sun, 30 Jan 2005 22:25:10 -0600, John Hunter wrote: > The question is: does shipping a backend which imports a module that > links with GPL code make some or all of the library GPL. This > question is complicated, in my mind at least, by several factors. I believe the best and most honest answer right now is, "Nobody knows." In fact, a careful reading of at least the LGPL (which I recently carefully read before putting a project under it, so I can speak to it where I can't speak to the GPL with quite as much confidence) shows that it is almost hopelessly based on the C way of doing things, with "linking" and "executables", that not only doesn't apply to Python, but doesn't apply to a lot of other modern languages as well. (I am fairly confident that the GPL has identical shortcomings, I just haven't read it as recently.) Specifically, I put a Javascript project under the LGPL and felt compelled to augment it with an appendix of just under 3K, just to make the LGPL make sense. I had to redefine "library", clarify the "work based on the library" and "work using the library" distinction in a context where there is no "linking" occurring, and correctly apply my Appendix to the clause that allows you to use future versions of the LGPL. And my problem is much simpler than yours. (I'm in control of the license, so I was able to simply clarify it, but there would still be the problem of what the raw LGPL would mean to someone had I not amended it, so from a certain point of view there is some similarity despite the difference in our positions; it is the user dilemma that prompted my solution.) Right now, when it comes down to it, I don't think we can even define "program" in a legal sense that is clear and useful; without that, trying to *deeply* understand the (L)GPL is probably a hopeless affair. From fredrik at pythonware.com Wed Jan 26 11:49:35 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Jan 2005 17:49:35 +0100 Subject: Help With Python References: Message-ID: Peter Maas wrote: > > Can anybody help me get started? I am completely new to programming! > Online: > > - http://www.python.org/moin/BeginnersGuide (Beginner, Advanced) > - http://www.freenetpages.co.uk/hp/alan.gauld/ (Beginner) > - http://docs.python.org/tut/tut.html (Beginner) > - http://diveintopython.org/ (Advanced) also: http://www.byteofpython.info/ > Books (Look for most recent editions): > > - Mark Lutz, Learning Python (Beginner) > - Alex Martelli, Python in a Nutshell (Beginner, Advanced) > - Frederik Lundh, Python Standard Library (Beginner, Advanced) on-line here: http://effbot.org/librarybook on-line here: http://effbot.org/zone/librarybook.htm (pdf version) > - Alex Martelli, Python Cookbook (Beginner, Advanced) > - Mark Pilgrim Dive Into Python (Advanced) on-line here: http://diveintopython.org From michele.simionato at gmail.com Thu Jan 27 06:40:24 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 27 Jan 2005 03:40:24 -0800 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106814263.835719.181360@z14g2000cwz.googlegroups.com> Message-ID: <1106826024.655143.227050@c13g2000cwb.googlegroups.com> Peter Maas: >michele.simion... at gmail.com schrieb: >> Davor is right: even if >> you do not want to use it, the stuff is *there* and somebody in your >> team will. So definitely there is an audience of programmers that just >> do not have an use for all the sophistication and actually are >> penalized by it. >No, because Python does not enforce using advanced concepts. You >can write programs that are as simple as in 1991. A group of developers >always has to find some kind of common style with a chance that some >are penalized. This can happen with every language. No. In theory C++ could be kept as simple as C but in practice it is not. >> There is not much than can be done at the Python level. But I would >> see with interest a Python spinoff geared towards simplicity. >I think this would be useless because advanced concepts exist for >a reason. A simplified spin-off would aquire advanced concepts >over time and would just become a clone of Python. And then we will need another simplified spinoff ;) There is always a fight between simplificity and complexity. Some complexity is not needed, and I am sure even in Python something could be dropped. But it is difficult to find what can be removed. Remember that Saint-Exupery quote? Something like "a work of art is finished when there is nothing left to remove?" M.S. From jeff at ccvcorp.com Tue Jan 11 15:41:44 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 11 Jan 2005 12:41:44 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <10u5fu3o7v4h9e3@corp.supernews.com> Message-ID: <10u8e65lju3atbd@corp.supernews.com> Jacek Generowicz wrote: > Given a population with previous exposure to computer programming, my > money is on the map-lambda version. But this last point is mostly > irrelevant. The fact is that you cannot program computers without > doing a bit of learning ... and the lambda, map and friends really do > not take any significant learning. I guess we'll have to agree to disagree, because given the same conditions, I *still* think that a list comprehension expresses its semantics more clearly than map/lambda. I'd also point out that not all Python programmers will have significant prior exposure to programming ideas, and even those who do will not necessarily have prior exposure to lambdas. It's true that programming requires learning, and that map/lambda aren't a tremendous burden to learn. Still, to my mind they make a program a tiny increment more complicated. (I find that reading a lambda requires mentally pushing a stack frame to parse the lambda and another to translate map() into a loop, whereas a list comp's expression doesn't require such a shift, and a function name works as a good placeholder that makes reading easier.) It's not a big difference in any individual case, but incremental differences build up. From the sounds of it, you may have the opposite experience with reading map/lambda vs. reading list comps, though, so we could go back and forth on this all week without convincing the other. :) >>Speaking for *this* laboratory rat, at least, map/lambda was always a >>nasty puzzle for me and difficult to sort out. But when list comps >>were introduced, after reading just a sentence or two on how they >>worked, they were completely clear and understandable -- much more so >>than map/lambda after many months of exposure. > > Forgetting about lambda, map, filter and reduce, do you find that you > pass callables around in your Python programs, or is this not > typically done in your programs? Sure, I pass callables around quite a bit. Usually they're GUI callbacks or the like. Usually they're also either complex enough that lambda would be undesireable if not impossible, or they're simple and numerous (e.g. calling a function with different parameters) such that it's easy to write a factory function that returns closures rather than feed the parameter in with a lambda. Jeff Shannon Technician/Programmer Credit International From tim at pollenation.net Sat Jan 29 09:41:05 2005 From: tim at pollenation.net (Tim Parkin) Date: Sat, 29 Jan 2005 14:41:05 +0000 Subject: Textual markup languages (was Re: What YAML engine do you use?) In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> Message-ID: <1107009665.5655.19.camel@localhost.localdomain> On Sun, 2005-01-23 at 13:41 +0100, Fredrik Lundh wrote: > Alan Kennedy wrote: > > If I can't find such a markup language, then I might instead end up using a WYSIWYG editing > > component that gives the user a GUI and generates (x)html. > > > > htmlArea: http://www.htmlarea.com/ > > Editlet: http://www.editlet.com/ > > > > But I'd prefer a markup solution. > > some of these are amazingly usable. have you asked your users what they > prefer? (or maybe you are your user? ;-) Most users prefer to write documents in word and then paste them into textareas. Not surprisingly means no semantic content, little chance of restyling, horrible encoding problems and far too long spent on the phone trying to explain why it's not a good idea. Giving users a wysiwyg textarea creates the problems that users start to spend time trying to create a 'styled' document, inevitably sacrificing semantics (many is the user that has applied a header style to make things bold or a quote sytle to indent a paragraph). Using text based layouts reinforces the perception that you aren't creating a styled document and that the semantic structure is important. People who have used non-wysiwyg editors have found that their initial reticence has been quickly overtaken by their joy at not having to fight with 'style' and the reassurance that their content is now 'redesign proof'. Tim Parkin http://www.pollenation.net From tjreedy at udel.edu Mon Jan 24 20:36:56 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Jan 2005 20:36:56 -0500 Subject: Another scripting language implemented into Python itself? References: Message-ID: "Roy Smith" wrote in message news:roy-97DBC5.19403124012005 at reader1.panix.com... > In article , > Quest Master wrote: > >> So, my question is simply this: is there an implementation of another >> scripting language into Python? > > Python *is* a scripting language. Why not just let your users write > Python modules which you them import and execute via some defined API? That was my thought also, with the note that you only need to document as much users will need, including specific modules (if any) to import. Terry J. Reedy From wittempj at hotmail.com Mon Jan 17 06:25:21 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 17 Jan 2005 03:25:21 -0800 Subject: getting a class attribute using a keyword argument In-Reply-To: References: Message-ID: <1105961121.277992.105630@f14g2000cwb.googlegroups.com> Guy Robinson wrote: > Hello, > > I have a list of class instances. I wish to get the appropriate class attribute > in each class instance depending on a SINGLE keyword in the calling class. > > How do I get the calling method to correctly recognise the keyword as a keyword > and not a class attribute? See example code below (which doesn't work). > > class tocall: > def __init__(self): > self.title = "test" > self.name = "name" > > def callingmethod(self,**kw): > for key in kw: > if tocall.key == kw[key]: > return tocall.key > > which should work as such(but doesn't): > > print callmethod(title = "test") > print callmethod(name = "name") > > Regards, > > Guy You probably want something like this: class tocall: def __init__(self): self.title = "test" self.name = "name" x = tocall() print getattr(x, 'title') print getattr(x, 'name') print getattr(x, 'bogus') From john.abel at pa.press.net Wed Jan 26 08:18:36 2005 From: john.abel at pa.press.net (John Abel) Date: Wed, 26 Jan 2005 13:18:36 +0000 Subject: FTP Server In-Reply-To: <1106743852.600769.72820@c13g2000cwb.googlegroups.com> References: <1106743852.600769.72820@c13g2000cwb.googlegroups.com> Message-ID: <41F798AC.3010305@pa.press.net> If you're after a simple FTP server, have a look at medusa. Regards John michele.simionato at gmail.com wrote: >What's the simplest way to write an FTP Server in Python? >A short research on the newsgroup and on the Cookbook did not >bring out anything relevant (but I hear a little voice in the >back of my head saying Twisted, Twisted! ...) >Michele Simionato > > > From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Tue Jan 25 06:15:03 2005 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Tue, 25 Jan 2005 12:15:03 +0100 Subject: Right place for third party modules (here: fixedpoint) In-Reply-To: References: <35kj2iF4n6sokU1@news.dfncis.de> Message-ID: <35mo1gF4oqib4U1@news.dfncis.de> Fredrik Lundh schrieb: > > ah, forget what I said. you need to put the fixedpoint.py *file* under site-packages, > not the entire directory. as that "python -v -v" would have told you: > Thank you (and Steve Holden), that did it. > >>more out > > ... > # trying C:\python24\lib\site-packages\fixedpoint.pyd > # trying C:\python24\lib\site-packages\fixedpoint.dll > # trying C:\python24\lib\site-packages\fixedpoint.py > # trying C:\python24\lib\site-packages\fixedpoint.pyw > # trying C:\python24\lib\site-packages\fixedpoint.pyc > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named fixedpoint > ... > > > Very helpful, not only directories, but full module names. I hope I'll remember (or find) "python -v -v" next time around. Python is nice, but Python + c.l.p. is a Really Good Thing. Koczian -- Dr. Sibylle Koczian Universitaetsbibliothek, Abt. Naturwiss. D-86135 Augsburg Tel.: (0821) 598-2400, Fax : (0821) 598-2410 e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE From stephen.thorne at gmail.com Sun Jan 9 05:45:16 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Sun, 9 Jan 2005 20:45:16 +1000 Subject: Pre/Postconditions with decorators In-Reply-To: <7x1xcvwkdj.fsf@ruckus.brouhaha.com> References: <1105094828.619317.315340@z14g2000cwz.googlegroups.com> <34814fF43bm4cU1@individual.net> <7x1xcvwkdj.fsf@ruckus.brouhaha.com> Message-ID: <3e8ca5c805010902455ef60947@mail.gmail.com> On 08 Jan 2005 15:50:48 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Stephen Thorne writes: > > Unresolved Problems: > > 1) How do you handle duck types, i.e. a method that accepts StringIO, > > cStringIO or any other object that has a .readlines(), .seek() and > > .read() method? > > That should really be done through having those classes inherit a > file-operations mixin, or else through interfaces (which might get > added to Python). Working under the assumption we cannot change the existing standard library. > > 2) How do you turn off the type checking for production code? > > It should be left on. Leaving it in for development and turning it > off for production is like wearing a parachute during ground training > and taking it off once you're in the air. So we can't use this for a case where we have an extremely large list then ;). Its an O(n) operation to just call a function that takes a list of a specific type. Stephen. From python-url at phaseit.net Sun Jan 9 12:11:09 2005 From: python-url at phaseit.net (Josiah Carlson) Date: Sun, 09 Jan 2005 17:11:09 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 9) Message-ID: QOTW: Jim Fulton: "[What's] duck typing?" Andrew Koenig: "That's the Australian pronunciation of 'duct taping'." "I'm thinking that the I-Ching is a vast untapped resource for programming wisdom, plus it makes it funny." -- Mark Carter Nick Coghlan brings up the 'lambdas are going away in 3.0' topic, which has been discussed before: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/81e17b1d3ccba538 A user asks about a non-generator-based method for iteration using class __iter__ and next() methods: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/6336a00ad217888a Daniel Bickett asks about getting Twisted and wxPython working together, and receives both a threaded and non-threaded version: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/73f1e7758225afc3 A question about iterating over floats...be careful! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1278866159ac4429 A Boogieman asks whether Python is easily learned and what can be done with it. Quick answer: yes, and anything you are capable of doing: This Boogieman later asks about GUI toolkits: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e67b776df72eb336 http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d502698b4adacd01 Erik Bethke writes Majong game after using Python for a month. Ahh, will the wonders of Python never cease? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/6d710e35007f0f32 Kamilche asks about getting warnings when not calling a function, and gets pointed to pychecker, something more of us should be using: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/dff810b7dacd247c Are people allowed to build commercial applications in Python? YES! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/aa953388db68b196 Questions about asyncore brings up a web server in asyncore from _Python Web Programming_, and a pointer to Twisted. Alternatively, one could look at the asynchat or smtpd modules in the standard library as sources of inspiration: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/81360ec06013e36d ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. deli.cio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From pythongnome at hotmail.com Thu Jan 6 17:10:33 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Thu, 06 Jan 2005 22:10:33 GMT Subject: Python Operating System??? In-Reply-To: <10trb0mgiflcj4f@corp.supernews.com> References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: David Brown wrote: > Hello. I recently came across a free operating system called Unununium (or > something like that) and it was developed in Python and Assembly. > > Now, I have been looking for a way to make an operating system for a long > long time and the only possibilities I could find were C++ and assembly. I > don't mind assembly so much if I don't have to use it very often. But C++ is > so complicated and errors are pretty much impossible to find in the code for > me. > > So, I was wondering if it would be possible to find a bootloader that loads > a python file at startup or something... > > Is there an example somewhere of a Python OS? > > Thanks! > > Hasn't there been numerous discussions about this in the past?? From lbates at syscononline.com Wed Jan 19 11:01:43 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 19 Jan 2005 10:01:43 -0600 Subject: Accessing MDB files on Windows In-Reply-To: <1635068.ZTfiooUzB4@strongwill.g2ctech> References: <1635068.ZTfiooUzB4@strongwill.g2ctech> Message-ID: I'm assuming the application will be run on Windows. You can use ODBC or DAO. An DAO solution that I wrote (and use) can be found at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303349 For ODBC you would just use the standard library module. Larry Bates Syscon, Inc. Jorge Luiz Godoy Filho wrote: > Hi, > > > What is the best way to deal with MDB files? I was thinking on using > ODBC... I'll need to read and write some information to it. The load > won't be so high, but there might be a lot of data. > > Any advices? Will my approach work? I'm not a Windows guy... :-) > From b_b at net.hr Sat Jan 15 11:29:57 2005 From: b_b at net.hr (Brane) Date: Sat, 15 Jan 2005 17:29:57 +0100 Subject: python to mssql References: Message-ID: <19womotgpx7sg.qru1ognhkyt7.dlg@40tude.net> On Fri, 14 Jan 2005 15:22:44 -0500, Richards Noah (IFR LIT MET) wrote: > "Robert Brewer" wrote in message > news:mailman.722.1105724341.22381.python-list at python.org... > Brane wrote: >> can someone please give me some info regarding subject >> >>http://sourceforge.net/projects/mysql-python >> >>Ask a broad question... >> >> >>Robert Brewer > > Robert, the question was about 'mssql', not 'mysql'. As for mssql, a search > on google will give you the following as the first result: > http://pymssql.sourceforge.net/ > > with others on the page that include: > http://www.object-craft.com.au/projects/mssql/ > http://www.egenix.com/files/python/eGenix-mx-Extensions.html > > > Don't be lazy, Brane. Your first point of reference should _always_ be > google. The fact that "I'm Feeling Lucky" points you to pymssql shows that > you didn't do any research before posting here. > > -Noah well i wonted to hear frome someone who already used it because there is lots of topics about subject anyway thnks for info brane From enleverlesO.OmcO at OmclaveauO.com Mon Jan 24 17:52:19 2005 From: enleverlesO.OmcO at OmclaveauO.com (Do Re Mi chel La Si Do) Date: Mon, 24 Jan 2005 23:52:19 +0100 Subject: add indexes on the fly to lists References: Message-ID: <41f69f0b$0$6606$8fcfb975@news.wanadoo.fr> Hi ! If you want only "search and found" element, look dictionnary ; if you want also to have the order, see the module set. Good night -- Michel Claveau From smitsky at mindspring.com Sat Jan 8 19:37:50 2005 From: smitsky at mindspring.com (Smitsky) Date: Sun, 09 Jan 2005 00:37:50 GMT Subject: Windows XP Installation Message-ID: Hi. I am a newbie to Python. I am running Win XP and want to know what the best course is for installing Python on my system. Could someone kindly direct me to some related resources? Thanks in advance, Steve From sjmachin at lexicon.net Tue Jan 18 02:41:31 2005 From: sjmachin at lexicon.net (John Machin) Date: 17 Jan 2005 23:41:31 -0800 Subject: Fuzzy matching of postal addresses References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <1106034091.153664.309670@z14g2000cwz.googlegroups.com> You can't even get anywhere near 100% accuracy when comparing "authoritative sources" e.g. postal authority and the body charged with maintaining a database of which streets are in which electoral district -- no, not AUS, but close :-) From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 12:27:15 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?UTF-8?B?TWFydGluIE1PS1JFSsWg?=) Date: Mon, 10 Jan 2005 18:27:15 +0100 Subject: Writing huge Sets() to disk In-Reply-To: References: Message-ID: <41E2BAF3.9070106@ribosome.natur.cuni.cz> Paul McGuire wrote: > "Martin MOKREJ?" wrote in message > news:mailman.448.1105373471.22381.python-list at python.org... > >>Hi, >> I have sets.Set() objects having up to 20E20 items, >>each is composed of up to 20 characters. Keeping >>them in memory on !GB machine put's me quickly into swap. >>I don't want to use dictionary approach, as I don't see a sense >>to store None as a value. The items in a set are unique. >> >> How can I write them efficiently to disk? To be more exact, >>I have 20 sets. _set1 has 1E20 keys of size 1 character. >> >>alphabet = ('G', 'A', 'V', 'L', 'I', 'P', 'S', 'T', 'C', 'M', 'A', 'Q', > > 'F', 'Y', 'W', 'K', 'R', 'H', 'D', 'E') > >>for aa1 in alphabet: >> # l = [aa1] >> #_set1.add(aa1) >> for aa2 in alphabet: >> # l.append(aa2) >> #_set2.add(''.join(l)) >>[cut] >> >> The reason I went for sets instead of lists is the speed, >>availability of unique, common and other methods. >>What would you propose as an elegant solution? >>Actually, even those nested for loops take ages. :( >>M. > > > _set1 only has 19 keys of size 1 character - 'A' is duplicated. Ahh, you are right. That's a typo, yet I have to figure out which char I have to use. But 'Z' will do for the tests anyway. > > Assuming you replace 'A' with another character (say 'Z'), then here is what > you get: > _set1 - 20 elements (20**1) > _set2 - 400 elements (20**2) > _set3 - 8000 elements (20**3) > ... > _set20 - 20**20 ~ 10 ^ (1.301*20) or 1E26 > > If you have no duplicates in your alphabet, then you wont need to use sets, > every combination will be unique. In this case, just use a generator. As I noted in later response, actually I will compare these ideal sets to some real world examples. I have no expectation how many entries will be common and how many unique. The only thing I know even in real world, I might be in size ranges of 2E6 or perhaps 2E8? > Here's a recursive generator approach that may save you a bunch of nested > editing (set maxDepth as high as you dare): > > alphabet = ('G', 'A', 'V', 'L', 'I', 'P', 'S', 'T', 'C', 'M', 'Z', 'Q', 'F', > 'Y', 'W', 'K', 'R', 'H', 'D', 'E') > > maxDepth = 3 > > def genNextCombo(root=list(),depth=1): > for a in alphabet: > thisRoot = root + [a] > yield "".join( thisRoot ) > if depth < maxDepth: > for c in genNextCombo(thisRoot, depth+1): > yield c > > for c in genNextCombo(): > print c # or write to file, or whatever Works nice, but http://www.python.org/doc/2.3.4/ref/yield.html doesn't really tell what happens here. :( But is quite fast and definitely saves those the stupid recursively hand-written for loops. Thanks Paul! M. From pierre.barbier at cirad.fr Wed Jan 19 03:07:59 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Wed, 19 Jan 2005 09:07:59 +0100 Subject: extension module, thread safety? In-Reply-To: References: <41ecbaae$0$1046$626a14ce@news.free.fr> <41eccfe4$0$16621$636a15ce@news.free.fr> Message-ID: <41ee14f7$0$26194$626a14ce@news.free.fr> David Bolen a ?crit : > Nick Coghlan writes: > > And even before that it was certainly possible to call into the Python > interpreter from a native thread using existing functions, albeit the > newer functions are more convenient (and perhaps more robust, I don't > know). > > My earliest interaction with Python (~1999, while writing a module > that extended and embedded Python 1.5.2) used PyEval_AcquireThread() > and PyEval_ReleaseThread() to get access to a thread state from a > native C application thread (not initiated by the Python interpreter) > to allow me to call safely into an executing Python script upon > asynchronous data reception by the C code. > > -- David Yes, now you mention this I remember trying to use these functions ! But there is two problems with them (and only one is solved by the new functions) ! The first problem is the dead lock is you try to acquire the same thread twice. This implies a very low level use of these function, and it can be a real pain to find where to put them without risking this dead lock. This is no more a problem with the new functions. But the second (and not solved) problem is: these functions block the current thread when you try to get the GIL ! This is an issue if you don't want your GUI thread to be blocked when a buggy module does not release the GIL during long computations. I didn't find any function like "test the state of the GIL and if it's free, then acquire it" ! And, IMO, it's missing ... Then, if python goes to a model where critical sections are identified and the GIL acquired only there, all these problems will disappear ! That's why I really hope Python 3 will include this kind of thread support ... Pierre From dw at botanicus.net Sun Jan 9 18:23:58 2005 From: dw at botanicus.net (David Wilson) Date: Sun, 09 Jan 2005 23:23:58 +0000 Subject: vi and python In-Reply-To: <20050110032348.GA1960@mrna.tn.nic.in> References: <20050110032348.GA1960@mrna.tn.nic.in> Message-ID: <41E1BD0E.1010805@botanicus.net> km wrote: >Is there a way to display inbuilt function syntax as the user starts typing a function name with 'Vi' editor in console mode? > > Hi there, Unfortunately due to the highly dynamic nature of Python, this is difficult to do reliably. It is one benefit that static typing, to a certain extent, would bring to the language. Sadly we don't have that, yet. :) David. From bokr at oz.net Wed Jan 5 15:07:43 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 05 Jan 2005 20:07:43 GMT Subject: Deferred expressions (was Re: Lambda as declarative idiom) References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> Message-ID: <41dc4099.75876003@news.oz.net> On Tue, 04 Jan 2005 19:31:37 +1000, Nick Coghlan wrote: >Steven Bethard wrote: >> Nick Coghlan: def-from syntax [4] >> (def f(a) + o(b) - o(c) from (a, b, c)) >> (def x * x from (x)) >> (def x from ()) >> (def x.bar(*a, **k) from (*a, **k)) >> ((def x(*a, **k) from ()) for x, a, k in funcs_and_args_list) > >After a bit more musing, this is definitely my preferred syntax. I'd call it a >'deferred expression' rather than an anonymous function, though. The name change >may seem minor, but it changes the emphasis of the feature from how it's >implemented to what it is useful for (i.e. deferring evaluation of an expression >until call time). I like the fact that 'def' can serve as a mnemonic for 'defer' or 'deferred' ;-) OTOH, I like concise notation for expressions, and the def and from aren't really necessary if you can tag the first expression with some syntax marker. I suggested (: rather than (def since (: is illegal now and won't break anything. But all this is just a rewrite of lambda params:expr as (def expr from params). What is the point again? (Not that my rewrite to (:expr)(params) is any more than a lambda rewrite either). If backticks could be used, `(expr:params) might be an interesting spelling of lambda params:expr. I do like being able to leave out the from clause. `(expr) would let you do that too, just as well as (:expr). > >It's also conducive to a clean no-argument syntax - simply make the 'from' claus >optional when the argument list is empty. That is an advantage of having it inside the outer parens, which my (:expr)(params) couldn't benefit from -- unless I just take your format and substitute ':' for both def and from: (: f(a) + o(b) - o(c) : (a, b, c)) (: x * x : (x)) (: x) # empty arg list (: x.bar(*a, **k) : (*a, **k)) ((: x(*a, **k) : (x=x, a=a, k=k) for x, a, k in funcs_and_args_list) > >'def' and 'from' are already keywords, so there shouldn't be any compatibility >problems. > >Michael Spencer's idea of using 'for' instead of 'from' was quite interesting, >but the use of 'for' without a corresponding 'in' feels a bit misleading :) What was the point of all this again? Pretending lambda goes away without really killing it? ;-) Regards, Bengt Richter From kent3737 at yahoo.com Wed Jan 26 11:21:40 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Wed, 26 Jan 2005 11:21:40 -0500 Subject: re.search - just skip it In-Reply-To: <1106754436.876675.144290@c13g2000cwb.googlegroups.com> References: <1106754436.876675.144290@c13g2000cwb.googlegroups.com> Message-ID: <41f7c10b$1_1@newspeer2.tds.net> rasdj at frontiernet.net wrote: > Input is this: > > SET1_S_W CHAR(1) NOT NULL, > SET2_S_W CHAR(1) NOT NULL, > SET3_S_W CHAR(1) NOT NULL, > SET4_S_W CHAR(1) NOT NULL, > ; > > .py says: > > import re, string, sys > s_ora = re.compile('.*S_W.*') > lines = open("y.sql").readlines() > for i in range(len(lines)): > try: > if s_ora.search(lines[i]): del lines[i] When you delete for example lines[0], the indices of the following lines change. So the former lines[1] is now lines[0] and will not be checked. The simplest way to do this is with a list comprehension: lines = [ line for line in lines if not s_ora.search(line) ] Even better, there is no need to make the intermediate list of all lines, you can say lines = [ line for line in open("y.sql") if not s_ora.search(line) ] In Python 2.4 you don't have to make a list at all, you can just say open("z.sql","w").writelines(line for line in open("y.sql") if not s_ora.search(line)) ;) Kent > except IndexError: > open("z.sql","w").writelines(lines) > > but output is: > > SET2_S_W CHAR(1) NOT NULL, > SET4_S_W CHAR(1) NOT NULL, > ; > > It should delete every, not every other! > > thx, > > RasDJ > From http Sat Jan 29 07:11:41 2005 From: http (Paul Rubin) Date: 29 Jan 2005 04:11:41 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> Message-ID: <7xacqsbfk2.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > Indeed, if it was a single new function to an existing module, I would > not require that this be delivered to users first. It is entire new > libraries that I worry about. Why is it different if a single new function is added to an existing module, or if the single new function has the boilerplate of a new module wrapped around it? Look at the sha and md5 modules. They are very similar in both interface and implementation. The only internal function that's really different is the update operation; they actually might have been combined into one module that did the other operations with the same code. But, it's also reasonable to have them as separate modules. If users start needing sha256, it could be done the same way, one new update operation and the rest boilerplate, but in practice it would probably be a separate module. Are you saying if there was user demand for an sha256 module and someone wrote one, you'd still require a year of separate distribution? > A module *is* typically more complex than a single function. If > your new module has only a single new function, we should discuss > whether it really needs to be a separate module. I previously had the mistaken belief that urandom was a new module rather than a function inserted into an existing module. Note that the urandom's implementation is not ultra-trivial. An AES or DES addition to an existing module that implements just one call: ECB(key, data, direction) would be a huge improvement over what we have now. A more complete crypto module would have some additional operations, but ECB is the only one that's really essential. I already have a pure-Python module that does all the other operations using ECB as a subroutine. It's speed isn't great but it's useable in some real applications. It's only the ECB operation that's intolerably slow in Python. If you think a function like that could be added to some existing module with less hassle than adding a new module, then I can write one and submit it. > > Well, if he indicates that it's not a policy and that the question is > > still open, then I could see getting interested again in writing an > > AES module. At the moment I continue to see his python-dev post as > > quite discouraging. > > And, again, I consider this perfectly fine. This would be a volunteer > effort, and volunteers are free to work on whatever they please. Well, volunteers are more likely to work on modules that are mentioned as being welcome by the developers, than modules affected by explicit prior developers' public decisions that cast a chill over the hope of ever getting such a module accepted. > Furthermore, people who want an AES module for Python could get one from Come on, you're being deliberately obtuse, we've discussed this over and over. There are plenty of AES modules that people can get from somewhere. The topic is what it takes to have an AES module that people don't NEED to get from anywhere, because they already have it from having Python installed. Do I have to keep repeating "batteries included" until you understand what it means? > http://sourceforge.net/projects/cryptkit/ > > Maybe Bryan Mongeau will contribute this code to Python some day. Well, that code has been around for over a year, people are using it, etc. Are you saying you'll support its inclusion if Bryan offers to contribute it? I've examined that module, I wouldn't consider it ideal for the core (besides AES, it has some complicated additional functions that aren't useful to most people), but it would certainly take care of my AES needs (it's apparently missing DES though). > I did not say that. I said we don't normally invite people to work > on anything - I said not that we *should* not invite them. I would say that inviting people to work on a module for the stdlib means the developers have thought about whether such a module would be useful and worth including, and are indicating that they're favorable to the idea. However, you wrote: In Message-ID: <41f4324a$0$1547$9b622d9e at news.freenet.de> So if the module was primarily written to be included in the core, I would initially reject it for that very reason. After one year or so in its life, and a recognizable user base, inclusion can be considered. The context was new modules in general, not specifically an AES module. Since "considered" means "thought about", so you said inclusion shouldn't even be thought about until the module is already done. That's completely in conflict with the idea of inviting anyone to work on a new module, since inviting means that there's been some thought. > Now that you mention it, I find that there is an important exception > from my factual statement: I do regularly ask people reporting bugs > or requesting features to work fixing the bugs or implementing the > features. It is perfectly fine if they say "no" then. If they say > yes, there is an implied promise that I'll review their code when > they are done. I would say there's an implied promise of something more than a code review. There's an implied statement that you agree that the proposed new functionality is useful, which means the patch has a good chance of being accepted to the stdlib if it's not too messy or cumbersome. That's a heck of a lot different from saying "why don't you write that patch and distribute it independently for a year on a purely speculative basis, and then I'll think about whether it's worthwhile to include it or not". > As it appears to be clear that you are not going to implement an AES > module in the foreseeable future, The reason for that is as far as I can tell, even if I follow 100% of your prescription of writing the module, releasing it independently and supporting it for a year, and then offering to contribute it complete with favorable user reviews and a promise of two years of further support, the probability of it being accepted and included is still close to zero. In more recent messages you've suggested that my reading of that probability is wrong and that it's actually higher than zero. So let me just ask you one final question: suppose I do all that stuff. The question: in your personal opinion, based on the best information you have, what is the your own subjective estimate of the probability? I won't say I'd immediately replace my estimate with yours, but if you name a reasonably high number and tell me that you really believe that number, then I could get interested again. > and as it also seems to be clear that you cannot talk me into > changing my views on how Python should be developed, I think further > discussing this entire thing is pointless. Well, you can have whatever views you want, but one I've thing I've realized from this thread is that many of the frustrations I often encounter with Python are a direct result of a development process that's successful in some ways but dysfunctional in others. From itsme at yahoo.com Thu Jan 6 20:58:51 2005 From: itsme at yahoo.com (It's me) Date: Fri, 07 Jan 2005 01:58:51 GMT Subject: Another PythonWin Excel question References: <41ddb59e$0$8338$afc38c87@news.optusnet.com.au> Message-ID: Yes, Mike, Others pointed that out as well. The difficulty is that they are all in VBAs. Most of them can be translated to Python fairly easily, and some I can get from looking at the recorded macro - but some requires quite a bit of head scratching. For instance, I wanted to figure out how create a new window. So, I went through the record macro process and looked at the VBA code, it says: ActiveWindow.NewWindow Okay. Now what??? And for switching window, it says: Windows("Book1:1").Activate Okay. ??? So, I look through the online information on msdn and viola! No mentioning of that anwhere.... Would be nice if there's a Python specific of it....but just dreaming... Back to reading MSDN..... Thanks, "Mike Thompson" wrote in message news:41ddb59e$0$8338$afc38c87 at news.optusnet.com.au... > It's me wrote: > > I followed the example in > > http://stompstompstomp.com/weblog/technical/2004-05-20 and learned that to > > add a new worksheet to an Excel workbook, you would use the > > workbook.Worksheets.Add() method. That works. However, the new worksheet > > got added *in front* of the last worksheet I was at. How can I get it to > > add *after*? > > > > Thanks, > > > > -- > > Me > > > > > > Does this help? > > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_wrcore/html/wrtskhowtomoveworksheetswithinworkbooks.asp > > -- > Mike From kbk at shore.net Sun Jan 23 15:15:45 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Sun, 23 Jan 2005 15:15:45 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200501232015.j0NKFjhi001559@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 273 open ( +1) / 2746 closed ( +9) / 3019 total (+10) Bugs : 797 open ( +4) / 4789 closed (+12) / 5586 total (+16) RFE : 166 open ( +1) / 141 closed ( +0) / 307 total ( +1) New / Reopened Patches ______________________ fix distutils.install.dump_dirs() with negated options (2005-01-17) CLOSED http://python.org/sf/1103844 opened by Wummel Add O_SHLOCK/O_EXLOCK to posix (2005-01-17) http://python.org/sf/1103951 opened by Skip Montanaro setup.py --help and --help-commands altered. (2005-01-17) http://python.org/sf/1104111 opened by Titus Brown new-style exceptions (2005-01-18) http://python.org/sf/1104669 opened by Michael Hudson misc doc typos (2005-01-18) CLOSED http://python.org/sf/1104868 opened by DSM chr, ord, unichr documentation updates (2004-10-31) http://python.org/sf/1057588 reopened by mike_j_brown Faster commonprefix in macpath, ntpath, etc. (2005-01-19) http://python.org/sf/1105730 opened by Jimmy Retzlaff get rid of unbound methods (mostly) (2005-01-17) CLOSED http://python.org/sf/1103689 opened by Guido van Rossum Updated "Working on Cygwin" section (2005-01-22) http://python.org/sf/1107221 opened by Alan Green Add Thread.isActive() (2005-01-23) http://python.org/sf/1107656 opened by Alan Green Speed up function calls/can add more introspection info (2005-01-23) http://python.org/sf/1107887 opened by Neal Norwitz Patches Closed ______________ fix distutils.install.dump_dirs() with negated options (2005-01-17) http://python.org/sf/1103844 closed by theller ast-branch: fix for coredump from new import grammar (2005-01-11) http://python.org/sf/1100563 closed by kbk Shadow Password Support Module (2002-07-10) http://python.org/sf/579435 closed by loewis misc doc typos (2005-01-18) http://python.org/sf/1104868 closed by fdrake extending readline functionality (2003-02-11) http://python.org/sf/684500 closed by fdrake self.button.pack() in tkinter.tex example (2005-01-03) http://python.org/sf/1094815 closed by fdrake Clean up discussion of new C thread idiom (2004-09-20) http://python.org/sf/1031233 closed by fdrake Description of args to IMAP4.store() in imaplib (2004-12-12) http://python.org/sf/1084092 closed by fdrake get rid of unbound methods (mostly) (2005-01-17) http://python.org/sf/1103689 closed by gvanrossum New / Reopened Bugs ___________________ email.base64MIME.header_encode vs RFC 1522 (2005-01-17) http://python.org/sf/1103926 opened by Ucho wishlist: os.feed_urandom(input) (2005-01-17) http://python.org/sf/1104021 opened by Zooko O'Whielacronx configure doesn't set up CFLAGS properly (2005-01-17) http://python.org/sf/1104249 opened by Bryan O'Sullivan Bugs in _csv module - lineterminator (2004-11-24) http://python.org/sf/1072404 reopened by fresh Wrong expression with \w+? (2005-01-18) CLOSED http://python.org/sf/1104608 opened by rengel Bug in String rstrip method (2005-01-18) CLOSED http://python.org/sf/1104923 opened by Rick Coupland Undocumented implicit strip() in split(None) string method (2005-01-19) http://python.org/sf/1105286 opened by YoHell Warnings in Python.h with gcc 4.0.0 (2005-01-19) http://python.org/sf/1105699 opened by Bob Ippolito incorrect constant names in curses window objects page (2005-01-19) http://python.org/sf/1105706 opened by dcrosta null source chars handled oddly (2005-01-19) http://python.org/sf/1105770 opened by Reginald B. Charney bug with idle's stdout when executing load_source (2005-01-20) http://python.org/sf/1105950 opened by imperialfists os.stat int/float oddity (2005-01-20) CLOSED http://python.org/sf/1105998 opened by George Yoshida README of 2.4 source download says 2.4a3 (2005-01-20) http://python.org/sf/1106057 opened by Roger Erens semaphore errors from Python 2.3.x on AIX 5.2 (2005-01-20) http://python.org/sf/1106262 opened by The Written Word slightly easier way to debug from the exception handler (2005-01-20) http://python.org/sf/1106316 opened by Leonardo Rochael Almeida os.makedirs() ignores mode parameter (2005-01-21) http://python.org/sf/1106572 opened by Andreas Jung split() takes no keyword arguments (2005-01-21) http://python.org/sf/1106694 opened by Vinz os.pathsep is wrong on Mac OS X (2005-01-22) CLOSED http://python.org/sf/1107258 opened by Mac-arena the Bored Zo Bugs Closed ___________ --without-cxx flag of configure isn't documented. (2003-03-12) http://python.org/sf/702147 closed by bcannon presentation typo in lib: 6.21.4.2 How callbacks are called (2004-12-22) http://python.org/sf/1090139 closed by gward rfc822 Deprecated since release 2.3? (2005-01-15) http://python.org/sf/1102469 closed by anthonybaxter codecs.open and iterators (2003-03-20) http://python.org/sf/706595 closed by doerwalter Wrong expression with \w+? (2005-01-18) http://python.org/sf/1104608 closed by niemeyer Wrong expression with \w+? (2005-01-18) http://python.org/sf/1104608 closed by effbot Bug in String rstrip method (2005-01-18) http://python.org/sf/1104923 closed by tim_one No documentation for zipimport module (2003-12-03) http://python.org/sf/853800 closed by fdrake distutils/tests not installed (2004-12-30) http://python.org/sf/1093173 closed by fdrake urllib2 doesn't handle urls without a scheme (2005-01-07) http://python.org/sf/1097834 closed by fdrake vertical bar typeset horizontal in docs (2004-08-13) http://python.org/sf/1008998 closed by fdrake write failure ignored in Py_Finalize() (2004-11-27) http://python.org/sf/1074011 closed by loewis os.stat int/float oddity (2005-01-20) http://python.org/sf/1105998 closed by loewis os.pathsep is wrong on Mac OS X (2005-01-22) http://python.org/sf/1107258 closed by bcannon From wyojustin at hotmail.com Sun Jan 30 21:41:53 2005 From: wyojustin at hotmail.com (Justin Shaw) Date: Sun, 30 Jan 2005 21:41:53 -0500 Subject: tkSnack pitch() for frequency estimation Message-ID: <4MOdnfuccsdhB2DcRVn-jg@comcast.com> I am using the tkSnack library to estimate the frequency from a sound file. The pitch seems to drop down an octave at 400 Hertz. For example A~440 Hertz comes out at 220 Hertz. When I use the maxpitch and minpitch options to limit the response to say 380 - 460 the result is all zeros. Any ideas on how I can estimate the pitch of a sound up to 880 Hertz (with tkSnack or not)? Thanks Justin Shaw From sp1d3rx at gmail.com Tue Jan 25 15:50:10 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 25 Jan 2005 12:50:10 -0800 Subject: Question Regarding SocketServer In-Reply-To: <1106684900.771730.218060@f14g2000cwb.googlegroups.com> References: <1106684900.771730.218060@f14g2000cwb.googlegroups.com> Message-ID: <1106686210.372444.314020@f14g2000cwb.googlegroups.com> you are missing quotes in "socketserver.py". Make sure the comments at the top are quoted out. In "IDLE" they should be green. From daniel at bowettsolutions.com Wed Jan 26 13:42:14 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Wed, 26 Jan 2005 18:42:14 +0000 Subject: MySQLdb executemany Message-ID: I seem to have found a bug/limitation of executemany in MySQLdb. I am inserting 3100 records into a database. It works fine and adds them in about 1 second. I went back to the program today and realised i'd missed a field so added it to the insert statement. This seems to break it if I try to add all the records in one go. Through trial and error I have realised the limit is 2786 records in one go. Any more than that I get two different errors on the executemany statement: "MySQL server has gone away" - This occurs if I try to add all 3100 records in one go. "Lost Connection to MySQL server during query" - This happens if I am near the 2786 threshold. Is there a known limit with this function??? From fuzzyman at gmail.com Wed Jan 5 07:06:31 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jan 2005 04:06:31 -0800 Subject: Cookbook 2nd ed Credits In-Reply-To: <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> Message-ID: <1104926791.222640.183770@z14g2000cwz.googlegroups.com> Hmm... I'd love to see a list... just to know if I'm on it. Permission was sought for several of my recipes, but I don't know if any were actually used. I'm very curious... Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From rbt at athop1.ath.vt.edu Wed Jan 26 17:32:47 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Wed, 26 Jan 2005 17:32:47 -0500 Subject: exclude binary files from os.walk In-Reply-To: <41f8167b$0$8648$a1866201@visi.com> References: <41f8167b$0$8648$a1866201@visi.com> Message-ID: Grant Edwards wrote: > On 2005-01-26, rbt wrote: > > >>Is there an easy way to exclude binary files (I'm working on >>Windows XP) from the file list returned by os.walk()? > > > Sure, assuming you can provide a rigorous definition of 'binary > files'. :) non-ascii From grahamd at dscpl.com.au Wed Jan 5 17:25:28 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 5 Jan 2005 14:25:28 -0800 Subject: modpython, apache and windows References: <41DB3F0A.2010706@tiscali.co.uk> Message-ID: <1104963928.944830.39170@c13g2000cwb.googlegroups.com> Bob Van Zant wrote: > Fortunately most of the Python-for-the-web implementations do not follow > closely to the PHP paradigm of web-based programming. There are some, > like PSP, that more closely model what PHP does. > > It is not uncommon to have something like index.py which does hardly > anything except fire up a framework that takes care of parsing the rest > of the URI and passing control over to the proper script. Using some > relatively cryptic features of Apache you can hide the fact that > everything goes through index.py (mod_rewrite). I have never really liked how all these different mod_python extensions insist on using their own special file extensions, eg., .psp, .mps etc. All it does is to expose what you are using to implement a site and makes it hard for you to convert to a different implementation mechanism as all your URLs then need to change. As you point out, the only way around it is to use mod_rewrite rules. Overall, from what I have seen all it does is make configuration files harder to understand and spawn lots of newbie questions as to why they can't get anything to work. To me it is more sensible to use REST principles and not use file type extensions at all, or use an extension which reflects the type of content being delivered up and not the mechanism used to generate it. FWIW, the Vampire package tries to address this problem in mod_python by providing a simple mechanism as an extension to mod_python which gives one greater control over the file extension used in a URL and what handler that then maps to. To set it up, one has a single directive in your httpd.conf or htaccess file of the form: PythonHandler vampire You can then place in your directory any number of content handler .py files. Eg. you might have index.py, about.py, report.py etc. In the first instance, no matter what the file type extension on the URL, if the basename in the URL request matches the basename of the content handler file, then it is that file which is the target of the request. Thus, if you used the following URLs, they would map as shown: index.html --> index.py about.html --> about.py report.pdf --> report.py report.csv --> report.py feedback --> feedback.py Now normally the content handler would be called "handler()". Using vampire though, you extend the name with the file type, thus: index.html --> will call handler_html() in index.py about.html --> will call handler_html() in about.py report.pdf --> will call handler_pdf() in report.py report.csv --> will call handler_csv() in report.py feedback --> will call handler() in feedback.py Thus, you can use a more sensible file type in the URL without having to resort to mod_rewrite rules. Further, where a specific resource can be represented in multiple formats which are both generated on the fly, you can have a handler for each in the same content handler .py file, eg., as in .pdf and .csv case. You can also follow REST princinples and have no extension at all. You aren't restricted to just having content handlers in a directory though. You can still have other files such .html and .jpg files. If Vampire determines that there is no content handler corresponding to a request, it will decline to service it and pass it back to Apache which will then serve up the raw .html or .jpg file directly. I should point out that Vampire is not a framework in the sense that it doesn't dictate how your pages are rendered. That handler function which is called is basically the same as a stock standard mod_python handler method. Inside that function you still need to provide the code which creates the response, although there is no reason why you can't on a per resource case trigger off a different system such as PSP, mpservlets or HTMLTemplate to generate the HTML. More could be said, but best to check out: http://www.dscpl.com.au/projects/vampire -- Graham Dumpleton From sxanth at ceid.upatras.gr Fri Jan 7 13:25:16 2005 From: sxanth at ceid.upatras.gr (Stelios Xanthakis) Date: Fri, 07 Jan 2005 10:25:16 -0800 Subject: python-dev Summary for 2004-11-16 through 2004-11-30 In-Reply-To: <1105002357.261642.292880@f14g2000cwb.googlegroups.com> References: <1105002357.261642.292880@f14g2000cwb.googlegroups.com> Message-ID: <41DED40C.3030000@ceid.upatras.gr> michele.simionato at gmail.com wrote: >>Would you like the source with your function? > > > Yes, since I asked for this feature something like two years ago ;-) Well, the main objection seemed to be that we can get the source of a function one way or another. For functions with a file (1) with "inspect" , for functions defined dynamically with "exec"(2), by "knowing what we pass to exec and storing it", and for functions defined in the interactive prompt (3), by using a higher level IDE/shell that is not the pure raw_input, but does sophisticated analysis of code fed to it and which will be responsible for storing functions (!!). Still I believe it's the job of the core python parser to get this info and attach it to function objects. The other problem was whether the source attribute should be saved to pyc files (or more generally marhsaled together with the function object). Logically it should. OTOH, for the application I had using this, I didn't need marshalling source because it stored all the code (initial functions + functions defined while the application was running) in python source form. So, I think that in practice one will use either bytecode or the __source__ feature and not both, but I can't prove it. 8) There's a PEP and an --ugly- patch for 2.3.4 +10 ? Stelios From skip at pobox.com Fri Jan 28 16:03:34 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 28 Jan 2005 15:03:34 -0600 Subject: debugging os.spawn*() calls In-Reply-To: References: <16890.22749.899414.324589@montanaro.dyndns.org> Message-ID: <16890.43174.16771.956147@montanaro.dyndns.org> Nick> If using 2.4 the subprocess module is a good solution too. It Nick> lets you catch stdout/stderr easily. Yeah, thought of that already. Currently not an option though. Thx, Skip From alan.gauld at btinternet.com Sun Jan 2 03:47:52 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Jan 2005 08:47:52 +0000 (UTC) Subject: Frameworks for "Non-Content Oriented Web Apps" References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <36dft0h1v561ejq8u9gnp37063ljjna3rc@4ax.com> On 1 Jan 2005 20:51:06 -0800, mirnazim at gmail.com wrote: > Is there something that can ease the development of application that > are not content oriented(I call them "NON CONTENT-ORIENTED WEB > APPLICATIONS" because I don't know what else to call them). I mean the > applications like, accounting, high volume data entry apps, where > normally GUI clients have ruled. I know very high quality ERP I don;t know of any such frameworks. The Siebel CRM system may be the kind of thing you mean I think, but it uses standard technology. IT just puts up a form then uses client side Javascript to detect changes and send the data requests to/from the data server... No special frameworks as such... HTH, Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From elephantum at dezcom.mephi.ru Sun Jan 9 06:10:04 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 14:10:04 +0300 Subject: python3: 'where' keyword In-Reply-To: <7x3bxbe97m.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> Message-ID: <34choeF48qugdU1@individual.net> Paul Rubin wrote: >>What would be the advantage of that over this? >> >>. x = sqrt(a) + sqrt(b) where: >>. a = 2.0 >>. b = 3.0 > The idea of "where" is to allow re-using variable names instead of > having to keep track of which ones are in use. I just tried to give a > very simple example of how you might do that more than once in a > statement. then I'd write something like this: x = a + b where: a = sqrt(n) where: n = 2. b = sqrt(n) where: n = 3. From jelle.feringa at ezct.net Tue Jan 11 12:18:18 2005 From: jelle.feringa at ezct.net (Jelle Feringa // EZCT / Paris) Date: Tue, 11 Jan 2005 18:18:18 +0100 Subject: os.spawn & stdOUT trouble Message-ID: <20050111171736.D43EC1C0025D@mwinf0101.wanadoo.fr> Yikes, how painful, I meant stdOUT > trouble instead of stdin... Awefully sorry Cheers, Jelle ##thanks for pointing that out Denis! From ssaeed1973 at yahoo.com Sun Jan 30 02:49:00 2005 From: ssaeed1973 at yahoo.com (ssaeed1973 at yahoo.com) Date: 29 Jan 2005 23:49:00 -0800 Subject: Need programming tip Message-ID: <1107071340.486489.146580@f14g2000cwb.googlegroups.com> I am trying to write a program in python (brand new to Python) that would create a database of posts made to binary groups so the user can search for a certain file and have a nzb file returned. I am planning on using the XOVER command to get the list of posts and then dump those into a database. The part I am stuck at now is that some file posts consist of multiple parts as below (abbreviated XOVER reply) 1511156 As Requested 2000 adv server -2000AdvSrv.vol001+02.PAR2 (1/4) - 21/27 1511157 As Requested 2000 adv server -2000AdvSrv.vol001+02.PAR2 (2/4) - 21/27 1511158 As Requested 2000 adv server -2000AdvSrv.vol001+02.PAR2 (3/4) - 21/27 1511159 As Requested 2000 adv server -2000AdvSrv.vol001+02.PAR2 (4/4) - 21/27 I am trying to detect how many segments make up this post. One solution would be to look for (1/ in the subject string then find the denominator and loop thru as many times as the denominator to create the part of the nzb file. Is this the best way or is there an easier method? Also what would be the best way to search for the (1/ using string searches or RegExp? If REgExp could someone provide me with the RegExp for searching for this string? Thanks Salman From lee at example.com Sun Jan 2 10:32:58 2005 From: lee at example.com (Lee Harr) Date: Sun, 02 Jan 2005 15:32:58 GMT Subject: What can I do with Python ?? References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> <1gpqhbl.125l3evz09uefN%aleaxit@yahoo.com> Message-ID: On 2005-01-02, Brian Beck wrote: > Alex Martelli wrote: >> You _gotta_ be kidding, right...? The Beginner's Guide link takes you >> right to the BeginnersGuide page which starts with the reassurance that >> Python is easy to learn even if you're new to programming and continues >> with a zillion useful links. The Python Books link takes you to a huge > > While I agree that there is much useful content on the official Python > site, I particularly hate the BeginnersGuide and much of the resulting > introduction pages. Often when I happily refer Python to someone who > wants to learn a simple language, I go to the Python site and imagine > where I would start if I were them. Once I get to the BeginnersGuide I > don't see anything immediately useful, and when I look for it I get > frustrated. > I think it looks pretty good. The only problem I see is section 5 where it says: 5. Did we miss your concern? Please add a comment to this page. but the page is immutable. From tjreedy at udel.edu Thu Jan 6 19:16:06 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Jan 2005 19:16:06 -0500 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com><7xvfach813.fsf@ruckus.brouhaha.com><344l83F45rstqU1@individual.net> Message-ID: "Bulba!" wrote in message news:nocrt0119cncjco13l63l9d5nfeimk5820 at 4ax.com... > Which I find again wrong: suppose this developer used GPL-ed > library A, developed patches B and C. He provided you with > the source code of publicly available library A and a patch > C, but he doesn't want to release patch B. Then he does not have to. As I understand the GPL, as long as he does not release (distribute) the patch in any form (in particular, binary), then the GPL has no effect. What strikes me as funny about GPL sniping is that many programmers, including I am sure some of the snipers, sign Terms of Employment contracts far more restrictive of their freedom than one could possibly accuse the GPL of being. But I have seen little or no discussion of this (at least on clp). In fact, I wonder if the GPL might be a substitute target. Terry J. Reedy From irmen at -nospam-remove-this-xs4all.nl Sun Jan 16 17:29:05 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 16 Jan 2005 23:29:05 +0100 Subject: threading and sockets ? In-Reply-To: References: Message-ID: <41eaeaae$0$6203$e4fe514c@news.xs4all.nl> ionel wrote: > how to make a efficient server.. please point me to some good and clear examples I nominate SocketServer.ThreadingTCPServer from the standard library. --Irmen From P at draigBrady.com Thu Jan 6 08:56:04 2005 From: P at draigBrady.com (P at draigBrady.com) Date: Thu, 06 Jan 2005 13:56:04 +0000 Subject: get the IP address of a host In-Reply-To: References: Message-ID: J Berends wrote: > def getipaddr(hostname='default'): [snip] > > It returns the IP address with which it connects to the world (not lo), > might be a pvt LAN address or an internet routed IP. Depend on where the > host is. > > I hate the google trick actually, so any suggestions to something better > is always welcome. Yes your IP is determined really by what you connect to. So I did essentially the same as you. For reference see getMyIPAddress() at the following: http://www.pixelbeat.org/libs/PadSocket.c P?draig From hcslmf at texlife.com Mon Jan 10 12:49:12 2005 From: hcslmf at texlife.com (brolewis) Date: 10 Jan 2005 09:49:12 -0800 Subject: Importing Problem on Windows Message-ID: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> I have a directory that has two files in it: parse.py parser.py parse.py imports a function from parser.py and uses it to parse out the needed information. On Linux, the following code works without a problem: parse.py, line 1: from parser import regexsearch However, when I run the same command in Windows, I get the following error: ImportError: cannot import name regexsearch Any suggestions on why this would work on Linux but not on Windows? From beliavsky at aol.com Sun Jan 30 17:40:32 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 30 Jan 2005 14:40:32 -0800 Subject: Fortran pros and cons (was Re: Coding style article with interesting section on white space) References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> <1107105022.827941.114510@c13g2000cwb.googlegroups.com> Message-ID: <1107124832.327010.181490@f14g2000cwb.googlegroups.com> Michael Tobis wrote: > > Fortran programmers are generally happy with the portability of the > > language. > > Until they try to port something...? Honestly, I can't imagine where > anyone would get this impression. >From the fact that Fortran has been used on hundreds of platforms and that many portable libraries like LAPACK exist. Fortran 90+ allows one to write even more portable code using the KIND mechanism and the selected_int_kind and selected_real_kind functions, which let you specify the ranges of basic data types. > Now, about the terseness and expressiveness? Fortran 90/95 is more expressive than Fortran 77 in many ways, as described in (for example) pages 7-8 of the essay "Numerical Recipes: Does This Paradigm Have a Future?", available at http://www.nr.com/CiP97.pdf . Quoting that paper: "This, for us, was the revelation of parallel programming in Fortran 90. The use of parallel and higher-level constructions -- wholly independently of whether they are executed on tomorrow's parallel machines or today's ordinary workstations -- expresses more science per line of code and per programming workday. Based on our own experience, we think that productivity, or achievable complexity of project, is increased a factor of 2 or 3 in going from Fortran 77 to Fortran 90 -- if one makes the investment of mastering Fortran 90's higher level constructs." > > For scientific computation, consider the case of Numeric > > and Numarray. > > I'm not happy with these, because they either make temporary arrays > with wild abandon Some early Fortran 90 compilers did this but have improved significantly in this respect. > or enforce an unnatural style of expression. I wonder what this means. > I do not suggest that Python is currently competitive with C++ or > Fortran. I simply agree with > http://www.fortranstatement.com that something new ought to be > designed, that a backward compatible Fortran2003 cannot possibly be it, > and that attention to fortran diverts resources from [the sort] of > genuine progress that ought to be possible. You have not given specifics about what "genuine progress" in a scientific programming language would be. > Performance portability has nothing to do with what I'm talking about. > > The answer belies the attitude that programmers are there to put in > time and expend effort, because the only resource worth considering is > production cycles on a big machine. Nonsense. Fortran was originally created to make PROGRAMMERS more efficient by letting them code algebraic expressions instead of machine code. > This attitude explains why working with Fortran is so unpleasant an > experience for anyone who has been exposed to other languages. "Anyone"? Since I have been exposed to Python and C++ and still find Fortran 90+ enjoyable, your statement is demonstrably false. Have you ever used a version of Fortran past F77? The free Fortran 95 compiler called g95 http://www.g95.org is available. > Getting a python package working usually amounts to an install command > to the OS and an import command to the interpreter. Then you can get > down to work. Getting a Fortran package working involves not only an > endless dance with obscure compiler flags and library links, but then a > set of workarounds for codes that produce expected results on one > compiler and compile failures or even different results on another. If one writes standard-conforming code it does not. At least with Fortran one has multiple independent implementations of an ISO standardized language, about 10 each on Intel Windows or Linux, and 4 for Mac OS X. Links are at http://dmoz.org/Computers/Programming/Languages/Fortran/Compilers/ . If one Fortran compiler leaks memory when multiplying matrices, one can use another. If Python Numarray does, the only alternative I know of is Numeric, which is no longer supported according to http://www.pfdubois.com/numpy/ . I have found it extremely useful to work with multiple compilers and compiler options. A good compiler such as Lahey/Fujitsu has debugging options that aid programmer productivity by finding bugs, both at compile and run time, at some cost in speed. I gave a few examples in a previous thread. The existence of such compilers refutes your assertion that Fortran programmers think only machine time is important. From fperez.net at gmail.com Thu Jan 27 19:23:24 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Thu, 27 Jan 2005 17:23:24 -0700 Subject: gnuplot on Canvas widget References: <1106852695.371569.234820@f14g2000cwb.googlegroups.com> <1106865871.537454.128830@c13g2000cwb.googlegroups.com> Message-ID: Jonathan Ellis wrote: > Blues wrote: >> I have used two great models - Tkinter and Gnuplot.py - for a while. > I >> can display an image on a Canvas widget using Tkinter and I can also >> generate a gnuplot from Python on the fly in a separate window. Does >> anyone know how to display such a gnuplot on the Canvas widget with > an >> image in it? Thanks. > >>From my experience, the Gnuplot module isn't designed to be used in > "headless" mode -- it can save to the usual formats, but you have to > render everything in an x11 window interactively first. > It might not be hard to modify this, though. That's not correct. I have tons of Gnuplot.py based scripts which write directly to EPS output, without ever opening a gui window. Note that Gnuplot still tries to initialize the X11 terminal at startup, so they would require modifications to run over ssh without X forwarding. The default plot() command in Gnuplot.py doesn't make it too convenient to do this, but it's possible. The Gnuplot support in ipython (http://ipython.scipy.org) extends the syntax of the plot() command to make it trivial to render to EPS without a terminal. It shouldn't be hard to modify this to render to other formats, while avoiding opening an X11 window. Best, f From gsakkis at rutgers.edu Mon Jan 24 17:42:55 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Mon, 24 Jan 2005 17:42:55 -0500 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> <35l5d9F4licj2U1@individual.net> Message-ID: <35lbvdF4k3ss4U1@individual.net> "Peter Hansen" wrote in message news:A9OdnRotCdqJ-2jcRVn-jA at powergate.ca... > George Sakkis wrote: > > Fair enough. So perhaps the question is whether such cases are more regular than something like: > > a = give_me_a_huge_tuple() > > slices = [a[i:j] for i in xrange(len(a)) for j in xrange(i+1, len(a)+1)] > > I believe the general usage of tuples tends to mean that > "give_me_a_huge_tuple()" just doesn't happen except with > those who insist on using tuples as though they were nothing > other than read-only lists. > > If you use a tuple the way it was apparently intended, you > are extraordinarily unlikely to find yourself with a > huge one requiring slicing in such a way that you care > whether it is a "view" or a new object. > > -Peter Actually my initial motivation was not a huge tuple I had to slice many times. It was something much less extraordinarily unlikely, a recursive function with a sequence parameter: def foo(sequence): # base_case # do_stuff() combine(foo(sequence[:n]), foo(sequence[n:])) Having each slice be a view of the original sequence instead of a fresh copy would be a Good Thing (tm). George From ncoghlan at iinet.net.au Tue Jan 18 07:42:21 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 18 Jan 2005 22:42:21 +1000 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: <41ED042D.2000004@iinet.net.au> Antoon Pardon wrote: > More specific the Decimal class is mutable and usable as dict key. It's *meant* to be immutable though. The fact that we used __slots__ instead of __setattr__ to implement the immutability, so you *can* overwrite the slot variables if you really want to is merely an artifact of the current Python implementation. The limited mutability bug will disappear in Python 2.5, so it's not a good example of a 'mutable' dict key (especially given that the only way to mutate it is to modify private variables directly). And, as I've stated previously, if the issue of sane mutable keys in dictionaries and sets really bugs you so much - implement identity_dict and identity_set in C and lobby for their inclusion in the collections module. On the more general point of "don't use mutable objects with non-identity based comparisons as dictionary keys", try teaching students for a while (or listen to those who have): When stating useful general principles, it is never, ever worth it to get into the quibbly little details about exceptions to the principle. If students ask, admit that they exist, but point out that the exceptions are rare, and not worth worrying about at that point in their learning. Only when one is aware of the reasons for a principle, can one be aware of good reasons not to follow it :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jepler at unpythonic.net Sat Jan 29 23:00:51 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 29 Jan 2005 22:00:51 -0600 Subject: [Tkinter] problem In-Reply-To: References: Message-ID: <20050130040049.GB20609@unpythonic.net> These lines > if __name__ == '__main__': > OptionsWindow() mean "if this source code is the main program (not an imported module), call OptionsWindow()". So the behavior should be different when the source code is the main program ('python opt_newlogin.py') and when it's imported ('python -c "import opt_newlogin"') Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From tom at dtsam.com Wed Jan 26 10:39:31 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Wed, 26 Jan 2005 09:39:31 -0600 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: "Davor" wrote in message news:ct6kvm$edg$1 at rumours.uwaterloo.ca... > > On the other hand, this does beggar for a reason to bother with Python at > > all. It seems you could be happy doing BASH scripts for Linux or DOS batch > > files for Windows. Both are "nice&simple" scripting languages free of > > object oriented contamination. > > not really, what I need that Python has and bash&dos don't is: > > 1. portability (interpreter runs quite a bit architectures) > 2. good basic library (already there) > 3. modules for structuring the application (objects unnecessary) > 4. high-level data structures (dictionaries & lists) > 5. no strong static type checking > 6. very nice syntax > > so initially I was hoping this is all what Python is about, ... The irony here is that the OO approach woven into the warp and woof of Python is what make 1-6 possible. > but when I > started looking into it it has a huge amount of additional (mainly OO) > stuff which makes it in my view quite bloated now... Again, there is nothing "additional" about the OO in Python. It is the very foundation upon which it is built. > ... anyhow, I guess > I'll have to constrain what can be included in the code through > different policies rather than language limitations... It would be reasonable to decide that Python is not what you are looking for. I'm not sure that castrating it in this manner would be quite so reasonable. Thomas Bartkus From philippecmartin at sbcglobal.net Fri Jan 7 07:16:49 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Fri, 07 Jan 2005 13:16:49 +0100 Subject: Tkinter: passing parameters to menu commands Message-ID: <1105100209.6909.6.camel@localhost> Hi, I have he following need and do not find an easy way out: I have many menu items and would like them all to call the same method -However, I need the method called to react differently depending on the menu item selected. Since the menu command functions do not seem to receive any type of event style object, is there some type of Tkinter call that would let my method know the menu id selected ? Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From snacktime at gmail.com Sun Jan 23 18:50:50 2005 From: snacktime at gmail.com (snacktime) Date: Sun, 23 Jan 2005 15:50:50 -0800 Subject: Set parity of a string In-Reply-To: References: <1f060c4c050123140310e6f887@mail.gmail.com> Message-ID: <1f060c4c05012315506a2c9cb4@mail.gmail.com> On Sun, 23 Jan 2005 23:52:29 +0100, Fredrik Lundh wrote: > "snacktime" wrote: > > > Is there a module that sets the parity of a string? I have an > > application that needs to communicate with a host using even parity > > So what I need is before sending the message, convert it from space to > > even parity. And when I get the response I need to convert that from > > even to space parity. > > umm. shouldn't the communication library do this for you? > The communication is an https post, but the host needs the data in even parity before sending it into their internal systems (this is a large bank network) and it's up to the client to do the transformation. Chris From rkern at ucsd.edu Sat Jan 15 15:12:26 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 15 Jan 2005 12:12:26 -0800 Subject: hash patent by AltNet; Python is prior art? In-Reply-To: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> References: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> Message-ID: GerritM wrote: > ZDnet features an article about the had patent at AltNet > http://news.zdnet.com/2100-9588_22-5534087.html . Apparantly this issue > plays already for some time, now the p2p companies are threatened, becuase > they use hashing to recognize files. > > As far as I know hasing is a very old technique used to quickly look up > information. The use of hashing always requires an idnetity check, because > the lookup is not unique (mapping a very big amount of possibilities on a > limited amount of entries). This is a fast and robust way of finding > information, if the right hashing function is used. I don't know the details, but I'm willing to bet that the kind of hashes being disputed here are cryptographic hashes, not the kind that Python uses for dictionaries. I'm also willing to bet that the patent won't hold up in court because there's quite a lot of prior art with respect to cryptographic hashes, too. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From sjmachin at lexicon.net Tue Jan 11 17:16:07 2005 From: sjmachin at lexicon.net (John Machin) Date: 11 Jan 2005 14:16:07 -0800 Subject: Octal notation: severe deprecation References: Message-ID: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> Some poster wrote (in connexion with another topic): > ... unicode("\347", "iso-8859-1") ... Well, I haven't had a good rant for quite a while, so here goes: I'm a bit of a retro specimen, being able (inter alia) to recall octal opcodes from the ICT 1900 series (070=call, 072=exit, 074=branch, ...) but nowadays I regard continued usage of octal as a pox and a pestilence. 1. Octal notation is of use to systems programmers on computers where the number of bits in a word is a multiple of 3. Are there any still in production use? AFAIK word sizes were 12, 24, 36, 48, and 60 bits -- all multiples of 4, so hexadecimal could be used. 2. Consider the effect on the newbie who's never even heard of "octal": >>> import datetime >>> datetime.date(2005,01,01) datetime.date(2005, 1, 1) >>> datetime.date(2005,09,09) File "", line 1 datetime.date(2005,09,09) ^ SyntaxError: invalid token [straight out of the "BOFH Manual of Po-faced Error Messages"] 3. Consider this extract from the docs for the re module: """ \number Matches the contents of the group of the same number. Groups are numbered starting from 1. For example, (.+) \1 matches 'the the' or '55 55', but not 'the end' (note the space after the group). This special sequence can only be used to match one of the first 99 groups. If the first digit of number is 0, or number is 3 octal digits long, it will not be interpreted as a group match, but as the character with octal value number. Inside the "[" and "]" of a character class, all numeric escapes are treated as characters. """ I helped to straighten out this description a few years ago, but I fear it's still not 100% accurate. Worse, take a peek at the code necessary to implement this. === We (un-Pythonically) implicitly take a leading zero (or even just \[0-7]) as meaning octal, instead of requiring something explicit as with hexadecimal. The variable length idea in strings doesn't help: "\18", "\128" and "\1238" are all strings of length 2. I don't see any mention of octal in GvR's "Python Regrets" or AMK's "PEP 3000". Why not? Is it not regretted? From rmemmons at member.fsf.org Thu Jan 13 20:59:57 2005 From: rmemmons at member.fsf.org (Rob Emmons) Date: Thu, 13 Jan 2005 19:59:57 -0600 Subject: Newbie: module structure and import question References: <8fb821f9.0501120706.499dd04c@posting.google.com> Message-ID: > hi all, > i have question on how to design a module structure. > for example, i have 3 files. > [somewhere]/main.py > [somewhere]/myLib/Base/BaseA.py > [somewhere]/myLib/ClassA.py > .... > ..... > It's fine when i run main.py. > however when i run ClassA.py individually, it would fail in import > statment since the import path is incorrect. > I would like to know is something wrong in my design, or something i > missed. I think your issue is your module search path. Take a look at the doc for sys.path in the library reference. These are the directories that python searchies for modules. Usually the "." directory is included in this which makes python search the current working directory. Your example fails because your working directories are probably different when you ran the two modules. In any case always consider how you've setup sys.path and your libraries and modules. > Also, in practical usage, is that one class in one py file? I'm not exactly clear what your asking -- but I think yor asking if you'd normally only put one class in one py file. My answer is no -- generally you'd put many functions and classes in each py file. Modules are high level and should be used to create libraries essentailly -- this means many fucntions and classes per module. Rob From iseestars at gate.net Thu Jan 27 21:14:07 2005 From: iseestars at gate.net (inhahe) Date: Thu, 27 Jan 2005 21:14:07 -0500 Subject: Why do look-ahead and look-behind have to be fixed-width patterns? Message-ID: Hi i'm a newbie at this and probably always will be, so don't be surprised if I don't know what i'm talking about. but I don't understand why regex look-behinds (and look-aheads) have to be fixed-width patterns. i'm getting the impression that it's supposed to make searching exponentially slower otherwise but i just don't see how. say i have the expression (?<=.*?:.*?:).* all the engine has to do is search for .*?:.*?:.*, and then in each result, find .*?:.*?: and return the string starting at the point just after the length of the match. no exponential time there, and even that is probably more inefficient than it has to be. From shalabh at cafepy.com Sun Jan 23 17:39:08 2005 From: shalabh at cafepy.com (Shalabh Chaturvedi) Date: Sun, 23 Jan 2005 14:39:08 -0800 Subject: Solutions for data storage? In-Reply-To: <356c7tF4g3f64U1@individual.net> References: <356c7tF4g3f64U1@individual.net> Message-ID: <41F4278C.8000206@cafepy.com> Leif K-Brooks wrote: > I'm writing a relatively simple multi-user public Web application with > Python. It's a rewrite of a similar application which used PHP+MySQL > (not particularly clean code, either). My opinions on various Web > frameworks tends to vary with the phase of the moon, but currently, I'm > planning to use Quixote. Good choice, IMO! And while you're using Quixote, you might want to look at QLime [1] for all your data storage needs :) > I've looked at SQLObject, and it's very nice, but it doesn't provide > certain features I really want, like the ability to store lists of > strings or integers directly in the database (using commas in a varchar > column or something). In any mapper that lets you set attributes for storing columns (such as QLime), this should be fairly simple using properties. > My ideal solution would be an object database (or object-relational > mapper, I guess) which provided total transparency in all but a few > places, built-in indexing, built-in features for handling schema > changes, the ability to create attributes which are required to be > unique among other instances, and built-in querying with pretty syntax. Briefly, QLime uses RDBMS indexing, automatically handles schema changes (in fact you don't define the schema in Python at all, you just create the table). For uniqueness you'd have to set the constraint on the table. To look at the query syntax avaialable, (and OR mapping features) see http://www.qlime.org/0.5.1/qlime_or_mapping.html. Cheers, Shalabh [1] http://www.qlime.org/ From devries at idolstarastronomer.com Mon Jan 3 20:52:40 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: 3 Jan 2005 17:52:40 -0800 Subject: How do I make Windows Application with Python ? In-Reply-To: <1104802115.543884.96150@z14g2000cwz.googlegroups.com> References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> <1104802115.543884.96150@z14g2000cwz.googlegroups.com> Message-ID: <1104803560.244274.251150@c13g2000cwb.googlegroups.com> I should learn to type faster. You beat me to the response. Chris From http Sun Jan 30 06:43:26 2005 From: http (Paul Rubin) Date: 30 Jan 2005 03:43:26 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> <7xacqsbfk2.fsf@ruckus.brouhaha.com> <41fbcb11$0$12030$9b622d9e@news.freenet.de> <7xsm4j1wbe.fsf@ruckus.brouhaha.com> Message-ID: <7xpszngn1d.fsf@ruckus.brouhaha.com> Nick Craig-Wood writes: > There is a PEP about this... > > API for Block Encryption Algorithms v1.0 > http://www.python.org/peps/pep-0272.html Yes, I know about that and have been in contact with its author. He and I are in agreement (or at least were in agreement some time ago) that the proposed API of the new module is an improvement, at least for a generic module. PEP 272 seems to document the interface of something that had been implemented for some particular application. From zuerich at hebeler.net Thu Jan 27 11:20:21 2005 From: zuerich at hebeler.net (Felix Hebeler) Date: Thu, 27 Jan 2005 17:20:21 +0100 Subject: how to pass attribute name via sys.argv In-Reply-To: References: <41f8e31a$1@idnews.unizh.ch> Message-ID: <41f914c3$1@idnews.unizh.ch> Wolfram Kraus wrote: > Felix Hebeler wrote: > >> >> I need to call an object attribute: >> >> value = object.attrName[0] >> > > Use getattr: > value = getattr(object, attrName)[0] > > > > HTH, > Wolfram Thanks so much! Had I known earlier. Looks so easy... Now, why did I not find this in the online tutorial, the reference manual, or google? Not that I didn't try... I mean, I would find 'getattr' if I searched, but if you don't know what you're looking for.. I find the reference manual extremely (== too) compact to look things up. A couple of colleages and me agreed that it is much more difficult to find solutions and _useful_ tips for Python than e.g. for Java (where there's Javadoc for example). The syntax doc in the reference manual to me looks like computer linguists might understand, but unfortunately not me. And Python code IS really easy to read, I agree, but what if I can't find out how to write it? I'd appreciate any link to online resources or recommendations for books (english/german)! Chances are I'm a silly/lazy/deprived/stupid bugger, but I try to think there's still hope! again, thank you so much for your quick response (thanks Gilles Lenfant too!), I really DO like the Python community ;-) Cheers Felix From jerf at jerf.org Sat Jan 15 18:13:04 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 15 Jan 2005 18:13:04 -0500 Subject: threading and sockets ? References: Message-ID: On Sun, 16 Jan 2005 05:30:37 +0200, ionel wrote: > how to make a efficient server.. please point me to some good and clear examples Your question is too broad. There is no such thing as "a server", the server must *do* something and it is generally named for what it does.. Please read http://www.catb.org/~esr/faqs/smart-questions.html and try again. That said, Twisted is a likely good first stop. http://twistedmatrix.com/ But I have no way of knowing that, only a guess. From steven.bethard at gmail.com Thu Jan 27 13:06:18 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 11:06:18 -0700 Subject: Help With Python In-Reply-To: References: <87ekg8c4d0.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: Nick Craig-Wood wrote: > Steven Bethard wrote: >> py> orders = [Viking().order()] * 7 >> py> ', '.join(orders) >> 'Spam, Spam, Spam, Spam, Spam, Spam, Spam' > > Thats still one Viking making 7 orders surely? > > So you want this... > >>>>orders = [ Viking().order() for _ in range(7) ] Right, right. Thanks for the correction! This is why I never use the * operator on lists. ;) Steve From phil at riverbankcomputing.co.uk Mon Jan 10 07:30:04 2005 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Mon, 10 Jan 2005 12:30:04 -0000 (GMT) Subject: Command line and GUI tools : need a single threading solution In-Reply-To: <41e26e79@duster.adelaide.on.net> References: <41e26e79@duster.adelaide.on.net> Message-ID: <7461.82.68.80.137.1105360204.squirrel@82.68.80.137> > I have a collection of multi-threaded command line tools which I want wrap > a > PyQt gui around. I'm using queues to route messages from the command line > tools to the PyQt gui. The command line tools use python threads to do > their work. The gui uses a QThread object to read incoming messages. > > This does not work consistently - and I've since read that mixing python > threads and QThreads is a bad idea. The command line tools work well > using > python threads. How well mixing the two threading APIs works depends on version numbers. A PyQt generated with SIP v4.x (rather than SIP v3.x) with Python v2.4 should be Ok. > I don't want to maintain two copies of the tools - one for command line > and > another for the PyQt version. > > I'm thinking it may be possible to modify the command line tools to use qt > threads instead of native python threads. Is this the way to go? Are > there other options? Using QThreads only should work - just tell the QApplication ctor that you have a console application. Phil From asda at sdarta.com Sat Jan 8 21:22:54 2005 From: asda at sdarta.com (worzel) Date: Sun, 9 Jan 2005 10:22:54 +0800 Subject: The best way to do web apps with Python? References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41e0957d$0$21086$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Holy Moly - there's quite a few choices out there! I like the look of Karrigel for my immediate needs. Looking forward to the day there is a more 'j2ee' like standard in place for Python - looks like this is in the works. Thanks for all the feedback guys. "worzel" wrote in message news:41dfdc15$0$29387$5a62ac22 at per-qv1-newsreader-01.iinet.net.au... What is the best way to web developemnt with Python? Is there anything close to PHP style in-page script placement that can create and use other Python objects? I am not really interested in Zope (I believe that is more a CMS than anything else?) I am also looking for something a little more structured than a series of CGI Scripts. While on the topic - what is the expectataion of Python for this kind of stuff? Would one use Python for certain other things but turn to PHP for web apps - or would one use their Python skills in place of PHP? TIA From steve at holdenweb.com Thu Jan 6 08:45:21 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Jan 2005 08:45:21 -0500 Subject: Other notes In-Reply-To: References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> Message-ID: <41DD40F1.5030301@holdenweb.com> Timo Virkkala wrote: > bearophileHUGS at lycos.com wrote: > >> Andrew Dalke: >> >>> (BTW, it needs to be 1 .. 12 not 1..12 because 1. will be interpreted >>> as the floating point value "1.0".)< >> >> Uhm, I have to fix my ignorance about parsers. >> Cannot a second "." after the first tell that the first "." isn't in >> the middle of a floating point number? > > > Python uses an LL(1) parser. From Wikipedia: > """ LL(1) grammars, although fairly restrictive, are very popular > because the corresponding LL parsers only need to look at the next token > to make their parsing decisions.""" > Indeed, but if ".." is defined as an acceptable token then there's nothing to stop a strict LL(1) parser from disambiguating the cases in question. "Token" is not the same thing as "character". >>>> This may allow: assert 5 interval 9 == interval(5,9) >>> >>> Maybe you could give an example of when you need this in real life?< >> >> Every time you have a function with 2 parameters, you can choose to use >> it infix. > > > But why would you want to? What advantage does this give over the > standard syntax? Remember, in Python philosophy, there should be one > obvious way to do it, and preferably only one. Adding a whole another > way of calling functions complicates things without adding much > advantage. Especially so because you suggest it is only used for binary, > i.e. two-parameter functions. This part of your comments I completely agree with. However, we are used to people coming along and suggesting changes to Python on comp.lang.python. Ironically it's often those with less experience of Python who suggest it should be changed to be more like some other language. One of the things I like best about c.l.py is its (almost) unfailing politeness to such posters, often despite long stream-of-consciousness posts suggesting fatuous changes (not necessarily the case here, by the way). The level of debate is so high, and so rational, that the change requesters are often educated as to why their suggested changes wouldn't be helpful or acceptable, and having come to jeer they remain to whitewash, to use an analogy from "Tom Sawyer" [1]. All in all a very pleasant change from "F*&% off and die, noob". regards Steve [1]: http://www.cliffsnotes.com/WileyCDA/LitNote/id-2,pageNum-10.html -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From fumanchu at amor.org Mon Jan 10 13:14:24 2005 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 10 Jan 2005 10:14:24 -0800 Subject: Writing huge Sets() to disk Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339814F@exchange.hqamor.amorhq.net> Martin MOKREJ? wrote: > Robert Brewer wrote: > > Martin MOKREJ? wrote: > > > >> I have sets.Set() objects having up to 20E20 items, > >>each is composed of up to 20 characters. Keeping > >>them in memory on !GB machine put's me quickly into swap. > >>I don't want to use dictionary approach, as I don't see a sense > >>to store None as a value. The items in a set are unique. > >> > >> How can I write them efficiently to disk? > > > > > > got shelve*? > > I know about shelve, but doesn't it work like a dictionary? > Why should I use shelve for this? Then it's faster to use > bsddb directly and use string as a key and None as a value, I'd guess. If you're using Python 2.3, then a sets.Set *is* implemented with a dictionary, with None values. It simply has some extra methods to make it behave like a set. In addition, the Set class already has builtin methods for pickling and unpickling. So it's probably faster to use bsddb directly, but why not find out by trying 2 lines of code that uses shelve? The time-consuming part of your quest is writing the timed test suite that will indicate which route will be fastest, which you'll have to do regardless. Robert Brewer MIS Amor Ministries fumanchu at amor.org From danperl at rogers.com Fri Jan 28 08:54:28 2005 From: danperl at rogers.com (Dan Perl) Date: Fri, 28 Jan 2005 08:54:28 -0500 Subject: How to test that an exception is raised ? References: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> <41fa400b$0$2029$6c56d894@feed0.news.be.easynet.net> Message-ID: "StepH" wrote in message news:41fa400b$0$2029$6c56d894 at feed0.news.be.easynet.net... > > Do you say that it's not possible to test (using unittest) if an exception > is well raised if the tested code catch it ? > How to solve this paradoxe ? How to automaticaly test such code ? Then you need a side-effect in catching the exception. A return code would be such a side-effect. Setting a state variable that can be checked by the invoking code would be another such side-effect. > 1./ Cheking error-return value if not a good idea for me, cause this make > the code less clear. I don't want a code where i've to test each function > return value... > 2./ If I re-raise the exception, then how to not show the traceback. My > user will became crazy if they view such error msg. But then how will the user know if the call did what it is supposed to do? And if the user mis-used the function and used it for a file that does not exist, how is he/she supposed to know what the problem was and why nothing is coming out of calling your function? > It seems that there is 2 school here. I've read a lot on python, and > somed > 'guru' Python say that it's maybe better to use exception even for case > you > can "predict", no ? Or i'm completly wrong ? The IOError is an exception that you can predict and I was saying that you should catch it, but with a "except IOError:" statement instead of the "except:" statement that you used. From jjl at pobox.com Tue Jan 25 18:19:00 2005 From: jjl at pobox.com (John J. Lee) Date: 25 Jan 2005 23:19:00 +0000 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> <7xacr4ewjk.fsf@ruckus.brouhaha.com> <41ef4a7a.1323588509@news.oz.net> <7xwtu8vb17.fsf@ruckus.brouhaha.com> <41EF72DE.5030305@jessikat.fsnet.co.uk> <7xwtu8pgr4.fsf@ruckus.brouhaha.com> <7x7jm5m613.fsf@ruckus.brouhaha.com> Message-ID: <87d5vthzbv.fsf@pobox.com> Paul Rubin writes: > jjl at pobox.com (John J. Lee) writes: > > > Building larger ones seems to > > > have complexity exponential in the number of bits, which is not too > > > > Why? > > The way I understand it, that 7-qubit computer was based on embedding > the qubits on atoms in a large molecule, then running the computation Oh, you mean that particular kind, OK. Doesn't apply to QC in general. > > > It's not even known in theory whether quantum computing is > > > possible on a significant scale. > > > > Discuss. > > The problem is maintaining enough coherence through the whole > calculation that the results aren't turned into garbage. In any > physically realizeable experiment, a certain amount of decoherence > will creep in at every step. So you need to add additional qubits for > error correction, but then those qubits complicate the calculation and > add more decoherence, so you need even more error correcting qubits. Yes, that's much more interesting, dunno what the current state of play is. [...] > I'm not any kind of expert in this stuff but have had some > conversations with people who are into it, and the above is what they > told me, as of a few years ago. I probably have it all somewhat garbled. Me too :-) John From martin at v.loewis.de Mon Jan 24 18:51:24 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 25 Jan 2005 00:51:24 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> Message-ID: <41f589f9$0$3357$9b622d9e@news.freenet.de> phr at localhost.localdomain wrote: > Maybe we're not thinking about the same problems. Say I'm an app > writer and I want to use one of your modules. My development > environment is GNU/Linux, and I want to ship a self-contained app that > anyone can run without having to download additional components. That > includes people wanting to run my app on Windows, Macintosh, Amiga, > and various other Python target platforms that I don't have compilers > for. How do I do it? This is not possible - whether the module is included in Python or not. People *will* have to download something besides your application, namely Python - and in the version your require, too. If they cannot compile Python themselves, they will have to find somebody who did that for them. This is very easy if you are using Windows, Debian, or Mac OS X. It is very difficult if you are using an Amiga, or any of the other Python target platforms that you don't have compilers for. HP-UX users of your application will have a hard time to get it running even if the module was available as a built-in. This does not change much if the module is available separately, and it does not change much whether the separate module is written in Python or in C: Windows, Debian, and OS X users will still find precompiled binaries for the module, and all others will still have to build it themselves. This is very easy, since all they have to do is to use distutils. > So, if your modules are generally useful, I hope you > will try to get them into the core. Right - the critical condition is "if the modules are generally useful". I cannot possibly know whether they are generally useful until a general public has commented that they are. > I can't speak for the authors but I'd personally say that none of > those old modules are really suitable for the core on technical > grounds. That is my impression, too. > The module I'm discussing would simply implement the FIPS standard > block ciphers (AES and DES) and the FIPS operating modes. These are > the basic building blocks that I feel are missing from the core. They > should be enough to fill the crypto needs of most applications. Hmm. Most applications don't have any crypto needs. Those that do typically need TLS, or secure password hashing (crypt(3) specifically). So I somehow doubt that an AES module would be generally useful. >>So if the module was primarily written to be included in the core, I >>would initially reject it for that very reason. After one year or so >>in its life, and a recognizable user base, inclusion can be >>considered. > > > That makes no sense; improving the core is a perfectly valid reason to > write something. If someone wrote a straightforward patch that made > the Python interpreter 3x faster, would you still want to wait a year > before thinking about including it? I would have to apply the "generally useful" test. For an 3x speed improvement, about 100% of the Python users would find that useful. For an AES module with an interface nobody has ever used but yourself, it would be very difficult to argue that the module is generally useful. If the module does not serve a need that people have, in general, I don't see why it should be included (and yes, I wish a few of the modules that were included recently wouldn't have been added so quickly). > I certainly believe that every > contribution needs code review and user testing before entering wide > release, but that doesn't seem to be what you're getting at. I'm primarily looking for the user testing. I require that this happens *outside* the Python distribution. Make a distutils package, and report the user feedback. Then propose inclusion into the core. > I release this "app" and presto, every Python user on every OS > platform can run it with no fuss. That includes CGI authors who > aren't allowed to install C modules at all, without getting their > hosting service to do it. How do I do the same thing if there's no > built-in sha module and all I have is sha.c? It very much depends on the details of the target system. Yes, it is a bit more tricky to install the additional library - but that is the case with any additional library, whether it is C or not. For the CGI user who is not allowed to install binaries into /usr/local, she can still install the module in her home directory, no? > To me, the whole Python notion of "batteries included" expresses > precisely the idea that I'm trying to describe. Commonly-used > functions belong in the core, because making people download or > install them separately is a pain in the neck. See, this is the critical point: "commonly-used functions", not "functions I believe would be commonly used". You must have *existing* users for a function to be commonly-used. Regards, Martin From paul.kooistra at leaseplan.nl Tue Jan 25 09:23:29 2005 From: paul.kooistra at leaseplan.nl (Paul Kooistra) Date: 25 Jan 2005 06:23:29 -0800 Subject: Browsing text ; Python the right tool? Message-ID: I need a tool to browse text files with a size of 10-20 Mb. These files have a fixed record length of 800 bytes (CR/LF), and containt records used to create printed pages by an external company. Each line (record) contains an 2-character identifier, like 'A0' or 'C1'. The identifier identifies the record format for the line, thereby allowing different record formats to be used in a textfile. For example: An A0 record may consist of: recordnumber [1:4] name [5:25] filler [26:800] while a C1 record consists of: recordnumber [1:4] phonenumber [5:15] zipcode [16:20] filler [21:800] As you see, all records have a fixed column format. I would like to build a utility which allows me (in a windows environment) to open a textfile and browse through the records (ideally with a search option), where each recordtype is displayed according to its recordformat ('Attributename: Value' format). This would mean that browsing from a A0 to C1 record results in a different list of attributes + values on the screen, allowing me to analyze the data generated a lot easier then I do now, browsing in a text editor with a stack of printed record formats at hand. This is of course quite a common way of encoding data in textfiles. I've tried to find a generic text-based browser which allows me to do just this, but cannot find anything. Enter Python; I know the language by name, I know it handles text just fine, but I am not really interested in learning Python just now, I just need a tool to do what I want. What I would REALLY like is way to define standard record formats in a separate definition, like: - defining a common record length; - defining the different record formats (attributes, position of the line); - and defining when a specific record format is to be used, dependent on 1 or more identifiers in the record. I CAN probably build something from scratch, but if I can (re)use something that already exists it would be so much better and faster... And a utility to do what I just described would be REALLY usefull in LOTS of environments. This means I have the following questions: 1. Does anybody now of a generic tool (not necessarily Python based) that does the job I've outlined? 2. If not, is there some framework or widget in Python I can adapt to do what I want? 3. If not, should I consider building all this just from scratch in Python - which would probably mean not only learning Python, but some other GUI related modules? 4. Or should I forget about Python and build someting in another environment? Any help would be appreciated. From bokr at oz.net Wed Jan 12 21:45:03 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 02:45:03 GMT Subject: counting items References: Message-ID: <41e5ddc8.705938866@news.oz.net> On Wed, 12 Jan 2005 18:07:47 GMT, "Andrew Koenig" wrote: >"It's me" wrote in message >news:ukdFd.10645$5R.2000 at newssvr21.news.prodigy.com... > >> What's the best way to count number of items in a list? >> >> For instance, >> >> a=[[1,2,4],4,5,[2,3]] >> >> I want to know how many items are there in a (answer should be 7 - I don't >> want it to be 4) > >How about this? > > def totallen(x): > if isinstance(x, (list, tuple, dict)): > return sum(map(totallen, x)) > return 1 Since the requirement is to _count_, not flatten, ISTM your solution is best so far ;-) Regards, Bengt Richter From peter at engcorp.com Sat Jan 8 13:20:23 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Jan 2005 13:20:23 -0500 Subject: windows mem leak In-Reply-To: References: Message-ID: Bob Smith wrote: > Does the Win32 port of Python have a memory leak? I have some code that > runs flawlessly on Linux, but bombs after a few hours on Windows. It's > threaded and uses a lot of memory. Let's see what you're missing: 1. platform specifics 2. versions of things involved 3. any sort of detail about the code 4. how you're noticing/measuring the problem 5. what "bombs" means 6. any mention that you've checked Sourceforge to see whether a similar problem has been reported There have been memory leaks in various past versions of Python, and could easily be in the current version, but they're generally rather specific in terms of the code that can trigger it. Once it was doing some particular work with a socket, once it was trying to append (or extend?) to an empty list, and so on. There are also a few ways you could have written your application to cause memory to leak as a result of your own code, not as a result of Python's. And it's even possible that this would happen only on one platform (though I'm trying hard to think of an example and can't... maybe it's very unlikely.) -Peter From jack at performancedrivers.com Wed Jan 19 16:01:04 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 19 Jan 2005 16:01:04 -0500 Subject: RuntimeError: dictionary changed size during iteration In-Reply-To: References: Message-ID: <20050119210104.GJ26167@performancedrivers.com> On Wed, Jan 19, 2005 at 11:45:15PM +0300, Roman Suzi wrote: > > I think, the behaviour below is misfeature: > > >>> [e for e in vars()] > Traceback (most recent call last): > File "", line 1, in ? > RuntimeError: dictionary changed size during iteration > >>> e = None > >>> [e for e in vars()] > ['e', '__builtins__', 'rlcompleter', '__file__', '_[1]', 'atexit', '__name__', > 'readline', '__doc__'] > Chalk it up as a lesson in the slightly different behavior of genexps Python 2.4 (#2, Jan 8 2005, 20:18:03) [GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> list(e for e in vars()) ['__builtins__', '__name__', '__doc__'] >>> [e for e in vars()] Traceback (most recent call last): File "", line 1, in ? RuntimeError: dictionary changed size during iteration -Jack From rschroev_nospam_ml at fastmail.fm Fri Jan 14 13:33:05 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 14 Jan 2005 18:33:05 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <1CSFd.30772$Qv5.2842746@phobos.telenet-ops.be> Message-ID: Antoon Pardon wrote: > Op 2005-01-14, Roel Schroeven schreef : > >>Antoon Pardon wrote: >> >>>IMO we have a: dogs are mamals kind of relationship in Python. >> >>I see what you mean, but I don't think it's true. >> >> >>>Every expression can be used where a statement is expected. >>>(And this can be worded as: every expression is a statement.) >> >>Not really. An expression statement is a statement that looks like an >>expression, but actually it's more than that: not only does it calculate >>the value of the expression, it also prints the value. > > > 1) Only in an interactive environment. True, I wanted to add that but forgot it. Doesn't change what I'm saying though. > 2) That the semantics differ according to where the expression is > used doesn't make a difference. That an expression decides which > branch of an if statement is executed or what object is pass > as an argument in a call are also semantic difference, yet > we still have an expression in both cases. In both cases we have an expression, in both cases we have a statement, in both cases the expression is a part of the statement. In one case the expression is the only statement, in the other case the statement has other parts too. > >>Note that it would be perfectly possible to modify the syntax into >> >>expression_stmt ::= "exprstmt" expression_list >>... > > If you change the syntax, of course you will change the strings > that will be accepted. I could change the syntax to: > > if_stmt ::= "if" "ifexpr" expression ... > > Have I now proved that expressions after an if are not normal > expressions? No, you still have a statement with one or more parts, one of which is an expression. In OOP terms: I think that an expression statement 'has an' expression (I agree that is a very thin wrapper though), not that an expression statement 'is an' expression. >>>Not every statement can be used where an expression is expected. >> >>AFAIK *no* statement can be used where an expression is expected. > > > But that was not the implication of what Guido supposedly had said. > So that this is not the case doesn't counter what I said. Whether statements can be used in the place of expressions is indeed not relevant to the discussion. Regarding what Guido apparently said: Op 2005-01-12, Steve Holden schreef : >> Given that Guido is on record as saying that expressions aren't >> statements because he wants those things to be separate Antoon Pardon wrote: > Well, it seems that Guido is wrong then. The documentation clearly > states that an expression is a statement. I don't think it says that at all. > More specifically, everywhere you can use a statement, you can > simply use an expression according to the python syntax. If you use an expression where a statement is expected, you really write an expression statement that contains the expression (and nothing else, but that doesn't matter). -- "Codito ergo sum" Roel Schroeven From bac at OCF.Berkeley.EDU Sun Jan 23 14:49:06 2005 From: bac at OCF.Berkeley.EDU (Brett C.) Date: Sun, 23 Jan 2005 11:49:06 -0800 Subject: python-dev Summary for 2004-12-01 through 2004-12-15 Message-ID: <41F3FFB2.5070607@ocf.berkeley.edu> This is a summary of traffic on the `python-dev mailing list`_ from December 01, 2004 through December 15, 2004. It is intended to inform the wider Python community of on-going developments on the list. To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! This is the fifty-fourth summary written by Brett Cannon (amazed no one has complained about the lateness of these summaries!). To contact me, please send email to brett at python.org ; I do not have the time to keep up on comp.lang.python and thus do not always catch follow-ups posted there. All summaries are archived at http://www.python.org/dev/summary/ . Please note that this summary is written using reStructuredText_ which can be found at http://docutils.sf.net/rst.html . Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it, although I suggest learning reST; it's simple and is accepted for `PEP markup`_ and gives some perks for the HTML output. Also, because of the wonders of programs that like to reformat text, I cannot guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _PEP Markup: http://www.python.org/peps/pep-0012.html The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation on new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to forward the development and use of Python. But the PSF_ cannot do this without donations. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation (you can donate through PayPal or by check) helps. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. contents:: .. _last summary: http://www.python.org/dev/summary/2004-11-16_2004-11-30.html .. _original text file: http://www.python.org/dev/summary/2004-12-01_2004-12-15.ht ===================== Summary Announcements ===================== PyCon_ 2005 planning is well underway. The schedule has been posted at http://www.python.org/pycon/2005/schedule.html and looks great with a quite the varied topics. And there is still time for the early-bird registration price of $175 ($125 students) before it expires on January 28th. Some day I will be all caught up with the Summaries... .. _PyCon: http://www.pycon.org ========= Summaries ========= ---------------------------------- PEPS: those existing and gestating ---------------------------------- [for emails on PEP updates, subscribe to python-checkins_ and choose the 'PEP' topic] A proto-PEP covering the __source__ proposal from the `last summary`_ has been posted to python-dev. `PEP 338`_ proposes how to modify the '-m' modifier so as to be able to execute modules contained within packages. .. _python-checkins: http://mail.python.org/mailman/listinfo/python-checkins .. _PEP 338: http://www.python.org/peps/pep-0338.html Contributing threads: - `PEP: __source__ proposal `__ - `PEP 338: Executing modules inside packages with '-m' `__ ------------------- Deprecating modules ------------------- The xmllib module was deprecated but not listed in `PEP 4`_. What does one do? Well, this led to a long discussion on how to handle module deprecation. With the 'warning' module now in existence, PEP 4 seemed to be less important. It was generally agreed that listing modules in PEP 4 was no longer needed. It was also agreed that deleting deprecated modules was not needed; it breaks code and disk space is cheap. It seems that no longer listing documentation and adding a deprecation warning is what is needed to properly deprecate a module. By no longer listing documentation new programmers will not use the code since they won't know about it. And adding the warning will let old users know that they should be using something else. .. _PEP 4: http://www.python.org/peps/pep-0004.html Contributing threads: - `Deprecated xmllib module `__ - `Rewriting PEP4 `__ ------------------------------------------ PR to fight the idea that Python is "slow" ------------------------------------------ An article_ in ACM TechNews that covered 2.4 had several mentions that Python was "slow" while justifying the slowness (whether it be flexibility or being fast enough). Guido (rightfully) didn't love all of the "slow" mentions which I am sure we have all heard at some point or another. The suggestions started to pour in on how to combat this. The initial one was to have a native compiler. The thinking was that if we compiled to a native executable that people psychologically would stop the association of Python being interpreted which is supposed to be slow. Some people didn't love this idea since a native compiler is not an easy thing. Others suggested including Pyrex with CPython, but didn't catch on (maintenance issue plus one might say Pyrex is not the most Pythonic solution). This didn't get anywhere in the end beyond the idea of a SIG about the various bundling tools (py2app, py2exe, etc.). The other idea was to just stop worrying about speed and move on stomping out bugs and making Python functionally more useful. With modules in the stdlib being rewritten in C for performance reasons it was suggested we are putting out the perception that performance is important to us. Several other people also suggested that we just not mention speed as a big deal in release notes and such. This also tied into the idea that managers don't worry too much about speed as much as being able to hire a bunch of Python programmers. This led to the suggestion of also emphasizing that Python is very easy to learn and thus is a moot point. There are a good number of Python programmers, though; Stephan Deibel had some rough calculations that put the number at about 750K Python developers worldwide (give or take; rough middle point of two different calculations). .. _article: http://gcn.com/vol1_no1/daily-updates/28026-1.html Contributing threads: - `2.4 news reaches interesting places `__ =============== Skipped Threads =============== - MS VC compiler versions - Any reason why CPPFLAGS not used in compiling? Extension modules now compile with directories specified in the LDFLAGS and CPPFLAGS env vars - adding key argument to min and max min and max now have a 'key' argument like list.sort - Unicode in doctests - SRE bug and notifications - PyInt_FromLong returning NULL - PyOS_InputHook enhancement proposal - The other Py2.4 issue - MinGW And The other Py2.4 issue - Supporting Third Party Modules - Python in education From jurgenex at hotmail.com Tue Jan 18 09:35:57 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Tue, 18 Jan 2005 14:35:57 GMT Subject: [perl-python] 20050118 keyed list References: <1106027360.920787.321590@z14g2000cwz.googlegroups.com> Message-ID: Xah Lee wrote: > ? # in perl, keyed-list is done like this: Just FYI: those thingies are called hashes. The legacy name would be associative array. > ? %a = ('john',3, 'mary', 4, 'jane', 5, 'vicky',7); > ? use Data::Dumper qw(Dumper); > ? print Dumper \%a; Wow, my compliments. The very first time that using Data::Dumper actually may do something useful (formats the data more nicely). Still, why you are passing a reference is beyond me. > ? # the syntax of keyed list in Perl is too complex > ? # to be covered in a short message. Excuse me? If (using the same examples as for your Python section) print "Mary is $a{mary}"; delete $a{vicky}; print %a; print keys(%a); exists $a{mary}; is too complex for your to cover, then I strongly suggest you stop posting your "explanations". > ? # see "perldoc perldata" for an unix-styled course. Excuse me? Do you mind explaining where exactly perldata is "Unix-styled"? jue From Mark.English at liffe.com Fri Jan 21 12:41:11 2005 From: Mark.English at liffe.com (Mark English) Date: Fri, 21 Jan 2005 17:41:11 -0000 Subject: Class introspection and dynamically determining function arguments Message-ID: <40E605146701DE428FAF21286A97D309174511@wphexa02.corp.lh.int> Diez B. Roggisch wrote: > According to this > http://www-106.ibm.com/developerworks/library/l-pyint.html > > not really - and there are no special moduls neccessary, as > everything is at your hands using __dict__ and so on. Thanks for the link. I'd read that article but found it was too introductory (what is help, what is sys, etc.). It didn't even deal with inspect. As such, I didn't think it was definitive about Python's existing introspection code. This was much more the level of sophistication I was looking for, albeit aimed at (static) declared function syntax, rather than (dynamic) instance or class attributes: http://www.sff.net/people/neelk/open-source/Signature.py Also, I know the class __dict__ (which is actually a proxy object) may have class attributes currently, but that seems implementation dependent. At the moment it lists the attributes defined by *this* type, regardless of attributes defined in base types. Again, this happens to be what I want but I don't know that this behaviour is defined anywhere, and therefore it may be subject to change. It would be nice if I could ask a class if there are any attributes defined for it in "tp_getset", although that's just a small step along the path of attribute discovery... (Apologies for interchangeable use of the words type/class) Nick Coghlan wrote > Perhaps the simplest way is to require all such classes to have a "getExample" > class method that produces a fully populated example instance Thanks Nick. This was the kind of approach I've ended up going with (sorta). Still hunting for ideas... ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From asda at sdarta.com Sat Jan 8 10:03:44 2005 From: asda at sdarta.com (worzel) Date: Sat, 8 Jan 2005 23:03:44 +0800 Subject: tuples vs lists References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41dff650$0$29357$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Cheers - thanks for the feedback guys - pretty much answers the question for me. 'Two-Pull' it is then, thanks. "Steve Horsley" wrote in message news:croqtg$qo0$1 at news.freedom2surf.net... > worzel wrote: >> I get what the difference is between a tuple and a list, but why would I >> ever care about the tuple's immuutability? > > Mainly for security and speed. Many library functions return info by > returning > a reference to an internally held tuple, and could be damaged / > compromised > / corrupted if that internal data was modified by malicious code. If > tuples > were mutable (lists) then it would be necessary to return a copy instead. > >> Also, do you say 'too-ple' or 'chu-ple' - if you get my drift. (tomato or >> tomato kind of thing) > > Try 'Two-pull'. > > Steve From benji at zope.com Mon Jan 31 23:19:39 2005 From: benji at zope.com (Benji York) Date: Mon, 31 Jan 2005 23:19:39 -0500 Subject: barchart for webpage needed In-Reply-To: References: Message-ID: <41FF035B.3050900@zope.com> dimitri pater wrote: > I am looking for a Python tool to create graphs and charts on a > webpage. Chartdirector is too expensive for me. A simple script for > creating a barchart should be sufficient as a starting point. If all you want are bar charts, you can get by with simple HTML. Here's one technique: http://www.siteexperts.com/tips/contents/ts13/page1.asp. -- Benji York Sr. Software Engineer Zope Corporation From steve at holdenweb.com Thu Jan 6 09:06:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Jan 2005 09:06:05 -0500 Subject: navigating/changing directories In-Reply-To: References: Message-ID: <8FbDd.68968$Jk5.48112@lakeread01> skip wrote: > A simple script like the one below lets me jump through a directory > structure. However, if I run it from /this/directory and within it to go to > /a/totally/different/directory... I'm still actually going to be in > /this/directory when I exit the script. Is it possible to have a script > that can drop me off into a different directory than where I initiated it > from? > > import os > process = 1 > while (process): > # Display directories > for i in os.listdir(os.getcwd()): > if (os.path.isdir(os.path.join(os.getcwd(),i))): > print i > > # Change directory > goto_dir = raw_input(": ") > if (goto_dir in os.listdir(os.getcwd())): > os.chdir(os.path.join(os.getcwd(),goto_dir)) > else: > process = 0 # Exit > > As has already been reported, under Linux a change to the current working directory won't affect the environment of the parent process. You may find that under some Windows command line interpreters that the change to the working directory made by a program persists into the interactive session that triggered the program. One way to achieve your desired goal, of course, is to call your program using a shell expansion sequence (assuming Unix-like shell environments), as in: cd `myprogram.py` and then if your program outputs the path to a directory your shell's current working directory will be chaged as you require. there's-always-a-way-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From aleaxit at yahoo.com Mon Jan 24 04:28:25 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 24 Jan 2005 10:28:25 +0100 Subject: best way to do a series of regexp checks with groups References: <1gqvzm0.htfjsq10h8nruN%aleaxit@yahoo.com> Message-ID: <1gqw1sv.18zhgeqcb46t3N%aleaxit@yahoo.com> Steven Bethard wrote: > I get a bit uneasy from the repeated calls to m.group... If I was going > to build a class around the re, I think I might lean towards something like: > > class ReWithMemory(object): > def search(self, are, aline): > self.mo = re.search(are, aline) > return self.mo > def groups(self, *indices): > return [self.mo.group(i) for i in indices] > > m = ReWithMemory() > > if m.search(r'add (\d+) (\d+)', line): > do_add(*m.groups(1, 2)) > elif m.search(r'mult (\d+) (\d+)', line): > do_mult(*m.groups(1, 2)) > elif m.search(r'help (\w+)', line): > show_help(*m.groups(1)) > > Of course, this is even less general-purpose than yours... I'm not sure what advantage it's supposed to give. Would you have any problems writing, say, somecall(X[1], X[2]) ...? Python normally relies on indexing one thing at a time, and I see calling m.group(1) etc as just the same kind of approach. > (And if I saw myself using this much regex code, I'd probably reconsider > my strategy anyway.) ;) Surely joining all the regexp's into one big one with | would be faster and more compact, but, with variable numbers of groups per sub-regexp, determining which regexp matched can perhaps be tricky (issues with matching mo.lastindex to the correct sub-regexp). So, I can understand the desire to do it sequentially, regexp by regexp. Alex From ncoghlan at iinet.net.au Wed Jan 12 05:32:25 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 12 Jan 2005 20:32:25 +1000 Subject: else condition in list comprehension In-Reply-To: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: <41E4FCB9.4030200@iinet.net.au> Luis M. Gonzalez wrote: > Hi there, > > I'd like to know if there is a way to add and else condition into a > list comprehension. I'm sure that I read somewhere an easy way to do > it, but I forgot it and now I can't find it... > > for example: > z=[i+2 for i in range(10) if i%2==0] > what if I want i to be "i-2" if i%2 is not equal to 0? > Hmm: z = [newval(i) for i in range(10)] using: def newval(x): if x % 2: return x - 2 else: return x + 2 Just some more mental twiddling relating to the thread on statement local namespaces. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ncoghlan at iinet.net.au Tue Jan 25 09:09:10 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 00:09:10 +1000 Subject: Instances of class object not modifiable? In-Reply-To: References: Message-ID: <41F65306.4030008@iinet.net.au> Steven Bethard wrote: > Open Issues > =========== > What should the type be named? Some suggestions include 'Bunch', > 'Record' and 'Struct'. Add 'namespace' to the list of name suggestions :) Cheers, Nick. The name came up in some thread a few weeks back. . . -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From chris.peressotti at utoronto.ca Fri Jan 28 11:13:45 2005 From: chris.peressotti at utoronto.ca (Chris P.) Date: 28 Jan 2005 08:13:45 -0800 Subject: PythonWin (build 203) for Python 2.3 causes Windows 2000 to grind to a halt? References: <3f233389.0501271147.43572416@posting.google.com> <41f9e4a9$1_1@127.0.0.1> Message-ID: <3f233389.0501280813.6be97b74@posting.google.com> AWESOME - my life just got THAT much better. The bug you suggested is exactly the problem that I was having... I had looked through the bugs being tracked, but the title of that one didn't jump out at me as something that would help. Thanks! - Chris P.S. For anyone reading this group who wants to know exactly what I did: 1) Uninstall Pywin32 2) Open the registry editor ('regedit' at the command prompt) 3) Go to HKEY_CURRENT_USER\Software\Python[version]\Python for Win32 You will likely find many many many keys that have the format "ToolbarDefault-Bar#". These keys filling up your registry cause Windows 2000 to become extremely slow/unstable when Python is running (especially if your debugger is running.) 4) Delete the keys... I just deleted it at the "Python[version]" root 5) Reinstall Pywin32 "Roger Upole" wrote in message news:<41f9e4a9$1_1 at 127.0.0.1>... > These look like symptoms of sf bug #1017504 > http://sourceforge.net/tracker/index.php?func=detail&aid=1017504&group_id=78018&atid=551954 > > What version of Pywin32 are you running ? > There's a (semi) fix for this in the latest build. > hth > Roger From aurora00 at gmail.com Mon Jan 31 19:07:41 2005 From: aurora00 at gmail.com (aurora) Date: Mon, 31 Jan 2005 16:07:41 -0800 Subject: Go visit Xah Lee's home page Message-ID: Let's stop discussing about the perl-python non-sense. It is so boring. For a break, just visit Mr Xah Lee's personal page (http://xahlee.org/PageTwo_dir/Personal_dir/xah.html). You'll find lot of funny information and quotes from this queer personality. Thankfully no perl-python stuff there. Don't miss Mr. Xah Lee's recent pictures at http://xahlee.org/PageTwo_dir/Personal_dir/mi_pixra.html My favor is the last picture. Long haired Xah Lee sitting contemplatively in the living room. The caption says "my beautiful hair, fails to resolve the problems of humanity. And, it is falling apart by age." From storchaka at ksf.kiev.ua Tue Jan 11 13:14:01 2005 From: storchaka at ksf.kiev.ua (Serhiy Storchaka1659322541) Date: Tue, 11 Jan 2005 20:14:01 +0200 Subject: else condition in list comprehension In-Reply-To: References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> <1105305000.052714.188980@c13g2000cwb.googlegroups.com> Message-ID: Nick Coghlan wrote: > Dan Bishop wrote: > >> Luis M. Gonzalez wrote: >> >>> Hi there, >>> >>> I'd like to know if there is a way to add and else condition into a >>> list comprehension. I'm sure that I read somewhere an easy way to do >>> it, but I forgot it and now I can't find it... >>> >>> for example: >>> z=[i+2 for i in range(10) if i%2==0] >>> what if I want i [sic] to be "i-2" if i%2 is not equal to 0? >> >> >> >> z = [i + (2, -2)[i % 2] for i in range(10)] > > > For the specific case of +/- a number, (-1) ** x works, too: > > z = [i + 2 * ((-1) ** i) for i in range(10)] > > Not that I'm claiming it's particularly readable or anything. . . just > that it works :) Yet another variant: z = [i + ( (i % 2) and -2 or 2 ) for i in range(10)] -- Serhiy Storchaka From tim.peters at gmail.com Wed Jan 26 20:59:11 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 26 Jan 2005 20:59:11 -0500 Subject: python memory blow out In-Reply-To: <3e8ca5c8050126174444967112@mail.gmail.com> References: <4e4a11f805012617082ebd9b80@mail.gmail.com> <3e8ca5c8050126174444967112@mail.gmail.com> Message-ID: <1f7befae050126175916958afd@mail.gmail.com> [Simon Wittber] >> According to the above post: >> a) If the allocation is > 256 bytes, call the system malloc. >> b) If the allocation is < 256, use its own malloc implementation, which >> allocates memory in 256 kB chunks and never releases it. >> >> I imagine this means that large memory allocations are eventually >> released back to the operating system. However, in my case, this >> appears to be not happening. Large chunks are returned to the platform C when they become unreferenced. More below. [Stephen Thorne] > There was a recent patch posted to python-dev list which allows python > to release memory back to the operating system once the 256kb chunk is > no longer used. Nope, the patch may return such a 256KB chunk to the platform C library's free() function. That's never what someone actually means by the vague "released back to the operating system", and whether the latter might happen is another platform-dependent (OS + C library + specific versions of each) can of worms. > I'm not saying running a bleeding edge CVS HEAD python plus untested > development patches is going to be a solution for you in the short > term, but I just wanted to mention it because I'm excited about this > limitation disappearing in python :). It's a necessary first step, anyway. Alas, there's no way to take a second step without messy platform-specific code (when does your favorite platform C free() "release memory back" to your favorite operating system? to "do something about that", exact knowledge of platform details is necessary). From removethis.kartic.krishnamurthy at gmail.com Sun Jan 30 20:28:59 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Mon, 31 Jan 2005 01:28:59 GMT Subject: Problem with loading textfiles into dictionaries. In-Reply-To: References: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> Message-ID: Kartic said the following on 1/30/2005 8:21 PM: > mercuryprey at gmail.com said the following on 1/30/2005 7:43 PM: > Hi - It looks like your code encountered a blank line when you got this > error. > > You should move "if len(siteline) == 0" part right after your readline. > The way you have done it really does not help. > > def do_load(self, arg): > sitefile = file('sitelist', 'r+', 1) > while True: > siteline = sitefile.readline() > if len(siteline) == 0: > break > site_rawlist = siteline.split() > sitelist[site_rawlist[0]] = site_rawlist[1:] Sorry...siteline = sitefile.readline().strip() From jgrahn-nntq at algonet.se Mon Jan 24 16:51:35 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 24 Jan 2005 21:51:35 GMT Subject: how to ncurses on win32 platform References: <3nkds3kzc9mp.18yfed1y3vo9d$.dlg@40tude.net> Message-ID: On Mon, 24 Jan 2005 20:26:28 +0000 (UTC), Alan Gauld wrote: > On Mon, 24 Jan 2005 17:06:52 +0100, Brane wrote: >> please advice > > You can use ncurses via cygwin. > There are DOS ports too but I couldn't get any of them to > work on my XP box, YMMV... Or, as Alex Martelli wrote in "Python in a nutshell": "The curses package works only on Unix-like platforms (there are persis- tent rumors of Windows ports of it, but I've never found a working one)." /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From tom at livelogix.com Wed Jan 26 01:01:57 2005 From: tom at livelogix.com (Tom) Date: 25 Jan 2005 22:01:57 -0800 Subject: Python with no significant whitespace In-Reply-To: References: <35oh4gF4nvvfoU1@individual.net> Message-ID: <1106719317.609935.38430@f14g2000cwb.googlegroups.com> Just though I'd point out that Logix *does* use whitespace for delimiting blocks. Or rather, it can use whitespace, and the languages that come as standard do. With Logix you could quite easily make a version of Python with, e.g., braces instead of whitespace for delimiting blocks. That's probably what the Stephen was getting at. Tom. From martin at v.loewis.de Sun Jan 23 18:15:29 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 24 Jan 2005 00:15:29 +0100 Subject: rotor replacement In-Reply-To: <7xllalljah.fsf@ruckus.brouhaha.com> References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> Message-ID: <41F43011.8020303@v.loewis.de> Paul Rubin wrote: > There's tons of such examples, but python-dev apparently reached > consensus that the Python maintainers were less willing than the > maintainers of those other packages to deal with those issues. As Andrew says, it is not apparent that there was consensus. > Martin, do you know more about this? I'm pretty certain that we (the PSF) sent a message to BXA, reporting the rotor module. While I can't find out exactly when this happened right now, the board meeting on 2002-04-09 decided that this should happen, see http://python.org/psf/records/board/minutes-2002-04-09.html Regards, Martin From elephantum at dezcom.mephi.ru Thu Jan 13 14:41:54 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Thu, 13 Jan 2005 22:41:54 +0300 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> Message-ID: <34o183F4b3in3U1@individual.net> Nick Coghlan wrote: > Nick Coghlan wrote: > >> Semantics >> --------- >> The code:: >> >> with: >> >> >> translates to:: >> >> def unique_name(): >> >> >> unique_name() > I've come to the conclusion that these semantics aren't what I would > expect from the construct. Exactly what I would expect can't really be > expressed in current Python due to the way local name bindings work. The > main thing to consider is what one would expect the following to print: > > def f(): > a = 1 > b = 2 > print 1, locals() > print 3, locals() using: > a = 2 > c = 3 > print 2, locals() > print 4, locals() > > I think the least suprising result would be: > > 1 {'a': 1, 'b': 2} # Outer scope > 2 {'a': 2, 'c': 3} # Inner scope > 3 {'a': 2, 'b': 2, 'c': 3} # Bridging scope > 4 {'a': 1, 'b': 2} # Outer scope as for me, I would expect following: 1 {'a': 1, 'b': 2} 2 {'a': 2, 'b': 2, 'c': 3'} 3 {'a': 2, 'b': 2, 'c': 3'} 4 {'a': 1, 'b': 2} otherwise that would be impossible to do calculations based on scope variables and "using:" would be useless =), consider example of usage: current_position = 1 current_environment # = ... current_a_lot_of_other_parameters # = ... scores = [count_score(move) for move in aviable_moves] using: def count_score(move): #walking through current_environment return score From kosh at aesaeion.com Tue Jan 11 21:23:46 2005 From: kosh at aesaeion.com (kosh) Date: Tue, 11 Jan 2005 19:23:46 -0700 Subject: Python.org, Website of Satan In-Reply-To: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: <200501111923.46511.kosh@aesaeion.com> On Tuesday 11 January 2005 7:06 pm, humblythegreatest at usa.com wrote: > python.org = 194.109.137.226 > > 194 + 109 + 137 + 226 = 666 > > What is this website with such a demonic name and IP address? What > evils are the programmers who use this language up to? Geeze did you miss out on the demon summoning rituals last week? Wow that was a great thing you missed out on. I am sorry I can't tell you about the future events though. Only great wizards are allowed to come and they all know when the events are. :) From rbt at athop1.ath.vt.edu Mon Jan 17 10:30:38 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 17 Jan 2005 10:30:38 -0500 Subject: Install Python 2.4 on Fedora 3 Core In-Reply-To: <1105975262.047782.6010@z14g2000cwz.googlegroups.com> References: <1105975262.047782.6010@z14g2000cwz.googlegroups.com> Message-ID: Bill wrote: > I have less than a week experience on linux, so I am a new newbie. > Python 2.3 came preinstalled. I installed version 2.4. All seemed to > go well except it installed to usr/local? > > 1. Was it wrong to install when logged in as 'root'? Does it make a > difference? > > 2. I looked in the package editor and there was no way to uninstall > 2.3? Should I? If so, how can I? If not,what are the problems, if > any, of having both. > > Thank you for your help. > Bill, /usr/local is the path on Unix systems where add-on software is traditionally installed. RH used to use Python heavily for many aspects of their RHL distribution. I suspect they still do this with Fedora. This is probably why the version of Python that came with Fedore cannot be removed (at least not easily). It's OK to have the RH version and the latest Python.org version installed. You'll just have to specify the path to the version you wish to use when running your scripts like this: /usr/local/python There are some more advanced things you could do and I suspect others will give you better advice. But all in all, you're OK. Have fun. From alan.gauld at btinternet.com Thu Jan 6 17:36:00 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 6 Jan 2005 22:36:00 +0000 (UTC) Subject: Securing a future for anonymous functions in Python References: Message-ID: On Thu, 30 Dec 2004 23:28:46 +1000, Nick Coghlan wrote: > GvR has commented that he want to get rid of the lambda keyword for Python 3.0. > Getting rid of lambda seems like a worthy goal, Can I ask what the objection to lambda is? 1) Is it the syntax? 2) Is it the limitation to a single expression? 3) Is it the word itself? I can sympathise with 1 and 2 but the 3rd seems strange since a lambda is a well defined name for an anonymous function used in several programming languages and originating in lambda calculus in math. Lambda therefore seems like a pefectly good name to choose. So why not retain the name lambda but extend or change the syntax to make it more capable rather than invent a wholly new syntax for lambdas? Slightly confused, but since I only have time to read these groups regularly when I'm at home I have probably missed the bulk of the discussion over the years. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From deetsNOSPAM at web.de Fri Jan 28 08:15:36 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 28 Jan 2005 14:15:36 +0100 Subject: Proccess termination References: <1106917700.730538.80320@f14g2000cwb.googlegroups.com> Message-ID: <35us3lF4rqg1oU1@individual.net> alexrait1 wrote: > I use popen.popen2 or popen.popen3 to start a new process and read from > it's stdout/ write to it's stdin. > But I need a way to know when a process terminates. If it closes it's > stdin/stdout, it doesn't mean it has really terminated... You can use the Popen-objects pid to see if a process still runs. > And if possible, I would like to see an exception thrown when that > happens.. Not possible - that exception would be asynchronous to your program flow. The only thing I can think of that would make this possible is to have a second thread waiting for process termination - and sending the own process a signal. If I'm not mistaken, that will be propagated to the main thread. All this is meant to be running on unix - not sure how thinks work out on windows. -- Regards, Diez B. Roggisch From bulba at bulba.com Sat Jan 8 23:01:58 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 09 Jan 2005 05:01:58 +0100 Subject: The Industry choice References: <7xhdluxh4i.fsf@ruckus.brouhaha.com> Message-ID: On 6 Jan 2005 20:07:19 -0500, aahz at pythoncraft.com (Aahz) wrote: >>Nope. That is not what I'm arguing. Really, I think you have >>jumped to conclusion about that: I merely pointed out that >>I don't like what I perceive as end effect of what GPL license >>writers are attempting to achieve: vendor lock-in. >> >>I think I stated that clearly. > >And my counter-argument is that I believe your perception is wrong. If >I agreed with your focus on lock-in, I'd say that what the GPL is trying >to lock in is a specific legal philosophy by subverting the existing >system. If it finally turns out that I'm wrong on this and GPL does not have that kind of economic "vendor lock-in" _effect_ behind it (note: effect, not intent), I will be only happy to see that. Re subverting existing legal philosophy, I could not care less. Obviously the only reason that I argued that way is that given the info that I have it simply looks like that from my viewpoint. -- It's a man's life in a Python Programming Association. From donn at drizzle.com Sun Jan 2 01:26:39 2005 From: donn at drizzle.com (Donn Cave) Date: 2 Jan 2005 00:26:39 -0600 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> <7xsm5kfyse.fsf@ruckus.brouhaha.com> Message-ID: <41d7941f$1_3@127.0.0.1> Quoth Paul Rubin : | beliavsky at aol.com writes: |> Overall I agree with you and would like to have OPTIONAL static type |> declarations in Python, as has often been discussed. But without |> facilities for generic programming, such as templates in C++, static |> type declarations can force one to duplicate a LOT of code, with one |> sorting routine each for integer, floats, strings, etc. | | I don't see that big a problem. The current Python sorting routine | operates on instances of class "object" and calls the __cmp__ method | to do comparisons. Every class of sortable objects either defines a | __cmp__ method or inherits one from some superclass, and sort calls | those methods. Static type declarations would not require writing any | additional sorting routines. Yes, it would be really weird if Python went that way, and the sort of idle speculations we were reading recently from Guido sure sounded like he knows better. But it's not like there aren't some interesting issues farther on downstream there, in the compare function. cmp(), and str() and so forth, play a really big role in Python's dynamically typed polymorphism. It seems to me they are kind of at odds with static type analysis, especially if you want type inference -- kind of a type laundering system, where you can't tell what was supposed to be there by looking at the code. Some alternatives would be needed, I suppose. Donn Cave, donn at drizzle.com From jzgoda at gazeta.usun.pl Fri Jan 14 15:27:01 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 14 Jan 2005 21:27:01 +0100 Subject: python to mssql In-Reply-To: <1lmwxbtst8x8x$.10hwcoinem3cs.dlg@40tude.net> References: <1lmwxbtst8x8x$.10hwcoinem3cs.dlg@40tude.net> Message-ID: Brane wrote: > can someone please give me some info regarding subject From Windows machine: http://adodbapi.sourceforge.net/ From elsewhere: FreeTDS + unixODBC + mxODBC is one of possible solutions. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From ysharma at catprosystems.com Thu Jan 13 18:09:07 2005 From: ysharma at catprosystems.com (Yogesh Sharma) Date: Thu, 13 Jan 2005 15:09:07 -0800 Subject: Embedding Multiplr Python interpreter in C++ In-Reply-To: References: Message-ID: <41E6FF93.9060406@catprosystems.com> one more question to add: Is there a way to have 2 local copies of python interpreter ? Yogesh Sharma wrote: > Hi, > > I have following setup: > OS Linux Fedora Core 3 > Python 2.3.4 > > How can I embed two python interpreters in one C++ program ? > > Thanks From peter at engcorp.com Thu Jan 13 18:15:21 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 18:15:21 -0500 Subject: newbie ?s In-Reply-To: <1105656971.768148@sj-nntpcache-5> References: <1105656971.768148@sj-nntpcache-5> Message-ID: Venkat B wrote: > Hi folks, > > I'm looking build a CGI-capable SSL-enabled web-server around Python 2.4 on > Linux. > It is to handle ~25 hits possibly arriving "at once". Content is non-static > and built by the execution of py cgi-scripts talking to a few backend > processes. Twisted? I'm not sure what, if anything, it has in the way of CGI support, but that could probably be hacked on pretty darn quick if you needed. At least Twisted has support for server-side SSL (i.e. it can deal with certificates). -Peter From rkern at ucsd.edu Sun Jan 9 11:46:22 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 09 Jan 2005 08:46:22 -0800 Subject: Python3: on removing map, reduce, filter In-Reply-To: <34d3c9F477m01U1@individual.net> References: <34csn1F4a46hqU1@individual.net> <5CcEd.70344$Jk5.19962@lakeread01> <34d3c9F477m01U1@individual.net> Message-ID: Andrey Tatarinov wrote: > Steve Holden wrote: > >> Andrey Tatarinov wrote: >> >>> Hi. >>> >>> How does GvR suggestions on removing map(), reduce(), filter() >>> correlate with the following that he wrote himself (afaik): >>> >>> http://www.python.org/doc/essays/list2str.html > > > > >> And note that the summary in the conclusiogn BEGINS with "Rule number >> one: only optimize when there is a proven speed bottleneck", which >> seems to adequately imply that straightforward code is to be preferred >> unless speed requirements override that. > > > My main question was: "how could be this advices applied, when map, > reduce and filter would be removed?" Since Python 3.0 is currently mythical and will involve a complete rewrite of the language and interpreter, I don't think that you should expect any optimization advice to carry over. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From fredrik at pythonware.com Sat Jan 15 04:31:37 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 15 Jan 2005 10:31:37 +0100 Subject: How to del item of a list in loop? References: Message-ID: "skull" wrote: > Hi everybody, it is my first post in this newsgroup. > I am a newbie for python though I have several years development experience in c++. > recently, I was stumped when I tried to del item of a list when iteration. > > here is the wrong way I did: > > lst = [1, 2, 3] > for i in lst: > print i > if i == 2: > lst.remove(i) > > the result is: > > 1 > 2 >>>> > > as you would see, '3' is missing. this problem is caused by 'lst.remove(i)'. the internal loop counter is incremented whether you remove stuff or not, so when you're moving things around by removing items in the middle, the loop will skip over items. this is basic for-in usage, and any decent tutorial should explain this. to fix this, you can build a new output list, loop backwards, or loop over a copy. the last is easiest to implement: lst = [1, 2, 3] for i in lst[:]: print i if i == 2: lst.remove(i) but the others may have advantages in certain use cases. if you want more details, see the language reference: http://docs.python.org/ref/for.html (note the warning) From aurora00 at gmail.com Fri Jan 28 11:25:29 2005 From: aurora00 at gmail.com (aurora) Date: Fri, 28 Jan 2005 08:25:29 -0800 Subject: Transparent (redirecting) proxy with BaseHTTPServer References: <35sfdaF4hka1hU1@individual.net> <35t9huF4rt829U1@individual.net> Message-ID: It should be very safe to count on the host header. Maybe some really really old browser would not support that. But they probably won't work in today's WWW anyway. Majority of today's web site is likely to be virtually hosted. One Apache maybe hosting for 50 web addresses. If a client strip the host name and not sending the host header either the web server wouldn't what address it is really looking for. If you caught some request that doesn't have host header it is a good idea to redirect them to a browser upgrade page. > > Thanks, aurora ;), > > aurora wrote: >> If you actually want the IP, resolve the host header would give you >> that. > I' m only interested in the hostname. > >> The second form of HTTP request without the host part is for >> compatability of pre-HTTP/1.1 standard. All modern web browser should >> send the Host header. > How safe is the assumtion that the Host header will be there? Is it part > of the HTTP/1.1 spec? And does it mean all "pre 1.1" clients will fail? > Hmm, maybe I should look on the wire whats really happening... > > thanks again > Paul From cdieterich at geosci.uchicago.edu Thu Jan 27 21:02:53 2005 From: cdieterich at geosci.uchicago.edu (Christian Dieterich) Date: Thu, 27 Jan 2005 20:02:53 -0600 Subject: inherit without calling parent class constructor? In-Reply-To: <10vj4ovqee29oc9@corp.supernews.com> Message-ID: On D?ardaoin, Ean 27, 2005, at 19:25 America/Chicago, Jeff Shannon wrote: > Okay, so size (and the B object) is effectively a class attribute, > rather than an instance attribute. You can do this explicitly -- Ah, now I'm getting there. That does the trick. > Probably not worth the trouble in this particular case, but maybe in > another case... :) Yeah, maybe not. But I'll remember it as a useful recipe. Cheers, Christian From peter at engcorp.com Thu Jan 6 10:36:28 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Jan 2005 10:36:28 -0500 Subject: OT: spacing of code in Google Groups In-Reply-To: References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> Message-ID: <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> Jacek Generowicz wrote: > Peter Hansen writes: >>Why the heck would I ever have to do "rectangle operations" on a >>regular basis? ;-) > > Well, given that all editors are cat equivalent[*], you don't _have_ > to use any of their features :-) This "cat equivalent" thing is a red-herring. I can rarely type more than a line of code without making a typographical error. Sometimes I won't catch that error until a bit later. Using "cat" alone would provide me little opportunity to fix the error, so I would never be able to produce a working program longer than a few lines. You might call this simply "less productive" (though I'd argue it becomes a qualitative difference). But, okay, let's work from there... > But just like Python (particularly in the hands of a skilled Python > programmer) is more productive than a Turing Machine, any featureful > editor (in the hands of an experienced user) is far more productive > than "cat > file". I don't disagree. I do, however, claim that the set of features that are required to make *me* orders of magnitude more productive than "cat" (to use your quantitative comparison) is very, very small. And that I use less than 2% of the features most editors have. And that if a programmer with equal abilities managed to learn to use 98% of the features of such an editor, such that he could readily use whichever such feature was most effective at any given time, he would not be more than 10% more effective than I am. But the whole argument is fairly moot... I've needed a rectangle operation only once in the last ten years, and if I hadn't known at the time that my editor could do it (and spent about half an hour figuring out how it worked), I could have written a utility to do the job faster if I'd been using Python at the time... Cheers, -Peter From martin at v.loewis.de Mon Jan 31 18:20:01 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 01 Feb 2005 00:20:01 +0100 Subject: serializing data structures In-Reply-To: References: Message-ID: <41FEBD21.5030306@v.loewis.de> Philippe C. Martin wrote: > I once wrote something in C to do that, but since python usually has a > solution for me .... If you use arbitrary data structures, you could use pickle or xmlrpclib to marshal the data. If you know the data is restricted to a few well-known data types, you could use XDR (Demo/rpc/xdr.py) or CORBA (e.g. through fnorb.sf.net) to come up with a wire format. Otherwise, if you want to define your own proprietary data format, you can probably use the struct module to generate messages according to this format. However, in any case, you need to define the wire format. Once you made a choice, Python can help implement it - but Python cannot chose a wire format for you (although pickle comes really close, as does Dopy - http://www.mindhog.net/~mmuller/projects/dopy/) Regards, Martin From http Sun Jan 9 00:40:40 2005 From: http (Paul Rubin) Date: 08 Jan 2005 21:40:40 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> Message-ID: <7xsm5b2m93.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > I think having to keep the names unique within the statement you are > currently writing is a reasonable request :) Um, you could say the same thing about the function, the module, etc. ;) From sjmachin at lexicon.net Fri Jan 21 23:34:08 2005 From: sjmachin at lexicon.net (John Machin) Date: 21 Jan 2005 20:34:08 -0800 Subject: why am I getting a segmentation fault? References: <1106330476.419418.46920@f14g2000cwb.googlegroups.com> <1106351339.457714.214940@f14g2000cwb.googlegroups.com> <1106356789.748649.259090@f14g2000cwb.googlegroups.com> Message-ID: <1106368448.725365.37030@f14g2000cwb.googlegroups.com> Jay donnell wrote: > >### Have you looked in your database to see if the >script has > actually > >updated item.goodImage? Do you have a test plan? > > Thank you for the help. Sorry for the messy code. I was under time > constraints. I had class, and I was rushing to get this working before > class. I should waited a day and read over it before I asked. Sorry > again. Apologise to _yourself_ for the messy code. If 'query' had been safely tucked away as a local variable instead of a global, that problem (typing 'query' instead of 'self.q') would have caused an exception on the first time around. A few points: Yes, don't rush. I've-forgotten-whom wrote something like "Don't program standing up". Good advice. Build things a piece at a time. Build your tests at the same time or earlier. In this case, a stand-alone method or function that checked that one file was OK, would have been a reasonable place to start. Then add the code to query the db. Then add the threading stuff, gingerly. If you build and test incrementally, then a segfault or other disaster is highly likely to have been caused by the latest addition. AND SOME MORE CRUFT: def __init__(self, url, filename, id): self.t = time.time() <<<<<<<<<======= never used again threading.Thread.__init__(self) self.db = MySQLdb.connect(host="localhost", user="xxx", passwd="xxx", db="xxx") # create a cursor self.cursor = db.cursor() <<<=== should be self.db.cursor() #### picks up the *GLOBAL* 'db' self.url = url self.filename = filename self.id = id =========================== threadList = [] [snip] threadList.append(imageChecker) ===>>>> that doesn't achieve much! ============================ N.B. You still have two problems: (1) Your script as you said now "seems to work". That doesn't sound like you have a test plan. (2) You have shuffled your code around and the segfault went away; i.e. you waved a dead chicken and the volcano stopped erupting. Most of the changes suggested by others and myself were of a style/clarity nature. The self.q/query thing would have caused a select instead an update; hardly segfault territory. I wouldn't expect that busy-wait loop to cause a segfault. You still don't know what caused the segfault. That means you don't know how to avoid it in the future. You are still living in the shadow of the volcano. Will the chicken trick work next time? Looking forward to the next episode, John From jfine at pytex.org Fri Jan 7 16:57:48 2005 From: jfine at pytex.org (Jonathan Fine) Date: Fri, 07 Jan 2005 21:57:48 +0000 Subject: What could 'f(this:that=other):' mean? References: <41DC52CA.5070104@pytex.org> <10toomjdjcs5v21@corp.supernews.com> <41DCE28B.70806@pytex.org> <10tr8eo5skqo2a3@corp.supernews.com> Message-ID: <41DF05DC.9060004@pytex.org> Jeff Shannon wrote: > Jonathan Fine wrote: > The use of *args and **kwargs allows functions to take a variable number > of arguments. The addition of ***nsargs does not add significantly. I've posted usage examples elsewhere in this thread. I think they show that ***nsargs do provide a benefit. At least in these cases. How significant is another matter. And how often do they occur. > Now, though, we've lost the ability to specify *only* the argname and > not the namespace as well -- that is, you *cannot* call f4 with keywords > but not namespaces. From the caller's vantage point, this means that > they need to know the full namespace spec of the function, which makes > it no different than simply using longer (but unique) keyword names. This is a major point. From the caller's point of view: fn_1(x_aa=1, x_bb=2, y_aa=3) fn_2(x:aa=1, x:bb=2, y:aa=3) are very similar. Replace '_' by ':'. So you are saying, I think, 'what does this buy the caller'. Well, by using ':' the namespacing is explicit. fn_3(my_path, my_file, any_file) Is this an example of implicit namespacing? (Rhetorical question.) Explicit is better than implicit, I'm told (smile). > So, we can see that allowing namespaces and ***nsargs doesn't add any > utility from the caller's perspective. How much does the callee gain > from it? > > Well, the following functions would be equivalent: > > def g1(arg1, arg2, arg3, arg4): > ns1 = {'arg1':arg1, 'arg2':arg2, 'arg3':arg3, 'arg4':arg4} > return ns1 > def g2(ns1:arg1, ns1:arg2, ns1:arg3, ns1:arg4): > return ns1 > > You might say "Wow, look at all that repetetive typing I'm saving!" But > that *only* applies if you need to stuff all of your arguments into > dictionaries. This is a key point. But there's more to it. Namespace arguments are good if you have to divide the arguments into two or more dictionaries. Based on the namespace prefix. > I suspect that this is a rather small subset of > functions. In most cases, it will be more convenient to use your > arguments as local variables than as dictionary entries. This is a matter of usage. If the usage is very, very small, then what's the point. If the usage is very, very large, then the case is very strong. > def gcd1(a, b): > while a: > a, b = b%a, a > return b > > def gcd2(ns1:a, ns1:b): > while ns1['a']: > ns1['a'], ns1['b'] = ns1['b']%ns1['a'], ns1['a'] > return ns1['b'] > > Speaking of repetetive typing.... :P > > Besides, another function equivalent to the above two would be: > > def g3(arg1, arg2, arg3, arg4): > ns1 = locals() > return ns1 > > ....which is quite a bit less repetetive typing than the 'namespace' > version. These are not good examples for the use of namespacing. And the results are horrible. So this is an argument _in favour_ of namespacing. Namely, that it _passes_ "there should be one (and preferably only one) obvious way to do things" test (quoted from your earlier message). > So, you're looking at making the function-calling protocol significantly > more complex, both for caller and callee, for the rather marginal gain > of being able to get arguments prepackaged in a dictionary or two, when > there already exist easy ways of packaging function arguments into a > dict. Given the deliberate bias against adding lots of new features to > Python, one needs a *much* better cost/benefit ratio for a feature to be > considered worthwhile. I believe that we _agree_, that it is a matter of cost/benefit ratio. My opinion is that studying usage examples is a good way of evaluating this ratio. Which is why I have posted some favourable usage examples. > I'd note also that the usage you're drawing from, in XML/XSLT, isn't > really comparable to function parameters. It's a much closer parallel > to object attributes. Python *does* have this concept, but it's spelled > differently, using a '.' instead of a ':'. In other words, the XML > fragment you give, > > > > .... would be more appropriate to render in Python as > > e = Element() > e.this.that = 'other' > > It's quite reasonable to suppose that some object of type Element may > have a set of font attributes and a set of image attributes, and that > some of these may have the same name. Python would use font objects and > image objects instead of 'namespaces' -- > > e.font.size = '14pt' > e.image.size = (640, 480) > > So while these namespaces are probably a great thing for XML, XSLT, > they're not very useful in Python. Which, given the rather different > goals and design philosophies behind the languages, shouldn't really be > much of a surprise. It may be better, in some cases, to write fp = FontParams() fp.size = 14 fp.slope = 0.1 f(this=this, font_params=fp) But not, I think, if the definition of f is something like: def f(this, font_params): fpd = font_params.__dict__ font_function(**fpd) (Assuming that font_function has got it right.) Prompted by your post, the idea of writing f(this.that='other') instead of f(this:that='other') came to my mind. At first I did not like it, but now it is growing on me a little. However, that is a syntactic issue. Which falls if the costs do not justify the benefits. And here, I think, the key question is this: How often do you have to divide the arguments to a function into two or more dictionaries? Which can be answered by studying usage. -- Jonathan http://www.pytex.org From ncoghlan at iinet.net.au Tue Jan 25 09:56:39 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 00:56:39 +1000 Subject: Memory Usage In-Reply-To: References: Message-ID: <41F65E27.5010108@iinet.net.au> Stuart McGarrity wrote: > Do you have a page file? > > The Mem column should be RAM usage and not total working set. Some of it > could be swapped to the page file. A free tool like process explorer can > give you better informaton than the task manager. As Tim pointed out, "View->Select Columns" and activating "VM Size" is enough to find out how much memory that program actually has *mapped* (rather than currently loaded into RAM). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From saint_infidel at hotmail.com Thu Jan 20 11:59:57 2005 From: saint_infidel at hotmail.com (infidel) Date: 20 Jan 2005 08:59:57 -0800 Subject: delay and force in Python In-Reply-To: <1106164457.982053.214970@f14g2000cwb.googlegroups.com> References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> <1106164457.982053.214970@f14g2000cwb.googlegroups.com> Message-ID: <1106240397.513679.107680@z14g2000cwz.googlegroups.com> Of course I meant to put a break out of the loop after the print statement. Duh on me. From steve at holdenweb.com Fri Jan 7 07:23:23 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 07 Jan 2005 07:23:23 -0500 Subject: Securing a future for anonymous functions in Python In-Reply-To: <7xis6930ah.fsf@ruckus.brouhaha.com> References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <7xis6930ah.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Anna" writes: > >>Having taken some calculus (derivatives, limits, some integrals) but >>never even heard of lambda calculus, to me, lambda means absolutely >>NOTHING. Less than nothing. > > > Lambda calculus is from mathematical logic, but more to the point > "lambda" has been the term used in Lisp for this operation since time > immemorial. Since the kinds of programmers who want to use anonymous > functions have probably been exposed to Lisp at one time or another, > "lambda" should not cause any confusion. That's probably not the most enthusiastic evangelical approach to functional programming I've ever heard :-) Perhaps what we really need is a good Lisp subsystem for Python? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From duncan.booth at invalid.invalid Fri Jan 28 07:50:10 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Jan 2005 12:50:10 GMT Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> <7x3bwlsqnj.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Duncan Booth writes: >> In other words, I'm intrigued how you managed to come up with >> something you consider to be a security issue with Python since >> Python offers no security. Perhaps, without revealing the actual >> issue in question, you could give an example of some other situation >> which, if it came up in Python you would consider to be a security >> issue? > > Until fairly recently, the pickle module was insufficiently documented > as being unsafe to use with hostile data, so people used it that way. > As a result, the Cookie module's default settings allowed remote > attackers to take over Python web apps. See SF bug 467384. SF doesn't seem to know about any such bug any more. Google finds me http://mail.python.org/pipermail/python-bugs-list/2001-October/007669.html which appears to be SF bug 467384, but it says nothing about security or the Cookie module, just that you wanted better documentation. I think its a bit borderline whether this really was a security bug in Python rather than just a problem with the way some people used Python. It was a standard library which if used in the wrong way opens a security hole on your machine, but there are plenty of ways to open security holes. The response seems to have been to document that there is a security concern here, but it is still just as possible to use python to expose your machine to attack as it was before. But thanks anyway, it does give me the sort of example I was asking for. From deetsNOSPAM at web.de Mon Jan 10 08:09:47 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 10 Jan 2005 14:09:47 +0100 Subject: Command line and GUI tools : need a single threading solution References: <41e26e79@duster.adelaide.on.net> Message-ID: <34f9lfF4af717U1@individual.net> > I'm thinking it may be possible to modify the command line tools to use qt > threads instead of native python threads. Is this the way to go? Are > there other options? Why don't you use python threads in qt - I do so and so far it didn't make any troubles for me. And I would strongly advise against using qthreads with your commandline-tools, as these then would only run on machines where pyqt is installed - which opens a small part of "dependency hell" for your users. -- Regards, Diez B. Roggisch From aut_gbarros at uolinc.com Wed Jan 5 11:18:51 2005 From: aut_gbarros at uolinc.com (Gabriel Cosentino de Barros) Date: Wed, 5 Jan 2005 14:18:51 -0200 Subject: tk the python way Message-ID: <2814F26DA6908F41927A81C410C4991A02079C32@siamun.server.bl.corp.intranet> I'm strugling a little with TK, and the docs on the web aren't helping much. I've already rewritten about twelve times a basic class that was supposed to simply draw a window. It's not even close the final draft, but i tought "well, let's start with something easy that can be done in less than an hour"... silly me. But keep reading, it's not just to vent my frustations :) The main issue here is: How to use TK eficiently. I'm already planing another post about the pack/grid/place-power-trio but for now: what's the better, most scalable and less cumbersome way to use Tk? 1. Windows a) hide Tkroot in __main__ and call the class, whom willcreate it's own windows. b) let __main__ pass the root window and make the class always require a parent. c) what's the "industry standandard" for a single or dual window small app? (no, it's not java, wrong topic) 2. Buttons What's the nicer way to pass arguments directly in a button action? I don't know if this one is me just being dumb. but `Button(..., command=doit(1) )` doesn't work for me and i haven't seen it in any doc... I came to the point of writing: btnHd = Button(..., command=self.__fileBrowseH) btnCd = Button(..., command=self.__fileBrowseC) btnFd = Button(..., command=self.__fileBrowseF) and self.__fileBrowse/[CHF]/() being just a wraper for self.__fileBrowse('/[chf]/') ...And don't miss on this same channel: my indignation with Tk's positioning systems :P Thanks! Gabriel -------------- next part -------------- An HTML attachment was scrubbed... URL: From none at none.net Tue Jan 4 06:11:23 2005 From: none at none.net (Iwan van der Kleyn) Date: Tue, 04 Jan 2005 12:11:23 +0100 Subject: Python evolution: Unease In-Reply-To: <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> Message-ID: <41DA79DB.7020507@none.net> > Also, you keep talking about "the core python team" on the basis, it > would appear, of reading one document by Guido. Have you bothered doing > a MINIMUM of homework, such as, looking at > http://www.amk.ca/diary/archives/cat_python.html Well, you being a member of that core team (meaning nog an organisational unit, but the group of people doing the really hard job, getting Python to work. An excellent job at that :-) I can repect you if not branding me a lamer at least admonishing me for not coming up with a thorough factual statement. But like I stated: "ramblings", remember. I'm not completely unknown with the workings of our species myself, though. Especially when discourse and policy is dictated by a select group of people (meaning: the one who actually create python, no criticism there) with final abritary powers for one indidual (again, no criticism), mindset *is* just as important as stated fact. Mindset will dictate future discourse and action. And I do sense (reading planet python/this newsgroup) a mindset or at least a tendency by the people who really matter in these discussion to keep on adding features to the syntax; to add "structure" to Python. My personal preference would be to leave the language alone for a while and to improve its infrastructure. Regards, Iwan From lance-news at augustmail.com Tue Jan 25 17:51:16 2005 From: lance-news at augustmail.com (Lance Hoffmeyer) Date: Tue, 25 Jan 2005 16:51:16 -0600 Subject: script to search ebay? Message-ID: Hi all, Anyone know where I can find a python script to search ebay? I have been looking around but haven't found anything. I know there must be one somewhere so I am probably just looking in the wrong places. Optimally, I would like the script to search ebay and then send an email out with the results. Lance From fu.limin.tao at gmail.com Thu Jan 27 10:13:03 2005 From: fu.limin.tao at gmail.com (Limin Fu) Date: Thu, 27 Jan 2005 16:13:03 +0100 Subject: Tao Scripting Language 0.8.5 beta released! In-Reply-To: <35scaqF4sqpqnU1@individual.net> References: <35scaqF4sqpqnU1@individual.net> Message-ID: Dear Claudio, Thank you for your kind testing, suggestions and encourages. I'm glad that you like it. For that problem in the Lexer, it can be corrected without increasing the size. I will do it soon. Best regards, Limin On Thu, 27 Jan 2005 15:32:13 -0000, Claudio Grondi wrote: > Dear Limin, > > Tao Script with its 300 KByte of code is so small, > that one just must love it forgiving all its baby > troubles. > > After changes (see below) to the code in taoModule.cpp > necessary because my compiler claimed repeated definition > of 'ref' e.g. in the section: > if(TaoReference *ref2a=inNameSpace->findDataShared(name) ){ > myData[name]=ref2a; > outNameSpace->nsData[name]=ref2a; > }else{ > TaoShareRefer*ref2b=new TaoShareRefer(); > myData[name]=ref2b; > outNameSpace->nsDataShared[name]=ref2b; > outNameSpace->nsData[name]=ref2b; > } > I was able to compile the code with > Microsoft Visual C++ .NET 2003 on W2K > (create an empty .NET project, add all source > code files, compile and be happy :-) > > Trying the examples provided on the > homesite of Tao Script which run ok as they > are, I found, that print("### \n") failes due to > the way the Lexer works beeing not able to > proper handle string literals. > One just can't probably use any of "#'" "//" "/*" > in strings because the lexer strips the > comments before it analyses the source > to handle content of the string literals. > > Hope this comment helps you to continue > the well done work on it. > I had fun with it because of its size, so > from my point of view please try to > keep the project as small as possible, so > that it remains easy to check out the entire > code. > Maybe it is even a good idea to keep > the problem with the strings as a "feature" > in order to keep the Lexer as simple as > possible? > > Best regards > > Claudio > > "Limin Fu" schrieb im Newsbeitrag > news:mailman.1426.1106825698.22381.python-list at python.org... > > Dear all, > > > > I am glad to announce in this mailing list that the lastest version > > of a new scripting language has come out. > > > > Welcome to try it out. > > > > Comments are welcome. > > > > Suggestions are appreciated. > > > > ======================= > > Here are some details: > > ======================= > > > > Design Goals: > > 1. Simple and efficient. > > 2. Integrate nice features of other languages whenever possible. > > > > Implementation language: C++ with STL. > > > > Designer: Fu Limin > > Email: fu [dot] limin [dot] tao [at] gmail.com > > > > Key features have been supported: > > > > 1. Dynamic-typing variables, supporting complex data structures > > such as array/list, hash/dictionary and matrix etc. > > > > 2. Object-oriented programming ( multi-inheritance not supported > > yet ). > > > > 3. Basic string regular expression matching. > > > > 4. Automatic garbage collection capable of collecting cyclically > > referenced objects. > > > > 5. Numeric data types: complex number and matrix, and their basic > > operations. > > > > 6. Convenient namespacing and dynamic creation of subroutines and > > classes. > > > > 7. Dynamic loading of C/C++ modules ( not complete, but enough for > > playing with it ^_^ ). > > > > 8. An embedded tiny XML parser. > > > > ToBeDone: > > More string operations, multi-inheritance of classes, improvements > > on C/C++ module loading, more on regular expression matching and > > possible optimizations etc. > > > > Documentation: > > > > http://taoscript.sourceforge.net/brief_tao.php > > > > Sample scripts: > > > > http://taoscript.sourceforge.net/sample.php > > > > Download: > > http://taoscript.sourceforge.net/downloads.php > > > > Best regards, > > > > Limin > > > > -- > > Homepage for Tao Language: > > http://taoscript.sourceforge.net > > > > Tao Language project at sourceforge.net: > > http://sourceforge.net/projects/taoscript > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Homepage for Tao Language: http://taoscript.sourceforge.net Tao Language project at sourceforge.net: http://sourceforge.net/projects/taoscript From alanmk at hotmail.com Sun Jan 23 14:11:30 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 23 Jan 2005 19:11:30 +0000 Subject: Textual markup languages (was Re: What YAML engine do you use?) In-Reply-To: <7xmzv0gw80.fsf@ruckus.brouhaha.com> References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <7xmzv0gw80.fsf@ruckus.brouhaha.com> Message-ID: [Alan Kennedy] >>So, I'm hoping that the learned folks here might be able to give me >>some pointers to a markup language that has the following >>characteristics [Paul Rubin] > I'm a bit biased but I've been using Texinfo for a long time and have > been happy with it. It's reasonably lightweight to implement, fairly > intuitive to use, and doesn't get in the way too much when you're > writing. There are several implementations, none in Python at the > moment but that would be simple enough. It does all the content > semantics you're asking (footnotes etc). It doesn't have an explicit > object model, but is straightforward to convert into a number of > formats including high-quality printed docs (TeX); the original Info > hypertext browser that predates the web; and these days HTML. Thanks Paul, I took a look at texinfo, and it looks powerful and good ....... for programmers. Looks like a very steep learning curve for non-programmers though. It seems to require just a few hundred kilobytes too much documentation ...... regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From ncoghlan at iinet.net.au Fri Jan 14 02:46:35 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 14 Jan 2005 17:46:35 +1000 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: <7xacrcdhzh.fsf@ruckus.brouhaha.com> References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: <41E778DB.2050601@iinet.net.au> Paul Rubin wrote: > Come on, that is vacuous. The claim was "expressions are not > statements". But it turns out that expressions ARE statements. The > explanation is "well, that's because they're expression statements". > And there is no obvious case of an expression that can't be used as a > statement. So it's not inherently obvious that there needs to be any > kind of statement that can't be used as an expression. It's just an > artifact. Whether the artifact is a desirable one is a matter of > discussion. No, it's entirely to do with building a readable language that uses significant whitespace to delineate scope. Simple statements are not allowed to contain other statements, but they are allowed to contain expressions. In their most degenerate form, ALL they contain is a *single* expression (e.g. a function call). That expression itself is still not a statement, though. Think of it as the difference between value and [value]. Suites are sequences of statements. Compound statements are statements which incorporate a suite as part of their syntax. Python allows statements inside suites and suites inside compound statements. It also allows expressions inside statements and expressions inside expressions. The one thing it never ever does is allow a suite or a statement inside an expression, because doing so would utterly destroy the handling of significant white space. And that's why expressions are special in Python - they demarcate the boundary of the significance of whitespace. Within an expression, whitespace is insignificant. At the level of statements and suites, whitespace is extremely significant. So, precisely how should one go about cleanly embedding something that cares about whitespace into a context which doesn't care in the slightest? Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From duncan.booth at invalid.invalid Thu Jan 27 06:57:18 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Jan 2005 11:57:18 GMT Subject: how to comment out a block of code References: <1106767695.572974.98920@z14g2000cwz.googlegroups.com> Message-ID: Xah Lee wrote: > > is there a syntax to comment out a block of code? i.e. like html's > or perhaps put a marker so that all lines from there on are ignored? > thanks. > The simplest way is to select the block of code in your editor and use the 'comment-region' command. If this doesn't work, upgrade your editor. Most editors have a command to do this although obviously the name will vary slightly: Idle calls it 'Comment Out Region', SciTe calls it 'Block Comment', emacs calls it 'comment-region'. From aurora00 at gmail.com Fri Jan 21 23:02:38 2005 From: aurora00 at gmail.com (aurora) Date: Fri, 21 Jan 2005 20:02:38 -0800 Subject: list unpack trick? Message-ID: I find that I use some list unpacking construct very often: name, value = s.split('=',1) So that 'a=1' unpack as name='a' and value='1' and 'a=b=c' unpack as name='a' and value='b=c'. The only issue is when s does not contain the character '=', let's say it is 'xyz', the result list has a len of 1 and the unpacking would fail. Is there some really handy trick to pack the result list into len of 2 so that it unpack as name='xyz' and value=''? So more generally, is there an easy way to pad a list into length of n with filler items appended at the end? From reinhold-birkenfeld-nospam at wolke7.net Tue Jan 18 12:38:09 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 18 Jan 2005 18:38:09 +0100 Subject: [perl-python] 20050118 keyed list In-Reply-To: <41ed0f4d.39606090@news.erols.com> References: <1106027360.920787.321590@z14g2000cwz.googlegroups.com> <41ed0f4d.39606090@news.erols.com> Message-ID: <354vs2F3oehr2U1@individual.net> Jay Tilton wrote: >: # the syntax of keyed list in Perl is too complex >: # to be covered in a short message. JFTR: "keyed lists" are called dictionaries in Python. > > [1]Message-ID: <7fe97cc4.0401242131.22acf485 at posting.google.com> > This guy's wish-wash is starting to be funny, after all! Reinhold From cam.ac.uk at mh391.invalid Fri Jan 14 20:37:53 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 15 Jan 2005 01:37:53 +0000 Subject: query python env In-Reply-To: References: Message-ID: Steve Holden wrote: > I suspect rather that the OP is looking for os.environ, as in: He was using the examples of PYTHONHOME and PYTHONPATH which have specific meanings. Using sys.prefix is better than os.environ["PYTHONHOME"], which is unlikely to be set. -- Michael Hoffman From irmen at -nospam-remove-this-xs4all.nl Fri Jan 14 12:55:19 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Fri, 14 Jan 2005 18:55:19 +0100 Subject: Why 'r' mode anyway? (was: Re: Pickled text file causing ValueError (dos/unix issue)) In-Reply-To: References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> Message-ID: <41e80785$0$6203$e4fe514c@news.xs4all.nl> Tim Peters wrote: > Yes: regardless of platform, always open files used for pickles in > binary mode. That is, pass "rb" to open() when reading a pickle file, > and "wb" to open() when writing a pickle file. Then your pickle files > will work unchanged on all platforms. The same is true of files > containing binary data of any kind (and despite that pickle protocol 0 > was called "text mode" for years, it's still binary data). I've been wondering why there even is the choice between binary mode and text mode. Why can't we just do away with the 'text mode' ? What does it do, anyways? At least, if it does something, I'm sure that it isn't something that can be done in Python itself if really required to do so... --Irmen From francis.girard at free.fr Tue Jan 25 01:27:21 2005 From: francis.girard at free.fr (Francis Girard) Date: Tue, 25 Jan 2005 07:27:21 +0100 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <1f7befae05012419297085cdf@mail.gmail.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> <200501241409.25598.francis.girard@free.fr> <1f7befae05012419297085cdf@mail.gmail.com> Message-ID: <200501250727.22371.francis.girard@free.fr> Ok I'll submit the patch with the prose pretty soon. Thank you Francis Girard FRANCE Le mardi 25 Janvier 2005 04:29, Tim Peters a ?crit?: > [Francis Girard] > > > For all the algorithms that run after their tail in an FP way, like the > > Hamming problem, or the Fibonacci sequence, (but unlike Sieve of > > Eratosthene -- there's a subtle difference), i.e. all those algorithms > > that typically rely upon recursion to get the beginning of the generated > > elements in order to generate the next one ... > > > > ... so for this family of algorithms, we have, somehow, to abandon > > recursion, and to explicitely maintain one or many lists of what had been > > generated. > > > > One solution for this is suggested in "test_generators.py". But I think > > that this solution is evil as it looks like recursion is used but it is > > not and it depends heavily on how the m235 function (for example) is > > invoked. > > Well, yes -- "Heh. Here's one way to get a shared list, complete with > an excruciating namespace renaming trick" was intended to warn you in > advance that it wasn't pretty . > > > Furthermore, it is _NOT_ memory efficient as pretended : it leaks ! > > Yes. But there are two solutions to the problem in that file, and the > second one is in fact extremely memory-efficient compared to the first > one. "Efficiency" here was intended in a relative sense. > > > It internally maintains a lists of generated results that grows forever > > while it is useless to maintain results that had been "consumed". Just > > for a gross estimate, on my system, percentage of memory usage for this > > program grows rapidly, reaching 21.6 % after 5 minutes. CPU usage varies > > between 31%-36%. Ugly and inefficient. > > Try the first solution in the file for a better understanding of what > "inefficient" means . > > > The solution of Jeff Epler is far more elegant. The "itertools.tee" > > function does just what we want. It internally maintain a list of what > > had been generated and deletes the "consumed" elements as the algo > > unrolls. To follow with my gross estimate, memory usage grows from 1.2% > > to 1.9% after 5 minutes (probably only affected by the growing size of > > Huge Integer). CPU usage varies between 27%-29%. > > Beautiful and effecient. > > Yes, it is better. tee() didn't exist when generators (and > test_generators.py) were written, so of course nothing in the test > file uses them. > > > You might think that we shouldn't be that fussy about memory usage on > > generating 100 digits numbers but we're talking about a whole family of > > useful FP algorithms ; and the best way to implement them should be > > established. > > Possibly -- there really aren't many Pythonistas who care about this. > > > For this family of algorithms, itertools.tee is the way to go. > > > > I think that the semi-tutorial in "test_generators.py" should be updated > > to use "tee". Or, at least, a severe warning comment should be written. > > Please submit a patch. The purpose of that file is to test > generators, so you should add a third way of doing it, not replace the > two ways already there. It should also contain prose explaining why > the third way is better (just as there's prose now explaining why the > second way is better than the first). From bulba at bulba.com Sat Jan 15 11:40:17 2005 From: bulba at bulba.com (Bulba!) Date: Sat, 15 Jan 2005 17:40:17 +0100 Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <1105734450.961150.32980@z14g2000cwz.googlegroups.com> <7xfz13zrb2.fsf@ruckus.brouhaha.com> Message-ID: On 14 Jan 2005 12:30:57 -0800, Paul Rubin wrote: >Mmap lets you treat a disk file as an array, so you can randomly >access the bytes in the file without having to do seek operations Cool! >Just say a[234]='x' and you've changed byte 234 of the file to the >letter x. However.. however.. suppose this element located more or less in the middle of an array occupies more space after changing it, say 2 bytes instead of 1. Will flush() need to rewrite the half of mmaped file just to add that one byte? flush() definitely makes updating less of an issue, I'm just curious about the cost of writing small changes scattered all over the place back to the large file. -- I have come to kick ass, chew bubble gum and do the following: from __future__ import py3k And it doesn't work. From mefjr75 at hotmail.com Sun Jan 30 20:16:07 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 30 Jan 2005 17:16:07 -0800 Subject: Problem with loading textfiles into dictionaries. In-Reply-To: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> References: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> Message-ID: <1107134167.206620.286290@z14g2000cwz.googlegroups.com> mercuryp... at gmail.com wrote: > Hello, > I want to do the following: > > def do_load(self, arg): > sitefile = file('sitelist', 'r+', 1) > while True: > siteline = sitefile.readline() > site_rawlist = siteline.split() > sitelist[site_rawlist[0]] = site_rawlist[1:] > if len(siteline) == 0: > break > > I want to load a textfile into a dictionaries and use the first word on > a line as the key for the list, then take the remaining words of the > line and make them values of the key. This doesn't work: > > File "ftp.py", line 57, in do_load > sitelist[site_rawlist[0]] = site_rawlist[1:] > IndexError: list index out of range Hello again Munin, First i'll start with a spanking! Post your code like this:(or pick your favorite starter) Py> def do_load(self, arg): ... sitefile = file('sitelist', 'r+', 1) ... while True: ... siteline = sitefile.readline() ... site_rawlist = siteline.split() ... sitelist[site_rawlist[0]] = site_rawlist[1:] ... if len(siteline) == 0: ... break See how much nicer that is even if the newsfeed gets mangled it comes out ok(mostly). If I guess right it looks like you are trying disect a line that was empty or only had one element. If you check for line length first you might do better. Py> def do_load(self, arg): ... sitefile = file('sitelist', 'r+', 1) ... while True: ... if len(siteline) == 0: ... break ... siteline = sitefile.readline() ... site_rawlist = siteline.split() ... sitelist[site_rawlist[0]] = site_rawlist[1:] Ok next thing is this smells like you really are trying to reinvent a sort of pickle. If you don't know search for 'python pickle module'. examples abound but here it is anyway: Py> import pickle Py> # Pickle a dictionary Py> f = open('/tmp/mydata', 'wb') Py> f.write(pickle.dumps(yourdict) Py> f.close() Py> # and it is easy to get back as well Py> f = open('tmp/mydata', rb') Py> pdata = f.read() Py> f.close() Py> yourdict = pickle.load(pdata) hth, M.E.Farmer From wuwei23 at gmail.com Sun Jan 23 20:57:04 2005 From: wuwei23 at gmail.com (alex23) Date: 23 Jan 2005 17:57:04 -0800 Subject: how to write a tutorial In-Reply-To: <1106472508.591411.40140@c13g2000cwb.googlegroups.com> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: <1106531824.833549.28720@c13g2000cwb.googlegroups.com> > the first paragraph of 9.1 "A Word About Terminology" is > epitome of masturbation. I'm tempted to concede this point to you given the sheer overwhelming testament to onanism that is your website but this is just nonsense. Defining terms is *always* necessary, it ensures that participants in whatever dialogue are at least partially using the terms with the same intent > For 99% of readers, it is incomprehensible and irrelevant. You're not 99% of the readers, so I find that remark difficult to swallow. Having read your comments on women, the whole idea that you have a superior insight into would-be python coders is just obscenely ludicrous. - alex23 From just at xs4all.nl Mon Jan 3 04:08:46 2005 From: just at xs4all.nl (Just) Date: Mon, 03 Jan 2005 10:08:46 +0100 Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: In article , JanC wrote: > Something like this: > > py> import cStringIO > py> import sys > py> > py> def foo(): > ... print "test" > ... > py> f = cStringIO.StringIO() > py> sys.stdout = f > py> foo() > py> s = f.getvalue() > py> sys.stdout = sys.__stdout__ You should always save stdout instead of using __stdout__. It may not be the same! I don't think anyone should *ever* use __stdout__ except when debugging. See also: http://mail.python.org/pipermail/python-dev/2000-October/010144.html > py> f.close() > py> print s.capitalize() > Test Just From fredrik at pythonware.com Tue Jan 25 02:51:21 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 Jan 2005 08:51:21 +0100 Subject: What's so funny? WAS Re: rotor replacement References: <200501241906.39865.hancock@anansispaceworks.com> Message-ID: Terry Hancock wrote: > And, well, I'm sorry Mr. Lundh, but your PIL module actually is something > of a pain to install still. The OP is right about that. Usually worth it, but I don't > like the fact that that pain is being passed on to the end-user of my software. > > The fact that you got all snide and refused to work with me when I asked > for a copy of the autoconf sources to try to fix the problem didn't make me > too happy, either. ah, you're the guy who flamed me and called me names because PIL didn't fit some hypothetical GNU-inspired definition of "open source software." it's always sad when people have to attack those who don't share their religion, but it's not that much I can do about that. > So, naturally, I just dropped it. which means that you have no idea how easy or hard it is to install PIL today (hint: things have changed) From ncoghlan at iinet.net.au Tue Jan 11 08:04:50 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 11 Jan 2005 23:04:50 +1000 Subject: else condition in list comprehension In-Reply-To: <1105305000.052714.188980@c13g2000cwb.googlegroups.com> References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> <1105305000.052714.188980@c13g2000cwb.googlegroups.com> Message-ID: <41E3CEF2.4070807@iinet.net.au> Dan Bishop wrote: > Luis M. Gonzalez wrote: > >>Hi there, >> >>I'd like to know if there is a way to add and else condition into a >>list comprehension. I'm sure that I read somewhere an easy way to do >>it, but I forgot it and now I can't find it... >> >>for example: >>z=[i+2 for i in range(10) if i%2==0] >>what if I want i [sic] to be "i-2" if i%2 is not equal to 0? > > > z = [i + (2, -2)[i % 2] for i in range(10)] For the specific case of +/- a number, (-1) ** x works, too: z = [i + 2 * ((-1) ** i) for i in range(10)] Not that I'm claiming it's particularly readable or anything. . . just that it works :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From danperl at rogers.com Sun Jan 30 19:24:06 2005 From: danperl at rogers.com (Dan Perl) Date: Sun, 30 Jan 2005 19:24:06 -0500 Subject: Regarding exception handling References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> Message-ID: "Aggelos I. Orfanakos" wrote in message news:1107127179.863445.55310 at c13g2000cwb.googlegroups.com... > Thanks. This should now be OK: > > #try: > # try: > # s = ... # socket opens > # > # # various code ... > # except socket.error, x: > # # exception handling > #finally: > # s.close() # socket closes > Why the nested try's? If I understand your intention correctly this should do the same thing: try: s = ... # socket opens # various code ... except socket.error, x: # exception handling s.close() # socket closes You would need the try-finally statement only if you expect it to handle other exceptions than socket.error or if the socket.error is re-raised in the "except" clause. Otherwise, the try-finally statement is redundant because no socket.error are getting out of the try-except statement. Dan From guettli at thomas-guettler.de Wed Jan 26 11:15:48 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 26 Jan 2005 17:15:48 +0100 Subject: Help With Python References: Message-ID: Am Wed, 26 Jan 2005 15:55:28 +0000 schrieb Judi Keplar: > > I am currently taking a course to learn Python and was looking for > some help. I need to write a Python statement to print a comma- > separated repetition of the word, "Spam", written 511 times ("Spam, > Spam, Spam"). > > Can anybody help me get started? I am completely new to programming! Hi, # This way, there is a comma after the last: import sys for i in range(511): sys.stdout.write("Spam, ") # No comma at the end: mylist=[] for i in range(511): mylist.append("Spam") print ", ".join(mylist) Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From tomi.hasa at gmail.com Mon Jan 10 08:46:32 2005 From: tomi.hasa at gmail.com (=?iso-8859-1?B?VG9taSBI5HPk?=) Date: 10 Jan 2005 05:46:32 -0800 Subject: OT: google groups bug, or worse? In-Reply-To: <1105127965.616198.302710@z14g2000cwz.googlegroups.com> References: <1105127965.616198.302710@z14g2000cwz.googlegroups.com> Message-ID: <1105364792.404039.65190@c13g2000cwb.googlegroups.com> aaronwmail-usenet at yahoo.com wrote: > I'm concerned that google groups is not correctly reflecting > the python lists. > [...] > Is it a google bug? Yes, Google Groups Beta is missing messages: http://groups-beta.google.com/group/google-labs-groups2/browse_thread/thread/c4108ad41c189d34?tvc=2 http://tinyurl.com/6vybw http://groups-beta.google.com/group/google-labs-groups2/msg/dc745c7784c81890 http://tinyurl.com/4keqh http://groups-beta.google.com/group/google-labs-groups2/msg/b54c12517c75eb24 From tjreedy at udel.edu Thu Jan 20 13:40:12 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 20 Jan 2005 13:40:12 -0500 Subject: RuntimeError: dictionary changed size during iteration References: Message-ID: RE: RuntimeError: dictionary changed size during iteration "Batista, Facundo" wrote [Robert Brewer] #- But not unexpected, since vars() returns a dictionary, and #- binding 'e' #- changes that dictionary while you are iterating over it. >For me, the point is: vars() returns the local variables > as a list or is a generator? As the OP said, it returns a *dictionary*. In particular: >>> help(vars) Help on built-in function vars: vars(...) vars([object]) -> dictionary Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__. >In the docs don't say nothing about this. You must be having a bad day ;-). From Lib Ref 2.1 Built-in Functions: vars( [object]) Without arguments, return a dictionary corresponding to the current local symbol table. With a module, class or class instance object as argument (or anything else that has a __dict__ attribute), returns a dictionary corresponding to the object's symbol table. The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined Terry J. Reedy From drewc at rift.com Fri Jan 21 08:23:08 2005 From: drewc at rift.com (drewc) Date: Fri, 21 Jan 2005 13:23:08 GMT Subject: how to write a tutorial In-Reply-To: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> Message-ID: <0n7Id.135415$Xk.80179@pd7tw3no> You should not be giving such advice! (and the crosspost ... WTF?). I've been trying to follow along with your perl/python yahoo group, but your posts are terrible. Perhaps you should provide the output of the code you post. Then i'd actually know what i'm trying to achieve. As it is i have to cut/paste your code into an interpreter just to figure out what it does. What does this have to do with Lisp? (i'm in c.l.l). drewc Xah Lee wrote: > i've started to read python tutorial recently. > http://python.org/doc/2.3.4/tut/tut.html > > Here are some quick critique: > > quick example: > If the input string is too long, they don't truncate it, but return it > unchanged; this will mess up your column lay-out but that's usually > better than the alternative, which would be lying about a value. (If > you really want truncation you can always add a slice operation, as in > "x.ljust( n)[:n]". > > better: > If the input string is too long, they don't truncate it, but return it > unchanged; > ----------------- > delete: Reverse quotes (``) are equivalent to repr(), but their use is > discouraged. > ----------------- > similarly, many places mentioning uncritical info such as warning or > reference to other languages should be deleted. > > the tutorial should be simple, concise, to the point, stand along. > Perhaps 1/5th length of the tutorial should be deleted for better. > Follow the above principles. > > at places often a whole paragraph on some so called computer science > jargons should be deleted. They are there more to showcase inane > technicality than do help the reader. (related, many passages with > jargons should be rewritten sans inane jargon. e.g. mutable object.) > > one easy way to understand these principles is to compare perl's > documentation or unix man pages to Python's. The formers are often > irrelevant, rambling on, not stand-along (it is written such that it > unnecessarily requires the reader to be knowledgable of lots of other > things). Python docs are much better, but like many computer language > manuals, also suffers from verbiage of tech jargons. (these jargons or > passages about them are usually there to please the authors > themselves). > > A exemplary writing in this direction is the Mathematica manual by > Stephen Wolfram. Any intelligent layman sans computer science degree > can read it straightforwardly, and learn unhindered a language that is > tantamount to features of lisp languages. Such documentation is not > difficult to write at all. (contrary to the lot of "computer > scientists" or IT pundits morons.) All it take is some simple > principles outlined above. > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html > From frans.englich at telia.com Mon Jan 17 13:45:46 2005 From: frans.englich at telia.com (Frans Englich) Date: Mon, 17 Jan 2005 18:45:46 +0000 Subject: Assigning to self Message-ID: <200501171845.46766.frans.englich@telia.com> Hello, I am having trouble with throwing class instances around. Perhaps I'm approaching my goals with the wrong solution, but here's nevertheless a stripped down example which demonstrates my scenario: #------------------------------------------------------------------------------------------ class foo: tests = {} def __init__( self, id ): try: me = self.__class__.tests[ id ] except KeyError: print "Did not exist, initializing myself.." self.attr = "exists" self.__class__.tests[ id ] = self else: print "Already exists! Re-using existing instance" self = me print "Me", self.attr + "!" # line 18 def yo(self): return self.attr # line 21 def main(): a = foo( "test" ) print "ATTR:", a.yo() b = foo( "test" ) print "ATTR:", b.yo() if __name__ == "__main__": main() #------------------------------------------------------------------------------------------ This is the output: Did not exist, initializing myself.. Me exists! ATTR: exists Already exists! Re-using existing instance Me exists! ATTR: Traceback (most recent call last): File "cpClass.py", line 32, in ? main() File "cpClass.py", line 29, in main print "ATTR:", b.yo() File "cpClass.py", line 21, in yo return self.attr # line 21 AttributeError: foo instance has no attribute 'attr' #------------------------------------------------------------------------------------------ What the code attempts to do is implementing a, to the API user, transparent memory-saver by ensuring that no more than one instance of the class foo exists for a particular id. E.g, the user can simply "create" an instance and if one not already exists, it is created. First of all; am I approaching the goal with the right solution? The way I do fails, obviously. The line 'self = me'(scary..) doesn't really work for the attribute attr; the attribute exists on line 21, but it fails when yo() tries to access it. What have failed? Is it a namespace scope issue? Do 'self = me' do what I think it should? Cheers, Frans From allen at cis.ohio-state.edu Tue Jan 4 17:37:20 2005 From: allen at cis.ohio-state.edu (Nick Allen) Date: Tue, 04 Jan 2005 17:37:20 -0500 Subject: Restore a unified diff Message-ID: After using ndiff from difflib, the function restore would return the sequence that generated the delta. Unfortunately, restore does not do the same for unified_diff. I do not see any similar function that is intended for unified_diff. Does anyone know how to "restore" from a unified diff generated delta? Thanks for all your help in advance. Best Regards, Nick Nick Allen From francis.girard at free.fr Wed Jan 26 18:19:39 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 27 Jan 2005 00:19:39 +0100 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <6PKdnVpD-4f3CGvcRVn-gQ@comcast.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> <6PKdnVpD-4f3CGvcRVn-gQ@comcast.com> Message-ID: <200501270019.39611.francis.girard@free.fr> Le mardi 25 Janvier 2005 19:52, Steven Bethard a ?crit?: Thank you Nick and Steven for the idea of a more generic imerge. To work with the Hamming problem, the imerge function _must_not_ allow duplicates and we can assume all of the specified iteratables are of the same size, i.e. infinite ! Therefore, Nick's solution fulfills the need. But it is admittedly confusing to call the function "imerge" when it doesn't merge everything (including duplicates). Anyway both solution sheds new light and brings us a bit farther. That's the beauty of many brains from all over the world collabarating. Really, it makes me emotive thinking about it. For the imerge function, what we really need to make the formulation clear is a way to look at the next element of an iteratable without consuming it. Or else, a way to put back "consumed" elements in the front an iteration flow, much like the list constructors in FP languages like Haskell. It is simple to encapsulate an iterator inside another iterator class that would do just that. Here's one. The additional "fst" method returns the next element to consume without consuming it and the "isBottom" checks if there is something left to consume from the iteration flow, without actually consuming anything. I named the class "IteratorDeiterator" for lack of imagination : -- BEGIN SNAP class IteratorDeiterator: def __init__(self, iterator): self._iterator = iterator.__iter__() self._firstVal = None ## Avoid consuming if not requested from outside ## Works only if iterator itself can't return None def __iter__(self): return self def next(self): valReturn = self._firstVal if valReturn is None: valReturn = self._iterator.next() self._firstVal = None return valReturn def fst(self): if self._firstVal is None: self._firstVal = self._iterator.next() return self._firstVal def isBottom(self): if self._firstVal is None: try: self._firstVal = self._iterator.next() except StopIteration: return True return False -- END SNAP Now the imerge_infinite which merges infinite lists, while allowing duplicates, is quite straightforward : -- BEGIN SNAP def imerge_infinite(*iterators): vItTopable = [IteratorDeiterator(it) for it in iterators] while vItTopable: yield reduce(lambda itSmallest, it: itSmallest.fst() > it.fst() and it or itSmallest, vItTopable).next() -- END SNAP To merge finite lists of possibly different lengths is a bit more work as you have to eliminate iterators that reached the bottom before the others. This is quite easily done by simply filtering them out. The imerge_finite function below merges "lists" of possibly different sizes. -- BEGIN SNAP def imerge_finite(*iterators): vItDeit = [IteratorDeiterator(it) for it in iterators] vItDeit = filter(lambda it: not it.isBottom(), vItDeit) while vItDeit: yield reduce(lambda itSmallest, it: itSmallest.fst() > it.fst() and it or itSmallest, vItDeit).next() vItDeit = filter(lambda it: not it.isBottom(), vItDeit) -- END SNAP Now, we want versions of these two merge functions that do not allow duplicates. Building upon what we've already done in a semi FP way, we just filter out the duplicates from the iteration streams returned by the above functions. The job is the same for the infinite and finite versions, hence the imerge_nodup generic function. -- BEGIN SNAP def imerge_nodup(fImerge, *iterators): it = fImerge(*iterators) el = it.next() yield el while True: el = dropwhile(lambda _next: _next == el, it).next() yield el imerge_inf_nodup = \ lambda *iterators: imerge_nodup(imerge_infinite, *iterators) imerge_finite_nodup = \ lambda *iterators: imerge_nodup(imerge_finite, *iterators) -- END SNAP I used the lambda notation for imerge_inf_nodup and imerge_finite_nodup to avoid another useless for-yield loop. Here the notation really just express function equivalence with a bounded argument (it would be great to have a notation for this in Python, i.e. binding a function argument to yield a new function). The merge function to use with hamming() is imerge_inf_nodup. Regards, Francis Girard FRANCE > Nick Craig-Wood wrote: > > Steven Bethard wrote: > >> Nick Craig-Wood wrote: > >>>Thinking about this some more leads me to believe a general purpose > >>>imerge taking any number of arguments will look neater, eg > >>> > >>>def imerge(*generators): > >>> values = [ g.next() for g in generators ] > >>> while True: > >>> x = min(values) > >>> yield x > >>> for i in range(len(values)): > >>> if values[i] == x: > >>> values[i] = generators[i].next() > >> > >> This kinda looks like it dies after the first generator is exhausted, > >> but I'm not certain. > > > > Yes it will stop iterating then (rather like zip() on lists of unequal > > size). Not sure what the specification should be! It works for the > > hamming problem though. > > Actually, it stops iterating on lists of equal size too: > > py> def imerge(*iterators): > ... iterators = [iter(i) for i in iterators] > ... values = [i.next() for i in iterators] > ... while True: > ... x = min(values) > ... yield x > ... for i, val in enumerate(values): > ... if val == x: > ... values[i] = iterators[i].next() > ... > py> list(imerge([1, 4, 7], [2, 5, 8], [3, 6, 9])) > [1, 2, 3, 4, 5, 6, 7] > > Note that 8 and 9 are not in the list. > > Steve From gsakkis at rutgers.edu Mon Jan 24 15:50:52 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Mon, 24 Jan 2005 15:50:52 -0500 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> Message-ID: <35l5d9F4licj2U1@individual.net> "Fredrik Lundh" wrote in message news:mailman.1214.1106591959.22381.python-list at python.org... > Steven Bethard wrote: > > >>>>>a = 1, 2, 3 > >>>>>b = a[:] > >>>>>a is b > >> True > > > > My impression was that full tuple copies didn't actually copy, but that slicing a subset of a > > tuple might. Not exactly sure how to test this, but: > > > > py> a = 1, 2, 3 > > py> a[:2] is a[:2] > > False > > yup. and to figure out why things are done this way, consider this case: > > >>> a = give_me_a_huge_tuple() > >>> len(a) > (a rather large number) > >>> b = a[:2] > >>> del a > > (IIRC, I proposed to add "substrings" when I implemented the Unicode string > type, but that idea was rejected, for the very same "and how do you get rid of > the original object" reason) > > Fair enough. So perhaps the question is whether such cases are more regular than something like: a = give_me_a_huge_tuple() slices = [a[i:j] for i in xrange(len(a)) for j in xrange(i+1, len(a)+1)] George From tmohr at s.netic.de Wed Jan 12 16:40:13 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Wed, 12 Jan 2005 22:40:13 +0100 Subject: reference or pointer to some object? References: Message-ID: Hi, thank you all for your explanations. I still wonder why a concept like "references" was not implemented in Python. I think it is (even if small) an overhead to wrap an object in a list or a dictionary. Isn't it possible to extend Python in a way to use real references? Or isn't that regarded as necessary? Thanks for any hints, Torsten. From ionel.mc at gmail.com Thu Jan 20 22:14:31 2005 From: ionel.mc at gmail.com (ionel) Date: Fri, 21 Jan 2005 05:14:31 +0200 Subject: What's the best python web-developer's editor In-Reply-To: <41EFFCD9.7060302@wild-flower.co.uk> References: <41EFFCD9.7060302@wild-flower.co.uk> Message-ID: how about editplus ? imho it's excelent On Thu, 20 Jan 2005 18:47:53 +0000, andy wrote: > Anybody like to comment on which editor they use for python web app > development - for both discrete and mixed python and html code, and why? > > I'm comfortable with IDLE (used it for years) but of course it lacks ftp > or webDAV abilities, obviously because it's not intended for that type > of use. > > I've had a look at Screem - and that seems to do python syntax > highlighting, but it dosn't seem to be python syntax aware (unless > there's a hidden option somewhere). Although I can live without auto > indent, I'd rather not... > > I'm sure emacs, xemacs, vi, elvis and so on can do the same, but I have > no experience with them for heavy python or html coding, nor the time > to trip off down a blind-alley to find out! I know Enough Vi To Get > By(tm) but it's by no means my favourite editor. Emacs is a complete > mystery to me. > > I guess I *could* use IDLE and Screem together, but that's a clunky > solution! > > all opinions greatfully received, > -andyj > -- > http://mail.python.org/mailman/listinfo/python-list > -- ionel. From ark at acm.org Sat Jan 22 12:33:49 2005 From: ark at acm.org (Andrew Koenig) Date: Sat, 22 Jan 2005 17:33:49 GMT Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> <7xu0p9lk4h.fsf@ruckus.brouhaha.com> <7x8y6l8k6l.fsf@ruckus.brouhaha.com> Message-ID: <18wId.68007$w62.25250@bgtnsc05-news.ops.worldnet.att.net> "Paul Rubin" wrote in message news:7x8y6l8k6l.fsf at ruckus.brouhaha.com... > It's not obvious to me how the compiler can tell. Consider: > > x = 3 > if frob(): > frobbed = True > squares = [x*x for x in range(9)] > if blob(): > z = x > > Should the compiler issue a warning saying the program should be taken > out and shot? With lexical comprehensions, the program is perfectly > valid and sets z to 3 if blob() is true. The whole point of lexical > comprhensions is to make Python safe for such programs. > > Without lexical comprehensions, the program still doesn't depend on > the listcomp leakage if frob() and blob() aren't simultaneously true > (envision "assert not frobbed" before the "z = x"). So "should be > taken out and shot" is maybe a little bit extreme. Actually, I don't think so. If you intend for it to be impossible for "z = x" to refer to the x in the list comprehension, you shouldn't mind putting in "from __future__ import lexical_comprehensions." If you don't intend for it to be impossible, then the program *should* be taken out and shot. From spam-trap-095 at at-andros.demon.co.uk Sun Jan 23 19:45:34 2005 From: spam-trap-095 at at-andros.demon.co.uk (Andrew McLean) Date: Mon, 24 Jan 2005 00:45:34 +0000 Subject: Fuzzy matching of postal addresses [1/1] References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> <1106517571.768306.23430@f14g2000cwb.googlegroups.com> Message-ID: <5jDnWqluUE9BFwTg@at-andros.demon.co.uk> In article <1106517571.768306.23430 at f14g2000cwb.googlegroups.com>, John Machin writes >Andrew McLean wrote: >> In case anyone is interested, here is the latest. > >> def insCost(tokenList, indx, pos): >> """The cost of inserting a specific token at a specific >normalised position along the sequence.""" >> if containsNumber(tokenList[indx]): >> return INSERT_TOKEN_WITH_NUMBER + POSITION_WEIGHT * (1 - pos) >> elif indx > 0 and containsNumber(tokenList[indx-1]): >> return INSERT_TOKEN_AFTER_NUMBER + POSITION_WEIGHT * (1 - >pos) >> elif tokenList[indx][0] in minorTokenList: >> return INSERT_MINOR_TOKEN >> else: >> return INSERT_TOKEN + POSITION_WEIGHT * (1 - pos) >> >> def delCost(tokenList, indx, pos): >> """The cost of deleting a specific token at a specific normalised >position along the sequence. >> This is exactly the same cost as inserting a token.""" >> return insCost(tokenList, indx, pos) > >Functions are first-class citizens of Pythonia -- so just do this: > >delCost = insCost > Actually, the code used to look like that. I think I changed it so that it would look clearer. But perhaps that was a bad idea. >Re speed generally: (1) How many addresses in each list and how long is >it taking? On what sort of configuration? (2) Have you considered using >pysco -- if not running on x86 architecture, consider exporting your >files to a grunty PC and doing the match there. (3) Have you considered >some relatively fast filter to pre-qualify pairs of addresses before >you pass the pair to your relatively slow routine? There are approx. 50,000 addresses in each list. At the moment the processing assumes all the postcodes are correct, and only compares addresses with matching postcodes. This makes it a lot faster. But may miss some cases of mismatched postcodes. Also it does two passes. One looking for exact matches of token sequences. This deals with about half the cases. Only then do I employ the, more expensive, edit distance technique. Overall, the program runs in less than half an hour. Specifically it takes about 60s per thousand addresses, which requires an average of about 8 calls to editDistance per address. Psyco.full() reduced the 60s to 45s. I'll only try optimisation if I need to use it much more. >Soundex?? To put it bluntly, the _only_ problem to which soundex is the >preferred solution is genealogy searching in the US census records, and >even then one needs to know what varieties of the algorithm were in use >at what times. I thought you said your addresses came from >authoritative sources. You have phonetic errors? Can you give some >examples of pairs of tokens that illustrate the problem you are trying >to overcome with soundex? I'm sure that in retrospect Soundex might not be a good choice. The misspellings tend to be minor, e.g. Kitwhistle and KITTWHISTLE Tythe and TITHE I was tempted by an edit distance technique on the tokens, but would prefer a hash based method for efficiency reasons. >Back to speed again: When you look carefully at the dynamic programming >algorithm for edit distance, you will note that it is _not_ necessary >to instantiate the whole NxM matrix -- it only ever refers to the >current row and the previous row. What does space saving have to do >with speed, you ask? Well, Python is not FORTRAN; it takes considerable >effort to evaluate d[i][j]. A relatively simple trick is to keep 2 rows >and swap (the pointers to) them each time around the outer loop. At the >expense of a little more complexity, one can reduce this to one row and >3 variables (north, northwest, and west) corresponding to d[i-1][j], >d[i-1][j-1], and d[i][j-1] -- but I'd suggest the simple way first. >Hope some of this helps, Thanks for that. The first edit distance algorithm I looked at did it that way. But I based my code on a version of the algorithm I could actually follow ;-). Getting the concatenation bit right was non-trivial and it was useful to store all of "d" for debugging purposes. As to Python not being Fortran. You've found me out. The three languages I am most comfortable with are Fortran, Matlab and Python. It did occur to me that numarray might be a more efficient way of dealing with a 4-dimensional array, but the arrays aren't very big, so the overhead in setting them up might be significant. The simplest optimisation would be to replace the two indices used to deal with concatenation by four explicit variables. And then, as you said, I could just store the three last rows, and avoid any multiple indexing. As with all these potential optimisations, you don't know until you try them. -- Andrew McLean From whereU at now.com Tue Jan 11 00:54:33 2005 From: whereU at now.com (Eric Pederson) Date: Mon, 10 Jan 2005 21:54:33 -0800 Subject: OT: MoinMoin and Mediawiki? In-Reply-To: <7x6524d6pv.fsf@ruckus.brouhaha.com> References: <7x6524d6pv.fsf@ruckus.brouhaha.com> Message-ID: <20050110215433.792683707.whereU@now.com> Paul Rubin wrote: > What I'm getting at is I might like to install MoinMoin now and > migrate to Mediawiki sometime later. Anyone have any thoughts about > whether that's a crazy plan? Disclaimer, I am neither using Moinmoin nor Mediawiki, and don't really have your answer. >From what I read, Mediawiki stores each page as "wikitext" in a MySQL database; wikitext "is a mixture of content, markup, and metadata." It seems essentially what you'd need for migration is a mapping function and I do not know how complex the mapping between the systems would be. I could imagine migrating from Moinmoin to Mediawiki via a script looping through the Moinmoin files in a directory, modifying a copy of each, and storing them in MySQL. I suspect it's less painful to just start with the wiki you want to end up with, but if you're going to migrate between the two, won't Python come in handy! ;-) Eric Pederson http://www.songzilla.blogspot.com ::::::::::::::::::::::::::::::::::: domainNot="@something.com" domainIs=domainNot.replace("s","z") ePrefix="".join([chr(ord(x)+1) for x in "do"]) mailMeAt=ePrefix+domainIs ::::::::::::::::::::::::::::::::::: From xah at xahlee.org Mon Jan 31 14:02:17 2005 From: xah at xahlee.org (Xah Lee) Date: 31 Jan 2005 11:02:17 -0800 Subject: Q: quoting string without escapes Message-ID: <1107198137.141990.246880@c13g2000cwb.googlegroups.com> in Python, is there a way to quote a string as to avoid escaping ' or " inside the string? i.e. like Perl's q or qq. thanks. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From g.brandl-2005-01 at gmx.net Sun Jan 23 15:11:32 2005 From: g.brandl-2005-01 at gmx.net (Georg Brandl) Date: Sun, 23 Jan 2005 21:11:32 +0100 Subject: Help on project, anyone? Message-ID: <35ienhF4lu88lU1@individual.net> Hello, to train my Python skills I am looking for some project I can contribute to. I learned Python about one year ago, and had already some programming background behind (I contributed to SharpDevelop for instance), so I'm not the complete newbie. About myself: I'm a 20 year old German with strong interests in programming and, of course, especially in Python (I love it...). Does anyone run, or participate in, a project looking for fellow programmers? I don't have a special area of interest, well, perhaps web programming... Thanks, Georg From ed at leafe.com Thu Jan 13 08:05:54 2005 From: ed at leafe.com (Ed Leafe) Date: Thu, 13 Jan 2005 08:05:54 -0500 Subject: wxPython and CheckListBox In-Reply-To: <1105613647.610479.13280@z14g2000cwz.googlegroups.com> References: <1105613647.610479.13280@z14g2000cwz.googlegroups.com> Message-ID: On Jan 13, 2005, at 5:54 AM, ncookson at networkusa.net wrote: > I am trying to add a caption or title to the box drawn around a > checklistbox and having no luck. Is there a way to do this? > I am using python 2.3.4 and wxPython 2.5 on a windows platform. I don't think you can do it directly. What you might want to try is to create a StaticBoxSizer with the label you want, and add the checkbox to that sizer. Then add the StaticBoxSizer to the panel's layout instead of the checkbox. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From http Wed Jan 19 04:42:00 2005 From: http (Paul Rubin) Date: 19 Jan 2005 01:42:00 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> Message-ID: <7x1xchlpqv.fsf@ruckus.brouhaha.com> Robin Becker writes: > What exactly are/were the political reasons for rotor removal? Some countries have laws about cryptography software (against some combination of export, import, or use). The Python maintainers didn't want to deal with imagined legal hassles that might develop from including good crypto functions in the distribution. Then it became obvious that the same imagined hassles could also befall the rotor module, so that was removed. > I might add that the source for rotormodule is still easily obtainable > and can be compiled trivially as an extension for Python-2.4. Does the > Python community take a position on the sources of removed modules? Those are still free to distribute, but I'd advise against doing so with the rotor module unless you absolutely need it for some interoperability purpose. Otherwise, it's insecure and should not be used. The routine I posted was intended as a straightforward replacement for the rotor module that doesn't depend on C compilers and is reasonably secure. If you don't mind using C extensions, there's various AES modules available, plus fancier packages like mxCrypto. From philippe at philippecmartin.com Mon Jan 24 17:30:38 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 24 Jan 2005 22:30:38 GMT Subject: Why I use private variables (WAS: RE:"private" variables a.k.a. name mangling?) References: Message-ID: I used double underscore because I thought it was the correct way to name private variables/methods - I will have to change those to single underscore since that it the current methodology. A private variable to me: 1) is internal to the processing of a class and needs not be accessed by external or derivated objects. (I won't get into the potential need of "protected" variables/methods - Python creators have not made those distinctions for reasons that they believe are good and I'm not the one to discuss them) 2) Must not be documented to library users as they're using it would go againts 'law' 1). 3) I wish I had one, but there is only one Isaac Asimov after all :-) Regards, Philippe On Mon, 24 Jan 2005 11:45:34 -0500, Jeremy Bowers wrote: > On Mon, 24 Jan 2005 15:35:11 -0600, Philippe C. Martin wrote: > >> The real reason behind my using private variables is so they do not appear >> in the epydoc generated documentation and confuse my users. > > You mean single or double underscores? I just checked and at least epydoc > 2.1 doesn't include single-underscore values, but those aren't "private" > in sense we're talking in this thread (some form of compiler enforcement). From invalidemail at aerojockey.com Fri Jan 14 06:22:23 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 14 Jan 2005 03:22:23 -0800 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: <1105701743.706951.257970@c13g2000cwb.googlegroups.com> Skip Montanaro wrote: > Fredrik> no, expressions CAN BE USED as statements. that doesn't mean > Fredrik> that they ARE statements, unless you're applying belgian logic. > > Hmmm... I'd never heard the term "belgian logic" before. Googling provided > a few uses, but no formal definition (maybe it's a European phrase so > searching for it in English is futile). The closest thing I found was > > Or is it another case of Belgian logic, where you believe it because > theres no evidence or motive whatsoever? Maybe it's Belgain logic, as opposed to Dutch logic. -- CARL BANKS From maxm at mxm.dk Mon Jan 17 10:01:23 2005 From: maxm at mxm.dk (Max M) Date: Mon, 17 Jan 2005 16:01:23 +0100 Subject: [ANN] iCalendar package 0.9 Message-ID: <41ebd292$0$253$edfadb0f@dread12.news.tele.dk> I have written a package that can parse and generate files according to RFC 2445 (iCalender). That should be any file ending with .ics :-) It is not quite polished yet, but fully functional, and choke full of doctest. It does support the full spec and all datatypes and parameter values. The Api is pretty stable, and will probably not change much. I would like anybody interrested to give it a test drive before I finish it off and make it a 1.0. http://www.mxm.dk/products/public/ical/ Any feedback would be welcome. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From reinhold-birkenfeld-nospam at wolke7.net Fri Jan 14 17:06:43 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 14 Jan 2005 23:06:43 +0100 Subject: Why would I get a TypeEror? In-Reply-To: References: <34ql1vF4dqd9pU1@individual.net> Message-ID: <34qu3jF4br3iqU2@individual.net> Steven Bethard wrote: > It's me wrote: >> Say again??? > > Please stop top-posting -- it makes it hard to reply in context. > >> "Reinhold Birkenfeld" wrote... >>>It's me wrote: >>>>If this is true, I would run into trouble real quick if I do a: >>>> >>>>(1/x,1.0e99)[x==0] >>> >>>Lazy evaluation: use the (x==0 and 1e99 or 1/x) form! > > If you want short-circuting behavior, where only one of the two branches > gets executed, you should use Python's short-circuiting boolean > operators. For example, > > (x == 0 and 1.0e99 or 1/x) > > says something like: > > Check if x == 0. > If so, check if 1.0e99 is non-zero. It is, so return it. > If x != 0, see if 1/x is non-zero. It is, so return it. > > Note that if you're not comfortable with short-circuiting behavior, you > can also code this using lazy evaluation: > > (lambda: 1/x, lambda: 1.0e99)[x==0]() Or even (x==0 and lambda: 1e99 or lambda: 1/x)() Or ... Reinhold From tjreedy at udel.edu Fri Jan 28 18:00:44 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Jan 2005 18:00:44 -0500 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com><1106911061.429966.303510@f14g2000cwb.googlegroups.com> Message-ID: OP: >>I find this response a bit dissappointing frankly. Open Source people >>make such a big deal about having lots of people being able to look at >>source code and from that discover security problems, thus making it >>somehow making it better than proprietary source code. OP: Did you discover this supposed security hole from black-box observation of behavior or by being one of the 'lots of people being able to look at source code', thereby giving evidence to the point? Everyone: I say 'supposed' because a) The OP has provided no info about his/her claim. b) The OP's original post is a classical troll: blast volunteer developers for not having anticipated and planned for a novel situation; argue against things not said, at least now here, not recently; imply that volunteers own him something. Most people with the expertise to detect a security hole would know better. c) The noise generated because of b) has alerted any malware writers monitering c.l.p for hints about exploitable security holes that there might be one in one of the few modules where such could reasonably be. OP: If my doubts are wrong and you really do have something to quietly report to the 'authority', then do so, and quit making a noise about it. Terry J. Reedy From hcslmf at texlife.com Mon Jan 31 16:35:04 2005 From: hcslmf at texlife.com (brolewis) Date: 31 Jan 2005 13:35:04 -0800 Subject: Spawning, and Killing, a Process Message-ID: <1107207304.586338.270080@c13g2000cwb.googlegroups.com> I am writing a program on Windows (XP Pro) that as part of the application takes advantage of rsync's ability to synchronize a client and server computer. However, because of the nature of our company's policies and our proxy, I must connect using SSH and use it as a tunnel to get to the location I need on the inside. My delimma is that I need to be able to spawn a process that uses the SSH, runs rsync, and then I need to be able to kill the SSH process and do not know a way to do that in Windows. I also would prefer to have SSH run invisible to the end user (no new window) which I get when using spawnl The commands I am running are as follows: SSH Tunnel: ssh ssh_user at proxy.example.com -i file_name -L 873:200.200.60.60:7000 -N Rsync Command: rsync -azv rsync_user at 127.0.0.1::package . I am aware that you should be able to run ssh inside of rsync but there seems to be a problem with the port of rsync that prevents me from accomplishing this. I thank you in advance for any assistance you are able to give. From gmanbauer at gmail.com Fri Jan 7 15:47:17 2005 From: gmanbauer at gmail.com (Gavin Bauer) Date: Fri, 7 Jan 2005 20:47:17 +0000 Subject: DOS problem (simple fix??) Message-ID: My DOS window (running in windows ME) closes the second it finishes running my programs. As you can imagine, this makes it hard to see the results. I've gotten in the habit of putting raw_input("Press enter to exit") at the end of every program, and in addition to being pain in the butt, it often fails to work. Being new to programming in general, I make more mistakes than most people. My programs often have errors before they get to my raw_input command. They then display the error and immediately close. It is naturally a lot easier to fix an error when you know what the error is. This makes debugging even more annoying than it ordinarily would be, if you can imagine that. I've heard that it should be a simple preference fix, but I've asked around and no one seems to know how. Thank you, and please make all answers simple enough to be understood by a highschool student and his father :) . From wcarus at comcast.net Wed Jan 12 08:45:12 2005 From: wcarus at comcast.net (Win) Date: 12 Jan 2005 05:45:12 -0800 Subject: Help Optimizing Word Search In-Reply-To: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Message-ID: <1105537512.711823.225530@f14g2000cwb.googlegroups.com> Hi Case. Just in case you're really, truly looking for a fast Scrabble word-search algorithm, the classic AI/CS article here is: Andrew W. Appel and Guy J. Jacobson, The world's fastest Scrabble program, Communications of the ACM, 31(5), pp 572--578, May 1988. You can find a copy of this article at, for example: http://counties.csc.calpoly.edu/~team12fk/F02/acm_worlds_fastest_scrabble_program.pdf This algorithm uses a "dawg" (Directed Acyclic Word Graph). You can find a well-documented example of this data structure implemented in Python in the the WordUtils package: http://cedar-solutions.com/software/wordutils/ Regards, Win From ncoghlan at iinet.net.au Mon Jan 17 05:27:47 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 17 Jan 2005 20:27:47 +1000 Subject: Executing a script created by the end user In-Reply-To: <41EAC49E.70209@earthlink.net> References: <41EAC49E.70209@earthlink.net> Message-ID: <41EB9323.3020805@iinet.net.au> Craig Howard wrote: > I am working on a python project where an object will have a script that > can be edited by the end user: object.script > > If the script is a simple one with no functions, I can easily execute it > using: > exec object.script Take a look at the execfile builtin. > But if the object script is a bit more complicated, such as the example > below, my approach does not work: Alternatively: Py> exec """ ... def main(): ... hello1() ... hello2() ... ... def hello1(): ... print 'hello1' ... ... def hello2(): ... print 'hello2' ... """ Py> main() hello1 hello2 'exec' is quite happy to deal with newlines and indenting. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jelle.feringa at ezct.net Mon Jan 17 04:53:14 2005 From: jelle.feringa at ezct.net (Jelle Feringa // EZCT / Paris) Date: Mon, 17 Jan 2005 10:53:14 +0100 Subject: OCAMl a more natural extension language for python? Message-ID: <20050117095248.90B8F1C015CF@mwinf0507.wanadoo.fr> After reading about extending python with C/Fortran in the excellent Python Scripting for Computational Science book by Hans Langtangen, I'm wondering whether there's not a more pythonic way of extending python. And frankly I think there is: OCAML Fortunately there is already a project up and running allowing you to extend python with OCAMl: http://pycaml.sourceforge.net/ Since I haven't got actual experience programming CAML I'd like to speculate that OCAML would be a very pythonic way of extending python: its open-source, object oriented, as fast as C, and ! garbage collecting! Would making an effort integrating python & CAML not be very worthwhile? I think an effort such as Joe Strouts python2c would be more relevant to a language as CAMl since its conceptually more closer to python (how could you automate programming memory allocation for instance) So my question is: wouldn't there be some serious synergy in bringing python & CAML closer together? ##of course this is speculation, I'm not informed well ##enough to make an educated guess Interested in hearing your thoughts about this matter! Cheers, Jelle. From fredrik at pythonware.com Sat Jan 22 13:55:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 19:55:36 +0100 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com><41EE24F7.7030303@jessikat.fsnet.co.uk><7x1xchlpqv.fsf@ruckus.brouhaha.com><41efeb82$0$27807$9b622d9e@news.freenet.de><41f1a70b$0$25959$9b622d9e@news.freenet.de><7xbrbiqdhk.fsf@ruckus.brouhaha.com><7xllalljah.fsf@ruckus.brouhaha.com><7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Excellent. I hope you will re-read it several times a day. Doing > that might improve your attitude. you really don't have a fucking clue about anything, do you? From beliavsky at aol.com Fri Jan 7 12:38:21 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 7 Jan 2005 09:38:21 -0800 Subject: how to extract columns like awk $1 $5 References: Message-ID: <1105119501.289155.264740@z14g2000cwz.googlegroups.com> It takes a few more lines in Python, but you can do something like for text in open("file.txt","r"): words = text.split() print words[4],words[5] (assuming that awk starts counting from zero -- I forget). From lcatalin at siadv.com Wed Jan 5 10:23:50 2005 From: lcatalin at siadv.com (Catalin Lungu) Date: Wed, 5 Jan 2005 16:23:50 +0100 Subject: Image capture Message-ID: Hi, Can anybody help me to implement the following VB code in Python. Thanks in advance. Private Declare Function SendMessage Lib "user32.dll" Alias _ "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, _ ByVal wParam As Long, ByVal lParam As Long) As Long Private Const WM_PAINT = &HF Private Const WM_PRINT = &H317 Private Const PRF_CLIENT = &H4& Private Const PRF_CHILDREN = &H10& Private Const PRF_OWNED = &H20& Private Sub Command1_Click() SendMessage grid.hwnd, WM_PAINT, picture.hDC, 0 SendMessage grid.hwnd, WM_PRINT, picture.hDC, PRF_CHILDREN Or PRF_CLIENT Or PRF_OWNED picture.Picture = picture.Image picture.Refresh End Sub Catalin lcatalin at siadv.com From http Sat Jan 8 04:55:03 2005 From: http (Paul Rubin) Date: 08 Jan 2005 01:55:03 -0800 Subject: python3: accessing the result of 'if' References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> Message-ID: <7xd5wgs0so.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > So let's use it for expression naming in 'if' statements, too. > > if someregexp.match(s) as m: > # blah using m > elif someotherregexp.match(s) as m: > # blah using m Certainly an improvement over what we have now. From jacek.generowicz at cern.ch Mon Jan 10 03:59:18 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Jan 2005 09:59:18 +0100 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> Message-ID: "Anna" writes: > With class and def, I at least have a *name* to start with - class > Square pretty obviously is going to have something to do with > geometric shapes, I would hope (or maybe with boring people...). Or maybe with multiplying something by itself. Or maybe the author made some changes in his program, and forgot to rename the class sensibly, and the class' functionality has nothing to do with squares of any sort any more. Or maybe he felt the name "Square" was very appropriate for something else in his program and inadvertently gave the same name to two different entities thereby clobbering the one whose use was intended at this point. > def getfoo() tells me I'm the function is likely to go elsewhere and > get something. It's a *start*, All too often a start in the wrong direction. > a handle, to deciphering whatever the following statements are > doing. (Yes, I realize that often class and function names suck Yup. I waste quite some time because of crappily chosen names. > - but more often than not, they give *some* clue). > > Whereas, with lambda - I have *nothing* to go on. Aaah. OK, you object to lambda because it gives you no clue as to what the function does, rather than with the word "lambda" itself? Is that it? So, IIUC, you consider def add_one(x): return x+1 map(add_one, seq) to be clearer than map(lambda x:x+1, seq) ? > With lambdas, all I know is that the programmer wanted to hide > whatever it is the program is doing behind the curtain... I find this a strange way of looking at it, given that, with lambda, what the program is doing is right there in front of your very eyes at the very point at which it is doing it. Were there a name, _then_ you could argue that the functionality is hidden ... and you would have to look the name up, to make sure that it really represents what you inferred it meant (and, to be absolutely sure, you'd have to double check that it hasn't been rebound by some other part of the program in some nasty way). None of these problems arise with lambda. > IMHO, YMMV, etc etc Of course. Same here. > Personally, I like lambdas less than regular expressions (of which > I'm particularly UNfond but understand their usefulness at > times). At least with regular expressions - I know that the > gibberish I need to decipher (probably) has to do with text > parsing... Hmm, that tells you about as much as lambda does. With lambda you know that the gibberish you need to decipher has to do with functions :-) From skip at pobox.com Wed Jan 26 22:03:07 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 26 Jan 2005 21:03:07 -0600 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: <16888.23019.818401.742296@montanaro.dyndns.org> phr> I don't see why you can't make up your mind enough to issue simple phr> statements like "the Python lib should have a module that does phr> so-and-so, and it should meet such-and-such requirements, so if phr> someone submits one that meets the requirements and passes code phr> review and testing and doesn't have unexpected issues or otherwise phr> fail to meet reasonable expectations, we'll use it". Because good requirements specification is difficult and testing improves the breed. Better to have the major API changes and bugs taken care of, and to have its popularity demonstrated *before* it gets into the Python distribution. The best way to do something isn't always obvious at the outset. If multiple solutions exist in the community, everyone benefits. The best survive. The worst don't. If one implementation is prematurely chosen for inclusion in the Python distribution, it stifles the vetting process. Finally, what if, saints be preserved, your whizbang new module is included in the core distribution and it's just not as popular as was first thought? It just winds up as a weight around the maintainers' necks. Once included in the distribution it's difficult to remove. Even rexec and Bastion, which are both known to be inadequate from a security standpoint, are still in the distribution. So, feel free to implement whatever it is you propose. Register it with PyPI, announce it on comp.lang.python.announce, etc. Support it for awhile. Run it through a couple revisions to fix API warts and bugs. When it's the category king and there is substantial community support for inclusion, it will be considered. Python is popular in part because of its fairly conservative development strategy. That goes for the libraries as well as the language itself. Skip From steven.bethard at gmail.com Thu Jan 27 12:58:23 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 10:58:23 -0700 Subject: String Fomat Conversion In-Reply-To: References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> Message-ID: Stephen Thorne wrote: > I did all I did in the name of clarity, considering the OP was on his > first day with python. How I would actually write it would be: > > inputfile = file('input','r') > inputfile.readline() > data = [map(float, line.split()) for line in inputfile] > > Notice how you don't have to call iter() on it, you can treat it as an > iterable to begin with. Beware of mixing iterator methods and readline: http://docs.python.org/lib/bltin-file-objects.html next( ) ...In order to make a for loop the most efficient way of looping over the lines of a file (a very common operation), the next() method uses a hidden read-ahead buffer. As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right. I haven't tested your code in particular, but this warning was enough to make me generally avoid mixing iter methods and other methods. Steve From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Tue Jan 11 17:57:08 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?iso-8859-1?Q?Michel_Claveau_-_abstraction_m=E9ta-galactique_non_trivial?= =?iso-8859-1?Q?e_en_fuite_perp=E9tuelle.?=) Date: Tue, 11 Jan 2005 23:57:08 +0100 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> <1105434532.132061.24030@f14g2000cwb.googlegroups.com> <1105434900.511862.54740@f14g2000cwb.googlegroups.com> Message-ID: <41e459e5$0$8025$8fcfb975@news.wanadoo.fr> ;o) Python ==. limits ,===> \________/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From ncoghlan at iinet.net.au Sun Jan 2 00:32:33 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 02 Jan 2005 15:32:33 +1000 Subject: when wxPython update to python2.4? In-Reply-To: <41B930B7.4040600@163.com> References: <41B930B7.4040600@163.com> Message-ID: <41D78771.8000404@iinet.net.au> alang_yl wrote: > i can't wait. > wxPython 2.5 already has a version which works with Python 2.4 (grab it from www.wxpython.org). For the wxPython 2.4 series, I understand Robin is planning a release which will both integrate the 2.4 series into the new wxPython versioning scheme, and also include a Python 2.4 compatible version. The timeframe for that isn't entirely clear, though. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From pierre.barbier at cirad.fr Wed Jan 12 08:36:35 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Wed, 12 Jan 2005 14:36:35 +0100 Subject: how to visualize symbol table? In-Reply-To: <41e5220c$0$15240$91cee783@newsreader01.highway.telekom.at> References: <41e5220c$0$15240$91cee783@newsreader01.highway.telekom.at> Message-ID: <41e52772$0$7880$626a14ce@news.free.fr> Thomas Korimort a ?crit : > Hi, > > how can i visualize the content of the symbol table in Python? > Sometimes i want to know which symbols are imported from apackage and > such kind of things > > Greetings, THomas Korimort Do you mean something like : dir(module) ??? Pierre From christian_stengel at yahoo.de Wed Jan 26 11:29:31 2005 From: christian_stengel at yahoo.de (christian_stengel) Date: Wed, 26 Jan 2005 16:29:31 -0000 Subject: unknown protocol error when connecting to an server via ssl Message-ID: Hi *, I have just started to learn python and I am having a problem with an python client connecting to a perl server using ssl (I tried this with pyOpenSSL and with the build in SSL Module). I don't want to check a cerificate, so i simply tried a from OpenSSL import SSL s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("127.0.0.1", 2000) s.sendall("100 Hello\n") ctx = SSL.Context(SSL.SSLv23_METHOD) ctx.set_verify(SSL_VERIFY_NONE,self.verify_cb) ss = SSL.Connection(ctx,s) ss.set_connect_state() ss.sendall("101 User\n") when writeing the 101 I'll get an SSL23_GET_SERVER_HELLO unknown protocol error. If I don't do the ssl stuff, everything works. I also tried this with the socket.ssl(s,None, None) to get a secure socket - but I got the same error. The server is not written by me - so I can't change that to python. The problem is, that there is first an unencrypted socket, that is converted to a secure socket. the perl (server) code is something like this: # creating a socket $socket = IO::Socket::INET->new(Listen => 5, LocalPort => 2000, Timeout => 15, Resue => 1, Proto => 'tcp'); # some more code # accepting a remote connection $session = $socket->accept; # some more code # convert the Socket to an ssl socket $sslsocket = IO::Socket::SSL::socket_to_SSL($session, SSL_verify_mode => 0x00) # some more code Does anybody know, where the UNKNOWN PROTOCOL error comes from? I have changed the connection Mode to SSLv2_METHOD but this gave me an GET_SERVER_HELLO read wrong packet type error. I have done this with python 2.3.4 under linux - and the perl stuff is done via the IO-Socket-SSL package. Thx, Chris From http Sun Jan 30 17:50:42 2005 From: http (Paul Rubin) Date: 30 Jan 2005 14:50:42 -0800 Subject: ANNOUNCE: KirbyBase 1.7 References: Message-ID: <7xy8ea1qgt.fsf@ruckus.brouhaha.com> Jamey Cribbs writes: > KirbyBase is a simple, plain-text, database management system written > in Python. It can be used either embedded in a python script or in a > client/server, multi-user mode. You use python code to express your > queries instead of having to use another language such as SQL. > KirbyBase is disk-based, not memory-based. Database changes are > immediately written to disk. That's cute, especially the part about using Python expressions instead of SQL to express queries. I don't see anything in the info page about what happens when you have multiple clients updating the db concurrently. Do you make any attempt to handle that? From morphex at gmail.com Wed Jan 12 23:49:56 2005 From: morphex at gmail.com (morphex) Date: 12 Jan 2005 20:49:56 -0800 Subject: Creating text on images Message-ID: <1105591796.422252.190990@f14g2000cwb.googlegroups.com> Hi all, I'm trying to create a script that will superimpose text on an image. I didn't find any great examples out there on how this can be done (I presume using PIL is necessary), do you know of any examples? Thanks, Morten From peter at engcorp.com Thu Jan 13 08:37:50 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 08:37:50 -0500 Subject: pyserial and com port interrupts In-Reply-To: <24lbu0htudrc9ir4b0na3r1m6g09qlbck4@4ax.com> References: <24lbu0htudrc9ir4b0na3r1m6g09qlbck4@4ax.com> Message-ID: engsol wrote: > I'm working on a s/w test program using python > code. Com1 and com2 play a part. The problem is that the python code > has a lot of work to do...and the results from the hardware under test can > come from either com1 or com2...at any time. It may be a few milliseconds, > or several seconds, sometimes minutes, before a response is expected. > I'm not sure what timeout value I'd use. Using threads, and re-loading the > timeout values on the fly may be a solution, but I'm not experienced with > threads....and was hoping to avoid them. I'm with Grant on this: threads in Python are really easy. If you can describe a little more about what you need/would like to do with the serial data when it *does* arrive, and how that relates to the "lot of work" that the rest of the code is doing, I'm sure there are a number of helpful replies just waiting to be written to convince you how easy it really is. For example, if you need to retrieve the data from the serial ports right away, so the sending device doesn't block or lose data, but can afford to just store it for later processing when the main thread has time, that's only a few lines of code. If you actually want to reply immediately, then the only real question is how you come up with the reply. If it needs data from the main thread, we can show you several easy and appropriate ways to do that with no thread safety issues. If you're not experienced with threads, there's almost no place better to start learning than with Python and c.l.p. :-) -Peter From michele.simionato at gmail.com Wed Jan 5 22:42:08 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 5 Jan 2005 19:42:08 -0800 Subject: Python evolution: Unease In-Reply-To: <7xzmzo6qk0.fsf@ruckus.brouhaha.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <1104910363.381748.105670@z14g2000cwz.googlegroups.com> <7xzmzo6qk0.fsf@ruckus.brouhaha.com> Message-ID: <1104982928.527510.29630@z14g2000cwz.googlegroups.com> Did you used Tkinter and Tix? Most of my problems were there. Of course, I also got in trouble when upgrading to Python 2.2 from 1.5.2 Finally they switched to Python 2.2, but at that moment Python 2.3 came out and I got tired. I switched to Mandrake 1.5 and I am happy with it. Never had any serious trouble with urpmi and lots of Python packages are available. Michele Simionato From woetzel at AUTO Wed Jan 19 05:08:18 2005 From: woetzel at AUTO (Gerd Woetzel) Date: 19 Jan 2005 12:08:18 +0200 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> Message-ID: <41ee3fa2$1@news.fhg.de> Robin Becker writes: >Paul Rubin wrote: >.....I'm also missing the rotor module and regret that something useful >was warned about and now removed with no plugin replacement. Hm, yes. Here is a (rather slow) replacement: """This module is derived from Modules/rotormodule.c and translated into Python. I have appended the Copyright by Lance Ellinghouse below. The rotor module has been removed from the Python 2.4 distribution because the rotor module uses an insecure algorithm and is deprecated. ============================================================== Of course, this does still hold. However, I think this module might be used and adapted for demonstration purposes and might help some poor users who have encrypted (or obfuscated) some old stuff with the rotor module and have no access to older Python versions any more. Documentation can be found in Python Library Reference, Guido van Rossum, Fred L. Drake, Jr., editor, PythonLabs, Release 2.3.4 May 20, 2004 ##################################################################### Copyright 1994 by Lance Ellinghouse, Cathedral City, California Republic, United States of America. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Lance Ellinghouse not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ##################################################################### """ class newrotor(object): def __init__(self, key, n_rotors=6): self.n_rotors = n_rotors self.setkey(key) def setkey(self, key): self.key = key self.rotors = None self.positions = [None, None] def encrypt(self, buf): # Reset (encrypt) positions and encryptmore self.positions[0] = None return self.cryptmore(buf, 0) def encryptmore(self, buf): return self.cryptmore(buf, 0) def decrypt(self, buf): # Reset decrypt positions and decryptmore self.positions[1] = None return self.cryptmore(buf, 1) def decryptmore(self, buf): return self.cryptmore(buf, 1) def cryptmore(self, buf, do_decrypt): size, nr, rotors, pos = self.get_rotors(do_decrypt) outbuf = [] append = outbuf.append for c in map(ord, buf): if do_decrypt: # Apply decrypt rotors and xor in reverse order for i in xrange(nr-1,-1,-1): c = pos[i] ^ rotors[i][c] else: # Apply xor and ecrypt rotors for i in xrange(nr): c = rotors[i][c ^ pos[i]] append(c) # Advance rotors, i.e. add the (fixed) rotor increments to the # variable rotor positions with carry. # Note: In the C-implementation, the result of the carry addition # was stored to an "unsigned char". Hence the next carry # is lost if pos[i] == size-1 and pnew >= size. # Masking with 0xff simulates this behavior. # pnew = 0 # (pnew >= size) works as "carry bit" for i in xrange(nr): pnew = ((pos[i] + (pnew >= size)) & 0xff) + rotors[i][size] pos[i] = pnew % size return ''.join(map(chr, outbuf)) def get_rotors(self, do_decrypt): # Return a tuple (size, nr, rotors, positions) where # - size is the rotor size (== 256, because of 8-bit bytes) # - nr is the number of rotors. # - rotors is a tuple of nr encrypt or nr decrypt rotors # for do_decrypt == 0 or do_decrypt == 1 respectively. # - postions is a list of nr "rotor positions". # # The rotors represent the static aspect of the rotor machine which # is initially computed from key and fixed during en/decryption. # A rotor is a random permutation of range(size) extended # by an "increment value" in range(size). # # The followng statements hold for a tuple of encrypt rotors E and # and the corresponding tuple of decrypt rotors D. # # D[i][E[i][j]] == j for i in range(nr) for j in range(size) # # E[i][D[i][j]] == j for i in range(nr) for j in range(size) # # This means that the corresponding rotors E[i] and D[i] are # inverse permutations. # The increments are equal for the corresponding encrypt and # decrypt rotors and have an odd value: # # D[i][size] == E[i][size] and E[i][size] == 1 mod 2 and # 0 < E[i][size] < size for i in range(nr) # # The position vector represents the dynamic aspect. # It changes after each en/decrypted character (the rotors # are "advanced"). The initial position vector is also computed # from the key # nr = self.n_rotors rotors = self.rotors positions = self.positions[do_decrypt] if positions is None: if rotors: positions = list(rotors[3]) else: # Generate identity permutation for 8-bit bytes plus an # (unused) increment value self.size = size = 256 id_rotor = range(size+1) # Generate nr "random" initial positions and "random" # en/decrypt rotors from id_rotor. # rand = random_func(self.key) E = [] D = [] positions = [] for i in xrange(nr): i = size positions.append(rand(i)) erotor = id_rotor[:] drotor = id_rotor[:] drotor[i] = erotor[i] = 1 + 2*rand(i/2) # increment while i > 1: r = rand(i) i -= 1 er = erotor[r] erotor[r] = erotor[i] erotor[i] = er drotor[er] = i drotor[erotor[0]] = 0 E.append(tuple(erotor)) D.append(tuple(drotor)) self.rotors = rotors = ( tuple(E), tuple(D), size, tuple(positions)) self.positions[do_decrypt] = positions return rotors[2], nr, rotors[do_decrypt], positions def random_func(key): # Generate a random number generator that is "seeded" from key. # This algorithm is copied from Python2.3 randommodule.c. # mask = 0xffff x=995 y=576 z=767 for c in map(ord, key): x = (((x<<3 | x>>13) + c) & mask) y = (((y<<3 | y>>13) ^ c) & mask) z = (((z<<3 | z>>13) - c) & mask) # Emulate (unintended?) cast to short maxpos = mask >> 1 mask += 1 if x > maxpos: x -= mask if y > maxpos: y -= mask if z > maxpos: z -= mask y |= 1 # avoid very bad seed, why not for x and z too? # Oh, dear, for compatibility, we must evaluate the first seed transition # the hard way, later it becomes much simpler x = 171 * (x % 177) - 2 * (x/177) y = 172 * (y % 176) - 35 * (y/176) z = 170 * (z % 178) - 63 * (z/178) if x < 0: x += 30269 if y < 0: y += 30307 if z < 0: z += 30323 # At least all values are > 0 by now but may be greater than expected .. def rand(n, seed=[(x, y, z)]): # Return a random number 0 <= r < n # x, y, z = seed[0] seed[0] = ((171*x) % 30269, (172*y) % 30307, (170*z) % 30323) return int((x/30269.0 + y/30307.0 + z/30323.0) * n) % n # Original code was like this: # from math import floor # val = x/30269.0 + y/30307.0 + z/30323.0 # val = val - floor(val) # if val >= 1.0: # val = 0.0 # n = int(val*n) % n return rand From aahz at pythoncraft.com Sun Jan 9 19:26:59 2005 From: aahz at pythoncraft.com (Aahz) Date: 9 Jan 2005 19:26:59 -0500 Subject: Old Paranoia Game in Python References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> Message-ID: In article , Lucas Raab wrote: >Aahz wrote: >> In article <5JcEd.1988$KJ2.907 at newsread3.news.atl.earthlink.net>, >> Lucas Raab wrote: >>>Sean P. Kane wrote: >>>> >>>>Equipment: Red Reflec Armour, Laser Pistol, Laser Barrel (red), >>>> Notebook & Stylus, Knife, Com Unit 1, Jump suit, >>>> Secret Illuminati Eye-In-The-Pyramid(tm) Decoder ring, >>>> Utility Belt & Pouches >>> >>>The Illuminati really have infiltrated our society. >> >> Stay alert! >> Trust no one! >> Keep your laser handy! > >Well, I really meant "Secret Illuminati Eye-In-The-Pyramid(tm) Decoder >ring", but if you wanted to go in another direction... Trust the computer, the computer is your friend. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From tmohr at s.netic.de Fri Jan 14 01:23:53 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Fri, 14 Jan 2005 07:23:53 +0100 Subject: reference or pointer to some object? References: Message-ID: Hi, thank you all for your explanations. That's really great and helps me a lot. Thanks, Torsten. From toop82 at comcast.net Tue Jan 25 00:01:08 2005 From: toop82 at comcast.net (Robert Toop) Date: Tue, 25 Jan 2005 00:01:08 -0500 Subject: error References: Message-ID: http://www.python.org/2.4/bugs.html ...suggests that firewall running on python host (read Windows software firewall) may block the localhost TCP connection required between IDLE parent and child processes. I don't think this problem is specific to python 2.4. IDLE should work if you change firewall config to allow local (i.e. intramural) TCP connections. HTH /old goat/ "me" wrote in message news:RAfJd.37$587.2870 at news.uswest.net... > whenever i try and run my Python GUI, my computer thinks for a sec, then > drops the process, without ever displaying the window. the command prompt > window seems to work fine, but the IDLE GUI won't start. > > i'm running Windows 2K professional and python 2.4, so any advice help would > be appreciated. i've already tried reinstalling and use a thread response, > as the e-mail on this account is bogus. > > From petite.abeille at gmail.com Fri Jan 28 18:21:16 2005 From: petite.abeille at gmail.com (PA) Date: Sat, 29 Jan 2005 00:21:16 +0100 Subject: what's OOP's jargons and complexities? In-Reply-To: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> Message-ID: On Jan 29, 2005, at 00:10, Xah Lee wrote: > Tomorrow i shall cover more manmade jargons and complexities arising > out of the OOP hype, in particular Java. Good read. Keep them coming :) Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From tundra at tundraware.com Fri Jan 7 05:28:31 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 07 Jan 2005 05:28:31 EST Subject: Tkinter Puzzler Message-ID: I am trying to initialize a menu in the following manner: for entry in [("Up", KeyUpDir), ("Back", KeyBackDir), ("Home", KeyHomeDir), ("Startdir", KeyStartDir), ("Root", KeyRootDir)]: func = entry[1] UI.ShortBtn.menu.add_command(label=entry[0], command=lambda: func(None)) However, at runtime, each of the menu options binds to the *last* function named in the list (KeyStartDir). Explicitly loading each entry on its own line works fine: UI........command=lambda:KeyWHATEVERDir(None) Any ideas why the first form does not fly? TIA, ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From apardon at forel.vub.ac.be Wed Jan 19 09:40:24 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Jan 2005 14:40:24 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> <41ed8c13.1209309354@news.oz.net> Message-ID: Op 2005-01-19, Nick Coghlan schreef : > Antoon Pardon wrote: > > I can be wrong, but until now I have seen no indication that I was >> using mutable and immutable differently than other people. AFAICT >> we all refer to whether an object belongs to a mutable or immutable >> class. > > The difference is that when you take a copy of the key and stick it in the > dictionary, such that the dictionary now holds the *sole* reference to that key, > you have made that key *effectively* immutable. > > This is why no-one really batted an eyelid when you mentioned that mutable keys > can be used safely by making a copy - doing so makes the key *effectively* > immutable, and means that modifying the original key object (i.e. the > application's copy, not the dict's copy), and reusing it to look up in the > dictionary is likely to give a KeyError. > > These semantics would be understandably surprising to many users, and hence, are > not supplied by default. This seems like circle reasoning. The reason why these semantics would be surprising is that those are not the semantics supplied. > Additionally, a dictionary's keys are accessible via its API. Accordingly, to > preserve this 'effective immutability', making a copy on key input is > insufficient - keys must be copied on *output* as well (that is, dict.keys, > dict.items etc must return *copies* of the key objects, not the key objects > themselves). Yes I haven been thinking about this too. I also think not making a copy on output is less dangerous than not making a copy on input. > Since there is no reliable way in Python to tell if an object is mutable or not > (the closest equivalent is the presence of __hash__, which clearly can't be used > in this example), this copying would need to be done for *every* object. > > Alternately, the dictionary can say to the API clients, "make an immutable copy > and supply that instead. It is left to API clients to decide how best to make > the immutable version". The API client copies the key once (to make the > immutable version), and everyone lives happily ever after. > > For example: > > Py> class mylist(list): > ... def __init__(self, arg): > ... super(mylist, self).__init__(arg) > ... self._tuple = None > ... def frozen(self): > ... if self._tuple is None: > ... self._tuple = tuple(self) > ... return self._tuple > ... def unfreeze(self): > ... self._tuple = None > ... > Py> x = mylist(range(10)) > Py> x > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > Py> x.frozen() > (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) > Py> x.append(10) > Py> x.frozen() > (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) > Py> x.unfreeze() > Py> x.frozen() > (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) > > This is much safer than having a list subclass that implements __hash__, and > still lets you avoid redundant copy operations. > > Nicely, so long as you don't unfreeze the object you used to key the dictionary, > reusing the same object will always get you the correct dictionary entry, and > two lists that compare equal at the time they are frozen will also get you the > same dictionary entry. The equivalent tuples can be used for the lookup, too. Interesting idea. But I think you are wrong when you say that two lists that compare equal at the time they are frozen, will get the same dictionary entry. The problem is an object must compare equal to the key in the dictionary to get at the same entry. So if you freeze a list and its copy but then mutate them differently, they no longer are equal and so wont get you at the same entry. [ Rest snipped, this is getting into a semantic debate on what 'mutable' means. This may be interesting enough on its own but I feel it detracts too much from what I consider the more important issue. ] -- Antoon Pardon From john at grulic.org.ar Mon Jan 17 14:23:27 2005 From: john at grulic.org.ar (John Lenton) Date: Mon, 17 Jan 2005 16:23:27 -0300 Subject: strange note in fcntl docs In-Reply-To: <16875.54085.712019.524951@montanaro.dyndns.org> References: <20050117053949.GA28456@grulic.org.ar> <16875.54085.712019.524951@montanaro.dyndns.org> Message-ID: <20050117192327.GA4723@grulic.org.ar> On Mon, Jan 17, 2005 at 09:01:25AM -0600, Skip Montanaro wrote: > > I could have sworn that os.open supported the O_SHLOCK and O_EXLOCK flags. > I'm pretty sure I've used them in the past, but don't see them now. (They > aren't in 2.2 either.) > > If you try this: > > O_SHLOCK = 0x0010 > O_EXLOCK = 0x0020 > > (those are the definitions on my Mac - YMMV) does > > os.open("somefile", O_SHLOCK|) > > work? I grepped for O_..LOCK in /usr/include on my linux computer and came up barehanded. The flags you mention are not, AFAIK, part of POSIX (the open(3posix) manpage does not list them). And, even if they were, the note is *still* wrong and misleading: fcntl is available on Windows, and os.open's flags won't be. from http://www.daemon-systems.org/man/open.2.html, I gather that O_..LOCK are a BSD extension, which is why you have then on the Mac. But they do *not* belong in posix; they belong in os for your platform, and the note in fcntl should be removed. The only way this wouldn't be true is if os.open is extended to understand O_..LOCK, and call out to flock as needed. That would go against what I understand is the essence of os.open (i.e., a direct road to open(2)). Hmm, if the above sounds a little harsh, sprinkle :)s in. I've had too little sleep. -- John Lenton (john at grulic.org.ar) -- Random fortune: If you're right 90% of the time, why quibble about the remaining 3%? -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From fperez.net at gmail.com Tue Jan 25 12:37:34 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Tue, 25 Jan 2005 10:37:34 -0700 Subject: Installer made with bdist_wininst segfaulting... References: Message-ID: Hi Thomas, Thomas Heller wrote: > Fernando Perez writes: >> Here is a brief summary: if the installer file is run from a windows drive >> which is different from the one where python resides (and hence where >> ipython will >> end up), the installer segfaults. No traceback, nothing, just a segfault >> (well, one of those Windows dialogs asking me to send a binary traceback to >> Redmond, but not a proper Python traceback). > > There are a couple of known bugs in bdist_wininst, and you just reported > another one. All these bugs are related to using the > post_install_script, and show up when either (thats what I currently > remember): [...] many thanks for following up on this. In my case, I realized I could avoid the chdir() call and things were then OK. But it's good to see the bug fixed. Best regards, f From roy at panix.com Fri Jan 7 20:43:03 2005 From: roy at panix.com (Roy Smith) Date: Fri, 07 Jan 2005 20:43:03 -0500 Subject: EOF for binary? References: <1105147072.909665.242360@z14g2000cwz.googlegroups.com> Message-ID: In article <1105147072.909665.242360 at z14g2000cwz.googlegroups.com>, "flamesrock" wrote: > Hi, > > So if I understand correctly, there are NO eof characters in any binary > file. If so, is there an easier way to check for the end of the file > than: > > os.path.getsize(infile) <= infile.tell() How you detect EOF depends on how you're reading the file. For example, read() indicates EOF by returning fewer characters than you asked for (possibly zero). Checking the length of a file is perilous. Files change size. File sizes don't have much meaning on things like network sockets to begin with. From mahs at telcopartners.com Tue Jan 25 19:03:11 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 25 Jan 2005 16:03:11 -0800 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: References: Message-ID: Cameron Laird wrote: > In article , > Michael Spencer wrote: > . > . > . > >>Right - the crux of the problem is how to identify dangerous objects. My point >>is that if such as test is possible, then safe exec is very easily implemented >>within current Python. If it is not, then it is essentially impossible. >> > > > > I'll suggest yet another perspective: add another indirection. > As the virtual machine becomes more available to introspection, > it might become natural to define a *very* restricted interpreter > which we can all agree is safe, PLUS a means to extend that > specific instance of the VM with, say, new definitions of bindings > for particular AST nodes. Then the developer has the means to > "build out" his own VM in a way he can judge useful and safe for > his own situation. Rather than the Java there-is-one-"safe"-for- > all approach, Pythoneers would have the tools to create safety. That does sound good. And evolutionary, because the very restricted VM could be implemented today (in Python), and subsequently PyPy (or whatever) could optimize it. The safe eval recipe I referred to earlier in the thread is IMO a trivial example of of this approach. Of course, its restrictions are extreme - only constant expressions, but it is straightforwardly extensible to any subset of the language. The limitation that I see with this approach is that it is not, in general, syntax that is safe or unsafe (with the notable exception of 'import' and its relatives). Rather, it the library objects, especially the built-ins, that present the main source of risk. So, if I understand your suggestion, it would require assessing the safety of the built-in objects, as well as providing an interpreter that could control access to them, possibly with fine-grain control at the attribute level. M From timj at tolisgroup.com Mon Jan 17 14:22:44 2005 From: timj at tolisgroup.com (brucoder) Date: 17 Jan 2005 11:22:44 -0800 Subject: Adjusting the 1024 byte stdin buffer limit References: <1105989047.516986.59990@z14g2000cwz.googlegroups.com> Message-ID: <1105989764.168794.113430@z14g2000cwz.googlegroups.com> Currently, when sending a data stream that exceeds 1024 bytes via stdin, the stream blocks at the 1024th byte. This precludes completion of the submission of the data stream. Tim From klapotec at chello.at Thu Jan 6 19:27:33 2005 From: klapotec at chello.at (Christopher Koppler) Date: Fri, 07 Jan 2005 00:27:33 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <1105056774.393244.199250@f14g2000cwb.googlegroups.com> Message-ID: On Thu, 06 Jan 2005 16:12:54 -0800, Carl Banks wrote: > Arich Chanachai wrote: >> But >> then again, if you don't like C++, you probably won't like Java. > They >> can be very different languages, but in my experience, the reasons > why >> one does not like C++ is usually due to a quality/flaw that can also > be >> found in Java. > > Oh, brother. > > The Zen of Python says that "simple is better than complex" and > "complex is better than complicated". Java does pretty well here. C++ > didn't even get "complicated is better than convoluted" right. There's > are a ton of flaws in C++ not found in Java. Still, Java feels like C++ done right, while being more wrong >:-[ -- Christopher If there was a scheme for Lisp world domination... From michele.simionato at gmail.com Wed Jan 5 22:31:53 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 5 Jan 2005 19:31:53 -0800 Subject: Python evolution: Unease In-Reply-To: <10to8qulnc3vke1@news.supernews.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> Message-ID: <1104982313.217034.308760@z14g2000cwz.googlegroups.com> John Roth: > The bottom line is that I'm not going to be writing any > extensive pieces of Python documentation. My time > is better spent elsewhere. Well, a couple of years ago I realized that some documentation on the MRO was missing. I wrote a document in reST, posted here, and Guido put it on python.org. It was as easy as it sounds. So I don't see your problem. Dave Kulhman wrote some utility to convert reST in latex using the same style of the standard library docs; I haven't used it myself, but you may check with him: http://www.rexx.com/~dkuhlman/ P.S. since you cite descriptors, what's wrong with Raimond Hetting documentation? http://users.rcn.com/python/download/Descriptor.htm The only problem I see is that it is not integrated with the official docs, but this is a minor issue, I think. Michele Simionato From rnd at onego.ru Tue Jan 4 09:06:45 2005 From: rnd at onego.ru (Roman Suzi) Date: Tue, 4 Jan 2005 17:06:45 +0300 (MSK) Subject: Python evolution: Unease In-Reply-To: References: Message-ID: On Tue, 4 Jan 2005, Batista, Facundo wrote: Maybe OP doesn't yet fully comprehend the ways of Python universe? As for his claims, I am quite surprised that Python lacks something in the docs. Concerning better hierarchy in the standard library, it is interesting that there are some movements in this direction: xml package, email package, etc. Probably Iwan thinks that letting more "hierachiesness" into std lib Python will be "cleaner". Yes, it will probably look "more organized" this way, but I do not like the idea: import time.time import time.calendar ... import web.url.openers import net.http ... import datatypes.string import textprocessing.re etc. > [Iwan van der Kleyn] > > #- need: a better standard ide, an integrated db interface with > #- a proper > #- set of db drivers (!!), a better debugger, a standard widget/windows > #- toolkit, something akin to a standard for web programming, better > #- documentation, a standard lib which is better organized, a > #- formalized > #- set of protocols and patterns for program construction. And an > #- interpreter which is fast enough to avoid using C or Pyrex in most > #- obvious cases. > > Let's take one by one: > > - IDE: Better than what? Than IDLE? Than Eclipse? Than SPE? Than Pythonwin? > > - Integrated DB interface with a proper set of db drivers (what means the > "!!"?): What do you mean with an integrated db interface? An standard API to > access different DB engines? Something like the Database API specification > (http://www.python.org/topics/database/DatabaseAPI-2.0.html)? There's a SIG > on DB at http://www.python.org/sigs/db-sig/ you may want to look at. > Regarding drivers, to what DB do you miss one? > > - Debugger: Again, better than what? I use the debugger in IDLE and it's > pretty ok. > > - Standard widget/windows toolkit: More standard than Tk? > > - Something akin to a standard for web programming: specifically? > > - Better documentation: Did you find *any* issue in the docs? And why you > didn't post a bug on that? > > - Better organization of the std lib: What do you propose (specifically)? > Please, in your proposal, take in consideration migration plans and how the > migration affect actual systems. And of course, why the new organization is > better than the old one. BTW, I also think that it should be better > organized, but don't know how. > > - a formalized set of protocols and patterns for program construction: a > what? > > - an interpreter which is fast enough to avoid using C or Pyrex in most > obvious cases: CPython is More Than Fast Enough. In which obvious cases it's > not enough for you? > > Don't misinterpret this response. I know it was a rambling. But *maybe* you > have something to contribute to Python development, even good ideas only and > no work. > > . Facundo Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From zathras at thwackety.com Sun Jan 2 20:13:04 2005 From: zathras at thwackety.com (Michael Sparks) Date: Mon, 3 Jan 2005 01:13:04 +0000 (GMT) Subject: PEP 288 ponderings In-Reply-To: <41D794BA.8090408@colorstudy.com> Message-ID: On Sun, 2 Jan 2005, Ian Bicking wrote: > Steven Bethard wrote: > > PEP 288 was mentioned in one of the lambda threads and so I ended up > > reading it for the first time recently. I definitely don't like the > > idea of a magical __self__ variable that isn't declared anywhere. It > > also seemed to me like generator attributes don't really solve the > > problem very cleanly. An example from the PEP[1]: > > > > def mygen(): > > while True: > > print __self__.data > > yield None > > > > g = mygen() > > g.data = 1 > > g.next() # prints 1 > > g.data = 2 > > g.next() # prints 2 > > I don't get why this isn't good enough: > > def mygen(data): > while True: > print data[0] > yield None It's OK, but rather limited. IMHO a nicer approach is to use decorators to decorate a generator with extra attributes. Specifically to embed the generator inside an iterator inside an anonymous class. (We're exploring this as a alternative approach to the system we currently use at work) (Hmm... Now I describe it that sounds rather hideous, but the result is nice) First of all the decorator: import copy def wrapgenerator(bases=object, **attrs): def decorate(func): class statefulgenerator(bases): __doc__ = func.__doc__ def __init__(self,*args): super(statefulgenerator, self).__init__(*args) self.func=func(self,*args) for k in attrs.keys(): self.__dict__[k] = copy.deepcopy(attrs[k]) self.next=self.__iter__().next def __iter__(self): return iter(self.func) return statefulgenerator return decorate This would be used thus: @wrapgenerator(component) def forwarder(self): # The generator, note the explicit self for local state # for this generator "Simple data forwarding generator" while 1: if self.dataReady("inbox"): self.send("outbox",self.recv("inbox")) elif self.dataReady("control"): if self.recv("control") == "shutdown": break yield 1 self.send("signal","shutdown") yield 0 This clearly assumes a set of attributes, local methods etc. In this case our local methods, attribute etc are from this class: class component(object): def __init__(self, *args): # Default queues self.queues = {"inbox":[],"control":[],"outbox":[],"signal":[]} def send(self, box, object): self.queues[box].append(object) def dataReady(self,box): return len(self.queues[box])>0 def recv(self, box): # NB. Exceptions aren't caught X=self.queues[box][0] del self.queues[box][0] return X This then gets used in the usual way: >>> f = forwarder() >>> f <__main__.statefulgenerator object at 0x402dcccc> >>> f.send("inbox", "some data") >>> f.send("inbox", "some more data") >>> f.next() 1 >>> f.next() 1 >>> f.recv("outbox") 'some data' >>> f.recv("outbox") 'some more data' If you "just" want (arbitrary) generator attributes, then that's a lot easier (since we don't need to support an arbitrary base class): import copy def add_attrs_to_generator(**attrs): def decorate(func): class statefulgenerator: __doc__ = func.__doc__ def __init__(self,*args): self.func=func(self,*args) for k in attrs.keys(): self.__dict__[k] = copy.deepcopy(attrs[k]) self.next=self.__iter__().next def __iter__(self): return iter(self.func) return statefulgenerator return decorate @add_attrs_to_generator() def simpleGen(self): while True: print dir(self) yield None We can also add default attributes: @add_attrs_to_generator(test=1,simple=2) def simpleGen(self): while True: print dir(self) yield None >>> g=simpleGen() >>> g.next() ['__doc__', '__init__', '__iter__', '__module__', 'func', 'next', 'simple', 'test'] We've been using this general approach of giving generators local state for communications for a while now, and it's been rather interesting/fun to use. However we've been using explicit declaration of a class, and then a standard fixed name for the generator (main) instead. (we've been thinking about using decorators as syntactic sugar) Being able to pass exception in would be very nice, however we've used a "control" attribute, queue in practice, to allow for need to be able to shutdown an arbitrary generator. However, I don't think the __self__ part of the PEP is explicitly required - since you can build that onto generators using python quite happily now (@add_attrs_to_generator). The code for the stuff we're playing with (in case anyone's interested :) is at http://kamaelia.sourceforge.net/. The specific subsystem that uses this approach has been released as a separate download (Axon[1]) on the sourceforge project page[2], and the main system (obviously) uses this heavily and can be browsed via viewcvs. [3] [1] http://kamaelia.sourceforge.net/Docs/Axon.html [2] http://sourceforge.net/projects/kamaelia [3] http://cvs.sourceforge.net/viewcvs.py/kamaelia/Code/Python/Kamaelia/Kamaelia/ Best Regards, Michael. From peter at engcorp.com Mon Jan 10 19:32:48 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Jan 2005 19:32:48 -0500 Subject: exceptions and items in a list In-Reply-To: References: <34g8i6F4ad39oU1@individual.net> Message-ID: <3r-dnftx4-syg37cRVn-uQ@powergate.ca> rbt wrote: > Andrey Tatarinov wrote: >> # skip bad object and continue with others >> for object in objects: >> try: >> #do something to object >> except Exception: >> pass > > Thanks Andrey. That's a great example of how to do it. Actually, it's not really a "great" example, since it catches _all_ exceptions that might happen, and quietly ignores them. For example, in the following code, you might not realize that you've made a typo and none of the items in the list are actually being checked, even though there is obviously no problem with any of these simple items (integers from 0 to 9). def fornat_value(val): return '-- %5d --' % val L = range(10) for val in L: try: print format_value(val) except Exception: pass It's almost always better to identify the *specific* exceptions which you are expecting and to catch those, or not do a simple "pass". See Vincent's response, for example, where he explicitly asks only for ValueErrors and lets others propagate upwards, to be reported. (I realize these were contrived examples, but examples that don't mention this important issue risk the propagation of buggy code...) -Peter From ncoghlan at iinet.net.au Thu Jan 20 05:32:12 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 20 Jan 2005 20:32:12 +1000 Subject: Zen of Python In-Reply-To: <7xekggbrns.fsf@ruckus.brouhaha.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> Message-ID: <41EF88AC.9030703@iinet.net.au> Paul Rubin wrote: > But it's often predictable at the > beginning what the final destination is going to be. So once we can > see where it's going, why not proceed to the finish line immediately > instead of bothering with the intermediate steps? Because getting there incrementally helps to make sure you end up with the features you need, without the irrelevant baggage an overengineered solution may bring with it. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From gurpreet.sachdeva at gmail.com Thu Jan 6 04:15:24 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Thu, 6 Jan 2005 14:45:24 +0530 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: <2b7d8b420501060057270f1878@mail.gmail.com> References: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> <003801c4f3b9$af17fa20$0800a8c0@vishnu> <2b7d8b42050105232546083758@mail.gmail.com> <2b7d8b420501060057270f1878@mail.gmail.com> Message-ID: On Thu, 6 Jan 2005 14:27:40 +0530, Binu K S wrote: > I'm sorry, I didn't get what you trying to say here. Where do you see > a read altering the file? An example might help. Please try: logfile=file(r'test.txt','w+') logfile.write('datetime') Check the contents of test.txt, you will get what ever was required... Now Run: logfile=file(r'test.txt','w+') logfile.write('datetime') logfile.readlines() and check the contents of test.txt??? My doubt is that logfile.write('datetime') will write datetime that is universaly accepted but why all that junk is appending to that when I add logfile.readlines() Strange or Am I on drugs??? :o) Please Comment... Garry From bokr at oz.net Thu Jan 6 13:58:59 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 06 Jan 2005 18:58:59 GMT Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> Message-ID: <41dcf582.122188317@news.oz.net> On 05 Jan 2005 23:19:39 -0800, Paul Rubin wrote: >bokr at oz.net (Bengt Richter) writes: >> What do you think of automated secure importing/installing from a >> remote server? You know, you try to import something and it imports >> a stub that was included as a battery-place-holder and that has >> basic help info and will give you reasonable options in directing >> the installation of the full thing (or subset you are interested in). > >You mean for Python modules, in ordinary operation? I'd hate that. >For things like apt-get, used for installing nonstandard programs or >getting security updates, I guess it's about as good as one can hope >for. The user has to activate it explicitly though. I definitely >don't want my computer opening internet connections unless I >specifically ask it to. Doing otherwise is almost spyware. I agree 1000% !! Importing a stub should get you an imported stub that prints info as it imports, so you know its not functional. And just gives you the options to type help(themodule) or if you know you want to go ahead, themodule.install() -- and nothing would touch the internet until you gave a final "yes" to an "Are you sure" at the end of a what-will-happen-if-you-say-yes summary. I didn't mean any activity that you don't control. Just activity that you can control easily. > >This may sound a little extreme but my distribution philosophy is I'd >like to get closer to an environment where users normally never >install any software of any type, ever. Microsoft cornered the OS >market cornered by acheiving something pretty close to this: they >deliver Windows with no installation needed. When people buy new >computers, Windows is already on the hard drive, so the user just >turns the computer on and Windows is there. It makes a lot of sense for a "core" plus a delivered specific application base, but IMO if you try to cover the world with a monolith you will inevitably still have the problem of getting the latest version of particular packages for bug fixes or enhancements. The more you have in your giant collection the more that will be true. > >Fedora Core (what I'm running now) isn't shipped that way by any >computer makers that I know of, but it makes up for it by having lots >of applications included. So I buy a new computer, put in the >bootable Fedora DVD-ROM, and sit back for half an hour while a >one-time installation runs. That's about as close as I can get to >just turning on the new computer and having Fedora already there. > >> I don't see why every gee whiz thing has to be on your hard disk >> from the first. And for those that want a big grabbag, the stubs >> ought to be designed to to be runnable from a configured script, so >> you can turn it loose and see what's up IRL. > >If I have a 400 gig hard drive, I don't see why I need 99.99% of it >empty instead of 99.0% after I do my OS install. I don't want to >hassle over downloading stuff for hours or days at a time, or about >what components depend on other components, if the distro can just >include it. I just tried to install a Python program that uses >wxPython, except that meant I had to download both wxPython and >wxWidgets, and the installations failed because of some version >mismatch between the current wxWidgets distro and the version of GTK >included with FC3. I spent an hour or so messing with it and then >said screw it and gave up on the GUI part of that program. I'm more >technical than most users (I'm a programmer) yet this installation >stuff is too much hassle even for me. So I'd really rather that all >that stuff be pre-configured. There are several parts to those frustrations. But you are presuming that they would have been solved for you and put on a DVD with all dependency problems resolved. Ok, let's assume that. In that case, an installation stub module could just as well have the solution built into it as to what versions etc are needed to make the module work. With a large collection, you may need several versions of some support libs. To bring a large collection into version-alignment ISTM you need a version freeze across too many libraries of different kinds with different development schedules and resources to make it reliable. So you're still going to need the ability to add updates and new modules and more. I'd rather see effort going into making that process simple and reliable (and fully controlled by the user -- i.e. no unauthorized hidden internet activity!!) than to solve the same version problems for some mega DVD make file where you don't have the script and config info in a concise single-problem stub form, and can't ask here for help finding an updated stub. It's a matter of being able to limit the problem you need to solve when something particular doesn't work. When your wxPython-using program didn't work, wouldn't it have been nice to have downloaded a standard stub program (with older stub versions still available if you have an older system) and have it tell you what was missing that it needed before you decided to let it continue and get those things? Or choose not to? With broadband most apps will be ready before you can make fresh coffee, or maybe watch the Simpsons. Otherwise what? Send for a new DVD? Yes, core stuff + plenty of compatible goodies in a distro is a good idea, but problems are inevitable, and IMO it's more important to have a standard reliable way to solve problems than to have them "solved" on periodic monoliths DVDs that can't ever be problem free. > >If a system has N downloadable components that are supposedly >independent, there are 2**N combinations of them that anyone might >have installed. In reality the indepdence is never that complete, so >something can easily go wrong if you pick a combination that hasn't >been tested and debugged by someone, and there's no way to test more >than a few of the possibilities. So I'd rather that all N components >already be included with the OS so that the combination will have been >tested by the distro maintainers before the end user has to deal with You are asking a lot from these distro maintainers if you expect recent versions of everything, and for them to watch for new stuff to evaluate and include after researching compatibility problems. They aren't in the best position to do that. The author/s of the new stuff is/are. And if such authors had a standard stub module they could prepare, then distros could include those, and you would find version updates for those rather than trying to solve the integration problems yourself. And if there were still bugs, a new version would likely be posted here after some discussion. And then everyone could have an easy download of the new stub, and be able to go for coffee. I think if python.org had a trusted-software registry that could be a flat CSV text file of names, versions, urls, sizes, and md5 digests and maybe some trust level, then the stubs could access that for a standard way of finding components. Or course for a DVD distro, stubs could access the DVD rather than the internet for things at the DVD's version level. I realize this problem has been "solved" with various RPM and app-loading methods, but I think python could wrap its solution nicely. I don't think distutils and setup.py is easy enough to create (at least I have been somewhat frustrated in using it effectively), though it deals with a lot of what has to be done. >it. Hard drives and distro media (DVD) are big enough now that it's >quite reasonable for distros to include just about everything that >most users could want. Agreed for some "core" set. How shall we define what belongs in the "core?" ;-) Regards, Bengt Richter From marklists at mceahern.com Wed Jan 12 13:23:30 2005 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 12 Jan 2005 12:23:30 -0600 Subject: counting items In-Reply-To: References: Message-ID: <41E56B22.6020708@mceahern.com> It's me wrote: >Okay, I give up. > >What's the best way to count number of items in a list [that may contain lists]? > > a = [[1,2,4],4,5,[2,3]] def iterall(seq): for item in seq: try: for subitem in iterall(item): yield subitem except TypeError: yield item all = [x for x in iterall(a)] print len(all) From bokr at oz.net Mon Jan 24 23:52:12 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 25 Jan 2005 04:52:12 GMT Subject: Another scripting language implemented into Python itself? References: <1106624803.825442.73870@f14g2000cwb.googlegroups.com> Message-ID: <41f5cf0f.1750685172@news.oz.net> On 24 Jan 2005 19:46:43 -0800, "Carl Banks" wrote: [...] >> Imbed > >EMBED. > >This spelling error wouldn't bother me if I didn't work with people >whose own job title is embedded control engineer, yet who still >misspell it "imbedded." > wordnet seems to accept it as an alternative spelling (not too recent): [20:44] C:\pywk\sovm>wn imbed -over Overview of verb imbed The verb imbed has 1 sense (first 1 from tagged texts) 1. implant, engraft, embed, imbed, plant -- (to fix or set securely or deeply: "Kneeling, Cobb p lanted a sturdy knee in the small of his back,") funny that googling define:imbed gets nothing. Nor define:embed ?? I've had a number of misses in that kind of search. I wonder if it's temporarily broken (or maybe it hit a licensing snag with the various online dictionaries?) Regards, Bengt Richter From jlenton at gmail.com Wed Jan 12 12:05:14 2005 From: jlenton at gmail.com (John Lenton) Date: 12 Jan 2005 09:05:14 -0800 Subject: Iteration over two sequences In-Reply-To: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> Message-ID: <1105549514.563799.307030@z14g2000cwz.googlegroups.com> > Quite frequently, I find the need to iterate over two sequences at the > same time, and I have a bit of a hard time finding a way to do this in a > "pythonic" fashion. One example is a dot product. The straight-ahead > C-like way of doing it would be: > > def dotproduct(a, b): > psum = 0 > for i in range(len(a)): > psum += a[i]*b[i] > return psum for this particular example, the most pythonic way is to do nothing at all, or, if you must call it dotproduct, >>> from Numeric import dot as dotproduct From elbertlev at hotmail.com Mon Jan 31 15:03:49 2005 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: 31 Jan 2005 12:03:49 -0800 Subject: py-xmlrpc postpone question Message-ID: <1107201829.674563.79000@z14g2000cwz.googlegroups.com> Hi! I'm trying to use py-xmlrpc. All works fine (and very fast) in one-threaded case, but I really have to serve many clients. As advertised, py-xmlrpc supports non-blocking calls (via select). When request is received the handler is called with proper parameters. As I understood from reading the source, if rpc call can't be executed immediately (or takes long time) respond can be postponed by raising postpone exception and when respond is ready, calling queueResponse() . I wanted to have a pool of worker threads listening on a queue. In the "lengthy command handlers", post data on the queue and raise postpone. Threads from the pool respond by calling queueResponse() when rpc is done. Server trace tells me that postpone was received, but client reacts as if socket was closed (got EOS while reading). I tryed to supress default error handling on the client side by returning from OnErr() xmlrpc.ONERR_KEEP_WORK, but this kills the interpreter! What am I doing wrong? From paul at prescod.net Mon Jan 31 21:27:04 2005 From: paul at prescod.net (Paul Prescod) Date: Mon, 31 Jan 2005 18:27:04 -0800 Subject: Vancouver Python/Zope/Plone: Creating OS X Cocoa Applications Using XML and Python Message-ID: <41FEE8F8.9000906@prescod.net> February 1, 2005 Creating OS X Cocoa Applications Using XML and Python, Dethe Elza This talk will cover the use of Renaissance and Python to develop programs for OS X, focussing on both rapid application development, and ease of maintenance. Renaissance is an XML dialect for describing Cocoa (or GNUstep) user interfaces, which can be used as an alternative to Apple's binary NIB format. It grew out of the GNUstep? project and is intended for use with Objective-C, but works seamlessly from Python with the PyObjC bridge. Hosted by ActiveState ("a division of Sophos") at 580 Granville St., Vancouver From me at privacy.net Fri Jan 28 16:19:36 2005 From: me at privacy.net (JanC) Date: 28 Jan 2005 21:19:36 GMT Subject: Where can I find sample "beginner" programs to study? References: <_6CdnWIOB8AaA2fcRVn-rg@speakeasy.net> Message-ID: Todd_Calhoun schreef: > I'm trying to learn Python (and programming), and I'm wondering if > there are any places where I can find small, simple programs to study. Try: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From tjreedy at udel.edu Sat Jan 1 04:51:27 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 1 Jan 2005 04:51:27 -0500 Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> Message-ID: "JanC" wrote in message news:Xns95D132B172343JanC at 213.118.32.224... > I don't know if gmane keeps formating of messages intact when posting? > That could be an alternative too... Reading posts via gmane with Outlook Express preserves leading spaces just fine. However, OE deletes tabs regardless of what newsgroup does. The funny thing is that typing a tab gets converted to 4 spaces. Terry J. Reedy From jason at tishler.net Mon Jan 17 16:27:48 2005 From: jason at tishler.net (Jason Tishler) Date: Mon, 17 Jan 2005 16:27:48 -0500 Subject: Cygwin Popen object In-Reply-To: <1105994485.770313.141910@f14g2000cwb.googlegroups.com> References: <1105994485.770313.141910@f14g2000cwb.googlegroups.com> Message-ID: <20050117212748.GB2388@tishler.net> On Mon, Jan 17, 2005 at 12:41:25PM -0800, christiancoder wrote: > Is anybody else getting the following error with the Popen object in > cygwin? The code works fine in windows and linux. > > File "d:\atg\personal\python\buildroot\util.py", line 100, in System > pipe = subprocess.Popen( command, shell=True, > stdout=subprocess.PIPE, stderr=subprocess.STDOUT, > universal_newlines=True ) > File "/usr/local/lib/python2.4/subprocess.py", line 554, in __init__ > errread, errwrite) > File "/usr/local/lib/python2.4/subprocess.py", line 914, in > _execute_child > self.pid = os.fork() > OSError: [Errno 11] Resource temporarily unavailable Try rebasing your Cygwin installation. See the README: /usr/share/doc/Cygwin/python-2.4.README for more information. Does it solve your problem? Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From invalidemail at aerojockey.com Fri Jan 14 11:02:19 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 14 Jan 2005 08:02:19 -0800 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: <34q69pF4dvkhqU1@individual.net> References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> <34q69pF4dvkhqU1@individual.net> Message-ID: <1105718539.916246.174950@z14g2000cwz.googlegroups.com> Tim Jarman wrote: > IANA French person, but I believe that Belgians are traditionally > regarded as stupid in French culture, so "Belgian logic" would be > similar to "Irish logic" for an English person. (Feel free to insert > your own cultural stereotypes as required. :) Ok. http://www.urbandictionary.com/define.php?term=belgian&r=f -- CARL BANKS From jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com Sun Jan 9 17:25:19 2005 From: jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com (Miklós P) Date: Sun, 9 Jan 2005 23:25:19 +0100 Subject: Guild of Python consultants? References: Message-ID: "Peter Hansen" wrote in message news:rtednbVd1tsF4XzcRVn-oQ at powergate.ca... > I also know of many people (myself included) who restrict the term > to those who have a deep expertise in one or more areas and who > look for projects where they can be brought in to apply that > expertise, usually by telling the customer what to do (or what > not to do any more, perhaps). This sort of work can be hourly, > or quite often daily or even at a fixed price (say, for specialized > "emergency" troubleshooting, or for a design task). > > (The second type will take on jobs that the former would take, > often grudgingly if work is scarce, while the former are rarely > qualified to take on the sort of work that interests the latter.) > > Which type do you mean? Well, I consider myself a consultant of the second kind. Using Python for maths/stats (often meaning decision support systems) or science related custom software is what I prefer to do .. But I also tend to enjoy "firefighting" web projects because they pay well and they are never boring.. rather on the contrary.. :-) ...and I second what you said in parenthesis. So my interest follows. Though one could surely have two divisions of a huge guild. :-)) Best, Mikl?s From steve at holdenweb.com Mon Jan 31 14:20:10 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 14:20:10 -0500 Subject: Relocatable binary installs.... In-Reply-To: References: <1107195180.462949.222980@z14g2000cwz.googlegroups.com> <41FE7F26.1090209@holdenweb.com> Message-ID: <41FE84EA.3030501@holdenweb.com> Fredrik Lundh wrote: > Steve Holden wrote: > > >>>>Is there a way to make a relocateable python binary... that is... a >>>>python installation that won't care where it is on the machine... and >>>>won't care if it gets put somewhere else besides / ? >>> >>> >>>the standard CPython interpreter is 100% "relocatable". If you think >>>it isn't, you have to be a bit more specific. >>> >> >>Is it possible that you are using "relocatable" in the standard sense of "code can be located >>anywhere in physical memory", where the OP is using the same term to mean "can live anywhere in >>the filestore"? > > > nope. > > >>I suspect the problem the OP is seeing is because the --prefix configuration parameter will cause >>an interpreter to look in a specific place for standard libraries. Clearly if you "relocate" the >>libraries to another directory entirely then an interpreter without any further nouse (and no >>symbolic links to help it) is going to crap out badly. > > > clearly? > > [fredrik at brain build] mv python2.3 /tmp > [fredrik at brain build] mkdir /tmp/lib > [fredrik at brain build] mv lib /tmp/lib/python2.3 > [fredrik at brain build] cd /tmp > [fredrik at brain tmp]$ ./python2.3 > >>>>import sys >>>>sys.prefix > > '/tmp' > >>>>sys.path > > ['', '/tmp/lib/python23.zip', '/tmp/lib/python2.3', ...] > > [fredrik at brain tmp]$ mkdir spam > [fredrik at brain tmp]$ mv python2.3 spam > [fredrik at brain tmp]$ mv lib spam > [fredrik at brain tmp]$ cd spam/ > [fredrik at brain spam]$ ./python2.3 > >>>>import sys >>>>sys.prefix > > '/tmp/spam' > >>>>sys.path > > ['', '/tmp/spam/lib/python23.zip', '/tmp/spam/lib/python2.3', ...] > > > [fredrik at brain spam]$ mkdir bin > [fredrik at brain spam]$ mv python2.3 bin > [fredrik at brain spam]$ bin/python2.3 > >>>>import sys >>>>sys.prefix > > '/tmp/spam' > > > [fredrik at brain spam]$ cd bin > [fredrik at brain bin]$ ./python2.3 > >>>>import sys >>>>sys.prefix > > '/tmp/spam' > > [fredrik at brain fredrik]$ export PATH=/tmp/spam/bin:$PATH > [fredrik at brain bin]$ cd > [fredrik at brain fredrik]$ python2.3 > >>>>import sys >>>>sys.prefix > > '/tmp/spam' > > > and so on... > Well, OK, maybe it's not quite as clear as I thought :-) regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From bokr at oz.net Mon Jan 24 15:35:09 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 24 Jan 2005 20:35:09 GMT Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) References: <41f325b5.1576259210@news.oz.net> <6I2dnYLoXdcTmGncRVn-vw@comcast.com> <41f490e8.1669238027@news.oz.net> Message-ID: <41f5568c.1719834331@news.oz.net> On Mon, 24 Jan 2005 00:31:17 -0700, Steven Bethard wrote: >Bengt Richter wrote: >> So, e.g., for >> >> >>> presets = dict(a=1, b=2, deftime=__import__('time').ctime()) >> >> in the decorator args, the next version will act as if the decorated >> function had the source code >> >> >>> print '%s = __frompresets__' % ', '.join(sorted(presets)) >> a, b, deftime = __frompresets__ >> >> for the current version, except that it will be hidden. > >Cool! Keep us posted. I assume you'll put this into the Cookbook? > Not ready for prime time, I guess, but I made a module that does presets and also adjusts parameters and count to do currying without nested function calling in the curried function. >>> from presets import presets, curry >>> @presets(verbose=True, a=1, b=2, deftime=__import__('time').ctime()) ... def foo(): ... print (a, b) ... print deftime ... presets: -- "name(?)" means name may be unused a = 1 b = 2 deftime = 'Mon Jan 24 12:16:07 2005' >>> foo() (1, 2) Mon Jan 24 12:16:07 2005 >>> @curry(verbose=True, y=444) ... def bar(x=3, y=4): ... return x*y ... presets: -- "name(?)" means name may be unused y = 444 >>> bar(2) 888 >>> bar(2, 3) Traceback (most recent call last): File "", line 1, in ? TypeError: bar() takes at most 1 argument (2 given) >>> bar() 1332 >>> import dis >>> dis.dis(bar) 1 0 LOAD_CONST 1 (444) 3 STORE_FAST 1 (y) 3 6 LOAD_FAST 0 (x) 9 LOAD_FAST 1 (y) 12 BINARY_MULTIPLY 13 RETURN_VALUE >>> dis.dis(foo) 1 0 LOAD_CONST 1 ((1, 2, 'Mon Jan 24 12:16:07 2005')) 3 UNPACK_SEQUENCE 3 6 STORE_FAST 0 (a) 9 STORE_FAST 1 (b) 12 STORE_FAST 2 (deftime) 3 15 LOAD_FAST 0 (a) 18 LOAD_FAST 1 (b) 21 BUILD_TUPLE 2 24 PRINT_ITEM 25 PRINT_NEWLINE 4 26 LOAD_FAST 2 (deftime) 29 PRINT_ITEM 30 PRINT_NEWLINE 31 LOAD_CONST 0 (None) 34 RETURN_VALUE Now I have to see whether I can optimize the result with Raymond's make_constants as two decorators in a row... (pre without keyword args is an alias for Raymond's make_constants, just handy for the moment) >>> from pre import pre >>> @pre(verbose=True) ... @presets(verbose=True, a=1, b=2, deftime=__import__('time').ctime()) ... def foo(): ... print (a, b) ... print deftime ... print __name__ ... presets: -- "name(?)" means name may be unused a = 1 b = 2 deftime = 'Mon Jan 24 12:29:21 2005' __name__ --> __main__ >>> foo() (1, 2) Mon Jan 24 12:29:21 2005 __main__ >>> dis.dis(foo) 1 0 LOAD_CONST 1 ((1, 2, 'Mon Jan 24 12:29:21 2005')) 3 UNPACK_SEQUENCE 3 6 STORE_FAST 0 (a) 9 STORE_FAST 1 (b) 12 STORE_FAST 2 (deftime) 3 15 LOAD_FAST 0 (a) 18 LOAD_FAST 1 (b) 21 BUILD_TUPLE 2 24 PRINT_ITEM 25 PRINT_NEWLINE 4 26 LOAD_FAST 2 (deftime) 29 PRINT_ITEM 30 PRINT_NEWLINE 5 31 LOAD_CONST 2 ('__main__') 34 PRINT_ITEM 35 PRINT_NEWLINE 36 LOAD_CONST 0 (None) 39 RETURN_VALUE Regards, Bengt Richter From steve at holdenweb.com Sun Jan 9 17:19:31 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 09 Jan 2005 17:19:31 -0500 Subject: Python serial data aquisition In-Reply-To: References: Message-ID: Flavio codeco coelho wrote: > Hi, > > I am using pyserial to acquire data from an A/D converter plugged to > my serial port. > > my hardware represents analog voltages as 12bit numbers. So, according > to the manufacturer, this number will be stored in two bytes like > this; > |-------------bits(1-8)-----------| > Byte1: x x x n1 n2 n3 n4 n5 > Byte2: x n6 n7 n8 n9 n10 n11 n12 > > where x is some other information, and nx are the digits of my number. > > My problem is to how to recover my reading from these bytes, since > pyserial gives me a character (string) from each byte... I dont know > how to throw away the unneeded bits and concatenate the remaining > bits to form a number... > > > Fl?vio Code?o Coelho Try something like (here I'm assuming that n12 is the least-significant bit) (untested): ((ord(byte1) & 31) << 7 ) + (ord(byte2) & 127) This takes the rightmost five bits from the first byte's integer value, shifts them up seven bits, and then adds the rightmost seven bits of the second byte's integer value. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From aaronwmail-usenet at yahoo.com Thu Jan 27 09:19:22 2005 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 27 Jan 2005 06:19:22 -0800 Subject: On benchmarks, heaps, priority queues References: Message-ID: <1106835562.598569.211370@c13g2000cwb.googlegroups.com> me> PQPython23 - the Lib implementation me> PQ0 - my insertion sort based variant me> PQueue - my "heap" based variant me> (like PQPython23, but different). Tim D: > First of all, you should be running these benchmarks using Python 2.4. > heapq is considerably faster there ... (Raymond Hettinger rewrote it all > in C). > http://www.python.org/2.4/highlights.html > Tim Delaney WHOOPS. Okay after getting past my initial embarassment I tried this, and it turns out it doesn't make much of a difference. In particular PQ0 is still always better if you intersperse many deletes with inserts or in all cases of size <10000. Of course other machines will probably have different characteristics (and yes my py24 contains the _heapq extension module). The nasty behavior of PQ0 for insertBench at >100000 I think has to do with large list reallocation. Hmmm. This makes me wonder if my bplustree implementation(s) are faster than the bsddb modules too... -- Aaron Watters === SOMETHING WENT WRONG IN AIRLINE CRASH, EXPERT SAYS -- a "real life headline" (that'll be $50,000, please) ENCLOSURE: Python 2.4 run of http://xsdb.sourceforge.net/bench/pq3.py on my machine. ======================= BENCHMARKS FOR 1000 insertBench __main__.PQPython23 on 1000 elapsed 0.0199999809265 got 1000 __main__.PQ0 on 1000 elapsed 0.00999999046326 got 1000 __main__.PQueue on 1000 elapsed 0.0300002098083 got 1000 mixBench __main__.PQPython23 on 1000 elapsed 0.0 got 502 __main__.PQ0 on 1000 elapsed 0.00999999046326 got 502 __main__.PQueue on 1000 elapsed 0.0 got 502 BENCHMARKS FOR 10000 insertBench __main__.PQPython23 on 10000 elapsed 0.260999917984 got 10000 __main__.PQ0 on 10000 elapsed 0.210000038147 got 10000 __main__.PQueue on 10000 elapsed 0.359999895096 got 10000 mixBench __main__.PQPython23 on 10000 elapsed 0.0700001716614 got 5003 __main__.PQ0 on 10000 elapsed 0.050999879837 got 5003 __main__.PQueue on 10000 elapsed 0.0699999332428 got 5003 BENCHMARKS FOR 100000 insertBench __main__.PQPython23 on 100000 elapsed 3.26499986649 got 100000 __main__.PQ0 on 100000 elapsed 7.88100004196 got 100000 __main__.PQueue on 100000 elapsed 4.81699991226 got 100000 mixBench __main__.PQPython23 on 100000 elapsed 0.65099978447 got 50000 __main__.PQ0 on 100000 elapsed 0.461000204086 got 50000 __main__.PQueue on 100000 elapsed 0.661000013351 got 50000 BENCHMARKS FOR 200000 insertBench __main__.PQPython23 on 200000 elapsed 6.99000000954 got 200000 __main__.PQ0 on 200000 elapsed 28.5010001659 got 200000 __main__.PQueue on 200000 elapsed 10.3849999905 got 200000 mixBench __main__.PQPython23 on 200000 elapsed 1.29099988937 got 100001 __main__.PQ0 on 200000 elapsed 0.922000169754 got 100001 __main__.PQueue on 200000 elapsed 1.34200000763 got 100001 BENCHMARKS FOR 300000 insertBench __main__.PQPython23 on 300000 elapsed 11.6970000267 got 300000 __main__.PQ0 on 300000 elapsed 70.3009998798 got 300000 __main__.PQueue on 300000 elapsed 16.8840000629 got 300000 mixBench __main__.PQPython23 on 300000 elapsed 1.93300008774 got 150000 __main__.PQ0 on 300000 elapsed 1.39199995995 got 150000 __main__.PQueue on 300000 elapsed 1.96300005913 got 150000 BENCHMARKS FOR 400000 insertBench __main__.PQPython23 on 400000 elapsed 15.5419998169 got 400000 __main__.PQ0 on 400000 elapsed 127.253000021 got 400000 __main__.PQueue on 400000 elapsed 23.0629999638 got 400000 mixBench __main__.PQPython23 on 400000 elapsed 2.64399981499 got 200000 __main__.PQ0 on 400000 elapsed 1.95300006866 got 200000 __main__.PQueue on 400000 elapsed 2.73399996758 got 200000 BENCHMARKS FOR 500000 insertBench __main__.PQPython23 on 500000 elapsed 20.8800001144 got 500000 __main__.PQ0 on 500000 elapsed 246.954999924 got 500000 __main__.PQueue on 500000 elapsed 35.9609999657 got 500000 mixBench __main__.PQPython23 on 500000 elapsed 3.55599999428 got 250000 __main__.PQ0 on 500000 elapsed 2.48300004005 got 250000 __main__.PQueue on 500000 elapsed 3.48500013351 got 250000 BENCHMARKS FOR 1000000 insertBench __main__.PQPython23 on 1000000 elapsed 44.6940000057 got 1000000 __main__.PQ0 on 1000000 elapsed 1400.5940001 got 1000000 __main__.PQueue on 1000000 elapsed 70.6619999409 got 1000000 mixBench __main__.PQPython23 on 1000000 elapsed 6.63000011444 got 500001 __main__.PQ0 on 1000000 elapsed 4.73600006104 got 500001 __main__.PQueue on 1000000 elapsed 6.82999992371 got 500001 From cpl.19.ghum at spamgourmet.com Thu Jan 27 04:07:09 2005 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Thu, 27 Jan 2005 09:07:09 +0000 (UTC) Subject: py2exe problem References: <41f7213c$0$2343$a1866201@visi.com> Message-ID: Thomas, > Would the above (include all encodings stuff by default) be a good > solution, or do you have other ideas? I assume a good solution would involve switching pythons default from "ASCII" to "UNICODE" :) But ... as far as py2exe is concerned, yeah, I think it would be helpfull to include all encoding by default (undefaultable, of course), or at least provide in the very very first simple setup.py example the include encodings.* stuff. Harald Armin From mcfletch at rogers.com Sat Jan 22 13:44:06 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sat, 22 Jan 2005 13:44:06 -0500 Subject: Class introspection and dynamically determining function arguments In-Reply-To: <41f2212f.1509565800@news.oz.net> References: <41f18d10.1471646806@news.oz.net> <41f2212f.1509565800@news.oz.net> Message-ID: <41F29EF6.7030909@rogers.com> Bengt Richter wrote: >On Fri, 21 Jan 2005 20:23:58 -0500, "Mike C. Fletcher" wrote: > > > >>>On Thu, 20 Jan 2005 11:24:12 -0000, "Mark English" wrote: >>> >>> ... >Does the BasicProperty base class effectively register itself as an observer >of subclass properties and automatically update widgets etc., a la Delphi >data-driven visual components? I've thought of doing a light-weight form >extension class that would use a text (maybe CSV) definition to control >contruction, and easy programmatic manipulation by python of the definition >parameters, like a stripped-down version of the text view of Delphi forms. >It could also be done via Tkinter, to prototype it. It would be interesting >to allow dragging widgets and edges around in Tkinter and round-trip the parameter >changes automatically into the text representation. A little (well, ok, a fair amount ;-) >further and you'd have a drag-n-drop GUI design tool. But don't hold your breath ;-) > > BasicProperty itself doesn't register as an observable/observer, BasicProperty is the lowest-level of the software stack, so it allows you to override and provide notification (e.g. using PyDispatcher) on property-setting. ConflictSolver (old project to create a room scheduler) used that to do automatic updating of widgets in the wxPython UI based on Model changes (though I don't remember if it was per-property or per-object). My goal for the wxoo project was to provide hooks in the wxPython GUI designers for dropping in property sheets and/or property-aware controls such that you would have the equivalent of "data aware" controls in VB or Access (keeping in mind that BasicProperty properties can also represent fields in database rows). Aside: The VRML97 field class in OpenGLContext does notifications for every set (using PyDispatcher), btw. It's a little more limited in its scope (focus on 3D data-types), but the effect is what allows the scenegraph to cache and then rebuild its internal rendering structures with very low overhead. ... >>Anyway, if you aren't interested in BasicProperty for this task; another >>project on which I work, PyDispatcher provides fairly robust mechanism >>(called robustApply) for providing a set of possible arguments and using >>inspect to pick out which names match the parameters for a function in >>order to pass them in to the function/method/callable object. That >>said, doing this for __init__'s with attribute values from an object's >>dictionary doesn't really seem like the proper way to approach the problem. >> >> >Sounds like a workaround for parameter passing that maybe should have been >keyword-based? > > Not as such, that is, not a workaround, and it shouldn't be keyword based ;) . The problem with using keyword-based passing is that every method needs to be written with this awareness of the keyword-handling structures. You spread pointless implementation details throughout your codebase. PyDispatcher lets you write very natural functions for dealing with events without having every function use **named parameters. I've now written quite a few such systems, and I'm currently balanced between two approaches; that taken in PyDispatcher (define only natural parameters, have the system figure out how to deliver them to you), and that taken in OpenGLContext (define an event-class hierarchy which encapsulates all information about the events). The PyDispatcher approach is nice in that it makes simple things very simple. You want access to the "lastValue" parameter in the "environment" of the event and nothing else, you define your function like so: def handler( lastValue ): print 'got last value', lastValue which works very nicely when you're early in the development of a system, or are linking multiple systems. There's no need to do all sorts of extra work defining event hierarchies, you can often leave given handlers entirely alone during refactoring if they aren't dealing with the changed properties in the event-environment. The OpenGLContext approach is more appropriate when you have a large system (such as OpenGLContext), where defining an event class is a trivial task compared to the total system expenditure. It allows for such things as putting methods on the event objects to make debugging easy, and providing common functionality. It starts to show it's worth when you start needing to reason about the phenomena of events themselves, rather than just about the phenomena the events represent (e.g. when you need to cache, delay, or reorder events). The named argument passing approach has the disadvantage that every function must be written with knowledge of that use of named arguments: def handler( lastValue, **named ): print 'got last value', lastValue when using such systems in the past I've often wound up with errors deep in an application where some seldom-called callback didn't have a **named parameter, so the system would abort (well, log an error) trying to call it. Is it a huge overhead? No. But its unnecessary if you've got a tool that takes care of that "implementation-level" detail for you. Compared to robustApply, the difference is pretty minimal. If you define a **named parameter, for instance, you will get the remainder of the robustApply environment passed in. In another lifetime, you could imagine these systems being written as wrappers that added a nested scope around the definition of the function such that the scope forwarded unresolved name references to the environment of the event (non-lexical scoping), but that would lack the explicitness of passing in the arguments from the environment and would, I suppose be evil in a quite non-trivial way. Peace, and have fun, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From itsme at yahoo.com Wed Jan 5 17:29:31 2005 From: itsme at yahoo.com (It's me) Date: Wed, 05 Jan 2005 22:29:31 GMT Subject: Python 2.4 on Windows XP References: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> <10toje56oiebq24@corp.supernews.com> <10ton02dur41v0b@corp.supernews.com> Message-ID: Thanks, Jeff. That works. "Jeff Shannon" wrote in message news:10ton02dur41v0b at corp.supernews.com... > It's me wrote: > > > In my case, there is *no* error message of any kind. When I run pythonw.exe > > from the python23 directory, the screen blinked slightly and goes back to > > the command prompt. > > Right -- pythonw.exe is a console-less interpreter. Having no > console, it doesn't have an interactive mode, and since you didn't > give it a script to run, it simply started, found nothing to do, and > then terminated itself. > > You need to run idle.pyw, *not* pythonw.exe. The idle.pyw script runs > inside the pythonw.exe interpreter, but the latter can't do anything > without instructions. > > Jeff Shannon > Technician/Programmer > Credit International > From miki.tebeka at zoran.com Sun Jan 16 06:44:27 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Sun, 16 Jan 2005 13:44:27 +0200 Subject: video analysis with python In-Reply-To: References: Message-ID: <20050116114407.GE3276@zoran.com> Hello Ashot, > I need to write a video analysis tool which extracts statistics from > microsocope video. Essentially what I need is to translate the video data > into numerical matrices. I have been using Python for the past 1.5 years > anytime I could for absolutely everything, because it has every library > imaginable... Alas, I can not find a library for decoding video/using > codecs. The only solution I have been able to come up with is to create > an image sequence and load those in with PIL, however this is not really > feasible as the images are too large (nor is it proffessional). > > Is there a library or project that I have missed, or is there a way > to incorporate something like vfw.lib directly? If there isn't I think > this would be a pretty large whole in Python's arsenal. Thanks in advance > for any help. 1. There is PyMedia (http://pymedia.org/) 2. Maybe you can use the code from VLC (http://www.videolan.org/vlc/) (using SWIG/PyBoost/Pyrex ...) HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From jzgoda at gazeta.usun.pl Thu Jan 20 15:10:35 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Thu, 20 Jan 2005 21:10:35 +0100 Subject: ElementTree cannot parse UTF-8 Unicode? In-Reply-To: <1106233137.588111.216480@z14g2000cwz.googlegroups.com> References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> <1106230846.455765.7310@c13g2000cwb.googlegroups.com> <1106233137.588111.216480@z14g2000cwz.googlegroups.com> Message-ID: Erik Bethke wrote: > So why are there non-UNICODE versions of wxPython??? To save memory or > something??? Win95, Win98, WinME have problems with unicode. GTK1 does not support unicode at all. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From steve at holdenweb.com Mon Jan 17 10:33:07 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 10:33:07 -0500 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Antoon Pardon wrote: > Op 2005-01-17, Steve Holden schreef : > >>Antoon Pardon wrote: >> >> >>>I don't see a big difference between these principles >>>and the hash key principle, so in the end may be we >>>should just stick with the more general principle: >>> >>> Don't use mutables! >>> >>> >>>and be done with it. >>> >> >>http://redwing.hutman.net/~mreed/warriorshtm/tirelessrebutter.htm >> >>regards >> Steve > > > I you want to play it like this > > http://redwing.hutman.net/~mreed/warriorshtm/crybaby.htm > Hey, I'm not crying, or trying to play it any particular way. It's a free Internet, and you are (more than) welcome to your opinions. Personally I'd say I'm actually more of a combination of http://redwing.hutman.net/~mreed/warriorshtm/diplomat.htm and http://redwing.hutman.net/~mreed/warriorshtm/evilclown.htm, with added touches of http://redwing.hutman.net/~mreed/warriorshtm/garble.htm and possibly http://redwing.hutman.net/~mreed/warriorshtm/toxicgranny.htm Whereas I also detect touches of http://redwing.hutman.net/~mreed/warriorshtm/ferouscranus.htm in your posts. It must be nice to *never* be wrong :-). Your resemblance to http://redwing.hutman.net/~mreed/warriorshtm/filibuster.htm, however, makes me wish you could be right rather more succinctly. Mostly, though, I was trying to say that I found your nitpicking insistence on terminological exactitude, even when giving advice to those new to the language, both inappropriate and tedious in the extreme. Have a nice day :-) regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From Serge.Orlov at gmail.com Fri Jan 14 17:45:49 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: Fri, 14 Jan 2005 22:45:49 +0000 (UTC) Subject: oddities in the datetime module References: <41e79a1a$0$264$edfadb0f@dread12.news.tele.dk> <41e84175$0$258$edfadb0f@dread12.news.tele.dk> Message-ID: Max M wrote: > Serge Orlov wrote: >> Max M wrote: > >> Yes, you did. datetime.timetuple is those who want *time module* >> format, you should use datetime.data, datetime.time, datetime.year >> and so on... As they say, if the only tool you have is timetuple, everything >> looks like tuple Try this: >> >>>>> dt = datetime(2005, 1, 1, 12, 0, 0) >>>>> dt.date() >> >> datetime.date(2005, 1, 1) > > This doesn't solve it. I don't think you understand my issue. I understand, but I don't think it's something that should be solved. Especially date(*dt.timetuple()[:3]) > class my_datetime(datetime): > > def __add__(self, other): > result = datetime.__add__(self, other) > return my_datetime(result.timetuple()[:6]) > What about: def __add__(self, other): result = datetime.__add__(self, other) return my_datetime.fromdatetime(result) Serge. From jjl at pobox.com Sat Jan 29 07:07:19 2005 From: jjl at pobox.com (John J. Lee) Date: 29 Jan 2005 12:07:19 +0000 Subject: cookielib and urllib2: thread-safe? References: Message-ID: <87vf9gv3pk.fsf@pobox.com> Alex Hunsley writes: > I'm writing a test script in python for pulling web pages from a web > server using urllib2 and cookielib. Since the main thing I am testing > is what happens when concurrent requests are made to the web server, I > need to make several requests concurrently, which I'll do from > different threads in my python script. So the important question is: > are cookielib and urllib2 thread safe? Are there any precautions that > apply to using these libs in a multi-threaded context? urllib2: For HTTP, yes, AFAIK. For other protocols, eg. FTP, perhaps not. cookielib: No. It's currently thread-broken, simply because I've never had reason to do threaded stuff with it. There is thread synchronization code in there, but I have little doubt that it's broken, because it's untested (I should have removed the synchronization code entirely, in fact, since nobody volunteered to test & fix before release: unfortunately the first beta caught me by surprise...). I won't be making it threadsafe, so don't wait for me to do it. I'm happy to help others do so. Nothing especially hard for somebody with plenty of thread experience to do, AFAIK. I had thought part of a patch had gone in which stated this thread-unsafety very prominently in the cookielib module docs, but it seems that never happened, or at least not in time for 2.4.0 -- eek! John From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Jan 13 07:26:23 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Thu, 13 Jan 2005 13:26:23 +0100 Subject: Free python server. References: Message-ID: <41e66aa0$0$25801$8fcfb975@news.wanadoo.fr> Hi ! Server, web ? Files server ? Web-services server ? XML-RPC server ? Mail-server ? Newsgroups server ? SGBD server ? Object server ? Persistance server ? Restaurant server ? or ALL ? From http Fri Jan 14 01:19:17 2005 From: http (Paul Rubin) Date: 13 Jan 2005 22:19:17 -0800 Subject: Pickled text file causing ValueError (dos/unix issue) References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> Message-ID: <7xk6qga5y2.fsf@ruckus.brouhaha.com> Open the file on windows for writing with "wb" mode, the b is for binary. From dave.benjamin at gmail.com Thu Jan 27 11:30:41 2005 From: dave.benjamin at gmail.com (Dave Benjamin) Date: Thu, 27 Jan 2005 09:30:41 -0700 Subject: python without OO In-Reply-To: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: Davor wrote: > Is it possible to write purely procedural code in Python, or the OO > constructs in both language and supporting libraries have got so > embedded that it's impossible to avoid them? Also, is anyone aware of > any scripting language that could be considered as "Python minus OO > stuff"? (As you can see I'm completely new to Python and initially > believed it's a nice&simple scripting language before seeing all this > OO stuff that was added in over time) Many people have answered your question already, but I thought I would share my opinion as well, since I think I understand where you are coming from. What attracted me to Python was not OO at all but the fact that it was somewhat similar to PHP (which I was using heavily at the time) but allowed me to encode certain higher-order programming techniques that PHP simply could not express. In short, I had become interested in functional programming after reading David Mertz's "Charming Python" tutorials, and after x attempts at trying to port the ideas to PHP, I finally gave up in frustration and started learning Python. At the time, I was decidedly anti-OO. I grew up around a very liberal, punk-rock, nonconformist culture, and the amount of hype around OO made it too easy to hate (and, I suppose, it still does). PHP at the time was 90% procedural; the prevaling attitude (which seems to have changed with the advent of PHP5) was that procedural code is all you need to solve most problems. With web scripting, it kind of makes sense, because (IMHO) objects really don't have much value unless you can hold onto them long enough for them to be useful, and many web scripts just pipe data from one place to another. Packing the data into objects is kind of like putting your possessions into boxes so that you can move them from one room to another and immediately unpack. So, I guess you could say, I learned Python in spite of its rich support for OO. =) It wasn't until I had to implement a large (to me), complex, graphical user interface, that I finally had to get off of my soapbox and realize that I had no better way to create sophisticated GUIs than OO. There are surely non-OO ways to build fancy GUIs, like functional-reactive programming, but a) I don't understand them, and b) I had to get my project done, and used the tools I had and the techniques I knew. At that time, I started learning about Smalltalk and Alan Kay's emphasis on the "messaging" aspect of OO, and it started making a lot more sense. One of the most difficult tasks sometimes is getting various parts of the screen to update when the user changes a field or clicks a button--in a way that is manageable and doesn't devolve into spaghetti. Aside from GUIs, however, I am rarely confronted with a task where I *need* OO. As a method for encoding abstract data types, it works, but it seems like more fashion than substance. As many have pointed out, the difference between "method(obj, args)" and "obj.method(args)" is subtle, and often inconsequential. In Python, you can program with just modules and functions/procedures, and never bother with the fact that you are using objects. Sure, a module is an object, and so is a procedure, but it's not all up in your face like, say, Java's arcane restriction that everything belong to some class. It has been said of Perl programmers that they often dislike abstraction. Sometimes, I really sympathize with this viewpoint. I hate having to use a class that offers no value to the problem whatsoever, merely because an API is hard-wired to use instances of that class. No abstraction can often be better than a bad abstraction, and when it comes to debugging, the last thing you want is a bunch of black boxes. These days, I do use classes and objects in Python, but mainly as a code organization technique, and only when I actually want my code organized that way. I tend to start with the problem at hand, building procedures to remove redundancy and keep my code small and simple. If I start noticing that a lot of procedures revolve around a particular data structure, I refactor them into a class. This way, I avoid creating abstractions that don't fit. It's much more mechanical than any feigned attempt at "modeling the real world". I think that functional programming (FP) is a very powerful methodology that can solve a lot of the same problems as OO, and does some things a lot better. FP and OO can live in harmony to some extent, but there are some places where they contradict each other. For instance, FP offers a mind-blowingly powerful tool called pattern matching, which is like a switch/case statement on steroids. OO dogma insists that this "violates encapsulation", and that any form of switch/case is evil... replace conditional with polymorphism... replace conditional with polymorphism... replace conditional with polymorphism... repl On the other hand, implementing something as seemingly simple as a "__str__" method in functional languages can be surprisingly non-trivial. The lesson to be learned here is that each methodology (including strctures/procedural) has its strong points and weak points, and there are always tradeoffs to be made. OO's biggest strong point is that a lot of people grok it, so it's a fashionable and friendly user interface for a programmer. Python in particular emphasizes this point with its no-nonsense, lightweight approach to defining classes and using objects. However, and this really the main point I wanted to make: *no* paradigm is sufficient to solve any interesting problem. I have gotten sucked into coutless language and paradigm pissing matches only to go back to my desk and try to finish a project I'm working on and realize that (gasp!) programming is still hard. It never stopped being hard! And sometimes the methodologies just create additional work (cf. jwz's comment on regular expressions: "now you have two problems"). The best way to crack through tough problems is to learn as many methods and techniques as you can, and develop an intuition for "the right tool for the job". What matters most is that you solve the problem at hand, in a way that people can hopefully understand and maintain later. Good luck, Dave From klachemin at comcast.net Sat Jan 22 01:08:59 2005 From: klachemin at comcast.net (Kamilche) Date: 21 Jan 2005 22:08:59 -0800 Subject: Reload Tricks In-Reply-To: References: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> Message-ID: <1106374139.853129.73310@z14g2000cwz.googlegroups.com> Would it be possible to just not copy any attribute that starts and ends with '__'? Or are there some important attributes being copied? From merkosh at hadiko.de Fri Jan 28 07:30:20 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Fri, 28 Jan 2005 13:30:20 +0100 Subject: example needed: sip + Qt Message-ID: Hi, can someone provide me with a running example for subclassing QWidget (or something similarly simple) in C++ and then creating SIP (4.x+) bindings for in for Python (2.3+)? I am looking for something I can start of with and work my way towards more complicated stuff (with Qt). The QLabel example in the SIP reference manual yields syntax errors for me. Same with: http://www.pegasus.rutgers.edu/~elflord/unix/siptute/subclass_example.tgz thanks, Uwe From ehenriqu at gmail.com Thu Jan 20 10:52:27 2005 From: ehenriqu at gmail.com (Eduardo Henriquez A.) Date: Thu, 20 Jan 2005 11:52:27 -0400 Subject: Python-list Digest, Vol 16, Issue 324 In-Reply-To: <20050120144143.7F2DB1E4011@bag.python.org> References: <20050120144143.7F2DB1E4011@bag.python.org> Message-ID: <810c6a5805012007521ea04edf@mail.gmail.com> On Thu, 20 Jan 2005 15:41:43 +0100 (CET), python-list-request at python.org wrote: > Send Python-list mailing list submissions to > python-list at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to > python-list-request at python.org > > You can reach the person managing the list at > python-list-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Python-list digest..." > > > Today's Topics: > > 1. Re: Class introspection and dynamically determining function > arguments (Diez B. Roggisch) > 2. Re: xml parsing escape characters (Luis P. Mendes) > 3. Problem in importing MySQLdb (Gurpreet Sachdeva) > 4. Re: Problem in importing MySQLdb (deelan) > 5. Re: mod_python friendly isps in europe (Daniel Bowett) > 6. Re: xml parsing escape characters (Kent Johnson) > 7. Re: Zen of Python (Steve Holden) > 8. Re: Freezing a mutable (was Re: lambda) (Antoon Pardon) > 9. Re: iteritems() and enumerate() (Steve Holden) > 10. Re: ElementTree cannot parse UTF-8 Unicode? (Erik Bethke) > 11. Re: ElementTree cannot parse UTF-8 Unicode? (Fredrik Lundh) > > > > ---------- Forwarded message ---------- > From: "Diez B. Roggisch" > To: python-list at python.org > Date: Thu, 20 Jan 2005 13:50:37 +0100 > Subject: Re: Class introspection and dynamically determining function arguments > Nick Coghlan wrote: > > > > If this only has to work for classes created for the purpose (rather than > > for an arbitrary class): > > > > Certainly a step into the direction I meant - but still missing type > declarations. And that's what at least I'd like to see - as otherwise you > don't know what kind of editing widget to use for a property. > -- > Regards, > > Diez B. Roggisch > > > > ---------- Forwarded message ---------- > From: "Luis P. Mendes" > To: python-list at python.org > Date: Thu, 20 Jan 2005 13:05:59 +0000 > Subject: Re: xml parsing escape characters > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > this is the xml document: > > > <DataSet> > ~ <Order> > ~ <Customer>439</Customer> > (... others ...) > ~ </Order> > </DataSet> > > When I do: > > print xmldoc.toxml() > > it prints: > > <DataSet> > ~ <Order> > ~ <Customer>439</Customer> > > ~ </Order> > </DataSet> > > __________________________________________________________ > with: stringNode = xmldoc.childNodes[0] > print stringNode.toxml() > I get: > <DataSet> > ~ <Order> > ~ <Customer>439</Customer> > > ~ </Order> > </DataSet> > ______________________________________________________________________ > > with: DataSetNode = stringNode.childNodes[0] > print DataSetNode.toxml() > > I get: > > <DataSet> > ~ <Order> > ~ <Customer>439</Customer> > > ~ </Order> > </DataSet> > _______________________________________________________________- > > so far so good, but when I issue the command: > > print DataSetNode.childNodes[0] > > I get: > IndexError: tuple index out of range > > Why the error, and why does it return a tuple? > Why doesn't it return: > <Order> > <Customer>439</Customer> > > </Order> > ?? > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.2.4 (GNU/Linux) > Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org > > iD8DBQFB76y3Hn4UHCY8rB8RAvQsAKCFD/hps8ybQli8HAs3iSCvRjwqjACfS/12 > 5gctpB91S5cy299e/TVLGQk= > =XR2a > -----END PGP SIGNATURE----- > > > > ---------- Forwarded message ---------- > From: Gurpreet Sachdeva > To: python-list at python.org > Date: Thu, 20 Jan 2005 18:53:06 +0530 > Subject: Problem in importing MySQLdb > I am using Mysql version 5.0.2-alpha on RedHat 9.0 (python2.2) > > When I try to import MySQldb > > I get: > Python 2.2.2 (#1, Feb 24 2003, 19:13:11) > [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import MySQLdb > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/site-packages/MySQLdb/__init__.py", line 27, in ? > import _mysql > ImportError: /usr/lib/libmysqlclient.so.10: symbol errno, version > GLIBC_2.0 not defined in file libc.so.6 with link time reference > > Is there any problem in library files?? Do I need to install anything > I have installed MySQL-shared-3.23.54a-1.i386.rpm, > MySQL-devel-5.0.2-0.i386.rpm, MySQL-client-5.0.2-0.i386.rpm, > MySQL-server-5.0.2-0.i386.rpm > > Please help, > Garry > > > > ---------- Forwarded message ---------- > From: deelan > To: python-list at python.org > Date: Thu, 20 Jan 2005 14:43:01 +0100 > Subject: Re: Problem in importing MySQLdb > Gurpreet Sachdeva wrote: > > I am using Mysql version 5.0.2-alpha on RedHat 9.0 (python2.2) > > > > When I try to import MySQldb > > i' not completely sure mysqldb works with mysql 5.0 and its > bundled client libraries. > > to be more precise: > > '' MySQL-5.0 and newer are not currently supported, > but might work.'' > > from: > > > > Is there any problem in library files?? Do I need to install anything > > I have installed MySQL-shared-3.23.54a-1.i386.rpm, > > MySQL-devel-5.0.2-0.i386.rpm, MySQL-client-5.0.2-0.i386.rpm, > > MySQL-server-5.0.2-0.i386.rpm > > are u sure you have compiled mysqldb against 5.0 > client libs? > > you may want to post on the mysqldb forum of ask > for help there: > > > > HTH, > deelan > > -- > @prefix foaf: . > <#me> a foaf:Person ; foaf:nick "deelan" ; > foaf:weblog . > > > > ---------- Forwarded message ---------- > From: Daniel Bowett > To: python-list at python.org > Date: Thu, 20 Jan 2005 08:48:37 +0000 > Subject: Re: mod_python friendly isps in europe > paulo.jpinto at gmail.com wrote: > > Hello everybody > > > > I'm thinking about improving my web site scripts > > and would like to use Python instead of PHP/Perl. > > > > Does anyone know of mod_python friendly ISPs in > > europe? With prices around 10? ? > > > > Thanks in advance, > > Paulo > > > > I would doubt you will find any commercial python ISP's out there. If > you do could you post them here? > > > > ---------- Forwarded message ---------- > From: Kent Johnson > To: python-list at python.org > Date: Thu, 20 Jan 2005 09:01:01 -0500 > Subject: Re: xml parsing escape characters > Luis P. Mendes wrote: > > -----BEGIN PGP SIGNED MESSAGE----- > > Hash: SHA1 > > > > this is the xml document: > > > > > > > > ~ > > ~ 439 > > (... others ...) > > ~ > > > > This is an XML document containing a single tag, , whose content is text containing > entity-escaped XML. > > This is *not* an XML document containing tags , , , etc. > > All the behaviour you are seeing is a consequence of this. You need to unescape the contents of the > tag to be able to treat it as structured XML. > > Kent > > > > ---------- Forwarded message ---------- > From: Steve Holden > To: python-list at python.org > Date: Thu, 20 Jan 2005 09:04:00 -0500 > Subject: Re: Zen of Python > Paul Rubin wrote: > > > Tim Peters writes: > > > >>>Huh? [1,2,[3,4,5],[6,[[[[7]],8]]]] is a perfectly valid Python list. > >> > >>You're claiming not to know any relevant difference between Python > >>lists and Lisp lists? Heh. > > > > > > Python doesn't provide syntactic sugar for [1,[2,[3,[4,[]]]]] if > > that's what you mean. In Lisp you'd say (1 2 3 4). It's still > > a perfectly valid list in Python. Python by convention uses > > multi-element arrays instead of lists of conses. > > > But how, in Lisp, would you transliterate the Python list [1, 2, 3, 4]? > Clearly the Python list *is* different, and the tradeoff was to obtain > speed of random access, presumably (I wasn't taking an interest in > Python in its early days) anticipating that non-recursive algorithms > would be the norm. > > > >>>And you can break out of a containing loop from a nested loop > >>>with try/raise. > >> > >>Heh heh. Yes, you can. I've never seen a real Python program that > >>did, but there's nothing to stop you. > > > > > I do that on a fairly routine basis. I won't say "often", but it's a > > standard technique that finds a use now and then. > > > Well, I blush to say I have done that (once, if my memory serves me > correctly), but it was an ugly program, and I did eventually refactor > the code so that the loops were in separate scopes, which made it much > cleaner. > > [...] > > > > There's a technique in numerical analysis called Richardson > > extrapolation, where you compute an integral by [...] > > Wow. Anyone who feels the need to explain numerical analysis techniques > to Tim Peters is wasting keystrokes big-time. Anyway, Richardson > extrapolation is merely one of many successive approximation techniques, > which is what you are talking about, no? > > > > > I see the same thing happening in Python. It's going through > > successively better approximations to get closer to a limit. Python > > has it harder than some other languages, because it tries to serve the > > needs of both throwaway scripts and large-scale development projects. > > The result is that feature after feature starts out with an > > implementation sufficient for small scripts, and then edges towards > > the needs of large-scale projects. But it's often predictable at the > > beginning what the final destination is going to be. So once we can > > see where it's going, why not proceed to the finish line immediately > > instead of bothering with the intermediate steps? > > Perhaps because we don't all have your psychic powers? > > regards > Steve > -- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/ > Holden Web LLC +1 703 861 4237 +1 800 494 3119 > > > > ---------- Forwarded message ---------- > From: Antoon Pardon > To: python-list at python.org > Date: 20 Jan 2005 14:07:57 GMT > Subject: Re: Freezing a mutable (was Re: lambda) > Op 2005-01-20, Nick Coghlan schreef : > > Antoon Pardon wrote: > >> I missed that you would use it with the idiom: dct[x.frozen()] > > > > The list itself isn't hashable with this approach, so you don't have much > > choice. I wasn't particularly clear about that point, though. > > > >> I have two problems with this approach. > >> > >> 1) It doesn't work when you get your keys via the keys/items > >> methods. > > > > True - the frozen object has no link back to the original object. That could be > > added though (by returning a tuple subtype with the extra attribute) > > > >> 2) This is rather minor, but a user could still unfreeze > >> untimely > > > > True - doing that is less likely than mutating a hashable list though :) > > > > I'm just noting this as a way to avoid copying data more than once when storing > > immutable copies of mutable data in a dictionary. You're quite right that there > > isn't a really clean idiom for doing that in Python (aside from moving to a > > different data structure that works natively as a dict key, naturally). > > The problem here is IMO is the, we are all consenting adults (which we > are not but I wont start on this now), approach. > > I have been thinking a bit in your freeze direction, but more thorough. > The idea i had was that freeze would replace all mutating methods > with methods that would throw an exception. a thaw method would inverse > the proces. It would then be the responsibilty of the dictionary to > freeze an object on entry and thaw it when removed. However this > wouldn't work with ordinary python objects, since there is no easy way > to have readonly or private variables. > > -- > Antoon Pardon > > > > ---------- Forwarded message ---------- > From: Steve Holden > To: python-list at python.org > Date: Thu, 20 Jan 2005 09:07:39 -0500 > Subject: Re: iteritems() and enumerate() > Xah Lee wrote: > > > Python has iteritems() and enumerate() to be used in for loops. > > > > can anyone tell me what these are by themselves, if anything? > > > > are they just for idiom? > > No, anyone can use them, not just idioms like you. > > regards > Steve > -- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/ > Holden Web LLC +1 703 861 4237 +1 800 494 3119 > > > > ---------- Forwarded message ---------- > From: "Erik Bethke" > To: python-list at python.org > Date: 20 Jan 2005 06:20:46 -0800 > Subject: Re: ElementTree cannot parse UTF-8 Unicode? > There is something wrong with the physical file... I d/l a trial > version of XML Spy home edition and built an equivalent of the korean > test file, and tried it and it got past the element tree error and now > I am stuck with the wxEditCtrl error. > > To build the xml file in the first place I had code that looked like > this: > > d=wxFileDialog( self, message="Choose a file", > defaultDir=os.getcwd(), defaultFile="", wildcard="*.xml", style=wx.SAVE > | wxOVERWRITE_PROMPT | wx.CHANGE_DIR) > if d.ShowModal() == wx.ID_OK: > # This returns a Python list of files that were selected. > paths = d.GetPaths() > layout = '\n' > L1Word = self.t1.GetValue() > L2Word = 'undefined' > > layout += '\n' > layout += ' \n' > layout += '' > open( paths[0], 'w' ).write(layout) > d.Destroy() > > So apprantly there is something wrong with physically constructing the > file in this manner? > > Thank you, > -Erik > > > > ---------- Forwarded message ---------- > From: "Fredrik Lundh" > To: python-list at python.org > Date: Thu, 20 Jan 2005 15:40:35 +0100 > Subject: Re: ElementTree cannot parse UTF-8 Unicode? > Erik Bethke wrote: > > > layout += '\n' > > layout += ' \n' > > what does "print repr(L1Word)" print (that is, what does wxPython return?). > it should be a Unicode string, but that would give you an error when you write > it out: > > >>> f = open("file.txt", "w") > >>> f.write(u'\uc5b4\ub155\ud558\uc138\uc694!') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode characters > in position 0-4: ordinal not in range(128) > > have you hacked the default encoding in site/sitecustomize? > > what happens if you replace the L1Word term with L1Word.encode("utf-8") > > can you post the repr() (either of what's in your file or of the thing, whatever > it is, that wxPython returns...) > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Atte, Eduardo Henr?quez A. 9-6975236 From kartic.krishnamurthy at gmail.com Wed Jan 26 16:55:52 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 26 Jan 2005 13:55:52 -0800 Subject: wx.Image: Couldn't add an image to the image list. References: Message-ID: <1106776552.518189.147400@c13g2000cwb.googlegroups.com> Laszlo, If you are using PIL just for scaling, you can do away with PIL. Even if you do other things with PIL, you can use the Rescale method of the wx.Image instance to resize. Here is the code (adapted from the Demo): data = open('C:/TEMP/test.bmp'), "rb").read() stream = cStringIO.StringIO(data) img = wx.ImageFromStream( stream ) img.Rescale(32, 32) # Resize your image to 32x32 bmp = wx.BitmapFromImage( img ) # Convert Image to Bitmap # Now display Bitmap in Panel wx.StaticBitmap(self, -1, bmp, (bmp.GetWidth(), bmp.GetHeight())) Try this and see if this works for you. Thank you, --Kartic From support at convertzone.com Tue Jan 4 11:22:08 2005 From: support at convertzone.com (support at convertzone.com) Date: 4 Jan 2005 08:22:08 -0800 Subject: Using python to convert PDF document to MSWord documents In-Reply-To: References: <20040928161317.88987.qmail@web8401.mail.in.yahoo.com> Message-ID: <1104855728.542769.220760@c13g2000cwb.googlegroups.com> You can use "pdf to word", it can help you to batch convert pdf to word or text at one time, keeping source layout, and Standalone software, MS Word, Adobe Acrobat and Reader NOT required! and you can get more information from http://www.convertzone.com/net/cz-PDF%20to%20Word-1-1.htm. ConvertZone Support team ConvertZone Software Co,.ltd http://www.convertzone.com support at convertzone.com ************************************************************ ConvertZone provides office(PDF, Word, Excel, PowerPoint, AutoCAD etc), video(DVD, VCD, SVCD etc), audio(MP3, WAV, MIDI etc), image(JPG, GIF, TIF, BMP etc) file converter. ************************************************************ From klachemin at comcast.net Fri Jan 21 23:29:37 2005 From: klachemin at comcast.net (Kamilche) Date: 21 Jan 2005 20:29:37 -0800 Subject: Reload Tricks Message-ID: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> I want my program to be able to reload its code dynamically. I have a large hierarchy of objects in memory. The inheritance hierarchy of these objects are scattered over several files. I find that after reloading the appropriate files, and overwriting the __class__ of object instances, one more thing is necessary: reloading the __bases__ of each reloaded class. If I don't do this, the modules reloaded first point to old versions of the classes from later modules, and when the later module is reloaded, it doesn't update the inheritance hierarchy of classes already loaded. This appears to be working... but now I'm wondering, what else did it not change? Can I expect more toes to be blown off? --Kamilche From dave at pythonapocrypha.com Sun Jan 23 23:17:09 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sun, 23 Jan 2005 21:17:09 -0700 Subject: Determining if a client PC has an Internet connection In-Reply-To: <1106364768.871474.92810@z14g2000cwz.googlegroups.com> References: <1095578301.31957.263.camel@devilbox.devilnet.internal> <1106364768.871474.92810@z14g2000cwz.googlegroups.com> Message-ID: <41F476C5.6020007@pythonapocrypha.com> torment wrote: [snip] > Have you tried just parsing the output from the command "ipconfig"? > > It's pretty obvious from the output that might give you if a connection > is availible. It's tempting to use ipconfig's output, but the info it gives you is unreliable - you can incorrectly infer the presence of an net connection when you don't really have one (if you also run VMWare, if you have installed a loopback adapter, if you have a static public IP, etc.). -Dave From michele.simionato at gmail.com Mon Jan 31 00:42:22 2005 From: michele.simionato at gmail.com (Michele Simionato) Date: 30 Jan 2005 21:42:22 -0800 Subject: future of computing languages In-Reply-To: <1107003465.707681.161950@f14g2000cwb.googlegroups.com> References: <1107003465.707681.161950@f14g2000cwb.googlegroups.com> Message-ID: <1107150142.589225.85200@z14g2000cwz.googlegroups.com> I found that page very shallow and superficial. What they call "the language of the future" is actually the language of the present. Python (but also, Ruby, Perl, Smalltalk, Lisp, Scheme, ...) have already most of the features they list. Then they claim "the language of the future will be so different from the languages we have now that we cannot imagine how it will be". This is pretty naive. A Lisper would say that nothing new happened in the last 40 years. Actually, I think that something new happened, but not that much. The progress was more in the technology than in the programming paradigms. I mean, OO was already there in Simula. It this very possible that the language of 2045 will not be very different from the current dynamic languages. The all page reminds me of the excitation of 60's about the space program (affirmations such "in the year 2000 we will have colonies on Mars") We all know how it ended :-( Michele Simionato From aleaxit at yahoo.com Fri Jan 7 05:55:08 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 11:55:08 +0100 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41dcf582.122188317@news.oz.net> <7xd5wh7qdf.fsf@ruckus.brouhaha.com> Message-ID: <1gq0odo.1x1uyr2kgdgiyN%aleaxit@yahoo.com> Paul Rubin wrote: > Really, I just want to buy a new > computer, turn it on, and have everything there. That's generally > impossible without running satanware from Redmond The princes of insufficient light from Cupertino will in fact be very happy to sell you such computers, and _their_ definition of "everything" includes a bit more than the Redmonders' (e.g., Python is there, perl is there, gcc is there, so is Apache, a good development GUI-based IDE, emacs, a solid firewall, a _usable_ Terminal/commandline program to run bash or tcsh on, ...), though it's no doubt still missing many pieces that you or I might want as parts of *our* "everything" (gvim rather than just vim, GUI/IDEs for Python, Python add-ons such as numarray, gmpy, ctypes, ...) -- all of those you still have to download and install, just as you would for the satanware. Alex From fredrik at pythonware.com Fri Jan 21 12:17:11 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 21 Jan 2005 18:17:11 +0100 Subject: circular iteration References: Message-ID: "Flavio codeco coelho" wrote: > is there a faster way to build a circular iterator in python that by doing this: > > c=['r','g','b','c','m','y','k'] > > for i in range(30): > print c[i%len(c)] have you benchmarked this, and found it lacking, or are you just trying to optimize prematurely? From Serge.Orlov at gmail.com Fri Jan 14 16:23:27 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: Fri, 14 Jan 2005 21:23:27 +0000 (UTC) Subject: oddities in the datetime module References: <41e79a1a$0$264$edfadb0f@dread12.news.tele.dk> Message-ID: Max M wrote: > # -*- coding: latin-1 -*- > > """ > > I am currently using the datetime package, but I find that the design > is oddly > asymmetric. I would like to know why. Or perhaps I have misunderstood > how it should be used? Yes, you did. datetime.timetuple is those who want *time module* format, you should use datetime.data, datetime.time, datetime.year and so on... [snip a lot of timetuple wrestling] > The other way around is also easy. > >>>> dt = datetime(2005, 1, 1, 12, 0, 0) >>>> date(*dt.timetuple()[:3]) > datetime.date(2005, 1, 1) As they say, if the only tool you have is timetuple, everything looks like tuple Try this: >>> dt = datetime(2005, 1, 1, 12, 0, 0) >>> dt.date() datetime.date(2005, 1, 1) Serge. From aahz at pythoncraft.com Fri Jan 7 16:05:43 2005 From: aahz at pythoncraft.com (Aahz) Date: 7 Jan 2005 16:05:43 -0500 Subject: Software archeology (was Re: Developing Commercial Applications in Python) References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> <87pt0iegga.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: In article , Stephen Waterbury wrote: >> eeykay at gmail.com writes: >>> >>>Can somebody there to point me any good commercial applications >>>developed using python ? > >Also see Python Success Stories: http://pythonology.org/success > >A notable example is Verity's search engine -- see >http://python.oreilly.com/news/PythonSS.pdf Actually, your statement is slightly inaccurate. The Verity search engine is more than fifteen years old in its core technology; it was started as a LISP project at IIRC MIT. (At one point I was much amused to look at the C source code and find car() and cdr() functions.) As of my last information, Python isn't used at all in or with the Verity search engine. What you're referring to is the Verity Ultraseek engine, originally written and owned by Infoseek before getting transferred to Verity through a series of dot-bomb transactions. The Ultraseek engine doesn't use Python, but Python is used to control the engine, and I think much of the spider is written in Python. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From __peter__ at web.de Sat Jan 22 03:56:45 2005 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Jan 2005 09:56:45 +0100 Subject: default value in a list References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: Paul McGuire wrote: >> Is there an elegant way to assign to a list from a list of unknown >> size? For example, how could you do something like: >> >> >>> a, b, c = (line.split(':')) >> if line could have less than three fields? > I asked a very similar question a few weeks ago, and from the various > suggestions, I came up with this: > > line = "AAAA:BBB" > expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen] > a,b,c = expand( line.split(":"), "", 3 ) Here is an expand() variant that is not restricted to lists but works with arbitrary iterables: from itertools import chain, repeat, islice def expand(iterable, length, default=None): return islice(chain(iterable, repeat(default)), length) Peter From lee at example.com Tue Jan 25 17:57:16 2005 From: lee at example.com (Lee Harr) Date: Tue, 25 Jan 2005 22:57:16 GMT Subject: Another scripting language implemented into Python itself? References: <10vb8cve125v0b0@corp.supernews.com> Message-ID: >> That approach creates a sort of fragility, though. >> Python includes, along with much else, os.unlink(). >> Suppose our original poster doesn't want end-users >> to be able to delete files (or directories ...). > > I don't remember if the OP specified *where* the scripted application is to > be run. If on a server, then *any* language with loops is vulnerable to > malicious users. If on a person's own desktop machine, where one can run > 'diskformat' or the equivalent, or pick up and drop the machine, then > worrying about Python security seems superfluous. Why worry, for instance, > about os.unlink when the user can just do the same much easier in a text or > gui shell? > What if you were creating a program that used programmable modules and wanted to let people safely share modules over the internet. It would be nice to be able to say "downloaded modules are safe to use. They can only do these things: x, y, z. They will not be able to access or damage anything outside of the application" From reinhold-birkenfeld-nospam at wolke7.net Sun Jan 2 15:14:01 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 02 Jan 2005 21:14:01 +0100 Subject: What can I do with Python ?? In-Reply-To: <33qk47F41507nU1@individual.net> References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> <33oir1F40vpumU2@individual.net> <33qk47F41507nU1@individual.net> Message-ID: <33r309F44620gU1@individual.net> Jabaru wrote: >> BTW, I don't know of >> a way to write fullscreen games in C#... >> > > Directx, Opengl, Gdi+, win32api, SDL... the list goes on Yes, that's right, but most of those you can use in Python, too. I should have inserted the word "specific" at the right point in my sentence Reinhold From rff_rff at remove-yahoo.it Wed Jan 5 06:27:37 2005 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Wed, 05 Jan 2005 11:27:37 GMT Subject: Cookbook 2nd ed Credits (was Re: The Industry choice) In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> Message-ID: Jacek Generowicz ha scritto: > aleaxit at yahoo.com (Alex Martelli) writes: > > >>...but each still gets ONE free copy...!-) > > > Who gets Luther Blissett's copy ? :-) > > And are all the Luther Blissetts the same Luther Blisset ? no, some of them are Wu Ming http://www.wumingfoundation.com/ (from http://www.lutherblissett.net/indexes/bibliography_it.html) From beliavsky at aol.com Mon Jan 31 00:16:11 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 30 Jan 2005 21:16:11 -0800 Subject: Fortran pros and cons (was Re: Coding style article with interesting section on white space) In-Reply-To: <1107144265.980844.9830@z14g2000cwz.googlegroups.com> References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> <1107105022.827941.114510@c13g2000cwb.googlegroups.com> <1107124832.327010.181490@f14g2000cwb.googlegroups.com> <1107144265.980844.9830@z14g2000cwz.googlegroups.com> Message-ID: <1107148571.179315.305970@z14g2000cwz.googlegroups.com> Michael Tobis wrote: > beliavsky at aol.com wrote: > > Michael Tobis wrote: > > > Fortran 90/95 is more expressive than Fortran 77 in many ways, as > > described in ... > > http://www.nr.com/CiP97.pdf . > > > > > ... expresses more science per > > line of code and per programming workday. > > The example shown on p 10 illustrates a shorter piece of code in f90 > than in f77, but it is not obviously more expressive or less complex. > Arguably the f77 code is easier to write and maintain, even though it > has more linefeeds in it, so I find the example far from compelling. Ok, here are some simple examples of the greater expressiveness of Fortran 95 compared to F77 or C for calculations involving arrays. (1) To compute the sum of squares for each column of a matrix of the positive elements, one can write in F90 just isum = sum(imat**2,dim=1,mask=imat>0) compared to do j=1,ncol isum(j) = 0 do i=1,nrows if (imat(i,j) > 0) isum(j) = isum(j) + imat(i,j)**2 end do end do I think there is a similar Numeric Python one-liner using the sum and compress functions. Array operations are not revolutionary (APL had them in 1960s), but they are faster to write and later read. (2) Suppose x and y are matrices of the same size and one wants to set each element y(i,j) = f(x(i,j)) for some elemental (no side-effects) function f. In Fortran 95, one can just write y = f(x) compared to do j=1,ncol do i=1,nrow y(i,j) = f(x(i,j)) end do end do The ufunc of Numeric Python and the map of basic Python offer similar functionality. With Fortran 95 one can code numerical algorithms involving arrays in a high-level manner similar to Python with Numeric/Numarray or Matlab, while retaining the advantages (better performance, stand-alone executables) and disadvantages (explicit variable declarations, no scripting ability) of a compiled language with static typing. That's all I am claiming. From fredrik at pythonware.com Fri Jan 14 03:26:59 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 14 Jan 2005 09:26:59 +0100 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com><7xmzvfn096.fsf@ruckus.brouhaha.com><7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >> > Huh? Expressions are not statements except when they're "expression >> > statements"? What kind of expression is not an expression statement? >> >> any expression that is used in a content that is not an expression statement, >> of course. > > Come on, that is vacuous. The claim was "expressions are not > statements". But it turns out that expressions ARE statements. no, expressions CAN BE USED as statements. that doesn't mean that they ARE statements, unless you're applying belgian logic. (if you have a problem figuring this out, try substituting other things for "expressions" and "statements", and see if you still think that "can be used as" and "are" are always the same thing. try "fish" and "pillow", for example). > It's just an artifact. Whether the artifact is a desirable one is a matter > of discussion. no, it's Python, and it's designed this way on purpose. go read the language reference. From aleaxit at yahoo.com Thu Jan 27 10:09:57 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 27 Jan 2005 16:09:57 +0100 Subject: exclude binary files from os.walk References: <41f8167b$0$8648$a1866201@visi.com> Message-ID: <1gr21db.19k3er3jlvz31N%aleaxit@yahoo.com> rbt wrote: > Grant Edwards wrote: > > On 2005-01-26, rbt wrote: > > > >>Is there an easy way to exclude binary files (I'm working on > >>Windows XP) from the file list returned by os.walk()? > > > > Sure, assuming you can provide a rigorous definition of 'binary > > files'. :) > > non-ascii The only way to tell for sure if a file contains only ASCII characters is to read the whole file and check. You _are_, however, using a very strange definition of "binary". A file of text in German, French or Italian, for example, is likely to be one you'll define as "binary" -- just as soon as it contains a vowel with accent or diaeresis, for example. On the other hand, you want to consider "non-binary" a file chock full of hardly-ever-used control characters, just because the American Standard Code for Information Interchange happened to standardize them once upon a time? Most people's intuitive sense of what "binary" means would rebel against both of these choices, I think; calling a file "binary" because its contents are, say, the string 'El perro de aguas espa?ol.\n' (the n-with-tilde in "espa?ol" disqualifies it from being ASCII), while another whose contents are 32 bytes all made up of 8 zero bits each (ASCII 'NUL' characters) is to be considered "non-binary". In any case, since you need to open and read all the files to check them for "being binary", either by your definition or whatever heuristics you might prefer, you would really not ``excluded them from os.walk'', but rather filter os.walk's results by these criteria. Alex From fumanchu at amor.org Tue Jan 18 12:33:29 2005 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 18 Jan 2005 09:33:29 -0800 Subject: simultaneous multiple requests to very simple database Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33981ED@exchange.hqamor.amorhq.net> Eric S. Johansson wrote: > I have an application where I need a very simple database, > effectively a very large dictionary. The very large > dictionary must be accessed from multiple processes > simultaneously. I need to be able to lock records within > the very large dictionary when records are written to. Just to clarify, you want shared-read until a write, at which point you want to lock just the item being written? Or would page or table locking be acceptable at that point? Robert Brewer MIS Amor Ministries fumanchu at amor.org From erikbethke at gmail.com Tue Jan 18 00:36:39 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 17 Jan 2005 21:36:39 -0800 Subject: wxPython and PyGame - do they play well together? Message-ID: <1106026599.092269.292170@c13g2000cwb.googlegroups.com> Hello All, I am having a great time with python and pygame, and last night I took a long look at the wxPython demo. I think that rocks as well. So now, my question is do wxPython and PyGame work together? How is the windows event loop managed? How is the display window managed? Is it possible to have some sort of master/slave relationship between the two? Is it possible that either could be dominant? Does this sound too weird? I appreciate any fingers pointing in any directions... Thank you, -Erik From roy at panix.com Sun Jan 16 09:18:57 2005 From: roy at panix.com (Roy Smith) Date: Sun, 16 Jan 2005 09:18:57 -0500 Subject: why are some types immutable? References: Message-ID: Torsten Mohr wrote: > reading the documentation (and also from a hint from this NG) > i know now that there are some types that are not mutable. > > But why is it this way? > > From an overhead point of view i think it is not optimal, > for example for a large string it could be much faster to > have it changed in place, not generating a new one for > every step in a change. There has been a huge amount written about immutable types recently. A search of the Google news archives should turn up tons of articles. But, in a nutshell, the biggest reason for immutable types (tuples and strings) is that this lets they be dictionary keys. If you want to know why dictionary keys have to be immutable, do that google search; there was a huge thread on exactly that subject just in the path month or two. Making strings immutable has some good points (in addition to making them usable as dictionary keys) and bad points. On the good side, it lets you intern strings and share memory. For example: >>> a = "fred" >>> b = "fred" >>> id (a) 3587520 >>> id (b) 3587520 when the interpreter saw the string "fred" in the second assignment statement, it looked it up and discovered that it already had a string with the value "fred", so it just re-used the same string (which is why they both have the same id). This saves memory (which can become important when you have a lot of strings). It also makes string comparison more efficient, since a test for equality can often be satisfied by just comparing id's. The bad side is that, as you mentioned, things like: s = "" for c in getCharacters(): s = s + c become very inefficient: O(n^2). Fortunately, there is an easy idiom to avoid that quadratic behavior. You just accumulate the characters in a list, O(n), and then convert the list to a string with join(), also O(n). Two O(n) passes is a heck of a lot better than a single O(n^2). l = [] for c in getCharacters(): l.append (c) s = "".join (l) Other types of in-place string manipulation could use the same trick. From bulba at bulba.com Thu Jan 6 19:29:17 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 01:29:17 +0100 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> <7xzmzmurte.fsf@ruckus.brouhaha.com> Message-ID: <8tlrt058dpe40naqj3pid3icptjnjg3p0d@4ax.com> On 06 Jan 2005 14:16:13 -0800, Paul Rubin wrote: >> Yes, apart from libraries and similar cases (frameworks etc), it's no >> doubt rare for closed-source "end-user packages" to be sold with >> licenses that include source and allow you to "do anything with it". >> >> However, allowing customization (at least for internal use within the >> customer organization), while rare, is far from unheard of. >There's no obstacle to doing that with GPL'd software either. Which is absolutely true, but generally it's not the main _expected effect_ that license writers aim to achieve.. -- It's a man's life in a Python Programming Association. From me at privacy.net Wed Jan 26 00:10:11 2005 From: me at privacy.net (JanC) Date: 26 Jan 2005 05:10:11 GMT Subject: Another scripting language implemented into Python itself? References: <1106624803.825442.73870@f14g2000cwb.googlegroups.com> Message-ID: Francis Girard schreef: > I'm really not sure but there might be some way to embed Java Script > within Jython. You can embed JavaScript in CPython, but I don't know how secure or stable it is: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From itsme at yahoo.com Wed Jan 5 17:39:27 2005 From: itsme at yahoo.com (It's me) Date: Wed, 05 Jan 2005 22:39:27 GMT Subject: Another PythonWin Excel question Message-ID: I followed the example in http://stompstompstomp.com/weblog/technical/2004-05-20 and learned that to add a new worksheet to an Excel workbook, you would use the workbook.Worksheets.Add() method. That works. However, the new worksheet got added *in front* of the last worksheet I was at. How can I get it to add *after*? Thanks, -- Me From duncan.booth at invalid.invalid Fri Jan 21 11:40:35 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Jan 2005 16:40:35 GMT Subject: circular iteration References: Message-ID: Flavio codeco coelho wrote: > hi, > > is there a faster way to build a circular iterator in python that by > doing this: > > c=['r','g','b','c','m','y','k'] > > for i in range(30): > print c[i%len(c)] > > thanks, > > Fl?vio > >>> import itertools >>> c=['r','g','b','c','m','y','k'] >>> circ = itertools.cycle(c) >>> for i in range(30): print circ.next(), r g b c m y k r g b c m y k r g b c m y k r g b c m y k r g >>> From peter at engcorp.com Mon Jan 24 08:59:03 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jan 2005 08:59:03 -0500 Subject: compile python to binary In-Reply-To: References: <1d6cdae3050123080242bf8994@mail.gmail.com> Message-ID: <4e6dnUp7mvK7YmncRVn-vA@powergate.ca> sam wrote: > Peter Hansen wrote: >> After all, source code is stored in binary too... >> > Sorry for the vagues terms. I meant compile a python script into a > binary program. As I said, "binary" is a very ambiguous term, so your clarification by itself wouldn't have helped. (That is, while the defined meaning is fairly precise, many people use "binary" to mean something different.) Anyway, the phrase you were actually looking for is "stand-alone executable". That's what py2exe and the like produce, and that's what distinguishes what you want from, for example, what some suggested in the first place. (In a Windows-only environment, asking "how do I create an EXE" would pretty much mean the same thing.) -Peter From aahz at pythoncraft.com Sat Jan 29 06:43:26 2005 From: aahz at pythoncraft.com (Aahz) Date: 29 Jan 2005 06:43:26 -0500 Subject: Textual markup languages (was Re: What YAML engine do you use?) References: <35a6tpF4gmat2U1@individual.net> Message-ID: In article , Alan Kennedy wrote: > >I think that is where a lot of markup languages fall down, in that they >end trying to develop a sophisticated metadata model that can capture >that kind of information, and re-engineering the markup to support it. >This co-evolution of the markup and model can go horribly awry, if the >designers are inexperienced or don't know where they're headed. Ayup. Fortunately, David Goodger (the primary architect of reST) has plenty of experience in this area; reST was written as a reaction to the, er, organic nature of some other experiments. Nobody involved with the reST project claims it's perfect, but most of us do think we've made good tradeoffs (just like Python ;-). Like Guido, David's also pretty comfortable saying "no".... One more thing: reST does make it fairly easy to write "self-documenting" forms -- give your users boilerplate plus some simple instructions, and they should find it very easy to write their content. (I'm particularly referring to using bibliographic fields in reST -- that's easier to do with boilerplate than explain how to do correctly.) The one thing I forgot to mention in my first post is that the biggest downside to reST for non-technical users is that it's possible to write incorrect documents. With a GUI interface, you can write butt-ugly junk, but it'll never generate a syntax error. However, given your requirements, it sounds more like you're using "non-technical" to mean "not computer experts" -- those people are probably more likely to feel comfortable with getting error messages. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From philippecmartin at sbcglobal.net Mon Jan 24 16:35:11 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 24 Jan 2005 15:35:11 -0600 Subject: Why I use private variables (WAS: RE:"private" variables a.k.a. name mangling?) Message-ID: <1106602511.15475.18.camel@localhost> The real reason behind my using private variables is so they do not appear in the epydoc generated documentation and confuse my users. Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From simon.brunning at gmail.com Wed Jan 12 08:54:49 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 12 Jan 2005 13:54:49 +0000 Subject: Excel module for Python In-Reply-To: References: Message-ID: <8c7f10c605011205541b561d93@mail.gmail.com> On Wed, 12 Jan 2005 15:18:09 +0800, sam wrote: > I m wondering which Excel module is good to be used by Python? If you are on Windows, and you have Excel, then the Python for Windows extensions[1] are all you need to drive Excel via COM. O'Reilly's "Python Programming on Win32" covers COM scripting extensively - and by good fortune, driving Excel is the example they use, and the COM scripting chapter is on-line[2]. You'll also need to know the objects and methods that Excel exposes. These are documented on Microsoft's web site[3], or in the Excel VBA help, which is an optional part of they Office installation. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ [1] http://starship.python.net/crew/mhammond/ [2] http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html [3] http://msdn.microsoft.com/library/en-us/modcore/html/deovrWorkingWithMicrosoftExcelObjects.asp From gh at ghaering.de Thu Jan 6 10:53:23 2005 From: gh at ghaering.de (Gerhard Haering) Date: Thu, 6 Jan 2005 16:53:23 +0100 Subject: Embedding a restricted python interpreter In-Reply-To: <7xbrc2a7zq.fsf@ruckus.brouhaha.com> References: <7xbrc2a7zq.fsf@ruckus.brouhaha.com> Message-ID: <20050106155323.GA11145@mylene.ghaering.de> On Thu, Jan 06, 2005 at 07:32:25AM -0800, Paul Rubin wrote: > Jp Calderone writes: > > A Python sandbox would be useful, but the hosting provider's excuse > > for not allowing you to use mod_python is completely bogus. All the > > necessary security tools for that situation are provided by the > > platform in the form of process and user separation. > > But mod_python is an apache module and runs in the same apache process > with other users' scripts. Which is why it's a good idea for each customer to have it's own system user and their virtual hosts running under this uid. Which was the idea for the perchild MPM for Apache 2 - which is abandoned now :-( muxmpm is a replacement project in beta. This really sucks when you use Apache2. I myself did make the switch some time ago, then noticed that this (for me) important feature was missing. It now works, somehow, but to make it work properly I'd need to either: - go back to Apache 1.3.x, missing some nice improvements - use different webservers per user, put them together with mod_proxy (yuck!) -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From ken at switchboard.ericsson.se Thu Jan 27 17:14:15 2005 From: ken at switchboard.ericsson.se (Kenneth Johansson) Date: Thu, 27 Jan 2005 23:14:15 +0100 Subject: Profiling python 2.3 Message-ID: I wonder what would be a good way to profile a python program where the main thread starts two worker threads that do all the work. I get no infomation at all from the threads. I tried to use profile.run as the first thing in the new thread and the thread starts and works fine but when it exits I get this error File "/usr/lib/python2.3/profile.py", line 71, in run prof = prof.run(statement) File "/usr/lib/python2.3/profile.py", line 403, in run return self.runctx(cmd, dict, dict) File "/usr/lib/python2.3/profile.py", line 409, in runctx exec cmd in globals, locals TypeError: exec: arg 1 must be a string, file, or code object The main problem I have is that when I add a small function to a program the resulting code takes longer than it should. The program takes about 80% normally and end up taking more than 100%. I did a small test of the new funtions and when I run that alone it only takes 20%-25% so the result sould not take more than 50% and now I need to know where the time is spent. From usenet_spam at janc.invalid Fri Jan 21 22:25:47 2005 From: usenet_spam at janc.invalid (JanC) Date: Sat, 22 Jan 2005 03:25:47 GMT Subject: Free NNTP (was Re: how to stop google from messing Python code) References: <5339b60d.0501160809.2eda8b23@posting.google.com> Message-ID: Paul Boddie schreef: > JanC wrote: >> Aahz schreef: >> >>> You also have access to the free netnews server >>> http://news.cis.dfn.de/ >> >> That address is now for DFN internal use only. >> >> Their public service moved to . > > To me, that seems to be the general problem with public NNTP services > - you have to play a game of following them around the net. The "http://news.cis.dfn.de/" address has worked for 1 year after they announced this change. DFN stands for the "German Science and Research Network" and is a government funded organisation, and they wanted/needed separate servers for public and member usage, so they had to find a new name for their public service: "individual.net". -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From peter at somewhere.com Sun Jan 16 15:15:35 2005 From: peter at somewhere.com (Peter Maas) Date: Sun, 16 Jan 2005 21:15:35 +0100 Subject: why are some types immutable? In-Reply-To: References: Message-ID: <3500epF4g7e38U1@individual.net> Torsten Mohr schrieb: > reading the documentation (and also from a hint from this NG) > i know now that there are some types that are not mutable. > > But why is it this way? Immutable types (e.g. strings, tuples) allow for code optimization in some situations and can be used as dictionary keys. For the latter reason see: http://www.python.org/moin/DictionaryKeys -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From roy at panix.com Sun Jan 16 12:41:02 2005 From: roy at panix.com (Roy Smith) Date: Sun, 16 Jan 2005 12:41:02 -0500 Subject: why are some types immutable? References: <1105896839.966379.220890@z14g2000cwz.googlegroups.com> Message-ID: In article <1105896839.966379.220890 at z14g2000cwz.googlegroups.com>, "Dan Bishop" wrote: > Roy Smith wrote: > > Torsten Mohr wrote: > > > reading the documentation (and also from a hint from this NG) > > > i know now that there are some types that are not mutable. > > > > > > But why is it this way? > > > > > > From an overhead point of view i think it is not optimal, > > > for example for a large string it could be much faster to > > > have it changed in place, not generating a new one for > > > every step in a change. > > > > There has been a huge amount written about immutable types recently. > A > > search of the Google news archives should turn up tons of articles. > > > > But, in a nutshell, the biggest reason for immutable types (tuples > and > > strings) is that this lets they be dictionary keys. If you want to > know > > why dictionary keys have to be immutable, > > More precisely, dictionary keys can't be mutable in any way that > affects the result of the hash function or the == or != operators. Yes, this is true. In fact, I spent a fair amount of time in the referenced thread arguing exactly that point. I was hoping people would take my hint, read the thread, and find that out :-) From john.hsu at clear.net.nz Wed Jan 19 18:01:25 2005 From: john.hsu at clear.net.nz (John Hsu) Date: Thu, 20 Jan 2005 12:01:25 +1300 Subject: getting a class attribute using a keyword argument In-Reply-To: References: Message-ID: <41eee75e@clear.net.nz> Guy Robinson wrote: > Hello, > > I have a list of class instances. I wish to get the appropriate class > attribute in each class instance depending on a SINGLE keyword in the > calling class. > > How do I get the calling method to correctly recognise the keyword as a > keyword and not a class attribute? See example code below (which doesn't > work). > > class tocall: > def __init__(self): > self.title = "test" > self.name = "name" > > def callingmethod(self,**kw): > for key in kw: > if tocall.key == kw[key]: > return tocall.key > > which should work as such(but doesn't): > > print callmethod(title = "test") > print callmethod(name = "name") > > Regards, > > Guy Hi, This may be more like you want. class tocall: def __init__(self): self.title = "test" self.name = "name" def callmethod(**kw): for key in kw: if hasattr(tocall(), key): return getattr(tocall(), key) print callmethod(title = "test") print callmethod(name = "name") From fuzzyman at gmail.com Mon Jan 17 08:52:11 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 17 Jan 2005 05:52:11 -0800 Subject: Executing a script created by the end user In-Reply-To: References: Message-ID: <1105969931.707580.20790@f14g2000cwb.googlegroups.com> compile and eval is a good way to go. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From pythongnome at hotmail.com Thu Jan 13 17:58:16 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Thu, 13 Jan 2005 22:58:16 GMT Subject: Python.org, Website of Satan In-Reply-To: References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: Arich Chanachai wrote: > Jane wrote: > >> "Lucas Raab" wrote in message >> news:UsuFd.5434$KJ2.1253 at newsread3.news.atl.earthlink.net... >> >> >>> Jane wrote: >>> >>> >>>> wrote in message >>>> news:1105495569.479185.166340 at z14g2000cwz.googlegroups.com... >>>> >>>> >>>> >>>>> python.org = 194.109.137.226 >>>>> >>>>> 194 + 109 + 137 + 226 = 666 >>>>> >>>>> What is this website with such a demonic name and IP address? What >>>>> evils are the programmers who use this language up to? >>>>> >>>>> >>>> >>>> Some people have too much time on their hands... >>>> >>>> Jane >>>> >>>> >>>> >>> >>> Better get some ointment for that burn!! >>> >> >> >> Huh??? >> >> Jane >> >> >> >> > You said that people have too much "time" on their "hands", so he > suggested ointment to prevent the irritation etc... He was probably > also getting at the topic of this thread (hint: Satan = Hell = Fire), so > the ointment puts out the burn. > Have fun folks! > > - Arich I'd also like to add that the term "burn" means to be made look stupid or be insulted. From jepler at unpythonic.net Mon Jan 24 15:41:35 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 24 Jan 2005 14:41:35 -0600 Subject: Tuple slices In-Reply-To: <35kn4mF4o44ufU1@individual.net> References: <35kn4mF4o44ufU1@individual.net> Message-ID: <20050124204135.GB14448@unpythonic.net> The cpython implementation stores tuples in memory like this: [common fields for all Python objects] [common fields for all variable-size python objects, including tuple size] [fields specific to tuple objects, if any] [array of PyObject*, one for each item in the tuple] This way of storing variable-size Python objects was chosen in part because it reuqires only one allocation for an object, not two. However, there is no way for one tuple to point to a slice of another tuple. there's no reason that some other python implementation couldn't make a different choice. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ncoghlan at iinet.net.au Tue Jan 18 03:52:38 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 18 Jan 2005 18:52:38 +1000 Subject: extension module, thread safety? In-Reply-To: <41ecbaae$0$1046$626a14ce@news.free.fr> References: <41ecbaae$0$1046$626a14ce@news.free.fr> Message-ID: <41ECCE56.9060200@iinet.net.au> Pierre Barbier de Reuille wrote: > With the current CPython, it's very hard to mix Python and C in a > multithreading application (with C-threads, not Python-threads). In fact > I never really succeeded in that task because of that GIL ! I have a > multi-thread application but every bit of Python code must be run into a > Python thread. To be more precise, I wanted to be able to call Python > code in response to some GUI events, and I didn't want to instanciate a > new interpreter for I wanted to be able to access the environment of my > main Python interpreter. I don't understand. This is what PyGILState_Ensure and PyGILState_Release are for - so C code can leave the GIL unlocked by default, and only grab it when they want to call into the C/Python API. Regards, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jbperez808 at wahoo.com Wed Jan 12 03:09:54 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Wed, 12 Jan 2005 16:09:54 +0800 Subject: Windows GUIs from Python In-Reply-To: References: Message-ID: <34k4aiF4bqr4vU1@individual.net> Still, what I think would appeal to a lot of people (although they might not know it yet) as a GUI solution for Python is Mozilla XUL with all the RDF and XPCOM crap surgically removed from it. If you've ever tried a couple of basic XUL tutorials, I think you would be convinced that XUL is an even better way to develop GUIs than visual RAD tools. After years of doing web apps, I feel the DHTML/DOM approach as applied to GUI creation is superior in terms of learning curve, productivity and ease of code maintenance to imperative language, event-driven, IDE-coupled frameworks like Delphi, Windows Forms or Swing... except for the fact that the HTML widgets (if you could even call them that) are very primitive. XUL essentially gives you full fledged GUI widgets and allows you to script them from Javascript the same way you script HTML elements via DOM or DHTML (very easily, in other words). Now, imagine being able to use Python instead of Javascript... sounds like a match made in heaven to me. Unfortunately, the Mozilla developers are too enamoured with Javascript and RDF and XPCOM to realize that XUL (which is really shaping up beautifully if you look at Firefox and Thunderbird) is the real star in their stable and many people would like to use it without being forced to deal with the other complicated, overengineered technologies surrounding it. From apardon at forel.vub.ac.be Mon Jan 17 09:58:32 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Jan 2005 14:58:32 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-17, Steve Holden schreef : > Antoon Pardon wrote: > >> I don't see a big difference between these principles >> and the hash key principle, so in the end may be we >> should just stick with the more general principle: >> >> Don't use mutables! >> >> >> and be done with it. >> > http://redwing.hutman.net/~mreed/warriorshtm/tirelessrebutter.htm > > regards > Steve I you want to play it like this http://redwing.hutman.net/~mreed/warriorshtm/crybaby.htm -- Antoon Pardon From sross at connectmail.carleton.ca Fri Jan 7 17:09:32 2005 From: sross at connectmail.carleton.ca (Sean Ross) Date: Fri, 7 Jan 2005 17:09:32 -0500 Subject: Getting rid of "self." References: <740c3aec05010705393048a374@mail.gmail.com><1105114214.359029.152240@f14g2000cwb.googlegroups.com> Message-ID: "BJ?rn Lindqvist" wrote in message news:mailman.306.1105116676.22381.python-list at python.org... Thank you for your replies. But they don't deal with my original question. :) I have read the thousands of posts all saying "self is good" and they are right. But this time I want to be different m-kay? I figure that there might be some way to solve my problem by doing this: [snip ...] But beyond that, I have no idea and I would be grateful if someone would like to help me with it. http://starship.python.net/crew/mwh/hacks/selfless.py From elephantum at dezcom.mephi.ru Sun Jan 9 09:32:55 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 17:32:55 +0300 Subject: Python3: on removing map, reduce, filter In-Reply-To: <7xekguof4a.fsf@ruckus.brouhaha.com> References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> Message-ID: <34ctkpF4b9ijlU1@individual.net> Paul Rubin wrote: >>How does GvR suggestions on removing map(), reduce(), filter() >>correlate with the following that he wrote himself (afaik): >>http://www.python.org/doc/essays/list2str.html > > I think that article was written before list comprehensions were added > to Python. anyway list comprehensions are just syntaxic sugar for >>> for var in list: >>> smth = ... >>> res.append(smth) (is that correct?) so there will be no speed gain, while map etc. are C-implemented From garyr at fidalgo.net Tue Jan 4 19:38:06 2005 From: garyr at fidalgo.net (Gary Richardson) Date: Tue, 4 Jan 2005 16:38:06 -0800 Subject: Reaching the real world References: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> Message-ID: <10tmdnnjl7djaad@corp.supernews.com> "Fuzzyman" wrote in message news:1104850540.610295.152240 at f14g2000cwb.googlegroups.com... > I have a friend who would like to move and program lights and other > electric/electro-mechanical devices by computer. I would like to help - > and needless to say Python would be an ideal language for the > 'programmers interface'. > > What I'd like is an electronic interface that connects to several > relays and a python extension module to switch on and off the relays. > I've had a quick google and can't see anything too similar to what I > want. pyro (python robotics) seems to require expensive (relatively) > robotic equipment. > > Does anyone know anything *similar* to what I have in mind, or have > alternative suggestions ? > Regards, > > Fuzzy > http://www.voidspace.org.uk/python/index.shtml > Take a look at: http://www.geocities.com/hagtronics/pic_das/index.html Very easy to interface to Python. From ola.natvig at infosense.no Tue Jan 18 08:03:26 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Tue, 18 Jan 2005 14:03:26 +0100 Subject: generator expressions: performance anomaly? In-Reply-To: References: <377Hd.77904$Jk5.30235@lakeread01> Message-ID: Antoon Pardon wrote: > Op 2005-01-18, Steve Holden schreef : > >>Antoon Pardon wrote: >> >> >>>Op 2005-01-18, Nick Coghlan schreef : >>> >>> >>>>Raymond Hettinger wrote: >>>> >>>> >>>>>[Delaney, Timothy C] >>>>> >>>>> >>>>> >>>>>>Nick's other suggestion - that genexps propagate __len__ - might >>>>>>still be interesting. Of course, it would only be applicable for >>>>>>unconditional genexps(i.e. no if clause). >>>>> >>>>>Length transparency for iterators is not as general as one would expect. I once >>>>>spent a good deal of effort exploring where it made sense, and I was surprised >>>>>to find that it only rarely works out. Length transparency is an unexpectedly >>>>>thorny subject with many dead-ends which precludes a fully general solution such >>>>>as that proposed by Nick. >>>>> >>>>>For a recap of my research, see the docstring for Lib/test/test_iterlen.py . >>>> >>>>"""The situation slightly more involved whenever an object allows length >>>>mutation during iteration. """ >>>> >>>>Ouch. Nice understatement. >>>> >>>>It's rather unfortunate that we can't make use of the length information even >>>>when the source *doesn't* mutate, though. I'll have to think some more to see if >>>>I can come up with any concrete ideas for you to shoot down :) >>> >>> >>>Something else I was thinking about. I think it would be nice if the >>>python compilor could figure out whether a genexp in a list or tuple >>>expression always generates the same list or tuple and then instead >>>of generating code would generate the list or tuple in place. >>> >> >>Since it doesn't yet optimize 2+5 to a constant-folded 7 you should >>realize that you are suggesting a large increase in the compiler's >>analytical powers. > > > Well I can dream, cant I? > > >>I agree it would be nice under certain circumstances, but don't forget >>that unlike list comprehensions (for which it would be even nicer) the >>whole point of generator expressions is often to defer the generation of >>the individual items until they are required and thereby relieve stress >>on memory. >> >>As an edge case to demonstrate the point, what about a constant but >>infinite sequence? > > > Maybe I was not clear enough. I meant to limit it to cases such as > > lst = list(genexp) > tpl = tuple(genexp) > > > Since in such cases the object is build in memory any way, I don't > think it would be a problem of having them prebuilt in memory, or am > I missing something? > Perhaps it had been better if that kind of functionality were implemented with a different syntax, I don't know enough about how the python interpreter works but perhaps it should be possible to execute some expressions with genexp syntax when compiling to bytecode. That should be a quite trivial extension. examples using '<' list-comp/genexp syntax '>': lst = or perhaps lst = list() Would result in the same bytecode as this expression lst = [0, 1, 2, 3, ..., 98, 99] It could be called static list comprehensions. But if it is a usefull extension is another dicussion. ola From newsgroups at jhrothjr.com Wed Jan 12 23:03:55 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 12 Jan 2005 22:03:55 -0600 Subject: why are people still using classic classes? References: Message-ID: <10ubsq4lii1dac7@news.supernews.com> "Simon Wittber" wrote in message news:mailman.605.1105586518.22381.python-list at python.org... > I've noticed that a few ASPN cookbook recipes, which are recent > additions, use classic classes. > > I've also noticed classic classes are used in many places in the > standard library. > > I've been using new-style classes since Python 2.2, and am suprised > people are still using the classic classes. > > Is there a legitimate use for classic classes that I am not aware of? > Is there a project to specifically migrate standard library classes to > new-style classes? Part of it is simply that it's a bit easier: you don't have to inherit from object. AFAIK, there's no project to migrate the standard library, and I'm not at all sure that would be a good idea since existing programs that asssume classic class behavior would be affected when classes they inherited from suddenly changed. Classic classes will go away sometime in the future, currently planned for the semi-mythical 3.0 release. John Roth > > Sw. From Noah.Richards at infineon.com Fri Jan 14 15:22:44 2005 From: Noah.Richards at infineon.com (Richards Noah (IFR LIT MET)) Date: Fri, 14 Jan 2005 15:22:44 -0500 Subject: python to mssql References: Message-ID: "Robert Brewer" wrote in message news:mailman.722.1105724341.22381.python-list at python.org... Brane wrote: > can someone please give me some info regarding subject > >http://sourceforge.net/projects/mysql-python > >Ask a broad question... > > >Robert Brewer Robert, the question was about 'mssql', not 'mysql'. As for mssql, a search on google will give you the following as the first result: http://pymssql.sourceforge.net/ with others on the page that include: http://www.object-craft.com.au/projects/mssql/ http://www.egenix.com/files/python/eGenix-mx-Extensions.html Don't be lazy, Brane. Your first point of reference should _always_ be google. The fact that "I'm Feeling Lucky" points you to pymssql shows that you didn't do any research before posting here. -Noah From jester at NOSPAM.mcsnospam.vuw.acNOSPAM.nz Tue Jan 18 21:05:06 2005 From: jester at NOSPAM.mcsnospam.vuw.acNOSPAM.nz (Mike McGavin) Date: Wed, 19 Jan 2005 15:05:06 +1300 Subject: Problem parsing namespaces with xml.dom.minidom In-Reply-To: References: <41eca38d@clear.net.nz> <41ece45f@clear.net.nz> Message-ID: <1106100306.989766@bats.mcs.vuw.ac.nz> Hi Fredrik. Fredrik Lundh wrote: >>It wouldn't need to conform to the official specifications of the DOM API, but I guess I'm after >>some comparable functionality. [--snip--] > sounds like this might be exactly what you need: > http://effbot.org/zone/element-index.htm > (it's also the fastest and most memory-efficient Python-only parser you > can get, but I suppose that's not a problem ;-) Thanks. The original problem I was having turned out to the be reversing a couple of parameters in a method call, as Paul pointed out, and I now feel pretty silly as a result. But I'll take a look at this, too. Much appreciated. Mike. From sp1d3rx at gmail.com Tue Jan 11 15:49:04 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 11 Jan 2005 12:49:04 -0800 Subject: Time script help sought! In-Reply-To: <1105474524.083536.129220@f14g2000cwb.googlegroups.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> Message-ID: <1105476544.039325.273010@f14g2000cwb.googlegroups.com> using my code above... start = x[3].split(":") #split the minutes from the seconds this splits something like 1:22:40 into three parts 1(hours), 22(mintes), 40(seconds) so, you must add a special case handler... if len(start) == 3: { start[1] = int(start[0]) * 60 + int(start[1]) start = start[1], start[2] } and there you go.... what this does is take the hours , multiply them by 60 and add it to the minutes. You will also have to change your output function to convert from "seconds" to "hours, minutes, seconds". From tim.peters at gmail.com Mon Jan 24 14:37:45 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 24 Jan 2005 14:37:45 -0500 Subject: Weakref.ref callbacks and eliminating __del__ methods In-Reply-To: <5lr9v0tg2i16irskb798f7rcti955j0c64@4ax.com> References: <41F427EB.3000200@rogers.com> <1f7befae0501231720428ca3c@mail.gmail.com> <5lr9v0tg2i16irskb798f7rcti955j0c64@4ax.com> Message-ID: <1f7befae05012411376821bb92@mail.gmail.com> [Tim] >> I'll note that one fairly obvious pattern works very well for weakrefs >> and __del__ methods (mutatis mutandis): don't put the __del__ method >> in self, put it in a dead-simple object hanging *off* of self. Like >> the simple: >> >> class BTreeCloser: >> def __init__(self, btree): >> self.btree = btree >> >> def __del__(self): >> if self.btree: >> self.btree.close() >> self.btree = None >> >> Then give self an attribute refererring to a BTreeCloser instance, and >> keep self's class free of a __del__ method. The operational >> definition of "dead simple" is "may or may not be reachable only from >> cycles, but is never itself part of a cycle". [Richie Hindle] > This is very nice - I've been wondering about just this problem recently, > and this will be very useful. Many thanks! Thank me if it's *actually* useful <0.5 wink>: depending on everything, it may leave problems anyway, including that there's no 100% guarantee that a __del__ method will ever get called, and that __del__ methods (weakref callbacks too, for that matter) triggered while Python is tearing itself down at exit may suffer bizarre exceptions (due to trying to use facilities in partially-torn down modules, including the module the __del__ method appears in). For those reasons, it's best practice to release critical resources explicitly. __del__ is more a crutch than a limousine. > One question: why the `self.btree = None` in the last line? Isn't > `self.btree` guaranteed to go away at this point anyway? (If the answer > is "it's necessary for weird cases that would take an hour to explain" > then I'll be more than happy to simply use it. 8-) Here, it was mostly just copy+paste from Mike's original example. In general, __del__ is a user-visible method like any other, and user code may call it explicitly. For that reason, it's safest to write __del__ methods in library objects such that they can be invoked multiple times gracefully. I think the nicest way to do that is along the lines Mike later showed: write a close()-like method to release resource explicitly (although naming it __call__ seems dubious), ensure close() is idempotent, and then write a one-liner __del__: def close(self): yadda yadda yadda def __del__(self): self.close() If you're writing code for your own use, and know __del__ will never be called explicitly, and know your __del__ can't resurrect self, then "`self.btree` [is] guaranteed to go away at this point" is true, and you can ignore all this safely. From engsolnorm at peak.org Sat Jan 15 17:02:07 2005 From: engsolnorm at peak.org (engsol) Date: Sat, 15 Jan 2005 14:02:07 -0800 Subject: Com port interrupts again References: <154gu09bghnq674s2nqot9si6d50igueq7@4ax.com> Message-ID: <3k4ju0t679d5fdv7gn4tkouqt8d9hi01bn@4ax.com> On Sat, 15 Jan 2005 19:38:19 +0000 (UTC), Chris Liechti wrote: >engsol wrote in >news:154gu09bghnq674s2nqot9si6d50igueq7 at 4ax.com: > >> I didn't fully think through my application before posting my >> question. Async com port routines to handle com port interrups >> only work well if one has access to the low level operating >> system. In that case the receive buffer interrupt would cause >> a jump to an interrupt service routine.. I don't believe that > >i would not go that route... the operating system provides sync and async >methods to access the serial port. it would make sense to use these before >hacking the operating system. (also see below) > >> Python provides that capabilty directly. The solution then would >> be to write a C extention? > >ctypes can do many things without a C compiler. it's a very nice an >valuable extension, but i won't like to encurage to use it for this >particular problem. > >> The suggestions offered by respondents to my original post >> were almost all of a "Use threads, and poll as needed" flavor. >> You're right...I need to learn threads as applied to com ports. > >if you realy want to do async programming, have a look at twisted >(http://twistedmatrix.com). it does not only provide async access to the >serial port (trough pyserial + some code in twisted) it also delivers some >nice utility functions, classes etc, like the reactor, defereds, thread >pools (if you can't resist ;-) and many protocol handlers. > >chris Chris, thanks for the pointer to twisted. I'm a bit snow bound, so it's a good time to actually read some docs...:) Norm B From peter at engcorp.com Thu Jan 6 20:51:37 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Jan 2005 20:51:37 -0500 Subject: Python Operating System??? In-Reply-To: <1105056994.107116.216480@f14g2000cwb.googlegroups.com> References: <10trb0mgiflcj4f@corp.supernews.com> <1105056994.107116.216480@f14g2000cwb.googlegroups.com> Message-ID: Fuzzyman wrote: > There is/was a project (Peter Hansen ?) to produce a pure python file > system. that could be an interesting component. Good memory... uh, sort of. :-) It was probably me you're thinking of, but the point of the project was solely a "virtual" file system, to be used exclusively as a tool for supporting automated testing. It has no concept of persistence, no support for it in the design, and wouldn't be what would help anyone in this respect. Sorry. (Work on it has actually not progressed lately, because there is no additional requirement driving the work. The primitive initial state of the tool suffices so far.) -Peter From michael at stroeder.com Thu Jan 6 21:26:11 2005 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 07 Jan 2005 03:26:11 +0100 Subject: Working with flat files [LDIF]. In-Reply-To: <1104871974.248122.102230@f14g2000cwb.googlegroups.com> References: <33A3E2B3.7F5CF6F0@whoi.edu> <1104871974.248122.102230@f14g2000cwb.googlegroups.com> Message-ID: <3j81b2-5v3.ln1@nb2.stroeder.com> generate at gmail.com wrote: > Scott A. McIntyre wrote: > >>I looked around but didn't see any LDIF tools for perl or python... > > Did you ever get this issue resolved? I have a similar need to merge > two LDIF files. Use module LDIF which is part of http://python-ldap.sourceforge.net/. You can use it stand-alone without installing the rest. Yes, docs are *very* sparse for this module but you can find sample code in directory Demo/Lib/ldif/ of the source distribution. Ciao, Michael. From a at b.c Sat Jan 22 15:18:10 2005 From: a at b.c (Doug Holton) Date: Sat, 22 Jan 2005 14:18:10 -0600 Subject: What YAML engine do you use? In-Reply-To: <35fo4iF4maov2U1@individual.net> References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> Message-ID: rm wrote: > this implementation of their idea. But I'd love to see a generic, > pythonic data format. That's a good idea. But really Python is already close to that. A lot of times it is easier to just write out a python dictionary than using a DB or XML or whatever. Python is already close to YAML in some ways. Maybe even better than YAML, especially if Fredrik's claims of YAML's inherent unreliability are to be believed. Of course he develops a competing XML product, so who knows. From tjreedy at udel.edu Tue Jan 25 14:51:24 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 Jan 2005 14:51:24 -0500 Subject: Another scripting language implemented into Python itself? References: <10vb8cve125v0b0@corp.supernews.com> Message-ID: "Cameron Laird" wrote in message news:bt6ic2-7dg.ln1 at lairds.us... > The original poster wants to work in Python. That's > fine. Several of us have suggested he further > expose Python itself to his end-users as an extension > language. That certainly is feasible. He needn't > explain all of Python to those end-users--probably > only a bit about "assignments", control structures, > and maybe lists. > > That approach creates a sort of fragility, though. > Python includes, along with much else, os.unlink(). > Suppose our original poster doesn't want end-users > to be able to delete files (or directories ...). I don't remember if the OP specified *where* the scripted application is to be run. If on a server, then *any* language with loops is vulnerable to malicious users. If on a person's own desktop machine, where one can run 'diskformat' or the equivalent, or pick up and drop the machine, then worrying about Python security seems superfluous. Why worry, for instance, about os.unlink when the user can just do the same much easier in a text or gui shell? Terry J. Reedy From http Fri Jan 28 08:23:56 2005 From: http (Paul Rubin) Date: 28 Jan 2005 05:23:56 -0800 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> <1106917317.595640.149010@z14g2000cwz.googlegroups.com> Message-ID: <7xy8edwutv.fsf@ruckus.brouhaha.com> "Fuzzyman" writes: > The sourceforge bug tracker *is* the single right place to post such > issues. The py-dev mailing list would be a second *useful* place to > post such a comment, although not really the right place. The OP seemed > to want an individual with whom he could have a private conversation > about it. I think he wanted a place to send a bug report that wouldn't be exposed to public view until the developers had a chance to issue a patch. With bugzilla, for example, you can check a bug labelled "this is a security bug, keep it confidential". There's lots of dilemmas and some controversy about keeping any bug reports confidential in an open source system. But the general strategy selected by Mozilla after much debate seems to mostly work ok. It basically says develop a patch quickly, keep the bug confidential while the patch is being developed, and once the patch is available, notify distro maintainers to install it, and then after a short delay (like a couple days), publish the bug. Note that anyone with access to the bug (that includes the reporter and selected developers) can uncheck the box at any time, if they think the bug no longer needs to be confidential. The bug then becomes visible to the public. From gurpreet.sachdeva at gmail.com Thu Jan 13 23:53:44 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Fri, 14 Jan 2005 10:23:44 +0530 Subject: pyPgSQL giving error! In-Reply-To: References: Message-ID: > did you really do ./configure, make and make install? No, I did python setup.py build and python setup.py install > where is libpq.* linpq is there in /usr/lib/python2.3/site-packages/pyPgSQL/ > was a postgres installation present while doing ./configure et all? No, But I installed postgresql-libs before installing pyPgSQL Regards, Garry From ncoghlan at iinet.net.au Wed Jan 26 08:12:20 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 23:12:20 +1000 Subject: execute python code from db In-Reply-To: References: Message-ID: <41F79734.3030301@iinet.net.au> robert wrote: > Hello, > > Anybody knows if it's possible to execute python code from an db. > > db=MySQLdb.connect(host="localhost",user="r",passwd="j",db="v") > > c=db.cursor() > c.execute("""SELECT * FROM table > WHERE id = %s""", (id,)) > > for python_code in c.fetchall(): > execute (python_code) > > Maybe feed python with stdin??. What's wrong with the exec statement? Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From engsolnorm at peak.org Wed Jan 12 17:24:48 2005 From: engsolnorm at peak.org (engsol) Date: Wed, 12 Jan 2005 14:24:48 -0800 Subject: pyserial and com port interrupts Message-ID: Has anyone done a script that will rspond to the serial com port(s) receive buffer interrupt, as opposed to polling and timeouts? Win2000 is the main interest right now. Thanks Norm B From Prikryl at skil.cz Thu Jan 20 04:15:35 2005 From: Prikryl at skil.cz (Petr Prikryl) Date: Thu, 20 Jan 2005 10:15:35 +0100 Subject: [OT] Good C++ book for a Python programmer Message-ID: Try also the Bruce Eckel's "Thinking in C++". It is also available on-line for free at http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html I like the book because it explains the things very clearly. After reading it, one will stop to think and say that C++ is "only C with strange OO things on the top". Petr "Paul Rubin" wrote in message news:<7x4qhdia8p.fsf at ruckus.brouhaha.com>... > "rick_muller at yahoo.com" writes: > > I was wondering whether anyone could recommend a good C++ book, with > > "good" being defined from the perspective of a Python programmer. I > > realize that there isn't a book titled "C++ for Python Programmers", > > but has anyone found one that they think goes particularly well with > > the Python way? > > I think it's not possible to really grok C++ without having worked on > large multi-person C projects and understood what problems C++ tried > to solve. The only good book I know about C++ is by Stroustrup, "The > C++ Programming Language" or something like that; it's not an easy > book though. From ncoghlan at iinet.net.au Fri Jan 28 19:07:34 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 29 Jan 2005 10:07:34 +1000 Subject: Coding style article with interesting section on white space Message-ID: <41FAD3C6.1030400@iinet.net.au> Thought some folks here might find this one interesting. No great revelations, just a fairly sensible piece on writing readable code :) The whole article: http://www.acmqueue.com/modules.php?name=Content&pa=showpage&pid=271&page=1 The section specifically on white space: http://www.acmqueue.com/modules.php?name=Content&pa=showpage&pid=271&page=3 Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From apardon at forel.vub.ac.be Wed Jan 19 09:55:23 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Jan 2005 14:55:23 GMT Subject: generator expressions: performance anomaly? References: <354esdF4fouh0U1@individual.net> <5PtHd.80946$Jk5.119@lakeread01> Message-ID: Op 2005-01-19, Steve Holden schreef : > Antoon Pardon wrote: > >> Op 2005-01-18, Steve Holden schreef : > [...] >> >> But you do have a point that I have a tendency to put salt on >> any snail. I'll try to restrain myself a bit more in the future. >> > Finally! :-) > > I find I like you much better after this reflective response. Thanks for > taking the time to read my snarking and respond to it. > > "A tendency to put salt on any snail" is a nice phrase I've never come > across before. Is it specifically Belgian? It is a literal translation of a dutch idiom: "Op alle slakken zout leggen". Most people in Belgium speak dutch although foreigner often seem to think we all speak native French. From __peter__ at web.de Tue Jan 11 08:02:31 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Jan 2005 14:02:31 +0100 Subject: SuSE 9.1: updating to python-2.4 References: Message-ID: Torsten Mohr wrote: > along with my distribution SuSE 9.1 came python 2.3.3. > > I'd like to update to 2.4 now, is this an easy thing to do > or will lots of installed modules refuse to work then? > > Is there an easy way to find out what i need to update? I shied away from a full upgrade and installed 2.4 from source just to play around with it. This is painless if you use make altinstall instead of make install If you want Tkinter support you have to install the tk-devel package before configuring 2.4. One easy way to find out what depends on python is to mark python for removal in yast, then click the [Abh?ngigkeiten pr?fen] (check dependencies) button -- and probably cancel the changes afterwards. Peter From mhartl at post.harvard.edu Wed Jan 12 17:09:44 2005 From: mhartl at post.harvard.edu (Michael Hartl) Date: 12 Jan 2005 14:09:44 -0800 Subject: counting items References: <1105559439.538736.87370@z14g2000cwz.googlegroups.com> Message-ID: <1105567784.297529.246800@c13g2000cwb.googlegroups.com> That's cool! Of course, walk returns a generator, so using a list comprehension to turn it into a list seems natural, but I didn't realize that list() does the same thing (and neither, apparently, did the original implementor) -- although, with a little reflection, it obviously must! Michael From jack at performancedrivers.com Wed Jan 19 21:58:55 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 19 Jan 2005 21:58:55 -0500 Subject: Zen of Python In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <10uu3iphdr23mf4@corp.supernews.com> Message-ID: <20050120025855.GN26167@performancedrivers.com> On Wed, Jan 19, 2005 at 09:28:13PM -0500, Peter Hansen wrote: > Jeff Shannon wrote: > >Timothy Fitz wrote: > >>Which I agree with, and which makes sense. However your "gist" is a > >>different meaning. It's not that "Flat is better than nested" it's > >>that "Too flat is bad and too flat is nested so be as nested (or as > >>flat) as you have to be and no more." Perhaps Tim Peters is far too > >>concise for my feeble mind > > > >Well, the way that the Zen is phrased, it implies a bit more than that. > > A Zen koan always implies more than the listener infers. I've met Zell Cohen, and you sir ... /got nothing. -Jack From steve at holdenweb.com Sun Jan 23 14:45:33 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 23 Jan 2005 14:45:33 -0500 Subject: OT: problems mirroring python-list to c.l.py? In-Reply-To: References: <1d6cdae305012310535980e82d@mail.gmail.com> <20050123190637.GA4820@grulic.org.ar> Message-ID: Daniel Bickett wrote: > John Lenton wrote: > >>>On Sun, Jan 23, 2005 at 01:53:52PM -0500, Daniel Bickett wrote: >>> >>>>Is there a reason that Google Groups isn't mirroring python-list >>>>exactly like it used to, or is it simply a conspiracy I'm not in on? >>> >>>You should not ask this kind of question in a public forum, >> >>and *you* should know better than to go around flapping your mouth >>like that. > > > Now I'm further confused, because I don't know what you quoted, but it > isn't on the mailing list and it isn't on c.l.py :) Maybe I should > give up trying to figure these things out. > > You didn't include a name at the beginning of your citation... Who had > the audacity to take my joke seriously? ;-) > > Daniel Bickett It is well known tha the PSU ha From sw at wordtech-software.com Thu Jan 27 17:05:57 2005 From: sw at wordtech-software.com (Kevin Walzer) Date: Thu, 27 Jan 2005 17:05:57 -0500 Subject: Configuring Python for Tk on Mac (continued) In-Reply-To: References: Message-ID: <41F965C5.3030909@wordtech-software.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Martyn Quick wrote: | From: Alex Martelli (aleaxit at yahoo.com) | |>No idea about any 10.2, sorry, but on 10.3 that's not the problem: Tk |>support is there alright, it's Tcl/Tk which _isn't_. Get MacPython, its |>PackageManager will explain where to get Tcl/Tk Aqua from, as a prereq |>for Tkinter and IDLE! | | | Ok, I've installed MacPython. It doesn't seem to work right though... | for example, if I try to run the 00-HELLO-WORLD.py example then it | crashes and tells me the IDE has unexpectedly crashed. | | I can't really see how to run things either. (I'm used to just typing | "python" in a terminal on Unix but that seems to just run the version | that comes pre-installed.) | | Sorry for not knowing much about Macs and being a bit clueless. | | Martyn You need to install Tk Aqua at this site: http://tcltkaqua.sourceforge.net You then need to install the tkinter bindings using Package Manager, which comes as part of the Macpython distribution. IDLE then should run fine. Also, you can't run Python gui programs by typing "python" in the console on the Mac: either double-click the script, or use "pythonw" as the launching program in the terminal. - -- Cheers, Kevin Walzer, PhD WordTech Software--Open Source Applications and Packages for OS X http://www.wordtech-software.com http://www.smallbizmac.com http://www.kevin-walzer.com mailto:sw at wordtech-software.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (Darwin) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFB+WXEJmdQs+6YVcoRAg5rAJ4zJYRVvEe0wvT3ZIJLwa79Am90CACdFeiv NXU/lT4hYVCPCtU6bGEWc40= =+Q7e -----END PGP SIGNATURE----- From aleaxit at yahoo.com Mon Jan 31 12:06:38 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 31 Jan 2005 18:06:38 +0100 Subject: variable declaration References: Message-ID: <1gr9ltj.1tiisn018pnse6N%aleaxit@yahoo.com> Robert Brewer wrote: > Bah. Nothing teaches you a new language like having your job depend upon > it. People who study languages merely for "personal growth" learn 50% of > the syntax and 1% of the concepts, and then fritter that learning away > on inconsequential newsgroups the world over. I disagree. I studied Python, even though it had nothing to do with my job, just with the idea of using it on hobby projects; yet I believe I can reasonably claim to have learned more than 50% of the syntax and 1% of the concepts, even though you might claim that, whatever percentage it may be, it's "frittered away on inconsequential newsgroups". Alex From mark.asbach at post.rwth-aachen.de Wed Jan 12 16:34:50 2005 From: mark.asbach at post.rwth-aachen.de (Mark Asbach) Date: Wed, 12 Jan 2005 22:34:50 +0100 Subject: readline, rlcompleter References: <1105429869.770262.14360@c13g2000cwb.googlegroups.com> Message-ID: <1gqaqap.1h5fh1voo5axiN%mark.asbach@post.rwth-aachen.de> Hi Michele, > readline.parse_and_bind("tab: complete") > > but I don't find a list of recognized key bindings. The python readline module just wraps the GNU Readline Library, so you need to check the manuals of the latter. It's not that much text and you'll find the information needed at: http://cnswww.cns.cwru.edu/php/chet/readline/rluserman.html#SEC10 Yours, Mark From stephen.thorne at gmail.com Wed Jan 19 02:06:29 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Wed, 19 Jan 2005 17:06:29 +1000 Subject: File objects? - under the hood question In-Reply-To: <20050118225310.1939807216.whereU@now.com> References: <20050119034955.75129.qmail@web50306.mail.yahoo.com> <20050118225310.1939807216.whereU@now.com> Message-ID: <3e8ca5c8050118230670ab3d9e@mail.gmail.com> On Tue, 18 Jan 2005 22:53:10 -0800, Eric Pederson wrote: > > I didn't come across any illuminating discussion via Google, thus my question here (though it may be a neophyte question.) I am interested in the workings under the hood of Python's access of "files". > > What is actually happening at the various stages when I create a file object and "read" it? > > (1) >>> f = file("C:/GuidosParrot.txt","r") You've just opened a file for reading. You haven't read any data, but at this point if the file wasn't there, the OS would have throw you an error. > (2) >>> hesjustsleeping = f.read() The entire file is read directly into a single python str. Regards, Stephen Thorne. From nobody at here.com Sat Jan 1 07:01:50 2005 From: nobody at here.com (fedor) Date: Sat, 01 Jan 2005 13:01:50 +0100 Subject: pickling a subclass of tuple Message-ID: <41d69113$0$14985$3a628fcd@reader2.nntp.hccnet.nl> Hi all, happy new year, I was trying to pickle a instance of a subclass of a tuple when I ran into a problem. Pickling doesn't work with HIGHEST_PROTOCOL. How should I rewrite my class so I can pickle it? Thanks , Fedor #!/usr/bin/env python import pickle class A(tuple): def __new__(klass, arg1,arg2): return super(A,klass).__new__(klass, (arg1,arg2)) a=A(1,2) print "no pickle",a print "normal pickle",pickle.loads(pickle.dumps(a)) print "highest protocol", pickle.loads(pickle.dumps(a,pickle.HIGHEST_PROTOCOL)) This is the output: ''' no pickle (1, 2) normal pickle (1, 2) highest protocol Traceback (most recent call last): File "./test.py", line 9, in ? print "highest protocol",pickle.loads(pickle.dumps(a,pickle.HIGHEST_PROTOCOL)) File "/usr/lib/python2.3/pickle.py", line 1394, in loads return Unpickler(file).load() File "/usr/lib/python2.3/pickle.py", line 872, in load dispatch[key](self) File "/usr/lib/python2.3/pickle.py", line 1097, in load_newobj obj = cls.__new__(cls, *args) TypeError: __new__() takes exactly 3 arguments (2 given) ''' From fredrik at pythonware.com Tue Jan 11 15:00:40 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 11 Jan 2005 21:00:40 +0100 Subject: Python Installation References: <1105220812.579690.292260@c13g2000cwb.googlegroups.com><1105232505.142279.85810@c13g2000cwb.googlegroups.com> <41E15306.7090108@holdenweb.com> Message-ID: Steve Holden wrote: > Hmm, effbot.org seems to be down just now. Sure it'll be back soon, though. http://news.bbc.co.uk/2/hi/europe/4158809.stm From rupole at hotmail.com Wed Jan 19 22:34:48 2005 From: rupole at hotmail.com (Roger Upole) Date: Wed, 19 Jan 2005 22:34:48 -0500 Subject: Automatic Windows printer creation? References: Message-ID: <41ef2765$1_2@127.0.0.1> You can probably do it through WMI. (class is Win32_Printer) WMI works well with win32com, and there's also a wrapper module http://tgolden.sc.sabren.com/python/wmi.html for simplified access. I imagine getting all the device parameters and port configuration right will be messy, though. Roger "GMane Python" wrote in message news:mailman.902.1106163375.22381.python-list at python.org... > Anyone know if there's a module which will allow me to 'create' windows > printer definitions? Not from a Windows domain network, but just to add a > printer that sends to a jet-direct-attached printer. > > Thanks! > Dave > > > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From jeff at ccvcorp.com Tue Jan 25 21:09:09 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 25 Jan 2005 18:09:09 -0800 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> Message-ID: <10vduiphjmli9d@corp.supernews.com> Davor wrote: > M.E.Farmer wrote: > >> Wrap your head around Python, don't wrap the Python around your head! >> This is NOT Java, or C++ or C , it IS Python. > > > that's interesting hypothesis that behavior will vary due to the use of > different language ... If using a different language doesn't require/encourage different programming habits, then what's the point of using a different language? "A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis Different languages offer different modes of expression, different ways of approaching the same problem. That's *why* we have so many different programming languages -- because no single approach is the best one for all problems, and knowing multiple approaches helps you to use your favored approach more effectively. Jeff Shannon Technician/Programmer Credit International From bokr at oz.net Fri Jan 7 21:01:48 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 08 Jan 2005 02:01:48 GMT Subject: Notification of PEP Updates References: <41df128d.260695390@news.oz.net> Message-ID: <41df3e19.271843109@news.oz.net> On Fri, 07 Jan 2005 16:05:31 -0700, Steven Bethard wrote: >Bengt Richter wrote: >> On Sat, 08 Jan 2005 03:28:34 +1000, Nick Coghlan wrote: >> >> >>>I can't recall which thread this came up in, so I'm starting a new one. . . >>> >>>Barry Warsaw has kindly added a "peps" topic to the python-checkins mailing >>>list. If you want to be notified only when PEP's get updated, then subscribe to >>>python-checkins and edit your settings to select just the 'peps' topic. >> >> How does one get to editing one's settings? > > >Go to the bottom of the page > >http://mail.python.org/mailman/listinfo/python-checkins > >under "Python-checkins Subscribers", fill in your email address and >click "Unsubscribe or edit options". Fill in the "password" field on >the next page and click "Log in". The topic option should be near the >bottom of the page. > Thanks. It was below the bottom of the screen, and I expected the option in the context of first subscribing, not coming back in after confirmation. D'oh ;-/ Regards, Bengt Richter From ialbert at mailblocks.com Tue Jan 18 10:42:31 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 18 Jan 2005 10:42:31 -0500 Subject: Integration with java (Jpype vs. JPE) In-Reply-To: References: <34s5krF4c85d5U1@individual.net> Message-ID: Steve Menard wrote: > To asnwer your question more fully, the jpype-specific cide is only for > looking up the Classes and startting/stopping the environment. For > everything else, Java objects and classes are used as regular Python > objects. Thanks for the response. Currently I don't need to use java but in the past when I explored such a possibility I looked at jpype and I was unable to understand from the documentation what it actually does. There is a lot of text there, but it is all concerning catching errors or other subtleties. For a new visitor the most important question is about how it works, what does it do, and how can it be applied for the given problem. > everything else, Java objects and classes are used as regular Python > objects. This is too generic. My question was a little more specific, how would I pass a python list as an argument of a java class/method or transform a java list into a python one? You don't have to answer it here, I'm just pointing out the kind of questions that I was unable to get an answer for on the jpype website. best, Istvan. From steve at holdenweb.com Sat Jan 8 13:56:30 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 08 Jan 2005 13:56:30 -0500 Subject: tuples vs lists In-Reply-To: <41dff650$0$29357$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dff650$0$29357$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: worzel wrote: > Cheers - thanks for the feedback guys - pretty much answers the question for > me. > > 'Two-Pull' it is then, thanks. > Well, it might be "Two-Pull" in American, but in English it's "tyoopl" -- NOT "choopl" (blearch!). I've also heard people say "tuppl". So, basically, say whatever you want. Language is about communication :-) you-say-tomato-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From alia_khouri at yahoo.com Wed Jan 26 13:57:31 2005 From: alia_khouri at yahoo.com (alia_khouri at yahoo.com) Date: 26 Jan 2005 10:57:31 -0800 Subject: .WAV processing library ? In-Reply-To: References: Message-ID: <1106765851.535421.150970@f14g2000cwb.googlegroups.com> Chris Stiles wrote: > Is there a library available for python that will enable me to process .wav > files ? > > Preferably extensible so I can write handlers for dealing with the non audio > sections. You will probably find everything you're looking for here: http://www.python.org/moin/PythonInMusic AK From sylvain.thenault at nospam.logilab.fr Tue Jan 11 04:37:20 2005 From: sylvain.thenault at nospam.logilab.fr (Sylvain Thenault) Date: Tue, 11 Jan 2005 10:37:20 +0100 Subject: PyChecker messages References: Message-ID: On Tue, 11 Jan 2005 06:54:54 +0000, Frans Englich wrote: > Hello, Hi > I take PyChecker partly as an recommender of good coding practice You may alos be interested by Pylint [1]. Pylint is less advanced in bug detection than pychecker, but imho its good coding practice detection is more advanced and configurable (as the pylint author, i'm a little biased... ;), including naming conventions, code duplication, bad code smells, presence of docstring, etc... Side note : I wish that at some point we stop duplicated effort between pylint and pychecker. In my opinion that would be nice if each one focus on its strenghs (as i said bugs detection for pychecker and convention violation / bad code smell for pylint). That would be even better if both tools could be merged in one, but (at least last time I took a look at pychecker) the internal architecture is so different that it's not an easy task today. Any thoughts ? [1] http://www.logilab.org/projects/pylint -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From firemoth at gmail.com Wed Jan 19 19:41:20 2005 From: firemoth at gmail.com (Timothy Fitz) Date: Wed, 19 Jan 2005 19:41:20 -0500 Subject: Zen of Python In-Reply-To: <1106177050.630141.33090@c13g2000cwb.googlegroups.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> Message-ID: <972ec5bd0501191641166972b0@mail.gmail.com> On 19 Jan 2005 15:24:10 -0800, Carl Banks wrote: > The gist of "Flat is better than nested" is "be as nested as you have > to be, no more," because being too nested is just a mess. Which I agree with, and which makes sense. However your "gist" is a different meaning. It's not that "Flat is better than nested" it's that "Too flat is bad and too flat is nested so be as nested (or as flat) as you have to be and no more." Perhaps Tim Peters is far too concise for my feeble mind From mike at hobbshouse.org Wed Jan 12 10:41:59 2005 From: mike at hobbshouse.org (Michael Hobbs) Date: Wed, 12 Jan 2005 15:41:59 -0000 Subject: Detecting shutdown of remote socket endpoint. References: <1105504107.d645f57ce935d6cb8e82567c0be1e97e@onlynews> Message-ID: <10uaha7b1o9i22f@corp.supernews.com> Tim Gosselin wrote: > I am writing a tcp tunnel but cannot find a way of detecting when a socket > shuts down its read end without writing to the socket. For testing the > write end of the remote endpoint I just do a: > > if not sock.recv(buffsize) > > I cannot write to the socket and check if send returns 0 though, because > that involves sending data out of the which may not have come in yet. > > When I try polling the socket with: > r, w, e=select([],[sock],[], 0) > w returns with the socket still writable, even if the other end was > closed. Even at the C level, I believe there were some differences between Unix and Windows sockets in regard to this, so this advice may be dependent on your platform. At any rate, on both Unix and Windows, a closed socket will continue to report itself as writable. To detect the closed socket, I believe that one system reports the socket as being in error whereas the other system reports the socket as being readable (where read() will then immediately return 0 because the socket is closed). So in summary, instead of: r, w, e=select([],[sock],[], 0) try this: r, w, e=select([sock],[],[sock], 0) If r or e is non-empty, then the socket has been closed (or there's some other error). HTH, - Mike From martin at v.loewis.de Fri Jan 28 03:21:04 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 28 Jan 2005 09:21:04 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xu0p2dvsa.fsf@ruckus.brouhaha.com> References: <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> Message-ID: <41f9f5e6$0$25927$9b622d9e@news.freenet.de> Paul Rubin wrote: >>I can say that assuming I know what so-and-so is. For the specific >>case of AES, I would say "I don't think the Python lib necessarily >>needs to have an AES module, but I would not object if it had one" > > > Well, ok, you're changing your tune a little bit now, and getting more > reasonable. Before, you were making blanket statements of any modules > written for the Python stdlib. Now you're limiting it to AES and basing > it on some AES-specific things. And I still stand by those blanket statements. Any new module (i.e. specific code) should see real users for some time before it can be incorporated into Python. The question whether I would like to see a certain *feature* in Python (whether as a separate module, a language feature, or otherwise) is an entirely different question. That I would not object to an AES code in general doesn't imply that I will agree to any AES module that somebody contributes. > I would say the first thing I'd request would be your sense of how > plausible it is that the current no-crypto policy might be relaxed. There is no such policy in force. Different people have different opinions, and those opinions change over time. I cannot speak for others. > Again OK. I had thought from earlier discussions that you were a > crypto developer and familiar with this stuff; no problem if you're > not. However, in that case, you probably wouldn't be using the module > if it got included. I think the best policy if you don't feel > comfortable supporting including some module (whether it's crypto or > something else) that you're not personally going to use, is don't > support inclusion, but also don't obstruct it. Thanks for the advise, but I'll have my own policies. I have included several modules in the past which I'm not personally using. >>In addition, for any new module, there is one primary requirement >>for acceptance that cannot be fulfilled in code quality: the >>contributor should promise to support the module in a foreseeable >>future (i.e. a couple of years). > > > That's not too unreasonable, though I don't think I've heard it > mentioned as a requirement before. See PEP 2. > I've never heard of any requirement before that there be two separate > implementations of every Python stdlib module, by the way. That would > be silly. And I did not suggest such a thing. You said you never heard about a process which requires an implementation before deciding that the proposed feature is good, and I said that, for an example, IETF even requires *two* implementations before deciding that the feature is good. >>>However, the result of my not writing an AES module is that Python >>>doesn't have an AES module. >> >>That's not true. PyCrypto does have AES support. > > That's not in any Python distro that I know of. Sure, but "Python" is more than the Python core. > I myself would probably never support including any > such module no matter how long it was distributed, but rather would > just defer the whole question to people experienced with such modules > and trust their sense of what the acceptance criteria should be for a > specific module. That is, I'd abstain from any decision. With that attitude, the patches tracker on SF would grow unbounded, because we *continuously* get patches that no core developer has any personal interest in. I'll try to look at *all* patches, whenever I can, and in the process, I have to learn about technologies which I've never used before (primarily operating systems, but also APIs and protocols). Rejecting all these patches would be unfair to the contributors. > Your answer is more like "make enough for 500 people and bring it to > the conference site and only then will we even THINK about whether to > serve it for breakfast. I cannot see these as the same thing. > I'm sure that's true of lots of modules. If you're the sole maintainer > of the Python distro, then you have to evaluate every module that anyone > submits. But since you're part of a reasonable sized group, I think > it's best to examine the modules you care about, but don't feel that > you have to have your hands in everything. Thanks again for the advise, but this is not how Python is being maintained. Regards, Martin From alanmk at hotmail.com Sun Jan 23 14:06:11 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 23 Jan 2005 19:06:11 +0000 Subject: Textual markup languages (was Re: What YAML engine do you use?) In-Reply-To: References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> Message-ID: [Alan Kennedy] >> From what I've seen, pretty much every textual markup targetted >> for web content, e.g. wiki markup, seems to have grown/evolved >> organically, meaning that it is either underpowered or overpowered, >> full of special cases, doesn't have a meaningful object model, etc. [Fredrik Lundh] > I spent the eighties designing one textual markup language after > another, for a wide variety of projects (mainly for technical > writing). I've since come to the conclusion that they all suck > (for exactly the reasons you mention above, plus the usual > "the implementation is the only complete spec we have" issue). Thanks Fredrik, I thought you might have a fair amount of experience in this area :-) [Fredrik Lundh] > the only markup language I've seen lately that isn't a complete mess > is John Gruber's markdown: > > http://daringfireball.net/projects/markdown/ > > which has an underlying object model (HTML/XHTML) and doesn't have > too many warts. not sure if anyone has done a Python implementation > yet, though (for html->markdown, see > http://www.aaronsw.com/2002/html2text/ ), and I don't think it > supports footnotes (HTML doesn't). Thanks for the pointer. I took a look at Markdown, and it does look nice. But I don't like the dual syntax, e.g. switching into HTML for tables, etc: I'm concerned that the syntax switch might be too much for non-techies. [Alan Kennedy] >> If I can't find such a markup language, then I might instead end up >> using a WYSIWYG editing component that gives the user a GUI and >> generates (x)html. >> >> htmlArea: http://www.htmlarea.com/ >> Editlet: http://www.editlet.com/ >> >> But I'd prefer a markup solution. [Fredrik Lundh] > some of these are amazingly usable. have you asked your users what > they prefer? (or maybe you are your user? ;-) Actually, I'm looking for a solution for both myself and for end-users (who will take what they're given ;-). For myself, I think I'll end up picking Markdown, ReST, or something comparable from the wiki-wiki-world. For the end-users, I'm starting to think that GUI is the only way to go. The last time I looked at this area, a few years ago, the components were fairly immature and pretty buggy. But the number of such components and their quality seems to have greatly increased in recent times. Particularly, many of them seem to address an important requirement that I neglected to mention in my original list: unicode support. I'll be processing all kinds of funny characters, e.g. math/scientific symbols, european, asian and middle-eastern names, etc. thanks-and-regards-ly-y'rs, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From sjmachin at lexicon.net Tue Jan 4 14:11:44 2005 From: sjmachin at lexicon.net (John Machin) Date: 4 Jan 2005 11:11:44 -0800 Subject: Reaching the real world In-Reply-To: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> References: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> Message-ID: <1104865904.543973.63380@z14g2000cwz.googlegroups.com> Fuzzyman wrote: > I have a friend who would like to move and program lights and other > electric/electro-mechanical devices by computer. I would like to help - > and needless to say Python would be an ideal language for the > 'programmers interface'. Try Googling for "Python X10" From sjmachin at lexicon.net Sat Jan 15 20:29:44 2005 From: sjmachin at lexicon.net (John Machin) Date: 15 Jan 2005 17:29:44 -0800 Subject: How to del item of a list in loop? In-Reply-To: References: Message-ID: <1105838984.045727.55730@f14g2000cwb.googlegroups.com> Michael Hoffman wrote: > skull wrote: > > but I still have an other thing to worry about coming with this way: does > > performance sucks when the list is big enough? > > It makes a copy operation! > > > > here is a faster and 'ugly' solution: > > > > lst = [1, 2, 3] > > i = 0 > > while i < len(lst): > > if lst[i] == 2: > > lst.remove(i) > > else: > > i += 1 > > Actually, that is the slowest of the three methods proposed so far for > large lists on my system. Assuming, as have other posters, that the requirement is to remove all elements whose value is 2: it doesn't work. The result is [2, 3] instead of the expected [1, 3]. > method_while: [3.8680000305175781, 3.8680000305175781, 3.872999906539917] Three significant figures is plenty. Showing just the minimum of the results might be better. > If you want to get really hairy, you can compare the bytecode instructions > for these three methods: Timing and bytecode-peeking a broken function are a little "premature". From roy at panix.com Fri Jan 7 11:36:36 2005 From: roy at panix.com (Roy Smith) Date: 7 Jan 2005 11:36:36 -0500 Subject: Getting rid of "self." References: <740c3aec05010705393048a374@mail.gmail.com> <1105114214.359029.152240@f14g2000cwb.googlegroups.com> Message-ID: Simon Brunning wrote: >On 7 Jan 2005 08:10:14 -0800, Luis M. Gonzalez wrote: >> The word "self" is not mandatory. You can type anything you want >> instead of self, as long as you supply a keyword in its place (it can >> be "self", "s" or whatever you want). > >You *can*, yes, but please don't, not if there's any chance that >anyone other than you are going to have to look at your code. >'self.whatever' is clearly an instance attribute. 's.whatever' isn't >clearly anything - the reader will have to go off and work out what >the 's' object is. +1. If there is one coding convention which is constant through the Python world, it's that the first argument to a class method is named "self". Using anything else, while legal, is just being different for the sake of being different. From fumanchu at amor.org Wed Jan 19 16:35:20 2005 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 19 Jan 2005 13:35:20 -0800 Subject: Accessing MDB files on Windows Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398207@exchange.hqamor.amorhq.net> Jorge Luiz Godoy Filho wrote: > What is the best way to deal with MDB files? I was thinking on using > ODBC... I'll need to read and write some information to it. The load > won't be so high, but there might be a lot of data. > > Any advices? Will my approach work? I'm not a Windows guy... :-) Use ADO unless you need to support older versions of Windows. It'll be a lot faster and cleaner than ODBC. Robert Brewer MIS Amor Ministries fumanchu at amor.org From craig at postnewspapers.com.au Fri Jan 21 10:42:21 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 21 Jan 2005 23:42:21 +0800 Subject: need help on need help on generator... In-Reply-To: <200501211605.40696.francis.girard@free.fr> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> <200501211605.40696.francis.girard@free.fr> Message-ID: <1106322141.19065.42.camel@bucket.localnet> On Fri, 2005-01-21 at 16:05 +0100, Francis Girard wrote: > I recently read David Mertz (IBM DeveloperWorks) about generators and > got excited about using lazy constructs in my Python programming. Speaking of totally great articles, and indirectly to lazyness (though not lazyily evaluated constructs), I was really impressed by this fantastic article on metaclasses: http://gnosis.cx/publish/programming/metaclass_1.html http://gnosis.cx/publish/programming/metaclass_2.html which shows that they're really just not that hard. That saved me an IMMENSE amount of utterly tedious coding just recently. > But besides the fact that generators are either produced with the new > "yield" reserved word or by defining the __new__ method in a class > definition, I don't know much about them. They can also be created with a generator expression under Python 2.4. A generator expression works much like a list comprehension, but returns a generator instead of a list, and is evaluated lazily. (It also doesn't pollute the outside namespace with its working variables). >>> print [ x for x in range(1,10)] [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print ( x for x in xrange(1,10) ) >>> print list(( x for x in xrange(1,10) )) [1, 2, 3, 4, 5, 6, 7, 8, 9] Not the use of xrange above for efficiency in the generator expressions. These examples are trivial and pointless, but hopefully get the point across. > In particular, I don't know what Python constructs does generate a > generator. As far as I know, functions that use yield, and generator expressions. I was unaware of the ability to create them using a class with a __new__ method, and need to check that out - I can imagine situations in which it might be rather handy. I'm not sure how many Python built-in functions and library modules return generators for things. > I know this is now the case for reading lines in a file or with the > new "iterator" package. But what else ? Does Craig Ringer answer mean > that list comprehensions are lazy ? Nope, but generator expressions are, and they're pretty similar. > Where can I find a comprehensive list of all the lazy constructions > built in Python ? (I think that to easily distinguish lazy from strict > constructs is an absolute programmer need -- otherwise you always end > up wondering when is it that code is actually executed like in > Haskell). I'm afraid I can't help you with that. I tend to take the view that side effects in lazily executed code are a bad plan, and use lazy execution for things where there is no reason to care when the code is executed. -- Craig Ringer From premshree.pillai at gmail.com Sat Jan 1 08:27:25 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Sat, 1 Jan 2005 18:57:25 +0530 Subject: Which blog tool In-Reply-To: <41d6a22f$0$42579$ed2619ec@ptn-nntp-reader03.plus.net> References: <41d6a22f$0$42579$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: On Sat, 01 Jan 2005 13:14:23 +0000, Mark Carter wrote: > I currently use python to automatically summarise a certain newsgroup > daily, and post the findings that it makes. Someone has suggested that > they would like a to see a blog of the posts. I wondered if there was a > python tool/library that could automate the blog postings. Any ideas? > > Some details: > * the summaries are basically just text files > * I already have a blog at www.blogger.com > (http://markcarterturriff.blogspot.com/), so I would like to use that if > possible; although any alternative free one that I can use to achieve my > objective would be OK, too. You can use the Blogger API to post to your Blogger account. There's a Python interface to the API -- PyBlogger -- available here: http://beetle.cbtlsl.com/archives/category/pyblogger You could also use a free service like LiveJournal (http://www.livejournal.com/). There are several clients available to post to LJ. I don't know if a Python wrapper to post is available or not. IAC, it'd be a few lines of code to make the XML-RPC calls. The protocol docs are available here: http://www.livejournal.com/doc/server/ljp.csp.protocol.html HTH > * I do have my own hosted website, which can use perl but not python; > but I'd rather use a freebie blog site > * the whole thing must be scriptable, because it will run daily. A GUI > would therefore likely get in the way. > * generating an RSS feed would be nice > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From Benjamin_Schmeling at gmx.de Mon Jan 31 08:01:56 2005 From: Benjamin_Schmeling at gmx.de (Benjamin Schmeling) Date: Mon, 31 Jan 2005 14:01:56 +0100 Subject: implicit conversion Message-ID: <41FE2C44.20205@gmx.de> Hi, I am working on exposing a bigint class to python. Now I've got the problem that methods which take an bigint as an parameter do not accept Python longs. For example: import _PythonLiDIA x=123L; c=_PythonLiDIA.bigint(); _PythonLiDIA.gcd(c,x); Traceback (most recent call last): File "test.py", line 132, in ? _PythonLiDIA.gcd(a,x); Boost.Python.ArgumentError: Python argument types in _PythonLiDIA.gcd(bigint, long) did not match C++ signature: gcd(LiDIA::bigint, LiDIA::bigint) I don't know how to achieve implicit conversion at this point, turning an long automatically into an bigint. The other way round, turning an bigint into long can be realized by defining __long__. Can someone help me please? Benjamin From jurgenex at hotmail.com Tue Jan 18 22:16:18 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Wed, 19 Jan 2005 03:16:18 GMT Subject: [perl-python] 20050118 keyed list References: <1106027360.920787.321590@z14g2000cwz.googlegroups.com> Message-ID: <6ikHd.10352$5t2.9480@trnddc01> Tassilo v. Parseval wrote: > Also sprach J?rgen Exner: > >> Xah Lee wrote: > >>> ? %a = ('john',3, 'mary', 4, 'jane', 5, 'vicky',7); >>> ? use Data::Dumper qw(Dumper); >>> ? print Dumper \%a; >> >> Wow, my compliments. The very first time that using Data::Dumper >> actually may do something useful (formats the data more nicely). >> Still, why you are passing a reference is beyond me. > > How else would you use 'Dumper' on a hash? Well, fair enough. If you do a plain print Dumper(%a); you do loose a lot of the nifty pretty printing that is provided by Dumper otherwise. jue From rNOSPAMon at flownet.com Sun Jan 2 12:26:14 2005 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 02 Jan 2005 09:26:14 -0800 Subject: Python! Is! Truly! Amazing! References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: In article <1104657461.868175.252380 at c13g2000cwb.googlegroups.com>, "Erik Bethke" wrote: > > I have NEVER experienced this kind of programming joy. Just wait until you discover Lisp! ;-) rg From emami at knmi.nl Wed Jan 5 09:08:37 2005 From: emami at knmi.nl (Nader Emami) Date: Wed, 05 Jan 2005 15:08:37 +0100 Subject: date/time Message-ID: L.S., Could somebody help me how I can get the next format of date from the time module? example: I have to have this time 20050105. It is the next attributes of format %Y%m%d. with regards, Nader From ncoghlan at iinet.net.au Sat Jan 8 23:49:11 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 14:49:11 +1000 Subject: python3: 'where' keyword In-Reply-To: <7x3bxbe97m.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> Message-ID: <41E0B7C7.5010607@iinet.net.au> Paul Rubin wrote: >>What would be the advantage of that over this? >> >>. x = sqrt(a) + sqrt(b) where: >>. a = 2.0 >>. b = 3.0 > > > The idea of "where" is to allow re-using variable names instead of > having to keep track of which ones are in use. I just tried to give a > very simple example of how you might do that more than once in a > statement. I think having to keep the names unique within the statement you are currently writing is a reasonable request :) Cheers, Nick -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ptmcg at austin.rr._bogus_.com Thu Jan 13 12:33:37 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 13 Jan 2005 17:33:37 GMT Subject: Refactoring; arbitrary expression in lists References: <41e5cb07.701137402@news.oz.net><41e5fdce.714136143@news.oz.net> Message-ID: Despite the regexp alternatives, I refuse to post a pyparsing solution to this! :) -- Paul From motokoit at tiscali.it Thu Jan 27 19:47:43 2005 From: motokoit at tiscali.it (motokoit) Date: Fri, 28 Jan 2005 01:47:43 +0100 Subject: python under java Message-ID: <41f98cba$0$129$5fc30a8@news.tiscali.it> For some reason i need to start a python script from inside a java code. The technique is standard Process proc = Runtime.getRuntime().exec("python myscript.py") and so worked for months.... since yestarday the same instruction does not work but the line is correct because from the terminal prompt it works! By the way the instruction work for every other command, for example Process proc = Runtime.getRuntime().exec("emacs") works. Some suggestion? My machine is a Linux Mandrake64 10.1 From ncookson at networkusa.net Thu Jan 13 05:54:07 2005 From: ncookson at networkusa.net (ncookson at networkusa.net) Date: 13 Jan 2005 02:54:07 -0800 Subject: wxPython and CheckListBox Message-ID: <1105613647.610479.13280@z14g2000cwz.googlegroups.com> I am trying to add a caption or title to the box drawn around a checklistbox and having no luck. Is there a way to do this? I am using python 2.3.4 and wxPython 2.5 on a windows platform. Noel From jacek at -no-spam-.devguide.net Fri Jan 14 13:52:14 2005 From: jacek at -no-spam-.devguide.net (Jacek) Date: Fri, 14 Jan 2005 19:52:14 +0100 Subject: python connect to db2 In-Reply-To: References: <1105689253.3167.0.camel@linux.tister.com> Message-ID: yuzx wrote: > anyone can help me ? this might help: http://www6.software.ibm.com/reg/devworks/dw-db2pylnx-i?S_TACT=104AHW03&S_CMP=EDU jacek From cdavisNOSP at NOSPstaffmail.ed.ac.uk Wed Jan 12 07:44:08 2005 From: cdavisNOSP at NOSPstaffmail.ed.ac.uk (Cory Davis) Date: Wed, 12 Jan 2005 12:44:08 +0000 Subject: distutils linux script installation broken? In-Reply-To: References: Message-ID: Thanks Albert. I already do use #!/usr/bin/env python in my package directory, but the build_scripts part of "setup.py install" changes this line to #!None before copying to my bin directory. Cheers, Cory. Albert Hofkamp wrote: > On Wed, 12 Jan 2005 10:09:03 +0000, Cory Davis wrote: > >>command has been behaving badly. In the part where it is supposed to >>adjust the first line of the script it now produces >> >>#!None >> >>instead of >> >>#!/whereverpythonis/python >> >>Has anyone else encountered this? > > > I haven't (as I am not using 2.4 :-) ) > > However, there is an easy way around this, just use > > #!/usr/bin env python > > instead. > > > Albert From steve at holdenweb.com Mon Jan 17 10:19:46 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 10:19:46 -0500 Subject: Native widgets for Python In-Reply-To: <87oefom7at.fsf@mrbun.watterson> References: <41EBC7F3.5050807@web.de> <87oefom7at.fsf@mrbun.watterson> Message-ID: Tim Heaney wrote: > Stephen Thorne writes: > >>there's someone writing 'dabo', which is apparently "wxpython but >>more python". > > > It looks like dabo uses, not replaces, wxPython > > http://dabodev.com/about Actually I think it *layers* wxPython, with the intention of being able to replace wxPython with other GUI kits at a later date. So, there should be a simpler graphical API, but since I haven't yet done more than dabble (dabole?) with dabo I can't be sure. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From stephen.thorne at gmail.com Sat Jan 8 18:46:35 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Sun, 9 Jan 2005 09:46:35 +1000 Subject: Pre/Postconditions with decorators In-Reply-To: <34814fF43bm4cU1@individual.net> References: <1105094828.619317.315340@z14g2000cwz.googlegroups.com> <34814fF43bm4cU1@individual.net> Message-ID: <3e8ca5c805010815462170f496@mail.gmail.com> On Fri, 7 Jan 2005 20:01:50 +0200, George Sakkis wrote: > > Hi George, > > it would be nice to see how you have tackled > > the task. > > Maybe we will have a checker > > module in Python one day... ;-) > > I posted my module on http://rafb.net/paste/results/voZYTG78.html and its unit test on > http://rafb.net/paste/results/MYxMQW95.html. Any feedback will be appreciated. Okay, nice. Unresolved Problems: 1) How do you handle duck types, i.e. a method that accepts StringIO, cStringIO or any other object that has a .readlines(), .seek() and .read() method? 2) How do you turn off the type checking for production code? Otherwise I quite like it. Please publish it somewhere. Stephen. From premshree.pillai at gmail.com Wed Jan 5 07:17:05 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Wed, 5 Jan 2005 17:47:05 +0530 Subject: is python more popular than coldfusion? In-Reply-To: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: On Wed, 5 Jan 2005 19:59:21 +0800, worzel wrote: > > > > is python more popular than coldfusion? I don't know if Coldfusion _was_ ever more "popular" than Python, but Python is definitely more "popular" _now_. This might be of some help: http://www.tiobe.com/tpci.htm > > I realsie that is a very general question as one thing does not directly > relate to the other. My issue is that I am ditching coldfusion due to there > being next to no work for it, and I am thinking of taking on python as a > second language to java in the hope of improving my resume. > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Premshree Pillai http://www.livejournal.com/~premshree From lee at example.com Wed Jan 5 17:35:21 2005 From: lee at example.com (Lee Harr) Date: Wed, 05 Jan 2005 22:35:21 GMT Subject: date/time References: Message-ID: On 2005-01-05, Nader Emami wrote: > L.S., > > Could somebody help me how I can get the next format of date > from the time module? > > example: I have to have this time 20050105. It is the next > attributes of format %Y%m%d. > I would use the datetime module: >>> import datetime >>> today = datetime.date.today() >>> today datetime.date(2005, 1, 5) >>> today.strftime('%Y%m%d') '20050105' >>> one_day = datetime.timedelta(1) >>> tomorrow = today + one_day >>> tomorrow.strftime('%Y%m%d') '20050106' From mcturra2000 at yahoo.co.uk Sun Jan 2 06:45:58 2005 From: mcturra2000 at yahoo.co.uk (Mark Carter) Date: Sun, 02 Jan 2005 11:45:58 +0000 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> > It might be nice if it was widely understood (in IT) that Python was a language any competent > programmer could pick up in an afternoon I am a programmer who works for a firm of engineers, where they program in VBA, badly. I've often mentioned Python, whereupon I'm usually dismissed as a crank. One of them expressed concern that if they used Python and I left, then nobody would understand what to do. I could have countered that Python is actually quite an easy language to pick up, but what's the point. We might be doing a project which involves web-type stuff. I pointed out that if they did, they wouldn't be able to use VB/VBA, and may need to use something like Python. I didn't get a reaction from that at the time, but no doubt they'll be telling me that I'll have to make Excel work through the internet, or something. From skip at pobox.com Sat Jan 29 09:53:45 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 29 Jan 2005 08:53:45 -0600 Subject: limited python virtual machine In-Reply-To: <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> Message-ID: <16891.41849.882856.527798@montanaro.dyndns.org> >> One thing my company has done is written a ``safe_eval()`` that uses >> a regex to disable double-underscore access. Alex> will the regex catch getattr(object, Alex> 'subclasses'.join(['_'*2]*2)...?-) Now he has two problems. ;-) Skip From abigail at abigail.nl Thu Jan 13 18:35:41 2005 From: abigail at abigail.nl (Abigail) Date: 13 Jan 2005 23:35:41 GMT Subject: [perl-python] 20050112 while statement References: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee (xah at xahlee.org) wrote on MMMMCLIII September MCMXCIII in : .. # here's a while statement in python. .. .. a,b = 0,1 .. while b < 20: .. print b IndentationError: expected an indented block .. a,b = b,a+b You have already proven you don't know Perl, but now it turns out, you don't know Python either. Go away. Abigail -- package Z;use overload'""'=>sub{$b++?Hacker:Another}; sub TIESCALAR{bless\my$y=>Z}sub FETCH{$a++?Perl:Just} $,=$";my$x=tie+my$y=>Z;print$y,$x,$y,$x,"\n";#Abigail From steven.bethard at gmail.com Thu Jan 20 18:34:55 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 20 Jan 2005 16:34:55 -0700 Subject: [Python-Dev] Updated Monkey Typing pre-PEP In-Reply-To: <001d01c4ff46$bec52040$793ec797@oemcomputer> References: <001d01c4ff46$bec52040$793ec797@oemcomputer> Message-ID: On Thu, 20 Jan 2005 18:21:17 -0500, Raymond Hettinger wrote: > > Instead of a __getattr__ solution, I recommend subclassing from a mixin: > > class RichMap(SomePartialMapping, UserDict.DictMixin): pass > > class RichFile(SomePartialFileClass, Mixins.FileMixin): pass I've been wondering for a while if there shouldn't be a mixins module for these kind of things. DictMixin, of course, and a maybe ListMixin to add extended slicing, append, extend, index, etc. I can see that a FileMixin might also be useful... If a mixins module was created, it would also give us the opportunity to break backwards compatibility with DictMixin and base it off of __getitem__(), __setitem__(), __delitem__(), and __iter__() instead of __getitem__(), __setitem__(), __delitem__(), and keys(). (According to the language reference, the __iter__ method is much more integral to mapping types than the keys method: http://docs.python.org/ref/sequence-types.html) Steve -- You can wordify anything if you just verb it. --- Bucky Katt, Get Fuzzy From michele.simionato at gmail.com Sun Jan 9 00:42:36 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 8 Jan 2005 21:42:36 -0800 Subject: Returning same type as self for arithmetic in subclasses In-Reply-To: <41df0d7b$0$190$edfadb0f@dread12.news.tele.dk> References: <41df0d7b$0$190$edfadb0f@dread12.news.tele.dk> Message-ID: <1105249356.919694.299020@c13g2000cwb.googlegroups.com> Max. M.: > So I wondered if there was a simlpler way to coerce the result into my > desired types rather than overwriting the __add__, __sub__ etc. methods? Tim Peters: >> Generally speaking, no. But I'm sure someone will torture you with a >> framework that purports to make it easy . I will not dispute the Timbot assessment ;) He is also right that people have already undergone under this level of torture: see http://tinyurl.com/6m373 for instance. Michele Simionato From cookedm+news at physics.mcmaster.ca Fri Jan 28 16:23:15 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 28 Jan 2005 16:23:15 -0500 Subject: LinearAlgebra incredibly slow for eigenvalue problems References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> Message-ID: "drife" writes: > Hello, > > I need to calculate the eigenvectors and eigenvalues for a 3600 X 3600 > covariance matrix. > > The LinearAlgebra package in Python is incredibly slow to perform the > above calculations (about 1.5 hours). This in spite of the fact that > I have installed Numeric with the full ATLAS and LAPACK libraries. > > Also note that my computer has dual Pentium IV (3.1 GHz) processors > with 2Gb ram. > > Every Web discussion I have seen about such issues indicates that > one can expect huge speed ups if one compiles and installs Numeric > linked against the ATLAS and LAPACK libraries. Are you *sure* that Numeric is linked against these? > Even more perplexing is that the same calculation takes a mere 7 min > in Matlab V6.5. Matlab uses both ATLAS and LAPACK. > > Moreover, the above calculation takes the same amount of time for > Numeric to complete with --and-- without ATLAS and PACK. I am certain > that I have done the install correctly. This is good evidence that Numeric *isn't* linked to them. If you're on a Linux system, you can check with ldd: cookedm at arbutus$ ldd /usr/lib/python2.3/site-packages/Numeric/lapack_lite.so liblapack.so.3 => /usr/lib/atlas/liblapack.so.3 (0x0000002a95677000) libblas.so.3 => /usr/lib/atlas/libblas.so.3 (0x0000002a95e55000) libg2c.so.0 => /usr/lib/libg2c.so.0 (0x0000002a96721000) libpthread.so.0 => /lib/libpthread.so.0 (0x0000002a96842000) libc.so.6 => /lib/libc.so.6 (0x0000002a96957000) libm.so.6 => /lib/libm.so.6 (0x0000002a96b96000) /lib64/ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2 (0x000000552aaaa000) You can see that lapack and blas (the Atlas versions) are linked to the lapack_lite.so. To install Numeric using Lapack: - remove the build/ directory in your Numeric sources, so you don't any old binaries - edit setup.py and follow the comments on using Lapack (you need to comment out a few lines, and set some directories) Also set use_dotblas to 1. - do the 'python setup.py build', 'python setup.py install' dance. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From macrocosm at fastmail.fm Sun Jan 9 09:50:19 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Sun, 09 Jan 2005 09:50:19 -0500 Subject: Python Operating System??? In-Reply-To: <10u19fmj9086b8b@news.supernews.com> References: <10trb0mgiflcj4f@corp.supernews.com> <1105219440.064891.199690@c13g2000cwb.googlegroups.com> <10u19fmj9086b8b@news.supernews.com> Message-ID: <41E144AB.8050002@fastmail.fm> John Roth wrote: > > "jtauber" wrote in message > news:1105219440.064891.199690 at c13g2000cwb.googlegroups.com... > >> My experiment, Cleese, was making progress before I got distracted by >> other things. >> .... >> >> I should probably get back to it at some stage. > > > As my ex-wife was fond of saying, "I wish you'd have > told me it was impossible before I did it." > > John Roth Is that why she divorced you? You will notice that tauber says he stopped working on Cleese due to "distraction" not a lack of progress or a notion of impending doom/"impossibility". > >> >> see http://cleese.sourceforge.net/ >> James Tauber >> http://jtauber.com/blog/ >> > From benn at cenix-bioscience.com Thu Jan 20 04:48:17 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Thu, 20 Jan 2005 10:48:17 +0100 Subject: Oddity is shutil.copyfileobj Message-ID: <41EF7E61.1090602@cenix-bioscience.com> Hello, I'm running a program which is using shutil.copyfileobj on a Win2K Pro, python 2.3 box. The source and dest file are both opened in textual mode as 'w', the source file on the local hard drive and the dest file is on a file server (transmitted through a samba server), the block size for copying is not entered - so the default setting is used (whatever that is). The files are copied across perfectly (diffing them shows they are identical), however I have one small problem, the destination filename has .read appended to the end. I've checked my code again and again and I'm definatly not apeending this. I'm also copying files across, in the same program but the source and dest are binary - this doesn't have the same problem, the filenames are not changed. My question is - has anyone else seen this behaviour? Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From peter at somewhere.com Tue Jan 11 15:37:20 2005 From: peter at somewhere.com (Peter Maas) Date: Tue, 11 Jan 2005 21:37:20 +0100 Subject: OT: MoinMoin and Mediawiki? In-Reply-To: References: <7x6524d6pv.fsf@ruckus.brouhaha.com> Message-ID: <34irrfF4bvjsvU1@individual.net> Alexander Schremmer schrieb: > Having a DBMS backend is good in your opinion? It has some severe > disadvantages like not easy to scale (you would need to setup DBMS > replication), two potential points of failure, more complex setup, bigger > memory requirements, etc. So nobody should use DBMS backends, right? Except those poor guys who need transactions, consistency rules, indexes, a standard query language, ... ;) What do you mean with scaling? If you multiply CPU and RAM by 8, good DBMS deliver nearly eightfold performance. If you distribute a DBMS on an 8 computer cluster, the DBMS will scale. If you distribute a DBMS on 8 arbitrary unrelated computers, you have 8 DBMSs which need to synchronize their data by replication. Do applications with file based persistence scale better? Since files need no setup beyond creation, every setup is complex compared to files ;) See e.g. the setup of an PostgreSQL DBMS: ./configure gmake su gmake install adduser postgres mkdir /usr/local/pgsql/data chown postgres /usr/local/pgsql/data su - postgres /usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data /usr/local/pgsql/bin/postmaster -D /usr/local/pgsql/data >logfile 2>&1 & /usr/local/pgsql/bin/createdb test /usr/local/pgsql/bin/psql test The first four lines are the same for every source based distribution, only 8 lines are PostgreSQL specific. I don't think this is too complex. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From peter at engcorp.com Sun Jan 23 21:07:46 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jan 2005 21:07:46 -0500 Subject: Help on project, anyone? In-Reply-To: <35ienhF4lu88lU1@individual.net> References: <35ienhF4lu88lU1@individual.net> Message-ID: Georg Brandl wrote: > Hello, > > to train my Python skills I am looking for some project I can contribute > to. I learned Python about one year ago, and had already some > programming background behind (I contributed to SharpDevelop for > instance), so I'm not the complete newbie. > > About myself: I'm a 20 year old German with strong interests in > programming and, of course, especially in Python (I love it...). > > Does anyone run, or participate in, a project looking for fellow > programmers? I don't have a special area of interest, well, perhaps web > programming... Maybe here? http://www.uselesspython.com/pythonchallenge.html From xun.ling at gmx.de Mon Jan 10 10:04:45 2005 From: xun.ling at gmx.de (xunling) Date: 10 Jan 2005 07:04:45 -0800 Subject: "Re: Re: Probleme mit der Installation der openSource Bittorrent.... python vs JAVA" Message-ID: i still need an answer ... anyone out there who could help me plz? :/ thx - xun From spam at nospam.org Tue Jan 25 20:48:53 2005 From: spam at nospam.org (Erik Johnson) Date: Tue, 25 Jan 2005 18:48:53 -0700 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> Message-ID: <41f6f4ee$1@nntp.zianet.com> "Davor" wrote > I do not hate OO - I just do not need it for the project size I'm > dealing with - and the project will eventually become open-source and > have additional developers... If you think your project is valuable enough to eventually be "Open Source", you can bet that one of the first criticisms it will face is that it is not OO if it is perceived that there would be any advantage to being so. If your question is "Can I write useful Python code without writing my own classes, without creating a class inheritance heirarchy, etc.?" then the answer is definitely "Yes!" Python has lots of very useful and practical libraries to allow you to do all sorts of cool things. Many of those interfaces though are presented in an OO manner (to varying degrees). >so I would prefer that we all stick to > "simple procedural" stuff rather than having to deal with a developer > that will be convincing me that his 50 layers inheritance hierarchy is > good since it exists in some weird pattern that he saw somewhere on > some Java design patterns discussion board :-) and other "proper" OO > design issues... If your question is "Can I somehow hobble Python so that there are no objects anywhere and it is not possible for other developers to even think about creating something I can't understand?" then I would ask how is it you are leading a team of other programmers that is apparently not afraid of OO concepts? You can write lot's of code that is just functions, and have functions call other functions, but what does a 'def' statement (python's syntax for function definition) do? It instantiates a function object. That function can be copied (well, the reference to it, anyway), passed to other functions, returned from functions, stored in variables, etc. You may or may not see any practical use for that, but Python was (very wisely) designed to be OO right from the very start - it definitely wasn't something that was added on later. You might want to spend a little time pondering why that is. If you don't understand the difference between pop(mylist) and mylist.pop(), it would be a wise career move to invest a little time to understand what the difference is and why the state of software development has come to prefer one over the other. At the bottom, practically everything in Python is an object... >>> dir(42) ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__hash__', '__hex__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__'] there's just no getting around it. If you want to set down the groundrules for your project that you will stick to basically just procedural code, fine - that's a project management issue. If you are insistent there can be no objects anywhere in your implementation, Python is definitely the WRONG choice. Well... there is no choice. It would be impossible with Python. Note also that Perl is definitely out, as is JavaScript and even PHP. ANSI C might work and (as pointed out earlier), some other likely candidates are sh, bash, csh, ksh... I don't know a lot about Tcl/Tk - I think it implements some rather OO'ish stuff, but worth consideration. Good luck. -ej From elbertlev at hotmail.com Wed Jan 12 17:45:21 2005 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: 12 Jan 2005 14:45:21 -0800 Subject: pyXLwriter and jython Message-ID: <1105569920.986226.253150@z14g2000cwz.googlegroups.com> Hi! I was using pyXLwriter in C-python, but recently had to code in jython. Tried to port pyXLwriter to jython and it does not work. Did somebody uset this module with jython? From klaus_neuner82 at yahoo.de Wed Jan 26 09:41:19 2005 From: klaus_neuner82 at yahoo.de (Klaus Neuner) Date: 26 Jan 2005 06:41:19 -0800 Subject: fast list lookup Message-ID: <3e96ebd7.0501260641.159e007f@posting.google.com> Hello, what is the fastest way to determine whether list l (with len(l)>30000) contains a certain element? Klaus From bulba at bulba.com Sun Jan 9 13:53:04 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 09 Jan 2005 19:53:04 +0100 Subject: Speed revisited References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> <1105237556.402188.126980@c13g2000cwb.googlegroups.com> Message-ID: On 8 Jan 2005 18:25:56 -0800, "John Machin" wrote: >> Both versions use local variables, etc. Both have their >> lists initially sorted. Both essentially use a loop with >> conditional for comparison, >> then process the record in the >> same way. > >"process the record in the same way"??? That's an interesting use of >"same". Meaning when the records with the same 'english' key is found, just write the comparison result to the result file. >> The overhead of second version is that it also >> uses cmp() function and two additional integer >> variables - that should not slow the program _so much_. >> I have measured the run of snippet 2 with time checkpoints >> written to a log (write time delta to log every 200 records), >> even made a graph of time deltas in spreadsheet and in fact >> snippet 2 seems after initial slowdown looks exactly linear, >> like that: >> >> ^ (time) >> | >> | /----------- >> | / >> |/ >> ---------------> (# of records written) >> >> So yes, it would scale to big files. > >On your empirical evidence, as presented. However, do read on ... >>However, why is it so >> frigging slow?! >Mainly, because you are (unnecessarily) deleting the first item of a >list. This requires copying the remaining items. It is O(N), not O(1). >You are doing this O(N) times, so the overall result is O(N**2). Your >graph has no obvious explanation; after how many cycles does the speed >become constant? After some 2000 records. I was "tracking" it with printouts of variables and initially the main loop was taking advantage of records being sorted, with the first condition (with keys being equal) quickly writing the records into a file, and the further into the dataset, the greater the distance was between the beginning of the list where the record was sought to the appropriate record, i.e. either o or n were becoming steadily higher. This could explain linearity further down the path: the list is becoming gradually shorter, so the deletion times were decreasing linearly, but in the meantime the search time was linearly increasing. >Secondly, you are calling cmp() up to THREE times when once is enough. >Didn't it occur to you that your last elif needed an else to finish it >off, and the only possible action for the else suite was "assert >False"? Sure, but I was trying to make it shorter and absolutely clear what I mean in this place (when people see the comparison in every place, they see immediately what it was, they don't have to recall the variable). Obviously I'd optimise it in practice. It was supposed to be "proof of concept" rather than any working code. BTW, this particular example didn't work out, but I still found Python to be the most convenient language for prototyping, I wrote smth like five versions of this thing, just to learn dictionaries, lists, sets, etc. In no other language I'd do it so quickly. >It would appear after reading your "snippet 2" a couple of times that >you are trying to implement the old 3-tape update method. Well, ahem, I admit you got me curious just how it would work with tapes (never used them), so I was sort of trying to simulate that - it's just a bit weird undertaking, I did it rather to explore the issue and try to learn smth rather than to get working code. Deleting the first item from a list was to be a convenient equivalent of forwarding the reading head on the tape one record ahead, because I assumed that any deletion from the list was to take more or less the same time, just like reading heads on tapes were probably reading the records with similar speeds regardless of what length of tape was already read. >It would also appear that you are assuming/hoping that there are never >more than one instance of a phrase in either list. Sure. Because using advice of Skip Montanaro I initially used sets to eliminate duplicates. It's just not shown for brevity. If the keys are guaranteed to be unique, it makes it easier to think about the algorithm. >You need something a little more like the following. >Note that in your snippet2 it was not very obvious what you want to do >in the case where a phrase is in "new" but not in "old", and vice versa >-- under one circumstance (you haven't met "end of file") you do >nothing but in the the other circumstance you do something but seem to >have not only a polarity problem but also a copy-paste-edit problem. What exactly is a "polarity problem"? I concede that the code is rather contrived, but I didn't bother to do smth like writing classes or functions that would simulate a tape reader, so the result is rather ugly. I only posted it because I could not explain why it were so slow. > In >the following code I have abstracted the real requirements as >handle_XXX_unmatched() Thanks, I'll have to try that out. -- It's a man's life in a Python Programming Association. From frans.englich at telia.com Wed Jan 12 14:18:36 2005 From: frans.englich at telia.com (Frans Englich) Date: Wed, 12 Jan 2005 19:18:36 +0000 Subject: Refactoring; arbitrary expression in lists In-Reply-To: <1105556212.036972.160470@z14g2000cwz.googlegroups.com> References: <1105556212.036972.160470@z14g2000cwz.googlegroups.com> Message-ID: <200501121918.36423.frans.englich@telia.com> On Wednesday 12 January 2005 18:56, wittempj at hotmail.com wrote: > I can not break the original code in 2.4, if I try this: [...] > > So although the dictionary solution is much nicer nothing seems wrong > with your code as it is - or am I missing something? Nope, the current code works. I'm just looking at Python's cool ways of solving problems. (the matter about 11 returns was a coding-style report from PyChecker). Cheers, Frans From john at grulic.org.ar Sun Jan 23 14:06:37 2005 From: john at grulic.org.ar (John Lenton) Date: Sun, 23 Jan 2005 16:06:37 -0300 Subject: OT: problems mirroring python-list to c.l.py? In-Reply-To: <1d6cdae305012310535980e82d@mail.gmail.com> References: <1d6cdae305012310535980e82d@mail.gmail.com> Message-ID: <20050123190637.GA4820@grulic.org.ar> > On Sun, Jan 23, 2005 at 01:53:52PM -0500, Daniel Bickett wrote: > > > > Is there a reason that Google Groups isn't mirroring python-list > > exactly like it used to, or is it simply a conspiracy I'm not in on? > > You should not ask this kind of question in a public forum, and *you* should know better than to go around flapping your mouth like that. -- John Lenton (john at grulic.org.ar) -- Random fortune: Comer se ha de hacer en silencio, como los frailes en sus conventos. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From Serge.Orlov at gmail.com Thu Jan 13 17:33:20 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 13 Jan 2005 14:33:20 -0800 Subject: Unicode conversion in 'print' In-Reply-To: References: Message-ID: <1105655600.059496.70350@z14g2000cwz.googlegroups.com> Ricardo Bugalho wrote: > Hello, > I'm using Python 2.3.4 and I noticed that, when stdout is a terminal, > the 'print' statement converts Unicode strings into the encoding > defined by the locales instead of the one returned by > sys.getdefaultencoding(). Sure. It uses the encoding of you console. Here is explanation why it uses locale to get the encoding of console: http://www.python.org/moin/PrintFails > However, I can't find any references to it. Anyone knows where it's > descrbed? I've just wrote about it here: http://www.python.org/moin/DefaultEncoding > > Example: > > !/usr/bin/env python > # -*- coding: utf-8 -*- > > import sys, locale > > print 'Python encoding:', sys.getdefaultencoding() > print 'System encoding:', locale.getpreferredencoding() > print 'Test string: ', u'Ol? mundo' > > > If stdout is a terminal, works fine > $ python x.py > Python encoding: ascii > System encoding: UTF-8 > Test string: Ol? mundo > > If I redirect the output to a file, raises an UnicodeEncodeError exception > $ python x.py > x.txt > Traceback (most recent call last): > File "x.py", line 8, in ? > print 'Test string: ', u'Ol? mundo' > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 2: ordinal not in range(128) > http://www.python.org/moin/ShellRedirectionFails Feel free to reply here if something is not clear, corrections in wiki are also welcome. Serge. From steve at holdenweb.com Sat Jan 8 14:02:23 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 08 Jan 2005 14:02:23 -0500 Subject: Returning same type as self for arithmetic in subclasses In-Reply-To: References: <41df0d7b$0$190$edfadb0f@dread12.news.tele.dk> Message-ID: <_aWDd.69984$Jk5.34806@lakeread01> Tim Peters wrote: > [Max M] > >>""" >>I subclass datetime and timedelta >> [...] > > Generally speaking, no. But I'm sure someone will torture you with a > framework that purports to make it easy . Clearly the easy way is to have the type declaration introspect on the definitions of datetime and timedelta and then auto-create methods wrapping the base types' methods in a "myxxx" conversion. left-as-an-exercise-for-the-reader-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From daranrife at yahoo.com Fri Jan 28 23:08:27 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 20:08:27 -0800 Subject: Installing Numeric with ATLAS and LAPACK In-Reply-To: References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> <1106940704.164253.134630@c13g2000cwb.googlegroups.com> Message-ID: <1106971706.986114.26420@c13g2000cwb.googlegroups.com> Could you clarify this please? Let's say that I want to make a call to the LAPACK routine sspevd, and pass it a matrix, and get the result. How do I accomplish this? Thanks, Daran From craig at postnewspapers.com.au Wed Jan 19 22:35:42 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Thu, 20 Jan 2005 11:35:42 +0800 Subject: [OT] Good C++ book for a Python programmer In-Reply-To: <1106151297.339844.95380@c13g2000cwb.googlegroups.com> References: <1106136496.719185.87850@c13g2000cwb.googlegroups.com> <1106151297.339844.95380@c13g2000cwb.googlegroups.com> Message-ID: <1106192142.20679.1.camel@bucket.localnet> On Wed, 2005-01-19 at 09:04 -0800, beliavsky at aol.com wrote: > Rick Muller wrote: > >I was wondering whether anyone could recommend a good C++ book, with > >"good" being defined from the perspective of a Python programmer. > > The STL and the template feature of C++ gives the programmer some of > the functionality of Python (using templates instead of duck typing, > vectors instead of lists etc.), I'm particularly fond of internally refcounted objects (as used extensively in Qt) and of guarded pointers, myself. The use of these two things means one can avoid the "sometimes works, sometimes doesn't" fun of referencing deleted memory by accident. -- Craig Ringer From max at alcyone.com Mon Jan 31 13:32:34 2005 From: max at alcyone.com (Erik Max Francis) Date: Mon, 31 Jan 2005 10:32:34 -0800 Subject: The next Xah-lee post contest In-Reply-To: References: <20050130114008.797088857.whereU@now.com> <1107137465.973491.42050@f14g2000cwb.googlegroups.com> Message-ID: <3YCdnbjoYNJe5GPcRVn-gQ@speakeasy.net> Steve Holden wrote: > Would there, I wonder, be any enthusiasm for a "Best Xah Lee impression" > prize at PyCon? I imagine standing in a corner, facing the wall, and screaming incoherently at the top of your lungs would be guaranteed at least second place. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis You've got me wondering / If you know that I am wondering about you -- India Arie From jurgenex at hotmail.com Fri Jan 14 11:24:45 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Fri, 14 Jan 2005 16:24:45 GMT Subject: [perl-python] 20050113 looking up syntax References: <1105699357.565028.107750@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > --------------------- > > for perl syntax lookup, use perldoc in the command line. For example: > perldoc perl Wrong. That command will give you a high-level overview of Perl but tell you nothing about the syntax. To lookup the Perl syntax you would have to use perldoc perlsyn > use 'perldoc -f functionName' for specific function. example: > perldoc -f qq BS. That will tell you what a function does, it doesn't tell you anything at all about the syntax of Perl. BTW: Why on earth are you using qq() as an example? That doc page just points you to 'perldoc perlop'. > note that keywords cannot be looked up with -f. For basic keywords > like > > if, while..., use > perldoc perlop BS. What gave you the idea that keywords were operators? Of course keywords can be found where they belong, in the syntax definition of the language, but not in the operator section of the documentation. Why don't you just stop posting this nonsense? jue From john at grulic.org.ar Mon Jan 10 19:40:30 2005 From: john at grulic.org.ar (John Lenton) Date: Mon, 10 Jan 2005 21:40:30 -0300 Subject: Writing huge Sets() to disk In-Reply-To: <8765246hix.fsf@sme.intra.citec.fi> References: <1105390704.241316.267690@f14g2000cwb.googlegroups.com> <8765246hix.fsf@sme.intra.citec.fi> Message-ID: <20050111004030.GA24860@grulic.org.ar> On Tue, Jan 11, 2005 at 12:33:42AM +0200, Simo Melenius wrote: > "John Lenton" writes: > > > you probably want to look into building set-like objects ontop of > > tries, given the homogeneity of your language. You should see > > imrpovements both in size and speed. > > Ternary search trees give _much_ better space-efficiency compared to > tries, at the expense of only slightly slower build and search time. > This is especially essential as the OP mentioned he could have huge > sets of data. hmm! sounds like *some*body needs to go read up on ternary trees, then. Ok, ok, I'm going... -- John Lenton (john at grulic.org.ar) -- Random fortune: Fortune finishes the great quotations, #6 "But, soft! What light through yonder window breaks?" It's nothing, honey. Go back to sleep. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From skip at pobox.com Wed Jan 12 23:12:37 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 12 Jan 2005 22:12:37 -0600 Subject: why not datetime.strptime() ? In-Reply-To: <20050111173335.GB26246@yucs.org> References: <20050111021152.GA20127@yucs.org> <16867.59681.423983.244528@montanaro.dyndns.org> <20050111173335.GB26246@yucs.org> Message-ID: <16869.62773.572880.581805@montanaro.dyndns.org> Josh> The datetime is full of these calls. Would it make sense to make Josh> this a separate patch? (Or maybe the PyImport_ImportModule could Josh> implement such a cache :) ?) Hmmm... I wonder why that wasn't done before. Perhaps it just doesn't matter performance-wise. I just checked in your changes. Thanks for the effort. Skip From steven.bethard at gmail.com Thu Jan 27 13:45:42 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 11:45:42 -0700 Subject: String Fomat Conversion In-Reply-To: <1gr2aln.1a15eud1xil75nN%aleaxit@yahoo.com> References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> <1gr2aln.1a15eud1xil75nN%aleaxit@yahoo.com> Message-ID: <-qWdnbQcLoZJq2TcRVn-vA@comcast.com> Alex Martelli wrote: > Steven Bethard wrote: > ... > >>Beware of mixing iterator methods and readline: > [snip] > > I hope this concisely indicates that the problem (in today's current > implementations) is only with switching FROM iteration TO other > approaches to reading, and (if the file is seekable) there's nothing so > problematic here that a good old 'seek' won't cure... Thanks for the clarification! Steve From newsgroups at jhrothjr.com Wed Jan 5 12:26:34 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Wed, 5 Jan 2005 11:26:34 -0600 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> Message-ID: <10to8qulnc3vke1@news.supernews.com> "Paul Rubin" wrote in message news:7xhdlwh5qs.fsf at ruckus.brouhaha.com... > "alex23" writes: >> It's called "having an opinion". "Good" documentation does its job, if >> noone else thought it was poorly documented then to them it wasn't. ... > >> In short: grow up and just write the damn documentation. I've been reading this thread and quietly congratulating myself on staying out of it, but this statement takes the cake. I would like to contribute some documentation to Python. I've got the time, I write quite a bit, etc. I've got fairly strong opinions about some things that need to be documented, (such as all the new style class descriptor stuff from 2.2) and I have relatively little difficulty matching the existing style. However, I don't know TEX, Latex, CVS or Sourceforge. (The latter two are on my "learn sometime soon so I can put PyFIT where it belongs" list.) I have no desire to install Perl to run the documentation toolchain. I also have no particular desire to write up a bunch of final format stuff and drop it on someone else to put into the latex format so it can be included. That means I'm not going to spend literally months learning all of this stuff so I can then spend the two or three days (each) it would take to write decent documentation for the places I think are lacking, and where I have the competence to write it up. I'm also not going to spend those same months writing a current source to XML translator, and then writing XSLT or more scripts to do the translations to final format, a strategy which would arguably be much more beneficial for the Python community as a whole. The bottom line is that I'm not going to be writing any extensive pieces of Python documentation. My time is better spent elsewhere. John Roth From grig.gheorghiu at gmail.com Tue Jan 18 11:22:25 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 18 Jan 2005 08:22:25 -0800 Subject: script to automate GUI application (newbie) References: Message-ID: <1106065345.967083.163970@f14g2000cwb.googlegroups.com> Bogdan, If your app is written in Java, take a look at Marathon (http://marathonman.sourceforge.net/). It uses Jython as its scripting language and it's pretty smart about how it does automation (i.e. it doesn't look at screen coordinates, but at control names). It also offers a capture/replay functionality, and it automatically builds the Jython script that drives your flow of actions. You can then edit and enhance the script manually. Grig bogdan romocea wrote: > Dear Python experts, > > I have a GUI application (Windows; apparently written in Java) which I > want to use through a script (without a mouse or keyboard). First, one > of several buttons needs to be clicked (no keyboard shortcuts > available, but I can measure the coordinates in pixels from the top > left corner of the window to the center of the button to be clicked). > Then, a window with a few drop-down lists pops up - I have to make some > choices and click OK (it's possible to navigate from one drop-down to > the next with Tab, and hit Enter for OK). > > I want to run the script above from code (if this then click "... and > OK") and perhaps by means of several desktop shortcuts (one shortcut > for each set of GUI inputs). > > Is such a script possible? If yes, how do I get there? I searched > comp.lang.python but didn't find something directly applicable (or so > it seemed to me - I'm a beginner). Directions (and sample code, if > possible) will be warmly appreciated. > > Thank you, > b. > > > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - Easier than ever with enhanced search. Learn more. > http://info.mail.yahoo.com/mail_250 From deetsNOSPAM at web.de Thu Jan 20 07:50:37 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 20 Jan 2005 13:50:37 +0100 Subject: Class introspection and dynamically determining function arguments References: <359lfnF4hd6e3U1@individual.net> Message-ID: <359nmoF4koiepU1@individual.net> Nick Coghlan wrote: > > If this only has to work for classes created for the purpose (rather than > for an arbitrary class): > Certainly a step into the direction I meant - but still missing type declarations. And that's what at least I'd like to see - as otherwise you don't know what kind of editing widget to use for a property. -- Regards, Diez B. Roggisch From tzot at sil-tec.gr Wed Jan 26 06:03:18 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 26 Jan 2005 13:03:18 +0200 Subject: string.atoi and string.atol broken? References: Message-ID: <0ttev01qgb9k6a9f34g185lhohkn2p3evq@4ax.com> On Wed, 26 Jan 2005 02:10:44 +0100, rumours say that "Fredrik Lundh" might have written: >Mike Moum wrote: >> s.atoi('4',3) should result in 11 >> >> s.atoi('13',4) should result in 31 >> >> s.atoi('12',4) should result in 30 >> >> s.atoi('8',4) is legitimate, but it generates an error. >> >> Is this a bug, or am I missing something obvious? >the function's named "atoi", not "atoitoa". s.itoa(4,3) should result in '11' s.itoa(13,4) should result in '31' s.itoa(12,4) should result in '30' s.itoa(8,4) should result in '20' s.atoi('4', 3) should fail s.atoi('13', 4) should result in 7 s.atoi('12', 4) should result in 6 s.atoi('8', 4) should fail :) -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From max at alcyone.com Sat Jan 15 19:27:05 2005 From: max at alcyone.com (Erik Max Francis) Date: Sat, 15 Jan 2005 16:27:05 -0800 Subject: ANN: BOTEC 0.3 -- An astrophysical and orbital mechanics calculator Message-ID: Summary BOTEC is a simple astrophysical and orbital mechanics calculator, including a database of all named Solar System objects. Overview BOTEC is intended as a simple but useful calculator to assist with making astrophysical, orbital mechanics, and space navigation calculations. As the origin of the acronym applies, BOTEC is more of a "back-of-the-envelope calculator" rather than an industrial-strength calculator, although this may change in the future. BOTEC is primarily intended for people familiar with physics and Python, and as such is unlikely to be useful to the average enduser. BOTEC really consists of two parts: The BOTEC software, which knows what to do with the data, and the Solar System data itself, which is represented in a large data file (a Python pickle, actually). This is deliberately modularized so that the Solar System data BOTEC uses can be updated independently of thet software, and also that alternative data files (*e.g.*, hypothetical stellar systems for fictional purposes) can be supported. All values are strictly in SI units. Getting the software The current version of botec is 0.3. The latest version of the software is available in a tarball here: http://www.alcyone.com/software/botec/botec-latest.tar.gz. The official URL for this Web site is http://www.alcyone.com/software/botec/. Requirements BOTEC requires Python 2.3 or greater. In its present state, BOTEC will also not be of much use to endusers not familiar with Python, or people without some basic working knowledge of physics, astrophysics, orbital mechanics, and space navigation. License This code is released under the GPL. ... Release history [since 0.2] - 0.3, 2005 Jan 15. Separate transfers from maneuvers; support Oberth maneuvers. - 0.2.1, 2005 Jan 8. Various collected modifications. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis The quickest way of ending a war is to lose it. -- George Orwell From peter at engcorp.com Mon Jan 3 17:19:22 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Jan 2005 17:19:22 -0500 Subject: How do I make Windows Application with Python ? In-Reply-To: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> Message-ID: BOOGIEMAN wrote: > Well that's it, how do I make Windows Application with Python ??? > Is there simple way that works 100% ? How can I rework visual design > done in VS 2003 to use it for my python program ? What do you mean by "Windows Applications"? I'm running Python on Windows XP, so every program I write with Python is a "Windows application" by my definition. Obviously you are using a different one. (And if you just mean "it has a GUI", then my answer is "I use wxPython with Python". There is also Tkinter, and other options. Please ask a more specific, detailed question to get useful answers.) -Peter From Mark.English at liffe.com Wed Jan 26 06:57:18 2005 From: Mark.English at liffe.com (Mark English) Date: Wed, 26 Jan 2005 11:57:18 -0000 Subject: threading.py Condition wait overflow error Message-ID: <40E605146701DE428FAF21286A97D309174516@wphexa02.corp.lh.int> > Date: Wed, 26 Jan 2005 00:10:31 -0500 > From: Tim Peters > The most common cause for "impossible exceptions" > is flawed C code in an extension that fails to > check a Python C API call for an error return. Yes, I use a lot of C modules which I wrote. It could certainly be one of them (although which one could be an interesting challenge to find out). It may even have something to do with moving to the VC7.1 compiler. Thank you very much for your suggestion. Without it I would never have thought to look at that code. Mark ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From and-google at doxdesk.com Wed Jan 12 22:31:38 2005 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 12 Jan 2005 19:31:38 -0800 Subject: Octal notation: severe deprecation References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> Message-ID: <1105587098.932273.315230@c13g2000cwb.googlegroups.com> John Machin wrote: > I regard continued usage of octal as a pox and a pestilence. Quite agree. I was disappointed that it ever made it into Python. Octal's only use is: a) umasks b) confusing the hell out of normal non-programmers for whom a leading zero is in no way magic (a) does not outweigh (b). In Mythical Future Python I would like to be able to use any base in integer literals, which would be better. Example random syntax: flags= 2x00011010101001 umask= 8x664 answer= 10x42 addr= 16x0E800004 # 16x == 0x gunk= 36x8H6Z9A0X But either way, I want rid of 0->octal. > Is it not regretted? Maybe the problem just doesn't occur to people who have used C too long. OT: Also, if Google doesn't stop lstrip()ing my posts I may have to get a proper news feed. What use is that on a Python newsgroup? Grr. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From tim.golden at viacom-outdoor.co.uk Wed Jan 19 03:41:18 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 19 Jan 2005 08:41:18 -0000 Subject: Print to Windows default Printer Message-ID: <9A28C052FF32734DACB0A288A35339910359CC@vogbs009.gb.vo.local> [Samantha] | I am new to Python and I am having considerable trouble | trying to print | (using a simple script) to the default printer rather than the screen. | Thanks for any help. | S It may be that something here will help you: http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html Specifically, I think that the section print raw text is closest to what you're asking (although not necessarily to what you'll eventually want): http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html#win32print TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From engsolnorm at peak.org Fri Jan 14 13:43:47 2005 From: engsolnorm at peak.org (engsol) Date: Fri, 14 Jan 2005 10:43:47 -0800 Subject: Com port interrupts again Message-ID: <154gu09bghnq674s2nqot9si6d50igueq7@4ax.com> I didn't fully think through my application before posting my question. Async com port routines to handle com port interrups only work well if one has access to the low level operating system. In that case the receive buffer interrupt would cause a jump to an interrupt service routine.. I don't believe that Python provides that capabilty directly. The solution then would be to write a C extention? The suggestions offered by respondents to my original post were almost all of a "Use threads, and poll as needed" flavor. You're right...I need to learn threads as applied to com ports. Norm B From R.Brodie at rl.ac.uk Wed Jan 12 11:09:36 2005 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 12 Jan 2005 16:09:36 -0000 Subject: Iteration over two sequences References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> Message-ID: "Henrik Holm" wrote in message news:1gq9qs9.3snutr1s4mcn2N%news+0409 at henrikholm.com... > I suppose I could also use a lambda here -- but is there a different, > efficient, and obvious solution that I'm overlooking? Check the itertools recipes in the library documentation. From mwm at mired.org Mon Jan 3 17:28:18 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 03 Jan 2005 16:28:18 -0600 Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: <86652eqha5.fsf@guru.mired.org> "It's me" writes: > Well, now that they are API based, they can easily add any script language > they so wish through SWIG (www.swig.org). > > Maybe not LISP. SNOBOL would be the right thing to do. (*NOT*) SWIG generates wrappers for GUILE, which is Scheme, which looks enough like LISP to fool most people. It's the GNU extensible embeddable language. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steven.bethard at gmail.com Thu Jan 13 13:23:09 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 13 Jan 2005 11:23:09 -0700 Subject: [perl-python] 20050112 while statement In-Reply-To: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> References: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > # here's a while statement in python. > > a,b = 0,1 > while b < 20: > print b > a,b = b,a+b > > --------------- > # here's the same code in perl > > ($a,$b)=(0,1); > while ($b<20) { > print $b, "\n"; > ($a,$b)= ($b, $a+$b); > } Because you're posting this to newsgroups, it would be advisable to use only spaces for indentation -- tabs are removed by a lot of newsreaders, which means your Python readers are going to complain about IndentationErrors. Personally, I think you should not do this over comp.lang.python (and perhaps others feel the same way about comp.lang.perl.misc?) Can't you start a Yahoo group or something for this? What you're doing is probably not of interest to most of the comp.lang.python community, and might me more appropriate in a different venue. Steve From peter at somewhere.com Tue Jan 11 15:08:40 2005 From: peter at somewhere.com (Peter Maas) Date: Tue, 11 Jan 2005 21:08:40 +0100 Subject: reference or pointer to some object? In-Reply-To: References: Message-ID: <34iq5oF4c83i9U1@individual.net> Torsten Mohr schrieb: > i'd like to pass a reference or a pointer to an object > to a function. The function should then change the > object and the changes should be visible in the calling > function. [..] > is something like this possible in python? Yes, wrap it in a container, e.g. a list or an object. Change the containers content in the called function. > The keyword "global" does NOT fit this purpose to > my understanding as it only makes the variables of > the UPPERMOST level visible, not the ones of ONE > calling level above. There are three namespaces in python, sorted according to priority: - local variables of the current scope (function or method), highest priority, show with locals() - global variables of the containing module, show with globals() - builtin builtin variables, show with __builtins__.__dict__ Since Python 2.1 the local namespace can be nested e.g. if a function is defined inside a function. Example: >>> def fo(u): ... def fi(v): ... v2 = 2*v ... print locals() ... return v2 ... u2 = fi(u) ... print locals() ... return u2 ... >>> fo(4) {'v2': 8, 'v': 4} <-- inner local namespace {'fi': , 'u': 4, 'u2': 8} <-- outer local namespace 8 -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 15:33:32 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?UTF-8?B?TWFydGluIE1PS1JFSsWg?=) Date: Mon, 10 Jan 2005 21:33:32 +0100 Subject: Writing huge Sets() to disk In-Reply-To: References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> Message-ID: <41E2E69C.7080104@ribosome.natur.cuni.cz> Istvan Albert wrote: > Martin MOKREJ? wrote: > > >> But nevertheless, imagine 1E6 words of size 15. That's maybe 1.5GB of raw >> data. Will sets be appropriate you think? > > > You started out with 20E20 then cut back to 1E15 keys > now it is down to one million but you claim that these > will take 1.5 GB. I gave up the theoretical approach. Practically, I might need up to store maybe those 1E15 keys. So you say 1 million words is better to store in dictionary than in a set and use your own function to get out those unique or common words? > > On my system storing 1 million words of length 15 > as keys of a python dictionary is around 75MB. Fine, that's what I wanted to hear. How do you improve the algorithm? Do you delay indexing to the very latest moment or do you let your computer index 999 999 times just for fun? > > I. From bokr at oz.net Wed Jan 12 05:10:26 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 12 Jan 2005 10:10:26 GMT Subject: Another look at language comparisons References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> <1105188426.955508.263030@c13g2000cwb.googlegroups.com> <41e00ac1$0$265$edfadb0f@dread12.news.tele.dk> <34kaf5F4ag9k6U1@individual.net> Message-ID: <41e4f770.646970063@news.oz.net> On Wed, 12 Jan 2005 17:54:49 +0800, Jon Perez wrote: >Max M wrote: >> Jan Dries wrote: >> >>> beliavsky at aol.com wrote: >>> And there is hope for Python, as Guido has recently been seen with a >>> beard :-) >>> http://www.tbray.org/ongoing/When/200x/2004/12/08/-big/IMG_3061.jpg >> >> >> LOL, he is working on linux, isn't he? >> >> So it was about bloody time. > >Guido Van Rossum is now working on linux?? Are they both left-handed? Hm, sinister ... Regards, Bengt Richter From bvande at po-box.mcgill.ca Sat Jan 22 20:46:11 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 22 Jan 2005 20:46:11 -0500 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xbrbhosh7.fsf@ruckus.brouhaha.com> References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> Message-ID: <41F301E3.9000904@po-box.mcgill.ca> Paul Rubin said unto the world upon 2005-01-22 20:16: > "Fredrik Lundh" writes: > >>>You're not making any bloody sense. >> >>oh, I make perfect sense, and I think most people here understand >>why I found your little "lecture" so funny. if you still don't get >>it, maybe some- one can explain it to you. > > > I would appreciate it if someone did. Hi, no Python expert, just a hobbyist. But, I think I can take this one on: Fredrik's contributed a lot to Python. The Standard Library book, several well know tools, and, I'd wager a finger, a fair bit of code in the standard lib. I don't think the community gives you a name like F-bot, but that you know a wee bit about how Python is actually used, etc. Best, Brian vdB From steve at holdenweb.com Mon Jan 10 20:15:53 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Jan 2005 20:15:53 -0500 Subject: exceptions and items in a list In-Reply-To: References: Message-ID: vincent wehren wrote: > rbt wrote: > >> If I have a Python list that I'm iterating over and one of the objects >> in the list raises an exception and I have code like this: >> >> try: >> do something to object in list >> except Exception: >> pass >> >> Does the code just skip the bad object and continue with the other >> objects in the list, or does it stop? >> >> Thanks > > > Fire up a shell and try: > > >>> seq = ["1", "2", "a", "4", "5", 6.0] > >>> for elem in seq: > .... try: > .... print int(elem) > .... except ValueError: > .... pass > > > and see what happens... > > -- > Vincent Wehren I suspect the more recent versions of Python allow a much more elegant solution. I can't remember precisely when we were allowed to use continue in an except suite, but I know we couldn't in Python 2.1. Nowadays you can write: Python 2.4 (#1, Dec 4 2004, 20:10:33) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> for i in [1, 2, 3]: ... try: ... print i ... if i == 2: raise AttributeError, "Bugger!" ... except AttributeError: ... print "Caught exception" ... continue ... 1 2 Caught exception 3 >>> To terminate the loop on the exception you would use "break" instead of "continue". regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From harold.fellermann at upf.edu Thu Jan 13 12:06:43 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 13 Jan 2005 18:06:43 +0100 Subject: Tix.FileSelectDialog wait for user? Message-ID: <7FE013CC-6585-11D9-B3E0-003065FB7B26@upf.edu> Hi, I have a question concerning the Tix file select mechanisms. Unfortunately, I have very little experience with neither tk, Tkinter nor Tix. Somewhere in my GUI I have a save button. What I want is that pressing the button opens a file requester. The user can either select a filename or cancel the action. I have found Tix.FileSelectDialog which seems to be nice for the task. But how can I use this dialog after all? how can I e.g. attach a command to the "Ok"-Button. Or isn't there a simple function that 1.) opens the requester 2.) waits until the requester is closed 3.) returns either a string (filename) or None (canceled) so that I can just write something like: fname = FileSelect() if fname != None : do_something_with(fname) Damn, I hate Tk's and Tix' so called "manuals": The Tk manual takes a user and makes it into a grammar parser. Further information, like common usage or examples, that might normally be expected in a manual cannot be found with no additional arguments. The Tk manual returns the completely clueless programmer. Start to like pydoc(Tkinter) and pydoc(Tix), though :-) - harold - -- "Mr Ghandi, what do you think of western civilization?" "Oh, this would be a great idea." From rmemmons at member.fsf.org Wed Jan 5 21:37:52 2005 From: rmemmons at member.fsf.org (Rob Emmons) Date: Wed, 05 Jan 2005 20:37:52 -0600 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: > I'd go further. It's not possible to force anyone to share, but the > GPL aims to remove software from a system that instead aims to force > people NOT to share. Well said. I do think the point is -- no one liscence fits all. The GPL is a great tool for those that write software for the purpose of sharing with those that want to mutually share. Personally it has the feel of justice to me -- but that's just me. But of course it does not fit all needs and the politics and personalities of all developers and teams of developers. For example, RMS developed the LGPL for other cases where it makes sense, and I think I read somewhere that RMS encouraged the release of BSD (is that right?) -- because that too is a help to free software in the end. As for Python -- I think the best liscence depends on the goals of the developers. If you want python to be infrastructure, especially, for applciation scripting -- it's kind of nice that it's BSD like or perhaps LGPL, on the other hand if you want it to be free software focused -- then GPL would be better. So there are many alternatives depending on goals. You see this played out throughout the Open Source community. In any case -- regardless of liscence -- I think Python is the greatest and I have great respect for all those that have made it possible. Rob From steven.bethard at gmail.com Wed Jan 19 01:09:57 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 18 Jan 2005 23:09:57 -0700 Subject: generator expressions: performance anomaly? In-Reply-To: <41edcc68.1225778626@news.oz.net> References: <377Hd.77904$Jk5.30235@lakeread01> <41ED1C0F.4030800@holdenweb.com> <41eda453.1215517842@news.oz.net> <41edcc68.1225778626@news.oz.net> Message-ID: <_NCdnVV_I9UrZHDcRVn-og@comcast.com> Bengt Richter wrote: > On Tue, 18 Jan 2005 17:38:20 -0700, Steven Bethard wrote: > > >>Bengt Richter wrote: >> >>>Which make me wonder what plans there are for providing a better >>>mechanism than default arguments as a way of initializing local function >>>variables. Nested def's to create a closure with initialized values is >>>pretty crufty for that, IMO. >> >>What about using a class? Associating functions with data is pretty >>much what they're for... >> >> >>>Maybe extending the default argument space >>>with whatever comes after e.g. a triple star delimiter in the argument list, >>>but which wouldn't be counted as part of the normal arguments? E.g., >>> >>> def foo(x, y=123, *args, **kw, *** i=1, deftime=time.ctime()): >>> return x*y, kw.get('which_time')=='now' and time.ctime() or deftime >> >>If what you want is to have i=1 and deftime=time.ctime() available >>within foo, you could do something like (untested): >> >>class foo(object): >> def __init__(self): >> self.i = 1 >> self.deftime = time.ctime() >> def __call__(self, x, y=123, *args, **kwds): >> return x*y, (kw.get('which_time') == 'now' >> and time.ctime() or self.deftime) >>foo = foo() > > Total: 8 lines, much irrelevant cruft. > > >>Or if you don't like 'foo = foo()', you could probably abuse the __new__ >>method (also untested): >> >>class foo(object): >> i = 1 >> deftime = time.ctime() >> def __new__(cls, x, y=123, *args, **kwds): >> return x*y, (kw.get('which_time') == 'now' >> and time.ctime() or self.deftime) > > Total: 6 lines, newbie-unfriendly abuse of __new__ ;-) > > >>I guess my point is that if you want attribute associated with the >>function, it's often easy enough to write a class instead... > > vs. 2 easy lines with minimal irrelevant cruft ;-) If you're really counting lines, you might compare with the more compact: class foo(object): def __init__(self): self.i, self.deftime = 1, time.ctime() def __call__(self): return x*y, kw.get('which_time') == 'now' and time.ctime() or self.deftime foo = foo() and class foo(object): i, deftime = 1, time.ctime() def __new__(cls, x, y=123, *args, **kwds): return x*y, kw.get('which_time') == 'now' and time.ctime() or self.deftime And probably what you want to compare is N lines (function only) versus N + 2 lines (using __new__) and N + 4 lines (using __call__). If N is more than 2 lines (which is probably true in most cases), the difference isn't so dramatic. Using a class also has the advantage that, assuming one already knows how classes work (which any Python programmer who wants the kind of scoping you're talking about should) you don't have to learn how something new to be able to use it -- that is, *** -> bound locals that don't contribute to arguments but are listed in the same place as arguments. If you really want locals that don't contribute to arguments, I'd be much happier with something like a decorator, e.g.[1]: @with_consts(i=1, deftime=time.ctime()) def foo(x, y=123, *args, **kw): return x*y, kw.get('which_time')=='now' and time.ctime() or deftime Then you don't have to mix parameter declarations with locals definitions. Steve [1] I have no idea how implementable such a decorator would be. I'd just like to see function constants declared separate from arguments since they mean such different things. From irmen at -nospam-remove-this-xs4all.nl Tue Jan 18 13:54:25 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 18 Jan 2005 19:54:25 +0100 Subject: hex notation funtion In-Reply-To: References: Message-ID: <41ed5b61$0$6211$e4fe514c@news.xs4all.nl> tertius wrote: > Hi, > > Is there a builtin function that will enable me to display the hex > notation of a given binary string? (example below) Does this help: >>> "hello".encode("hex") '68656c6c6f' >>> "deadbeef".decode("hex") '\xde\xad\xbe\xef' ? --Irmen From bj_666 at gmx.net Sat Jan 8 15:48:26 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 08 Jan 2005 21:48:26 +0100 Subject: EOF for binary? References: <1105147072.909665.242360@z14g2000cwz.googlegroups.com> Message-ID: In <1105147072.909665.242360 at z14g2000cwz.googlegroups.com>, flamesrock wrote: > os.path.getsize(infile) <= infile.tell() > > Because that returns the error: > # File "/usr/lib/python2.3/posixpath.py", line 142, in getsize > # return os.stat(filename).st_size > #TypeError: coercing to Unicode: need string or buffer, file found > for me. This error message gives a good hint what's wrong with your code snippet. >>> f = open('tmp.txt') >>> os.path.getsize(f) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/posixpath.py", line 142, in getsize return os.stat(filename).st_size TypeError: coercing to Unicode: need string or buffer, file found Something expected a string instead of a file object. >>> os.path.getsize("tmp.txt") 28190L Ciao, Marc 'BlackJack' Rintsch From aorfanakos at gmail.com Fri Jan 28 09:17:38 2005 From: aorfanakos at gmail.com (Aggelos I. Orfanakos) Date: 28 Jan 2005 06:17:38 -0800 Subject: python: can't open file 'timeit.py' Message-ID: <1106921858.598528.77300@f14g2000cwb.googlegroups.com> Hello. Under Gentoo Linux, I issue: $ python timeit.py python: can't open file 'timeit.py' $ ls -al /usr/lib/python2.3/timeit.py -rw-r--r-- 1 root root 9833 Oct 19 02:17 /usr/lib/python2.3/timeit.py But if I specify the full path, it works: $ python /usr/lib/python2.3/timeit.py -n 1 "pass" 1 loops, best of 3: 3.1 usec per loop Any ideas how can I fix this? I think it may have to do with where Python looks for modules, but I am not sure. Thanks in advance. From skip at pobox.com Fri Jan 21 11:23:50 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 21 Jan 2005 10:23:50 -0600 Subject: ElementTree.findtext() In-Reply-To: References: Message-ID: <16881.11414.228817.410692@montanaro.dyndns.org> Richie> I realised what the problem was the second after I hit Send (why Richie> is it never the second *before*?) So you could enlighten those of us who didn't realize what the problem was, even ten seconds later than that... Richie> The tree represents the top-level element, so of course Richie> searching within it for 'html' fails. Thanks... Skip From jeff at ccvcorp.com Thu Jan 13 13:36:21 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 13 Jan 2005 10:36:21 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <1105632841.461042.68310@c13g2000cwb.googlegroups.com> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <41e5ebee.709560864@news.oz.net> <1105632841.461042.68310@c13g2000cwb.googlegroups.com> Message-ID: <10udfj4c4rgkvcc@corp.supernews.com> Chris Lasher wrote: >>Given that the information content is 2 bits per character >>that is taking up 8 bits of storage, there must be a good reason >>for storing and/or transmitting them this way? I.e., it it easy >>to think up a count-prefixed compressed format packing 4:1 in >>subsequent data bytes (except for the last byte which have >>less than 4 2-bit codes). > > My guess for the inefficiency in storage size is because it is > human-readable, and because most in-silico molecular biology is just a > bunch of fancy string algorithms. This is my limited view of these > things at least. Yeah, that pretty much matches my guess (not that I'm involved in anything related to computational molecular biology or genetics). Given the current technology, the cost of the extra storage size is presumably lower than the cost of translating into/out of a packed format. Heck, hard drives cost less than $1/GB now. And besides, for long-term archiving purposes, I'd expect that zip et al on a character-stream would provide significantly better compression than a 4:1 packed format, and that zipping the packed format wouldn't be all that much more efficient than zipping the character stream. Jeff Shannon Technician/Programmer Credit International From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 16:28:44 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?UTF-8?B?TWFydGluIE1PS1JFSsWg?=) Date: Mon, 10 Jan 2005 22:28:44 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <1f7befae0501101245679b26f2@mail.gmail.com> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> <41E2E69C.7080104@ribosome.natur.cuni.cz> <1f7befae0501101245679b26f2@mail.gmail.com> Message-ID: <41E2F38C.30200@ribosome.natur.cuni.cz> Tim Peters wrote: > [Martin MOKREJ?] > >>... >> >>I gave up the theoretical approach. Practically, I might need up >>to store maybe those 1E15 keys. > > > We should work on our multiplication skills here . You don't > have enough disk space to store 1E15 keys. If your keys were just one > byte each, you would need to have 4 thousand disks of 250GB each to > store 1E15 keys. How much disk space do you actually have? I'm > betting you have no more than one 250GB disk. Can get about 700GB on raid5, but this doesn't help here of course. :( I definitely appreciate your comments, I somehow forgot to make sure I can store it. I was mainly distracted by the fact I might anyway hit almost the same size, if there's too few words used in reality. Therefore when looking for those words not found in such a dictionary, I'd be close to the teoretical, maximal size of say in order of E15 or E14. > ... > > [Istvan Albert] > >>>On my system storing 1 million words of length 15 >>>as keys of a python dictionary is around 75MB. > > >>Fine, that's what I wanted to hear. How do you improve the algorithm? >>Do you delay indexing to the very latest moment or do you let your >>computer index 999 999 times just for fun? > > > It remains wholly unclear to me what "the algorithm" you want might My intent is do some analysis in protein science. But it can be really thought of as analysing those 4 different languages. > be. As I mentioned before, if you store keys in sorted text files, > you can do intersection and difference very efficiently just by using > the Unix `comm` utiltity. Now I got your point. I understand the comm(1) is written in C, but it still has to scan file1 once and file2 n-times, where n is a number of lines in file1, right? Without any index ... I'll consider it, actually will test, thanks! I was really hoping I'll get an answer how to alter the indexes for dictionaries in python. You convinced me not to even try to construct to theoretical dictionary, as it will take ages just to create. Even if I'd manage, I couldn't save it (the theoretical and possibly not even the dict(theoret) - dict(real) result). Still, before I give the whole project, once more: I'll parse some text files, isolates separate words and add them to either Set(), list, dict, flatfile line by line. Depending on the above, I'll compare them and look for those unique to some "language". I need to keep track of frequencies used in every such language, so the dict approach would be the best. The number stored as a value vould be a float ^H^H^H^H^H^H Decimal() type - very small number. Once more, I expect to have between E4 or E5 to E8??? words stored in 20 dictionaries (remember words of sizes in range 1-20? Every of those 20 dictionaries should be, I believe, indexed just once. The indexing method should know all entries in a given file are of same size, i.e. 5 chars, 15 chars, 20 chars etc. I already did implement the logic to walk through those 20 different dictionaries from language a and from language b and find uout those unique to a or common to both of them. Why I went to ask on this list was to make sure I took right approach. Sets seemed to be better solution for the simple comparison (common, unique). To keep track of those very small frequencies, I anyway have to have dictionaries. I say that again, how can I improve speed of dictionary indexing? It doesn't matter here if I have 10E4 keys in dictionary or 10E8 keys in a dictionary. Or I wanted to hear: go for Sets(), having set with 1E8 keys might take 1/10 of the size you need for a dictionary ... but you cannot dump them efficiently on a disk. Using shelve will cost you maybe 2x the size of dictionary approach and will be also slover that writing dictionary directly. Something along these words. I really appreciate your input! Martin From cwilbur at mithril.chromatico.net Sun Jan 9 14:39:29 2005 From: cwilbur at mithril.chromatico.net (Charlton Wilbur) Date: Sun, 09 Jan 2005 19:39:29 GMT Subject: unicode support References: <1105259315.471816.291600@c13g2000cwb.googlegroups.com> Message-ID: <87r7ku5riu.fsf@mithril.chromatico.net> >>>>> "xah" == xah writes: xah> python supports unicode in source xah> code by putting a coding declaration as the first line. [...] xah> In perl, support of unicode is very flaky. The language does xah> not support it, [...] All: Xah Lee is trolling. (Whether he's *only* a troll, or a reasonable person who occasionally trolls to amuse himself, is a matter of perspective.) Please note the inaccuracy of his comment on Perl and the two newsgroups to which this message was posted before replying; this is a clear case of "lets you and him fight." Charlton -- cwilbur at chromatico dot net cwilbur at mac dot com From tundra at tundraware.com Wed Jan 12 04:28:28 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 12 Jan 2005 04:28:28 EST Subject: [ANN]: twander 3.160 Released And Available Message-ID: <41E4ED28.60906@tundraware.com> 'twander' Version 3.160 is now released and available for download at: http://www.tundraware.com/Software/twander The last public release was 3.146. Existing users are encouraged to upgrade to this release as it has a number of bug fixes and several nice new features including: - Mouse popups for all the menus (except Help). - Ability to force Unix-style paths under Windows when doing substitutions in command macros. (Very helpful for cygwin users.) - A smarter "adaptive" directory refresh mechanism. - A new "Shortcut" menu for fast navigation around the filesystem. Complete details of all fixes, changes, and new features can be found in the WHATSNEW.txt file included in the distribution. Users are strongly encouraged to join the twander-users mailing list as described in the documentation. What Is 'twander'? ------------------ 'twander' is a macro-programmable Filesystem Browser that runs on both Unix-like systems as well as Win32 systems. It embraces the best ideas of both similar GUI-driven programs (Konqueror, Windows Explorer) as well as text-based interfaces (Midnight Commander, List, Sweep). Or, If You Prefer The "Elevator Pitch" -------------------------------------- 'twander' is: - A better file browser for Unix and Win32. (Tested on FreeBSD, Linux, Win32.) - A way to make browsing the same on all the OSs you use. - A macro-programmable tool that lets *you* define the features. - A GUI navigation front-end for your shell. - A way to "can" workflows for your technically-challenged colleagues. - A way to free yourself from the shackles of the mouse. - A way to significantly speed up your day-to-day workflow. - A Python/Tkinter application - about 3100/1300 lines of code/comments - A RCT (Really Cool Tool) that will have you addicted in a day or two See the web page for more information, a screen shot, and the complete documentation. ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From rbt at athop1.ath.vt.edu Sun Jan 2 14:18:18 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Sun, 02 Jan 2005 14:18:18 -0500 Subject: arbitrary number of arguments in a function declaration Message-ID: How do I set up a function so that it can take an arbitrary number of arguments? For example, I have a bunch of expenses which may grow or shrink depending on the client's circumstance and a function that sums them up... hard coding them is tedious. How might I make this dynamic so that it can handle any amount of expenses? def tot_expenses(self, e0, e1, e2, e3): pass From frans.englich at telia.com Mon Jan 17 16:43:23 2005 From: frans.englich at telia.com (Frans Englich) Date: Mon, 17 Jan 2005 21:43:23 +0000 Subject: Assigning to self In-Reply-To: References: Message-ID: <200501172143.23022.frans.englich@telia.com> On Monday 17 January 2005 21:24, Peter Otten wrote: > Frans Englich wrote: > > On Monday 17 January 2005 20:03, John Roth wrote: > >> "Frans Englich" wrote in message > > > > > > > >> In other words, you're trying to create a singleton. In general, > >> singletons are frowned on these days for a number of reasons, > >> not least because of the difficulty of testing them. > > > > Then I have some vague, general questions which perhaps someone can > > reason from: what is then the preferred methods for solving problems > > which requires Singletons? Is it only frowned upon in Python code? > > Sorry, no answer here, but do you really want a singleton? > > Singleton: "Ensure a class only has one instance, and provide a global > point of access to it" > > whereas > > Flyweight: "Use sharing to support large numbers of fine-grained objects > efficiently" > > as per "Design Patterns" by Gamma et al. Hehe :) Singleton sounds like what I want, but OTOH I do not know what Flyweight is, except for sounding interesting. Darn, I really must save for that Design Patterns by GOF. Cheers, Frans From michele.simionato at gmail.com Thu Jan 6 04:05:57 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 6 Jan 2005 01:05:57 -0800 Subject: python-dev Summary for 2004-11-16 through 2004-11-30 In-Reply-To: References: Message-ID: <1105002357.261642.292880@f14g2000cwb.googlegroups.com> > Would you like the source with your function? Yes, since I asked for this feature something like two years ago ;-) Michele Simionato From __peter__ at web.de Wed Jan 26 03:17:15 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Jan 2005 09:17:15 +0100 Subject: string.atoi and string.atol broken? References: Message-ID: Nick Coghlan wrote: > Huh - you remind me that I forgot to put the "show_base" Bengt and I came > up with into the ASPN cookbook. . . > > Py> def show_base(val, base, min_digits=1, complement=False, > ...???????????????digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"): > ...???if?base?>?len(digits):?raise?ValueError("Not?enough?digits?for > base") ...???negative?=?val? ...???val?=?abs(val) > ...???if?complement: > ...?????sign?=?"" > ...?????max?=?base**min_digits > ...?????if?(val?>=?max)?or?(not?negative?and?val?==?max): > ...???????raise?ValueError("Value?out?of?range?for?complemented?format") > ...?????if?negative: > ...???????val?=?(max?-?val) > ...???else: > ...?????sign?=?"-"?*?negative > ...???val_digits?=?[] > ...???while?val: > ...?????val,?digit?=?divmod(val,?base) > ...?????val_digits.append(digits[digit]) > ...???result?=?"".join(reversed(val_digits)) > ...???return?sign?+?("0"?*?(min_digits?-?len(result)))?+?result > ... > Yes, that is a bit more general. For the cookbook you might consider factoring out the "".join() operation, thus entirely removing the upper limit for the base (the output of the first step would be a tuple of integers). Peter From stuart at zapata.org Fri Jan 21 07:25:27 2005 From: stuart at zapata.org (Stu) Date: 21 Jan 2005 04:25:27 -0800 Subject: map in Python Message-ID: <1106310327.213874.305660@f14g2000cwb.googlegroups.com> I have recently switched over to Python from Perl. I want to do something like this in Python: @test = ("a1", "a2", "a3"); map {s/[a-z]//g} @test; print @test; However, I take it there is no equivalent to $_ in Python. But in that case how does map pass the elements of a sequence to a function? I tried the following, but it doesn't work because the interpreter complains about a missing third argument to re.sub. import re test = ["a1", "a2", "a3"] map(re.sub("[a-z]", ""), test) print test Thanks in advance. Regards, Stuart From harold.fellermann at upf.edu Fri Jan 21 23:11:46 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Sat, 22 Jan 2005 05:11:46 +0100 Subject: Class introspection and dynamically determining functionarguments In-Reply-To: <40E605146701DE428FAF21286A97D30917450D@wphexa02.corp.lh.int> References: <40E605146701DE428FAF21286A97D30917450D@wphexa02.corp.lh.int> Message-ID: On 20.01.2005, at 12:24, Mark English wrote: > I'd like to write a Tkinter app which, given a class, pops up a > window(s) with fields for each "attribute" of that class. The user > could > enter values for the attributes and on closing the window would be > returned an instance of the class. The actual application I'm > interested > in writing would either have simple type attributes (int, string, > etc.), > or attributes using types already defined in a c-extension, although > I'd > prefer not to restrict the functionality to these requirements. I am working on nearly the same thing! Small sort of generic attribute editor in Tkinter (and Tix). Altough my implementation is still very unpythonic (== ugly) in many places, it can edit the attributes of instances and classes, as well as generate new instances / classes. I would like to create new attributes or delete them as well, but haven't done it so far. A still faraway dream would be, to allow the user to enter source code, that will be compiled into byte code and assign it to the instance, so the user can modify code at run time (if it is possible to disallow access to insecure modules while code is compiled). > Secondly, the code won't know exactly how to initialise the class > instance used to determinte the attributes. Do I need to make it a > prerequesite that all instances can be created with no arguments ? I did it this way, too. Maybe you can provide a parameterless __new__ in addition to the __init__. I imagine this is the way that e.g. pickle does the job. Well, I don't know. Let this sentence just be an invitation for an expert to write something here. > Should I force/allow the user to pass an instance instead of a class ? However you like. I prefer passing classes, otherwise you end up in a situation where you need to create dummy instances that are only used as "copying templates". If you get an instance: foo = type(bar)() would give you an instance of the same class as bar. But this just looks like a hack to me when compared to foo = Bar(). Passing an instance allows you to look at its __dict__ of course. But you have no assurance that the variables you find there are present in all instances of that class. Phython is just to dynamic for that. > Should I be using inspect.getargspec on the class __init__ method and > then a loop with a try and a lot of except clauses, or is there a nicer > way to do this ? Presumably the pickling code knows how do > serialise/deserialise class instances but I'm not sure how I'd use this > without already having a class instance to hand. Personally, I ended up writing a class Attribute that provides access to the attributes and allows more finetuning than a generic approach would do (think of e.g. validation). My overall setting works like this: For each attribute that you want to appear in the GUI you define an Attribute class Attribute(object) : def __init__(self, name, # name of the attribute type, # specifies the widget type values=None, # then OptionMenu is used instead validate=None, # if given, a callable that returns # either True or False get=None, # callable to get the actual value # None: generic getattr() widget_options={} # passed to the Tix widget used ) : pass # [...] The "controller" of an editable object gets the object and a list of those Attribute()'s. There is a generic one that handles validation and generic setattr(), but can be overwritten to allow more sophisticated stuff. When creating a new instance, I ask for initial arguments which I know (like __name__ and __doc__ if its a class that I create) in nearly the same way. If you already have your instance, it is possible to generate the Attribute()-list from the dict of this instance: attributes = [ Attribute(name,type(getattr(instance,name))) for name in dir(instance) ] > Lastly, does such an app already exist ? As you see, my solution is not as general as what you might have in mind. I needed to finetune so much of the underlying generic plan, that it looks more like declaration-based now. Anyway, if you are interested: This is the edit part of my app (It's only the mapping from attributes to widgets, so no instance creation in this part). As this was only a short snippet in the project I am doing, I could, never give it the time it deserved. So I am sure that my code is not the best sollution, but maybe it serves as a starting point for further discussion. All the best, - harold - import Tkinter import Tix class Attribute(object) : def __init__(self, name, type, values=None, validate=None, get=None, widget_options={} ) : if not get : get = lambda obj : getattr(obj,name) self.name = name self.type = type self.values = values self.get = get self.validate = validate self.widget_options = widget_options self.label = None self.widget = None class Edit(Tkinter.Frame) : import types def __init__(self,obj,items) : self.obj = obj self.items = items def create_widgets(self,master,**options) : Tkinter.Frame.__init__(self,master,**options) for item in self.items : if item.values : widget = Tix.OptionMenu(master,label=item.name) for v in item.values : widget.add_command(str(v),label=str(v)) item.label = None item.widget = widget else : widget = self.widget_types[item.type](master) widget.config(label=item.name,**item.widget_options) item.label = widget.label item.widget = widget.entry widget.pack(side=Tkinter.TOP,fill=Tkinter.X) self.pack() def update_widget(self,item) : if isinstance(item.widget,Tix.OptionMenu) : item.widget.set_silent(item.get(self.obj)) else : item.widget.delete(0,Tkinter.END) item.widget.insert(0,item.get(self.obj)) def update_widgets(self) : for item in self.items : self.update_widget(item) def validate(self,item) : if isinstance(item.widget,Tix.OptionMenu) : return True value = item.widget.get() if item.validate : valid = item.validate(value) elif item.values : valid = value in item.values else : try : valid = item.type(value) except ValueError : valid = False if valid : item.label.config(fg="black") else : item.label.config(fg="red") item.widget.focus_set() return valid def isvalid(self) : for item in self.items : if not self.validate(item) : return False return True def apply(self) : if self.isvalid() : for item in self.items : try : value = item.type(item.widget.get()) except AttributeError : value = item.type(item.widget.cget("value")) if value != item.get(self.obj) : setattr(self.obj,item.name,value) widget_types = { types.StringType : Tix.LabelEntry, types.IntType : Tix.Control, types.FloatType : Tix.LabelEntry, } if __name__ == "__main__" : class myClass : string = "hello world" float = 1. int = 0 proxy = Edit( myClass, [ Attribute("string",type(str())), Attribute("float",type(float())), Attribute("int",type(int()),validate=lambda x : int(x) in [-1,0,1] ) ] ) win = Tix.Tk(None) proxy.create_widgets(win) proxy.update_widgets() button1 = Tkinter.Button( win, text="apply", command=proxy.apply ) button1.pack() button2 = Tkinter.Button( win, text="update", command=proxy.update_widgets ) button2.pack() win.mainloop() -- Man will occasionally stumble over the truth, but most of the time he will pick himself up and continue on. -- Winston Churchill From news+0409 at henrikholm.com Wed Jan 12 10:54:12 2005 From: news+0409 at henrikholm.com (Henrik Holm) Date: Wed, 12 Jan 2005 09:54:12 -0600 Subject: Iteration over two sequences Message-ID: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> I am just starting to learn Python, mostly by going through the examples in Dive Into Python and by playing around. Quite frequently, I find the need to iterate over two sequences at the same time, and I have a bit of a hard time finding a way to do this in a "pythonic" fashion. One example is a dot product. The straight-ahead C-like way of doing it would be: def dotproduct(a, b): psum = 0 for i in range(len(a)): psum += a[i]*b[i] return psum However, the range(len(a)) term is awfully un-pythonic :) The built-in function map() gives me a way of "transposing" the a list and the b list, and now I can handle it with a list comprehension: def dotproduct(a, b): return sum([x*y for x, y in map(None, a, b)]) My concern is one of efficiency: it seems to me that I have two loops there: first one implied with map(...) and then the for loop -- which seems like a waste since I feel I should be able to do the multiplication via an argument to map. So far I have come up with an alternative via defining a separate function: def dotproduct(a, b): def prod(x,y): return x*y return sum(map(prod, a, b)) I suppose I could also use a lambda here -- but is there a different, efficient, and obvious solution that I'm overlooking? Thanks, Henrik -- "On some great and glorious day the plain folks of the land will reach in their heart's desire at last and the White House will be adorned by a downright moron." -H.L. Mencken (1880-1956) American Writer From tjreedy at udel.edu Sun Jan 9 21:17:43 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 9 Jan 2005 21:17:43 -0500 Subject: Python3: on removing map, reduce, filter References: <34csn1F4a46hqU1@individual.net> Message-ID: "Andrey Tatarinov" wrote in message news:34csn1F4a46hqU1 at individual.net... > How does GvR suggestions on removing map(), reduce(), filter() While GvR *might* prefer removing them completely on any given day, I think moving them to a functional module, as others have suggested and requested, is currently more likely. I believe that GvR has indicated at times that this would be an acceptible compromise. I am one of those who think the list of builtins is currently too long to be easily grasped and should be shrunk. Terry J. Reedy From tjreedy at udel.edu Tue Jan 18 02:32:08 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Jan 2005 02:32:08 -0500 Subject: wxPython and PyGame - do they play well together? References: <1106026599.092269.292170@c13g2000cwb.googlegroups.com> Message-ID: "Erik Bethke" wrote in message news:1106026599.092269.292170 at c13g2000cwb.googlegroups.com... > I am having a great time with python and pygame, and last night I took > a long look at the wxPython demo. I think that rocks as well. > > So now, my question is do wxPython and PyGame work together? I have no personal experience, but based on posts to the Pygame mailing list, also accessible via Google or as newsgroup thru Gmane (where I read it), the answer is yes. The subject of Pygame with guis has been discussed in the past couple of months. I recommend that you read the archives for the recent past and then join the list or subscribe via gmane or google. It is a low volume, low noise, list. Terry J. Reedy From belred1 at yahoo.com Sat Jan 1 18:15:32 2005 From: belred1 at yahoo.com (Bryan) Date: Sat, 01 Jan 2005 23:15:32 GMT Subject: what would you like to see in a 2nd edition Nutshell? In-Reply-To: References: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> <1104424176.958689.285570@z14g2000cwz.googlegroups.com> Message-ID: Nick Coghlan wrote: > JoeG wrote: > >> wxPython takes on more of the native platform's interface. I say seems >> to because I haven't actually written any code with it. > > > While Tkinter is the GUI toolkit shipped *with* Python, then that's the > correct toolkit for Alex to cover in PiaN. Mentioning other toolkits > (and providing references for additional information, including books if > they're available) seems like the most reasonable alternative. > > Now, if we could just switch to wxPython and Boa Constructor for Py3K. . . > > Cheers, > Nick. > Sorry Kurt! > i would prefer PiaN not to cover any gui toolkits, and instead use that space for more core funcionality. thanks, bryan From itsme at yahoo.com Thu Jan 6 11:44:22 2005 From: itsme at yahoo.com (It's me) Date: Thu, 06 Jan 2005 16:44:22 GMT Subject: Another PythonWin Excel question References: <344586F48830bU1@individual.net> Message-ID: "Marten Bauer" wrote in message news:344586F48830bU1 at individual.net... > > I did it yesterday like this way and it works well (part of my code): > > wb.Worksheets.Add(Count=nrMonths,After=wb.Worksheets(1)) > > As I read in MSDN you could not write After="sheet1" instead you must > use the Object of sheet1 like in my example and it works well in my > case. The Count=... statement will create n Sheets after the first worksheet > Yes, I learn that as well. The parameter to After is a Worksheet object. It appears if you don't specify any parameters, it would add it Before the current sheet. Thanks, > > By > Marten From mike.kreiner at gmail.com Fri Jan 14 00:58:36 2005 From: mike.kreiner at gmail.com (mike kreiner) Date: 13 Jan 2005 21:58:36 -0800 Subject: import problems *newbie* Message-ID: <1105682316.601321.118820@f14g2000cwb.googlegroups.com> I am having trouble importing a module I created. I'm running PythonWin on Windows XP if that helps. I saved my module in a folder called my_scripts in the site-packages directory. I edited the python path to include the my_scripts folder (it now reads C:\Python23\Lib;C:\Python23\DLLs;C:\Python23\Lib\lib-tk;C:\Python23\Lib\site-packages\my_scripts). When I try to import the module, I get this error: >>> from PolyDraw import * Traceback (most recent call last): File "", line 1, in ? ImportError: No module named PolyDraw When I select Browse PythonPath from the tools menu, I'm able to locate my module, PolyDraw.py. The problem goes away if I open PolyDraw.py from PythonWin, which I'm assuming is because opening the module makes my_scripts the current working directory. This is just a quick workaround, but I'd like to know how to fix the problem. Thanks. -Mike From vmlinuz at abisen.com Fri Jan 7 12:15:48 2005 From: vmlinuz at abisen.com (Anand S Bisen) Date: Fri, 07 Jan 2005 12:15:48 -0500 Subject: how to extract columns like awk $1 $5 Message-ID: <41DEC3C4.2030103@abisen.com> Hi Is there a simple way to extract words speerated by a space in python the way i do it in awk '{print $4 $5}' . I am sure there should be some but i dont know it. Thanks n00b From peter at engcorp.com Mon Jan 3 17:10:31 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Jan 2005 17:10:31 -0500 Subject: Advice request for project In-Reply-To: <41D957B1.3040500@holdenweb.com> References: <41D957B1.3040500@holdenweb.com> Message-ID: Steve Holden wrote: > Look at the Pyrex package to get you started thinking about remote > execution and client/server communications. This lets a program on one > machine call methods on objects on another machine. Steve meant to say "Pyro", not "Pyrex". The former is what he actually described. The latter is actually a Python-like language that lets one write code that can be compiled as an extension module, to write performance-critical code or interface to existing libraries more easily. -Peter From ncoghlan at iinet.net.au Sat Jan 8 23:43:50 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 14:43:50 +1000 Subject: python3: 'where' keyword In-Reply-To: <41dfc018.305122743@news.oz.net> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> Message-ID: <41E0B686.4090305@iinet.net.au> Bengt Richter wrote: > On Sat, 08 Jan 2005 16:42:16 +1000, Nick Coghlan wrote: > And, is the whole thing after the '=' an expression? E.g., > > x = ( foo(x) where: > x = math.pi/4.0 > ) where: > def foo(x): print 'just for illustration', x > > or is this legal? > > for y in ([foo(x) for x in bar] where: > bar = xrange(5) > ): baz(y) where: > def baz(arg): return arg*2 > > Not trying to sabotage the idea, really, just looking for clarification ;-) Actually, I was conceiving this as an addition to the grammar for the relevant 'simple statements', rather than to the grammar for expressions. Using the assignment statement as the ongoing example: Current: assignment_stmt ::= (target_list "=")+ expression_list augmented_assignment_stmt ::= target augop expression_list New: assignment_stmt ::= (target_list "=")+ expression_list [where_clause] augmented_assignment_stmt ::= target augop expression_list [where_clause] where_clause ::= "where" ":" suite So the expressions in existing compound statements (for, while, if, elif) would be out of luck. You could conceivably add the 'where' clause to the end of those as well, to give statement local variables that apply to the whole compound statement: for y in [foo(x) for x in bar]: baz(y) where: meaningful_name = xrange(5) def baz(arg): return arg * 2 This would only be appropriate for short loops - for long loops, the 'where' clause gets *too* hidden. Keeping the grammar simple might favour making the addition higher in the parse tree: Current: statement ::= stmt_list NEWLINE | compound_stmt New: statement ::= (stmt_list NEWLINE | compound_stmt) [where_clause] where_clause ::= "where" ":" suite However, doing it that way allows nonsense like this: pass where: print "This is just plain silly!" That would be something to be thrashed out in a PEP, though. The name 'statement local variables' also gave me an idea for a rough implementatation strategy. where: would be equivalent to: def stmt_with_locals(): stmt_with_locals() For the assignment versions, the behaviour would be: def assignment_with_locals(): return = assignment_with_locals() Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From fredrik at pythonware.com Sat Jan 22 06:17:03 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 12:17:03 +0100 Subject: Insanity References: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> Message-ID: Tim Daneliuk wrote: > Given an arbitrary string, I want to find each individual instance of > text in the form: "[PROMPT:optional text]" > > I tried this: > > y=re.compile(r'\[PROMPT:.*\]') > > Which works fine when the text is exactly "[PROMPT:whatever]" didn't you leave something out here? "compile" only compiles that pattern; it doesn't match it against your string... > but does not match on: > > "something [PROMPT:foo] something [PROMPT:bar] something ..." > > The overall goal is to identify the beginning and end of each [PROMPT...] > string in the line. if the pattern can occur anywhere in the string, you need to use "search", not "match". if you want multiple matches, you can use "findall" or, better in this case, "finditer": import re s = "something [PROMPT:foo] something [PROMPT:bar] something" for m in re.finditer(r'\[PROMPT:[^]]*\]', s): print m.span(0) prints (10, 22) (33, 45) which looks reasonably correct. (note the "[^x]*x" form, which is an efficient way to spell "non-greedy match" for cases like this) From firemoth at gmail.com Wed Jan 19 14:13:47 2005 From: firemoth at gmail.com (Timothy Fitz) Date: Wed, 19 Jan 2005 14:13:47 -0500 Subject: Zen of Python Message-ID: <972ec5bd050119111359e358f5@mail.gmail.com> While I agree that the Zen of Python is an amazingly concise list of truisms, I do not see any meaning in: Flat is better than nested. I strive for balance between flat and nested. Does anyone have a good example of where this is applied? (specifically to python, or in general) From esj at harvee.org Tue Jan 18 11:26:46 2005 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 18 Jan 2005 11:26:46 -0500 Subject: simultaneous multiple requests to very simple database Message-ID: I have an application where I need a very simple database, effectively a very large dictionary. The very large dictionary must be accessed from multiple processes simultaneously. I need to be able to lock records within the very large dictionary when records are written to. Estimated number of records will be in the ballpark of 50,000 to 100,000 in his early phase and 10 times that in the future. Each record will run about 100 to 150 bytes. speed is not a huge concern although I must complete processing in less than 90 seconds. The longer the delay however the greater number of processes must be running parallel in order to keep the throughput up. It's the usual trade-off we have all come to know and love. it is not necessary for the dictionary to persist beyond the life of the parent process although I have another project coming up in which this would be a good idea. at this point, I know they will be some kind souls suggesting various SQL solutions. While I appreciate the idea, unfortunately I do not have time to puzzle out yet another component. Someday I will figure it out because I really liked what I see with SQL lite but unfortunately, today is not that day (unless they will give me their work, home and cell phone numbers so I can call when I am stuck. ;-) So the solutions that come to mind are some form of dictionary in shared memory with locking semaphore scoreboard or a multithreaded process containing a single database (Python native dictionary, metakit, gdbm??) and have all of my processes speak to it using xmlrpc which leaves me with the question of how to make a multithreaded server using stock xmlrpc. so feedback and pointers to information would be most welcome. I'm still exploring the idea so I am open to any and all suggestions (except maybe SQL :-) ---eric From aurora00 at gmail.com Sat Jan 8 14:52:03 2005 From: aurora00 at gmail.com (aurora) Date: Sat, 08 Jan 2005 11:52:03 -0800 Subject: "A Fundamental Turn Toward Concurrency in Software" References: <7x4qhs52rq.fsf@ruckus.brouhaha.com> Message-ID: Of course there are many performance bottleneck, CPU, memory, I/O, network all the way up to the software design and implementation. As a software guy myself I would say by far better software design would lead to the greatest performance gain. But that doesn't mean hardware engineer can sit back and declare this as "software's problem". Even if we are not writing CPU intensive application we will certain welcome "free performace gain" coming from a faster CPU or a more optimized compiler. I think this is significant because it might signify a paradigm shift. This might well be a hype, but let's just assume this is future direction of CPU design. Then we might as well start experimenting now. I would just throw some random ideas: parallel execution at statement level, look up symbol and attributes predicitively, parallelize hash function, dictionary lookup, sorting, list comprehension, etc, background just-in-time compilation, etc, etc. One of the author's idea is many of today's main stream technology (like OO) did not come about suddenly but has cumulated years of research before becoming widely used. A lot of these ideas may not work or does not seems to matter much today. But in 10 years we might be really glad that we have tried. > aurora writes: >> Just gone though an article via Slashdot titled "The Free Lunch Is >> Over: A Fundamental Turn Toward Concurrency in Software" >> [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that >> the continous CPU performance gain we've seen is finally over. And >> that future gain would primary be in the area of software concurrency >> taking advantage hyperthreading and multicore architectures. > > Well, another gain could be had in making the software less wasteful > of cpu cycles. > > I'm a pretty experienced programmer by most people's standards but I > see a lot of systems where I can't for the life of me figure out how > they manage to be so slow. It might be caused by environmental > pollutants emanating from Redmond. From daranrife at yahoo.com Fri Jan 28 11:11:56 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 08:11:56 -0800 Subject: Installing Numeric with ATLAS and LAPACK Message-ID: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> Hello, Could someone please provide instructions for install Numeric with ATLAS and LAPACK? I've actually done this correctly, I think. But I don't see any difference in the speed. I'm calculating eigenvalues for a 3600 X 3600 covariance matrix. Calculating the eigenvalues for this matrix requires a mere 7 min in Matlab 6.5...which uses ATLAS and LAPACK. Thanks, Daran From fredrik at pythonware.com Fri Jan 21 13:08:06 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 21 Jan 2005 19:08:06 +0100 Subject: xml parsing escape characters References: <357s61F4iossjU1@individual.net><41eeda3a$0$27828$9b622d9e@news.freenet.de><359o5cF4il48kU1@individual.net><41efedf2$0$11622$9b622d9e@news.freenet.de><35adg4F4jgvpnU1@individual.net> <41F01A86.2040805@v.loewis.de> <35ctgpF4ktmgoU2@individual.net> Message-ID: Luis P. Mendes wrote: > xml producer writes the code in Windows platform and 'thinks' that every > client will read/parse the code with a specific Windows parser. Could > that (wrong) XML code parse correctly in that kind of specific Windows > client? not if it's an XML parser. > Do you know any windows parser that could turn that erroneous encoding > to a xml tree, with four or five inner levels of tags? any parser *can* do that, but I doubt many parsers will do it unless you ask it to (by extracting the string and parsing it again). here's the elementtree version: from elementtree.ElementTree import parse, XML wrapper = parse(urllib.urlopen(url)) dataset = XML(wrapper.findtext("{http://www......}string")) From steve at holdenweb.com Mon Jan 24 07:29:19 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 24 Jan 2005 07:29:19 -0500 Subject: short programming projects for kids In-Reply-To: <41f4e4b5@duster.adelaide.on.net> References: <1106332638.595750.150590@c13g2000cwb.googlegroups.com> <41f4e4b5@duster.adelaide.on.net> Message-ID: Adrian Casey wrote: > Andr? Roberge wrote: > > >>bobdc wrote: >> >>>I will be teaching an "Introduction to Programming" class to some >>>middle school aged children and will be using Python, obviously. Does >>>anyone have suggestions for simple little programs to create and >>>analyze with them after I get past turtle graphics? >>> >>>Turtle graphics will be plenty for the first session, and I will leave >>>time to ask them what they'd like to do in later sessions, but I was >>>curious if anyone on the list has experience picking pedagogical >>>programming examples appropriate for twelve-year-olds' attention spans. >>>thanks, >>> >>>Bob >>> >> >>While it is not python per se, I suggest you have a look at GvR >>(Guido van Robot) (The app is written in Python but is too complicated >>for beginners). It is hosted on sourceforge (gvr.sourceforge.net). >>It is a very interesting way (imho) to learn about programming, in >>a pythonic way. >> >>(somewhat shameless plug follows:) >>A 'more advanced version' of GvR which uses the full Python syntax >>is RUR-PLE (rur-ple.sourceforge.net). The version currently hosted >>there does NOT work under Linux (untested on Mac). >>It uses wxPython 2.4 and will not work with 2.5. >>An updated release that will work under both Linux and Windows, >>and under both wxPython 2.4 and 2.5 will come out very soon, I hope. >> >>I'm working on it :-) I have two kids (ages 11 and 13) and plan to use >>rur-ple to teach them about programming. Note that, even though >>I plan it to be suitable for motivated children (with some guidance), >>the end product (to be finished in a year?) is planned to be suitable >>for a complete first-year university computer science. >> >>Andre Roberge > > > I started teaching my 11 year old first of all by doing silly stuff like -: > for i in range(10): > print "Silly me!" > > Moving on to more useful stuff like times tables (which they have to learn > anyway). > > After times tables, I plan to work on a simple number guessing game where > the computer picks a random number between 1 and 100 and asks the user to > take a guess. This will help demonstrate many basic programming concepts. > > Not sure how to introduce graphics though as so much is relatively abstract. > Have them type in guesses to make something hit a target that appears in a different position each time to introduce the notion of 2-D position, then you can talk about drawing lines between two positions, then the next thing you know they're writing algorithms to compute convex hulls (well, maybe not, but you probably get the idea). regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From steven.bethard at gmail.com Fri Jan 21 21:21:57 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 19:21:57 -0700 Subject: finding name of instances created In-Reply-To: <1106359068.802501.35190@z14g2000cwz.googlegroups.com> References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106359068.802501.35190@z14g2000cwz.googlegroups.com> Message-ID: Andr? wrote: > Using the method suggested by Steven Bethard, I *almost* got it working > the way I would like. > Here's my program: > === > .class PrivateClass(object): > . dict = {} > . def not_so_simple_method(self): > . for name in PrivateClass.dict.keys(): > . if PrivateClass.dict[name] == self: > . print "instance " + name + " called not so simple" > . apparently_simple_method = not_so_simple_method > > . def __init__(self): > . print "instance created" > . for name, value in globals().iteritems(): > . if isinstance(value, PrivateClass): > . PrivateClass.dict[name] = value > > .def public_class(): > . return PrivateClass() > > .print "=== start===" > .alpha = public_class() > .print "created alpha" > .print PrivateClass.dict > .print "### alpha is not there\n" > > .beta = public_class() > .print "created beta" > .print PrivateClass.dict > .print "### we are always one behind in the dict content\n" > > .alpha.apparently_simple_method() > .beta.apparently_simple_method() It looks like you want PrivateClass.dict updated every time that globals() is updated. You can just use globals directly instead: py> class PrivateClass(object): ... def __init__(self, globals): ... self.globals = globals ... def apparently_simple_method(self): ... for name, value in self.globals.iteritems(): ... if value is self: ... print "instance %s called not so simple" % name ... py> def public_class(): ... return PrivateClass(globals()) ... py> alpha = public_class() py> alpha.apparently_simple_method() instance alpha called not so simple py> beta = public_class() py> beta.apparently_simple_method() instance beta called not so simple On the other hand, the iteration in PrivateClass.apparently_simple_method has a very bad code smell... Steve From tech at gpao.cc Mon Jan 31 10:40:48 2005 From: tech at gpao.cc (Olivier Noblanc ATOUSOFT) Date: Mon, 31 Jan 2005 16:40:48 +0100 Subject: import directory error References: <41fe49b5$0$2168$8fcfb975@news.wanadoo.fr> Message-ID: <41fe5181$0$10455$8fcfb975@news.wanadoo.fr> Problem solved thanks a lot "Steve Holden" a ?crit dans le message de news: f9sLd.101051$Jk5.32898 at lakeread01... > Olivier Noblanc ATOUSOFT wrote: > >> Hello, >> >> >> When i want to import a .py fire from another subdirectory i make >> >> import inc/setupxml >> >> >> but that make me an error message. >> >> A man tell me to put a dot but that doesn't work. >> >> Can you help me ? >> >> Thanks. >> >> >> > If you want to import a single .py (a Python module) then the ONLY way to > achieve that is to make sure it appears in a directory that is a member of > the sys.path list. (This is a slight simplification, but it will do as > long as you are only importing from the file store). > > There are various ways to affect the contents of sys.path, the best known > of which include > > 1. Setting the PYTHONPATH environment variable > 2. Creating *.pth files > 3. Altering sys.path inside site-customize.py in > your standard library > > Python does allow you to implement PACKAGES, which are directories > containing > > a) a file called __init__.py and (optionally) > b) other modules (.py files) and packages (directories > containing __init__.py files). > > The Python interpreter looks for packages in all the same places it looks > for modules, but it imports packages by running the __init__.py file (as > usual, this happens on the *first* time the package is imported). > > So, for example, under Cygwin or Linux/Unix, I can define a package (with > no Python in it, but still obeying the rules) as follows: > > sholden at dellboy ~ > $ mkdir mp1 > > sholden at dellboy ~ > $ touch mp1/__init__.py > > sholden at dellboy ~ > $ touch mp1/rhubarb.py > > sholden at dellboy ~ > $ mkdir mp1/p2 > > sholden at dellboy ~ > $ touch mp1/p2/__init__.py > > sholden at dellboy ~ > $ python > Python 2.4 (#1, Dec 4 2004, 20:10:33) > [GCC 3.3.3 (cygwin special)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import sys > >>> "" in sys.path > True > >>> import mp1 > >>> import mp1.rhubarb > >>> import mp1.p2 > >>> > > sholden at dellboy ~ > $ find mp1 > mp1 > mp1/p2 > mp1/p2/__init__.py > mp1/p2/__init__.pyc > mp1/rhubarb.py > mp1/rhubarb.pyc > mp1/__init__.py > mp1/__init__.pyc > > In this case mp1.rhubarb is a module from the mp1 package, mp1.p2 is a > sub-package of mp1. You can see what's been compiled by the interpreter on > import and when by looking at the .pyc files. > > Does this help any? > > regards > Steve > -- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/ > Holden Web LLC +1 703 861 4237 +1 800 494 3119 From jdhunter at ace.bsd.uchicago.edu Wed Jan 26 22:21:17 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 26 Jan 2005 21:21:17 -0600 Subject: python without OO In-Reply-To: (Davor's message of "Wed, 26 Jan 2005 21:55:49 -0500") References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> Message-ID: >>>>> "Davor" == Davor writes: Davor> not really - it was not my intention at all - but it seems Davor> people get upset whenever this OO stuff is mentioned - and Davor> what I did not expect at all at this forum as I believed Davor> Python people should not be so OO hardcore (seems not all Davor> as quite a few have indicated in their Davor> replies)... Nevertheless, I think the discussion has Davor> several quite good points! -- Davor> http://mail.python.org/mailman/listinfo/python-list Consider the case of a list, say x = [1,2,3,4] suppose you wanted to reverse the list, so that x becomes [4,3,2,1]. In a procedural language, one might do x = reverse(x) In an OO language such as python, one might do x.reverse() Is the OO way more obscure and complicated, etc? Not really -- it's only a minor syntactical difference. One of the core ideas behind OO programming is that data (the contents of the list 1,2,3,4) and methods (sorting, reversing) are bound together into a single entity, the object. On the face of it, this is rather sensible. You may rightly recoil against unnecessary abstraction and complexity, abuse of multiple inheritance and so on. That's perfectly sensible. But object orientation is probably not the bogey man here. python values readable code that is as simple as possible (but no simpler!) as you seem to. Focus on the actual problem, which is probably not OO programming, but colleagues who are making a design more complex than need be. Indeed, the third chant in the mantra of python is "Simple is better than complex." John-Hunters-Computer:~> python Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! From ola.natvig at infosense.no Wed Jan 26 09:04:54 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Wed, 26 Jan 2005 15:04:54 +0100 Subject: 4suite XSLT thread safe ? Message-ID: <6lkkc2-fbd.ln1@pluto.i.infosense.no> Anybody out there who knows if the 4suite implementation of XSLT are a threadsafe one? -- -------------------------------------- Ola Natvig infoSense AS / development From kartik_vad at yahoo.com Mon Jan 31 23:06:26 2005 From: kartik_vad at yahoo.com (kartik) Date: 31 Jan 2005 20:06:26 -0800 Subject: need for binary floats (except performance)? Message-ID: <81300027.0501312006.72454fd6@posting.google.com> Since the Decimal type can represent any given fractional number exactly, including all IEEE binary floating-point numbers, wouldn't it be advisable to use Decimals for all floating point numbers (except possibly for performance)? Thanks, Kartik. From steve at holdenweb.com Sat Jan 15 15:24:56 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 15 Jan 2005 15:24:56 -0500 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <1105734450.961150.32980@z14g2000cwz.googlegroups.com> <7xfz13zrb2.fsf@ruckus.brouhaha.com> Message-ID: <41E97C18.305@holdenweb.com> Bulba! wrote: > On 14 Jan 2005 12:30:57 -0800, Paul Rubin > wrote: > > >>Mmap lets you treat a disk file as an array, so you can randomly >>access the bytes in the file without having to do seek operations > > > Cool! > > >>Just say a[234]='x' and you've changed byte 234 of the file to the >>letter x. > > > However.. however.. suppose this element located more or less > in the middle of an array occupies more space after changing it, > say 2 bytes instead of 1. Will flush() need to rewrite the half of > mmaped file just to add that one byte? > Nope. If you try a[234] = 'banana' you'll get an error message. The mmap protocol doesn't support insertion and deletion, only overwriting. Of course, it's far too complicated to actually *try* this stuff before pontificating [not]: >>> import mmap >>> f = file("/tmp/Xout.txt", "r+") >>> mm = mmap.mmap(f.fileno(), 200) >>> mm[1:10] 'elcome to' >>> mm[1] = "banana" Traceback (most recent call last): File "", line 1, in ? IndexError: mmap assignment must be single-character string >>> mm[1:10] = 'ishing ::' >>> mm[1:10] 'ishing ::' >>> mm[1:10] = 'a' Traceback (most recent call last): File "", line 1, in ? IndexError: mmap slice assignment is wrong size >>> > flush() definitely makes updating less of an issue, I'm just > curious about the cost of writing small changes scattered all > over the place back to the large file. > Some of this depends on whether the mmap is shared or private, of course, but generally speaking you can ignore the overhead, and the flush() calls will be automatic as long as you don't mix file and string operations. The programming convenience is amazing. > -- > I have come to kick ass, chew bubble gum and do the following: > > from __future__ import py3k > > And it doesn't work. So make it work :-) regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From dieter at handshake.de Mon Jan 17 14:11:48 2005 From: dieter at handshake.de (Dieter Maurer) Date: 17 Jan 2005 20:11:48 +0100 Subject: Embedding a restricted python interpreter References: <7x4qhr4jis.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes on 08 Jan 2005 14:56:43 -0800: > Dieter Maurer writes: > > It uses a specialized compiler that prevents dangerous bytecode operations > > to be generated and enforces a restricted builtin environment. > > Does it stop the user from generating his own bytecode strings and > demarshalling them? Almost surely, I do not understand you: In the standard setup, the code has no access to most of Python's runtime library. Only a few selected modules are deemed to be safe and can be imported (and used) in "RestrictedPython". "marshal" or "unmarshal" are not considered safe. Security Declaration can be used to make more modules importable -- but then, this is an explicite decision by the application developper. *If* the framework decided to exchange byte code between user and iterpreter, then there would be no security at all, because the interpreter is the standard interpreter and security is built into the compilation process. Of course, you should not step in *after* the secured step ;-) Thus, "RestrictedPython" expects that the user sends Python source code (and not byte code!), it compiles this source code into byte code that enforces a strict access and facility policy. Dieter From steven.bethard at gmail.com Sat Jan 1 15:30:39 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 01 Jan 2005 20:30:39 GMT Subject: Looping using iterators with fractional values In-Reply-To: References: <1104609929.888351.8870@c13g2000cwb.googlegroups.com> Message-ID: Mark McEahern wrote: > drife wrote: > >> Hello, >> >> Making the transition from Perl to Python, and have a >> question about constructing a loop that uses an iterator >> of type float. How does one do this in Python? >> >> > Use a generator: > > >>> def iterfloat(start, stop, inc): > ... f = start > ... while f <= stop: > ... yield f > ... f += inc > ... > >>> for x in iterfloat(0.25, 2.25, 0.25): > ... print '%9.2f' % x > ... > 0.25 > 0.50 > 0.75 > 1.00 > 1.25 > 1.50 > 1.75 > 2.00 > 2.25 > >>> > Or use the numarray module: py> import numarray as na py> for f in na.arange(0.25, 2.25, 0.25): ... print '%9.2f' % f ... 0.25 0.50 0.75 1.00 1.25 1.50 1.75 2.00 Steve From steve at holdenweb.com Tue Jan 18 09:24:15 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Jan 2005 09:24:15 -0500 Subject: generator expressions: performance anomaly? In-Reply-To: References: <377Hd.77904$Jk5.30235@lakeread01> Message-ID: <41ED1C0F.4030800@holdenweb.com> Stephen Thorne wrote: > On Tue, 18 Jan 2005 07:12:18 -0500, Steve Holden wrote: > >>Since it doesn't yet optimize 2+5 to a constant-folded 7 you should >>realize that you are suggesting a large increase in the compiler's >>analytical powers. > > > As in interesting aside to this, you might be interested to know that > PHP has constant folding, allowing you to do things like > $foo = 7+9; and have it generate bytecode that is "let 'foo' equal 16" > or somesuch. > > PHP achieves this by having a subset of expression parsing available > only for situations where a folded constant is allowed. > > i.e. > class Foo { > var $bar = 1+4; /* this constant is folded */ > } > > static_scalar: /* compile-time evaluated scalars */ > common_scalar | T_STRING | '+' static_scalar | > '-' static_scalar | T_ARRAY '(' static_array_pair_list ')' > ; > common_scalar: > /* all numbers, strings-not-containing-variable-interpolation and a > few hacks like __FILE__ and __LINE__ */ > ; > > As you can see from the grammar, there are any number of ways this can break. > > i.e. > Parse Error, * isn't allowed: > class Foo { var $bar = 60*60*24; } > > Parse Error, neither is anything except + and -: > class Foo { var $bar = 256 & 18; } > > Parse Error, and definately not variables: > $baz = 12; > class Foo { var $bar = $baz*2; } > > I compute 60*60*24 every time around the loop: > foreach ($myarray as $value) { $x = 60*60*24*$value; } > > Thankful, Former PHP Programmer, > Stephen Thorne. Yes, well, this just goes to confirm my belief that PHP isn't a programming language. I am always amazed at what's been achieved with it (though I sometimes wonder at what cost). You probably already know that sensible compiled language systems have used constant folding since time immemorial, but Python has always eschewed it. That's what comes of being a pragmatist's language: if such optimizations really are required the programmer is expected to perform them. and-ninety-nine-point-nine-nine-percent-of-the-time-they-aren't-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From alan.gauld at btinternet.com Sun Jan 2 13:25:10 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Jan 2005 18:25:10 +0000 (UTC) Subject: screen clear question References: <10teqpdvramua3@corp.supernews.com> <8ucft0tf456g07iuuavgu31m6dhrgjbmh3@4ax.com> Message-ID: On Mon, 03 Jan 2005 02:15:23 +1000, Nick Coghlan > Alan Gauld wrote: > > But the bottom line is that there is no builtin command > > because the mechanism is different on each platform. > > I'd have said it was because the inpreter is line-oriented rather than > screen-oriented, but YMMV. Yeah, that might be a reason as well :-) But then the early PC GW-Basic or BASICA interpreters were line based too but both provided a CLS command because the *programs* that were written were usually screen based... But they ran on a single OS so a CLS was easily possible. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From rNOSPAMon at flownet.com Sun Jan 2 17:02:34 2005 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 02 Jan 2005 14:02:34 -0800 Subject: Rebinding stdout References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <41D85CAF.2090505@mceahern.com> Message-ID: In article , Mark McEahern wrote: > Ron Garret wrote: > > > But this topic does bring up a legitimate question: I have a bunch of > > code that generates HTML using PRINT statements. I need to convert > > all this code to return strings rather than actually printing them (so > > I can use the results to populate templates). In Lisp I could do this: > > > > (with-output-to-string (s) > > (let ( (*standard-output* s) ) > > (call-html-generating-code) > > s)) > > > > Is there an equivalent Python trick to capture a function call's > > output as a string? > > > > > Just to make sure I understand, I'm going to restate your question: > > Is there a way to capture stdout? > > The answer: Sure, replace it with something file-like: > > >>> import sys, StringIO > >>> default = sys.stdout > >>> writer = StringIO.StringIO() > >>> sys.stdout = writer > >>> print 'Whatever' > >>> sys.stdout = default > >>> print writer.getvalue() > Whatever > > >>> > > // m That's exactly what I was looking for. Thanks! rg From zathras at thwackety.com Sun Jan 30 16:13:44 2005 From: zathras at thwackety.com (Michael Sparks) Date: Sun, 30 Jan 2005 21:13:44 +0000 (GMT) Subject: Coding style article with interesting section on white space In-Reply-To: <1107100318.251828.86360@c13g2000cwb.googlegroups.com> Message-ID: On 30 Jan 2005 beliavsky at aol.com wrote: > Sparring > with Alex Martelli is like boxing Mike Tyson, except that one > experiences brain enhancement rather than brain damage :). +1 QOTW :-) Michael. From tim.peters at gmail.com Thu Jan 27 12:40:27 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 27 Jan 2005 12:40:27 -0500 Subject: On benchmarks, heaps, priority queues In-Reply-To: <1106843673.755688.244160@f14g2000cwb.googlegroups.com> References: <1106835562.598569.211370@c13g2000cwb.googlegroups.com> <1106842754.010427.74630@c13g2000cwb.googlegroups.com> <1106843673.755688.244160@f14g2000cwb.googlegroups.com> Message-ID: <1f7befae05012709402140a21b@mail.gmail.com> [aaronwmail-usenet at yahoo.com, on ] > Yes I know in theory the insertion sort approach should be bad for > large enough values, but the weird thing is that if you mix inserts and > deletes (with enough deletes) even 1M elements is not a large enough > value. Anyway, for 10K or less the insertion sort priority queue > implementation seems to always be better. > > Weird. -- Aaron Watters It's the distribution of queue sizes that matters here, not the total number of elements thrown at the queue. Your code mixes "self" and "this" seemingly at random, and the __len__ methods in particular often don't agree about which is in use. If you repair that, and instrument mixBench() to keep track of queue size statistics, you'll find that even at 1000000, the queue at the top of the loop never exceeds 30 entries, and has a mean size less than 3. If you expect your queues to have only a couple elements on average, then sure, the simplest thing that could possibly work may be the fastest too. And if your queues never exceed 30 entries, then the poor O() behavior of "interior" list insertion doesn't matter either. The "n%5<3" part should be true about 60% of the time if n were truly random, which is a strong bias in mixBench pushing toward keeping the queue very small. Can't guess how close n is to being random, but the random-number generator is suspect (the multiplier is extremely small). Suspect it's more the strong bias than the dubious generator accounting for the almost-always near-trivial queue sizes in mixBench(), though. Note that in 2.4, bisect.insort() is also coded in C, so moving to 2.4 gives a boost to all the builtin gimmicks used here. On my box (with self-vs-this straightened out, and mixBench() instrumented to track queue size stats), using Python 2.4, PQPython23 "wins" maxBench 1000000 anyway: BENCHMARKS FOR 1000000 mixBench queue min 0 mean 2.517008 max 30 __main__.PQPython23 on 1000000 elapsed 4.54699993134 got 500001 queue min 0 mean 2.517008 max 30 __main__.PQ0 on 1000000 elapsed 4.79699993134 got 500001 queue min 0 mean 2.517008 max 30 __main__.PQueue on 1000000 elapsed 6.54699993134 got 500001 From skip at pobox.com Tue Jan 4 10:43:05 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 Jan 2005 09:43:05 -0600 Subject: Python evolution: Unease In-Reply-To: <7xacrpdxy3.fsf@ruckus.brouhaha.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> Message-ID: <16858.47497.338059.125520@montanaro.dyndns.org> Paul> Care to figure out from the docs how tkinter works? That's not Paul> explained anywhere at all, except in some off-site resources and Paul> in some printed books. Even some language features like class Paul> methods and slots are explained only in PEP's and release notes, Paul> instead of in the language manual where you'd expect to find them Paul> since they're part of the language. Start writing (or reorganizing). Folks, this is open source. I'm sure by the traffic on the list most people here know how to write. In the case of Tkinter, you should probably get the okay of the authors of various external docs before incorporating them into the Python docs, but note that several Tkinter-related documents are referenced directly from the Tkinter module docs: Python Tkinter Resources The Python Tkinter Topic Guide provides a great deal of information on using Tk from Python and links to other sources of information on Tk. An Introduction to Tkinter Fredrik Lundh's on-line reference material. Tkinter reference: a GUI for Python On-line reference material. Tkinter for JPython The Jython interface to Tkinter. Python and Tkinter Programming The book by John Grayson (ISBN 1-884777-81-3). This being the Internet and all, it's not clear that referencing external documentation is somehow worse than incorporating it directly into the distribution. As for stuff that exists in PEPs and release notes, they should already all have the necessary copyright (either they were placed in the public domain or they are already part of the Python distribution) to allow you do just check out a CVS tree, make the necessary edits and either check the files back in or submit a patch to SourceForge. In the documentation arena, I think more thought should probably be given to producing online docs that can be directly annotated, thus further reducing the barrier to more complete documentation (and more updates). Take a look at latex2html, propose or implement changes, or just rewrite the damn thing in Python. I think latex2html is probably a recurring nightmare for Fred Drake. Skip From tim.peters at gmail.com Thu Jan 13 10:23:07 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 13 Jan 2005 10:23:07 -0500 Subject: python 2.3.4 for windows: float("NaN") throws exception In-Reply-To: <1105629033.442397.124820@c13g2000cwb.googlegroups.com> References: <1105629033.442397.124820@c13g2000cwb.googlegroups.com> Message-ID: <1f7befae050113072372bad736@mail.gmail.com> [asmirnov1234567890 at yahoo.com] > my python 2.3.4 for windows refuse to execute line float("NaN"). It > says: > > >>> float("NaN") > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for float(): NaN > > The same line works as expected on Linux and Solaris with python 2.3.4. > Could anybody explain what is possibly wrong here? is it bug or > feature? Neither -- all Python behavior in the presence of float NaNs, infinities, or signed zeroes is a platform-dependent accident. In this specific case, the accident is that the platform C runtime string->double functions on your Linux and Solaris boxes recognize "NaN", but Microsoft's string->double functions do not. Microsoft's libraries can't even read back the strings they *produce* for NaNs.(usually "-1.#IND"). From "iwk\" at (none) Sun Jan 2 08:24:00 2005 From: "iwk\" at (none) (@(none)) Date: Sun, 02 Jan 2005 14:24:00 +0100 Subject: Continuations Based Web Framework - Seaside. In-Reply-To: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> Message-ID: <41d7f5eb$0$10383$e4fe514c@dreader18.news.xs4all.nl> Mike Thompson wrote: > 'Seaside' is a Smalltalk framework for what might be called "Modal Web > Development" or "Synchronous Web Programming", or even "Continuation > Based Web Apps". Continuation Based Frameworks seem to be getting quite some attention lately. For example in the Lisp world. Check out Bill Clementson's blog for some excellent posts. http://home.comcast.net/~bc19191/blog/041229.html And Seaside looks indeed very nice. Would be good to see it generate some new interests in Smalltalk/Squeak. > I googled for the python spin-off but didn't find one. Does Python really need yet another framework? Apart from the intellectual excersise, wouldn't it be nice if Python would get a framework "for the rest of us" (meaning: mere mortals) which would focus upon getting work done in a simple manner instead of creating yet another, new, hip, exciting, way of creating dynamic websites? If Python cannot deliver a PHP clone, at least you would expect a Rails lookalike. And though part of the Rails stack may be surpassed easily by Python equivalents, no Python alternative offers (imho of course) the same level of simplicity, elegance and pragmatism (!!) as Rails does. Regards, Iwan From fumanchu at amor.org Sun Jan 2 16:34:47 2005 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 2 Jan 2005 13:34:47 -0800 Subject: Frameworks for "Non-Content Oriented Web Apps" Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3024F6C@exchange.hqamor.amorhq.net> mirnazim at gmail.com wrote: > Let me make an attemp at defining "Non-Content > Oriented Web Applications". > > A "Non-Content Oriented Web Application": > (1) will be accessed from web browser(obviously). Clear enough. > (2) will be developed using 'W3C' and other open > standards(STRICTLY, to ensure compatibility and > portablity). This is getting better IMO. But we're still at the point where exclusively following open standards ensures in-compatibility and non-portability. Meh. > (3) will expose some kind of functionality to the user, > not just some document to read. If I were to rephrase that, I would say "serves dynamic pages" as opposed to "static". > (4) functionality can be very simple to very complex. Which usually means a multitude of tools, depending on "how complex". The big issue with leaving this question so generic is that the answers are legion. So I'll just keep it short and make my own shameless plug: try Cation for the Web interface and Dejavu for the data layer, both developed by yours truly. ;) http://www.aminus.org/rbre/python or... svn://casadeamor.com/cation/trunk svn://casadeamor.com/dejavu/trunk Robert Brewer MIS Amor Ministries fumanchu at amor.org From aldo at nullcube.com Wed Jan 26 21:58:59 2005 From: aldo at nullcube.com (Aldo Cortesi) Date: Thu, 27 Jan 2005 13:58:59 +1100 Subject: Which is faster? In-Reply-To: <1106793602.782397.61260@z14g2000cwz.googlegroups.com> References: <1106793602.782397.61260@z14g2000cwz.googlegroups.com> Message-ID: <20050127025859.GA21360@nullcube.com> Thus spake Aggelos I. Orfanakos (aorfanakos at gmail.com): > Any idea which of the following is faster? > > 'a/b/c/'[:-1] > > or > > 'a/b/c/'.rstrip('/') > > Thanks in advance. > > P.S. I could time it but I thought of trying my luck here > first, in case someone knows already, and of course the > reason. Expecting other people to do something simply because you couldn't be bothered to do it yourself is not polite... That said, here are the timings on my system: > python ./timeit.py "'a/b/c/'[:-1]" 1000000 loops, best of 3: 0.511 usec per loop > python ./timeit.py "'a/b/c/'.rstrip('/')" 1000000 loops, best of 3: 1.3 usec per loop As you can see, this suggests that the list access method is quicker. This is to be expected, since the two methods don't do the same thing - rstrip will return a copy of your string with any number of trailing '/'es removed. If there aren't any, it will return the string as-is. The string access method will always chop exactly one character off the end. Even though the results for your specific input are the same, rstrip is a more complex, and therefore slower, beast. Cheers, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com Off: (02) 9283 1131 Mob: 0419 492 863 From kp8 at mac.com Tue Jan 11 16:49:11 2005 From: kp8 at mac.com (kpp9c) Date: 11 Jan 2005 13:49:11 -0800 Subject: Time script help sought! In-Reply-To: <1105479292.689762.155510@f14g2000cwb.googlegroups.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> <1105477084.525279.312970@f14g2000cwb.googlegroups.com> <1105479292.689762.155510@f14g2000cwb.googlegroups.com> Message-ID: <1105480151.431987.327080@c13g2000cwb.googlegroups.com> still working on it and also fixing the input data. I think for simplicity and consistency's sake i will have *all* time values input and output as hh:mm:ss maybe that would be easier.... but i have a few thousand find and replaceeseseses to do now (yes i am doing them by hand) grr... this is hard! From aut_gbarros at uolinc.com Thu Jan 27 12:17:51 2005 From: aut_gbarros at uolinc.com (Gabriel Cosentino de Barros) Date: Thu, 27 Jan 2005 15:17:51 -0200 Subject: Tkinter vs wxPython Message-ID: <2814F26DA6908F41927A81C410C4991A02079C77@siamun.server.bl.corp.intranet> *warning* My very own opinions ahead. no flame intended. > Try them both out for an hour or two, and go with whichever > one "feels right". You very likely won't be making a mistake. i did that for java+swing, python+tk, python+gtk, python+wxWindow and python+glade I limited myself in one hour, and at a maximum 2 hours if the docs aren't perfect (i had zero experience at the time with all of them) The program code was already written, it only needed the gui. Java took me 3 hours to hook all the ungly hacks for dealing with threads in the AWT... but i will not elaborate on it because it would be kicking a dead horse. now for something completely diferent: python :) tk: the docs where superberb! done everything in 25min! then spent an hour polishing and adding status bars for everything :) gtk: had to use the C api docs. wasted some time figuring it out, gave up after one hour and a half and ended up with a window layout that didn't maximezed well. wx: Almost two hours. Once you get used to the docs and get the knowledge to read some examples all is fine. i liked the result. and liked the api but disliked the sea of constants necessary (i hated it in gtk also) glade: i gave up after 2hours of reading licenses and dealing with broken libs. Also, i can't run in beOS or tweak widgets. bah! rather go back to visual basic ;) Now going back on topic: A think that neighter Tk nor wxWindow is a good choice for python. They both suck much of it when it came to abstraction. They're still better than glade or gtk. But could improve a lot. wxWindow has simple an ugly API, and Tk has a huge sin in the syntax to pass actions to the buttons. But after all, i'm using exclusively TK for now. But things might change as i'm in a project with a huge need of non-ortodox input, so i may be going back to read about wxWindow event handlers or even pygame. peace, Gabriel -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Sat Jan 15 12:12:15 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 15 Jan 2005 18:12:15 +0100 Subject: Pointer or unique id In-Reply-To: <1q9pydh06wjuk.fexsf964ckya$.dlg@40tude.net> References: <1q9pydh06wjuk.fexsf964ckya$.dlg@40tude.net> Message-ID: <41e94d40$0$29202$636a15ce@news.free.fr> Nomak a ?crit : > Hello, > > does python have an equivalent to Java: int Object.hashCode() ? > id(object) -> integer Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.) hash(obj) -> integer Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely. HTH Bruno From cam.ac.uk at mh391.invalid Sun Jan 16 20:01:40 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 17 Jan 2005 01:01:40 +0000 Subject: List problems in C code ported to Python In-Reply-To: <3SDGd.22010$Z%.6947@fe1.texas.rr.com> References: <3SDGd.22010$Z%.6947@fe1.texas.rr.com> Message-ID: Paul McGuire wrote: > So "A" == 'a' is true in Python, not true in C. >>> "A" == 'a' False I think you meant: >>> "A" == "A" True -- Michael Hoffman From google_groups_web at yahoo.com Tue Jan 25 20:07:41 2005 From: google_groups_web at yahoo.com (google_groups_web at yahoo.com) Date: 25 Jan 2005 17:07:41 -0800 Subject: HAVE YOU HEARD THE GOOD NEWS! Message-ID: <1106701661.128249.250310@c13g2000cwb.googlegroups.com> Good News! Do you know how simple it is to go to Heaven after this life has ended? Some people believe that belonging to a local church, temple, mosque or synagogue will get them to Heaven. Others believe that water baptism, obeying the ten commandments or just being a good person will get them to Heaven. There are many other beliefs as well, but the good news about God's way to Heaven is found in the Holy Bible. The good news is that God came from Heaven to earth in the person of Jesus Christ over 2000 years ago and died for our sins(misdeeds). He was born in the land of Israel supernaturally to a virgin Jewish woman named Mary. He lived a sinless life for thirty-three years and then sacrificed His sinless blood and died on a cross to pay the death penalty for our sins. After Jesus was placed in a tomb He rose from the dead three days later as He said He would. The Holy Bible also tells us that Jesus Christ ascended into Heaven and that all who accept Him as their Lord and Saviour will live forever with Him in Heaven where there is no more death, sorrow, sickness and pain. The Bible says, "For the wages of sin is death, but the gift of God is eternal life through Christ Jesus our Lord." (Romans 6:23) This verse in the Bible says, "For ALL HAVE SINNED, and come short of the glory of God." (Romans 3:23) This verse says, "But God demonstrates his own love for us in this: While we were still sinners, Christ died for us." (Romans 5:8) In this passage the Bible clearly explains how simple it is to be saved and on your way to Heaven, "For if you confess with your mouth, "Jesus is Lord," and believe in your heart that God raised him from the dead, you WILL BE SAVED." (Romans 10:9) You can be saved right now and on your way to Heaven if you will open your heart to Jesus and pray the following prayer: Dear Jesus Christ, I want to be saved so that I can have a home in Heaven when I die. I agree with You that I am a sinner. I believe You love me and want to save me. I believe that You bled and died on the cross to pay the penalty for my sins. I believe that You rose from the dead. Please forgive my sins and come into my heart and be my Lord and Saviour. Thank You Lord Jesus Christ for forgiving me and saving me through Your merciful grace. Amen. You are now a Christian if you said the prayer and allowed God to save you. Welcome to the family of God. Salvation is not a reward but a gift. The Bible says it this way, "For it is by GRACE you have been SAVED, through FAITH and this not from yourselves, it is the GIFT of God." (Ephesians 2:8) Nothing in the world is more important than your eternal destiny. The Bible says, "In Him(Jesus) we have redemption through His blood, the forgiveness of sins..." (Ephesians 1:7) If you have not yet made a decision to be saved, please do so now before it is too late. The reason why it is so important to be saved now is because you do not know exactly when you will die. You may die prematurely in a traffic accident, terrorist attack or some other way before you get another chance to be saved. The Bible tells us that we will spend eternity in Heaven or a place of eternal torment called Hell. It would be terrible to die and go to Hell when all you have to do is accept Jesus Christ as your personal Lord and Saviour. Some people that have already made Jesus Christ their Lord and Saviour worry about losing their salvation. The Bible teaches Christians that we can never lose our salvation no matter what happens. The Bible says it this way, "My dear children, I write this to you so that you will not sin. But if anybody does sin, we have one who speaks to the Father in our defense Jesus Christ, the Righteous One." Yes my friend, Jesus Christ is able to save you and keep you saved. Please tell your family and friends, thanks! Have a great day! Internet Evangelist R.L. Grossi 1. http://www.biblegateway.com << Free Online Bible 2. http://www.free-hoster.com/goodnews << Passion of the Christ 3. http://www.carm.org/cults/cultlist.htm << Beware Of Cults 4. http://www.equip.org/free/DH198.htm << About Hell 5. http://www.powertochange.com/questions/qna2.html << Is Jesus God? From steven.bethard at gmail.com Tue Jan 4 09:55:05 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 04 Jan 2005 14:55:05 GMT Subject: Lambda as declarative idiom (was RE: what is lambda used for in real code?) In-Reply-To: <41da41d1.1835252503@news.oz.net> References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> <41da41d1.1835252503@news.oz.net> Message-ID: Bengt Richter wrote: > On Mon, 03 Jan 2005 18:54:06 GMT, Steven Bethard wrote: > > >>Roman Suzi wrote: >> >>>I wish lambdas will not be deprecated in Python but the key to that is >>>dropping the keyword (lambda). If anybody could think of a better syntax for >>>lambdas _with_ arguments, we could develop PEP 312 further. >> >>Some suggestions from recent lambda threads (I only considered the ones >>that keep lambda as an expression): >> > > Just for reference, am I correct in assuming these are the equivalent > uses of lambda?: > > lambda a, b, c:f(a) + o(b) - o(c) > lambda x: x * x > lambda : x > lambda *a, **k: x.bar(*a, **k) > (lambda : x(*a, **k)) for x, a, k in funcs_and_args_list) Yeah, I believe that was the intention, though I stole the examples from [1]. > That last seems like it might need the default-arg-value hack: i.e., > (lambda x=x, a=a, k=k: x(*a, **k)) for x, a, k in funcs_and_args_list) Good point. Steve From snacktime at gmail.com Sun Jan 23 17:03:48 2005 From: snacktime at gmail.com (snacktime) Date: Sun, 23 Jan 2005 14:03:48 -0800 Subject: Set parity of a string Message-ID: <1f060c4c050123140310e6f887@mail.gmail.com> Is there a module that sets the parity of a string? I have an application that needs to communicate with a host using even parity So what I need is before sending the message, convert it from space to even parity. And when I get the response I need to convert that from even to space parity. The perl module String::Parity is what I have used to do this under perl. Chris From wuwei23 at gmail.com Sun Jan 23 03:38:32 2005 From: wuwei23 at gmail.com (alex23) Date: 23 Jan 2005 00:38:32 -0800 Subject: Comments in configuration files In-Reply-To: <41f20f4a$0$6599$8fcfb975@news.wanadoo.fr> References: <41f20f4a$0$6599$8fcfb975@news.wanadoo.fr> Message-ID: <1106469512.131381.256450@z14g2000cwz.googlegroups.com> > I would like it to be editable, through a web browser or a GUI > application. With ConfigParser I can read the configuration file and > edit the options, but when I write the result all the comments are lost Hey Pierre, I came across a good review of a number of possible solutions for this at http://www.python.org/moin/ConfigParserShootout Hope it helps. - alex23 From http Tue Jan 11 12:26:14 2005 From: http (Paul Rubin) Date: 11 Jan 2005 09:26:14 -0800 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> Message-ID: <7x8y6z7u89.fsf@ruckus.brouhaha.com> Richie Hindle writes: > > [MoinMoin] doesn't have [...] automatic update notification for > > specific pages of your choice > > Yes it does. See http://entrian.com/sbwiki for example - register there > and you'll see in your preferences "Subscribed wiki pages (one regex per Oh interesting, thanks. > MoinMoin has an option to display WikiWords with spaces between them > (albeit still capitalised), again in the user preferences. Oh good, that's cool too, though this goes to show that the MoinMoin documentation could stand a lot of improvement (this holds in other areas as well). I don't understand why using spaces is the default. Who except for demented Java programmers really likes this MixedCase nonsense? Is there a way to turn it off altogether, so you can use mixed case words on wiki pages without automatically generating a link? > I'm not saying that MoinMoin is better than MediaWiki, just that it really > does have some of the features you say it doesn't (perhaps you've been > looking at an old version). I'm not saying MoinMoin is "worse" than MediaWiki, just as I wouldn't say a rowboat is worse than an aircraft carrier. MediaWiki is the only choice that makes any sense for large wikis (say > 20k pages). For small ones, MoinMoin is easier to operate in many ways, which is a big plus. It would be nice if MoinMoin changed its markup language to be closer to MediaWiki's. I edit MediaWiki pages all the time and I hate having to switch back and forth between languages (actually that's another reason I've reacted not-so-well to MoinMoin's language). I think I saw something in the MoinMoin docs saying that some standard was being developed that would look like MediaWiki, and that MoinMoin would support the standard, so I guess this will work out in the long run. From andreasp at qbcon.com Thu Jan 27 09:45:40 2005 From: andreasp at qbcon.com (Andreas Pauley) Date: Thu, 27 Jan 2005 16:45:40 +0200 (SAST) Subject: Point of Sale In-Reply-To: References: Message-ID: On Thu, 27 Jan 2005, Cameron Laird wrote: > In article , > Andreas Pauley wrote: >> Hi, >> >> My company has given me a rather cool project: >> I have to provide them with an open-source python-based point-of-sale / >> cash register system that can integrate with their existing ERP backend. >> >> The project will include development to ensure that the features they >> require are included in the open-source POS system. >> >> Can you recommend anything that I can use? > . > . > . > Research. I think you're expecting an answer of the "I used > open-source openPOS project, and it worked great for me", but > I suspect all that is premature. What does POS mean to you? > What are your platform constraints? Does your company have > expectations about how POS will work? What access (CORBA? > RMI? SOAP? ...) is there to the ERP? Very well, I guess a little more detail would help. Platform: Cross-platform, although deployment would typically be done on Linux. My company typically expects that each POS station will have it's own database with all sales items and other info on it. The maintenance of sales items, prices etc. should however be done at a central location, and then be replicated to each POS station. The reason for this is that we will typically deploy such a system in deep-dark-africa where stable network connectivity cannot be taken for granted. If the network is down each POS station should still be able to function without interruption. These requirements is probably not available in a typical POS system, but I'm hoping for a general POS front-end for which I can develop a custom backend to plug in. At the moment the current POS system uses an inhouse developed message queing system to communicate with the ERP/Retail backend. A POS station submits each transaction (and other relevant messages) to a local queue, from where it is sent to the back-end system. If the network is down the messages just stay queued until the network is back up again. The central backend system uses the same queing technique to submit price updates etc. to each POS station. I'm not sure what protocol will be used to communicate with the backend. I might have SOAP available. The backend is written using Appservers from Progress Software Corporation (a proprietary database company). The Progress developers would probably be willing to help, so I'm relatively positive that we'll be able to figure out a solution there. The user interface for the current system is character-based. For the new POS we should ideally be able to use different user-interfaces that all access the same business logic, although I would primarily focus on a non-mouse driven GUI interface. I hope the above answers your question, if not feel free to ask again. Regards, Andreas Pauley From ialbert at mailblocks.com Wed Jan 26 09:46:12 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 26 Jan 2005 09:46:12 -0500 Subject: 4suite XSLT thread safe ? In-Reply-To: <35pntaF4os76kU1@individual.net> References: <6lkkc2-fbd.ln1@pluto.i.infosense.no> <35pntaF4os76kU1@individual.net> Message-ID: Diez B. Roggisch wrote: > What do you mean by that? You can of course transform xml using xslt in as > many threads as you like It is not unthinkable that some parts of the library would not be threadsafe. They could have some internal shared global variable that keeps track of an intermediate state. Some C string processing functions are not thread safe either. Istvan. From philippecmartin at sbcglobal.net Mon Jan 10 14:29:40 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 10 Jan 2005 20:29:40 +0100 Subject: fetching method names from a class, and the parameter list from a method Message-ID: <1105385380.10721.6.camel@localhost> Is this possible ? I am trying to have auto-completion working in a shell I wrote but I currently have the method lists done by hand (ie; if I add/subtract a method from that class, then my auto-completion is out of date). Same issue with method parameters. I have parsed through many of the attributes (ex: I use method.__doc__) but have not yet found a way to achieve the above goal. Is there a way? something like the following would be great: 1) list = Class.__methods__ 2) dict (because of default values: "param = None") = Class.__method__[0].__params__ Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From mwm at mired.org Wed Jan 5 14:54:53 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 05 Jan 2005 13:54:53 -0600 Subject: is python more popular than coldfusion? References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <1104933800.156835.91350@f14g2000cwb.googlegroups.com> Message-ID: <86d5wjps6q.fsf@guru.mired.org> beliavsky at aol.com writes: >>is python more popular than coldfusion? > For your specific purpose of learning a language to get a job, I > suggest visiting the site http://mshiltonj.com/sm/categories/languages/ > , where it appears that Python is mentioned about as often as Fortran > or Ada in job listings at dice.com . Apart from Java, two languages in > demand are C++ and Visual Basic. C++ may be easier to learn along with > Java since the syntax is similar, but VB is a very easy language to > learn and use. SQL is also in pretty high demand in the places I watch. Problem is, they usually want *specific* SQL variants, so it's a fragmented market. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From m at e.net Mon Jan 24 18:31:05 2005 From: m at e.net (me) Date: Mon, 24 Jan 2005 15:31:05 -0800 Subject: error Message-ID: whenever i try and run my Python GUI, my computer thinks for a sec, then drops the process, without ever displaying the window. the command prompt window seems to work fine, but the IDLE GUI won't start. i'm running Windows 2K professional and python 2.4, so any advice help would be appreciated. i've already tried reinstalling and use a thread response, as the e-mail on this account is bogus. From martin at v.loewis.de Thu Jan 20 15:54:30 2005 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 20 Jan 2005 21:54:30 +0100 Subject: xml parsing escape characters In-Reply-To: <35adg4F4jgvpnU1@individual.net> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efedf2$0$11622$9b622d9e@news.freenet.de> <35adg4F4jgvpnU1@individual.net> Message-ID: <41F01A86.2040805@v.loewis.de> Luis P. Mendes wrote: > When I access the url via the Firefox browser and look into the source > code, I also get: > > > <DataSet> > ~ <Order> > ~ <Customer>439</Customer> > ~ </Order> > </DataSet> Please do try to understand what you are seeing. This is crucial for understanding what happens. You may have the understanding that XML can be represented as a tree. This would be good - if not, please read a book that explains why XML can be considered as a tree. In the tree, you have inner nodes, and leaf nodes. For example, the document Hello World has 5 nodes (ignoring whitespace content): Element:a ---- Element:b ---- Text:"Hello" | \-- Element:c ---- Text:"World" So the leaf nodes are typically Text nodes (unless you have an empty element). Your document has this structure: Element:string ---- Text:""" 439 """ So the ***TEXT*** contains the letter "<", just like it contains the letters "O" and "r". There IS no element Order in your document, no matter how hard you look. If you want a DataSet *element* in your document, it should read 439 As this is the document you apparently want to process, complain to whoever gave you that other document. > should I take the contents of the string tag that is text and replace > all '<' with '<' and '>' with '>' and then read it with xml.minidom? No. We still don't know what you want to achieve, so it is difficult to advise you what to do. My best advise is that whoever generates the XML document should fix it. > or should I use another parser that accomplishes the task with no need > to replace the escaped characters? No. The parser is working correctly. The document you got can also be interpreted as containing another XML document as a text. This is evil, but apparently people are doing it, anyway. If you really want that embedded document, you need first to extract it. To see what I mean, do print DataSetNode.data The .data attribute gives you the string contents of a text node. You could use this as an XML document, and parse it again to an XML parser. This would be ugly, but might be your only choice if the producer of the document is unwilling to adjust. Regards, Martin From kartic.krishnamurthy at gmail.com Wed Jan 5 11:08:54 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 5 Jan 2005 08:08:54 -0800 Subject: get the IP address of a host In-Reply-To: References: Message-ID: <1104941334.814311.198610@z14g2000cwz.googlegroups.com> socket.gethostbyaddr(socket.gethostname()) will return a tuple containing fully qualified hostname, alternative hostnames, ip addresses (>1 if multihomed). Thanks, --Kartic From craig at postnewspapers.com.au Sun Jan 2 01:23:07 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sun, 02 Jan 2005 14:23:07 +0800 Subject: screen clear question In-Reply-To: <10teqpdvramua3@corp.supernews.com> References: <10teqpdvramua3@corp.supernews.com> Message-ID: <1104646987.25948.2.camel@rasputin.localnet> On Sun, 2005-01-02 at 11:31, jcollins wrote: > Is there a command in Python to clear the screen? That is without writing > multiple blank lines. Without knowing what 'screen' you're talking about, it's hard to say. If you mean clearing a terminal, you can call 'tput clear' or '/usr/bin/clear' on many UNIX systems; no idea about Windows. -- Craig Ringer From aorfanakos at gmail.com Mon Jan 31 02:38:21 2005 From: aorfanakos at gmail.com (Aggelos I. Orfanakos) Date: 30 Jan 2005 23:38:21 -0800 Subject: Regarding exception handling References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> <41FDD5F4.8030507@gmail.com> Message-ID: <1107157101.859032.37690@f14g2000cwb.googlegroups.com> Coming from C, I think that it's generally a good programming practice to make sure everything you create, closes; whether it's about a socket or a file. This may not be the case with Python though. To be honest, leaving this task to the garbage collector doesn't sound like a good idea to me (since the language gives you the means to do it yourself). From fredrik at pythonware.com Mon Jan 24 09:19:13 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 15:19:13 +0100 Subject: Memory Usage References: Message-ID: "rbt" wrote: > For example, say I have the same Python script running on two WinXP computers that both have > Python 2.4.0. One computer has 256 MB of Ram while the other has 2 GB of Ram. On the machine with > less Ram, the process takes about 1 MB of Ram. On the machine with more Ram, it uses 9 MB of Ram. > > Is this normal and expected behavior? 1 MB sounds low, 9 MB sounds more reasonable for a script that uses a few mega- bytes of data. what tool are you using to determine the process size? From tadmc at augustmail.com Mon Jan 17 23:52:32 2005 From: tadmc at augustmail.com (Tad McClellan) Date: Mon, 17 Jan 2005 22:52:32 -0600 Subject: [perl-python] 20050116 defining a function References: <1105886753.149519.194980@z14g2000cwz.googlegroups.com> Message-ID: Ala Qumsieh wrote: > Xah Lee wrote: > *plonk* Man, you are way behind the curve. I did that over 3 years ago! [1] [1] Message-ID: <7fe97cc4.0111080051.71a0c6f3 at posting.google.com> I followed the link in that post on a hunch, and found he says himself that he is a troll. Go figure... -- Tad McClellan SGML consulting tadmc at augustmail.com Perl programming Fort Worth, Texas From jeff at ccvcorp.com Wed Jan 5 15:32:19 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 05 Jan 2005 12:32:19 -0800 Subject: Python 2.4 on Windows XP In-Reply-To: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> References: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> Message-ID: <10toje56oiebq24@corp.supernews.com> DavidHolt wrote: > I have a problem that I see on two different machines, one running XP > SP1 and one XP SP 2. > > On both I installed Python 2.4. > > I can't seem to start IDLE. When I try to start it, I get an hourglass > cursor for a short time then nothing more happens. This happens whether > I click the IDLE shortcut or click the pythonw.exe directly, or attempt > to launch pythonw from a command line. Maybe I'm misinterpreting you, here, but pythonw.exe is *not* IDLE. It is, instead, a console-less version of the Python interpreter, which can run the Python scripts for IDLE (among other things). My version of Python is older, but in %pythondir%/Tools/idle, there is an idle.pyw file. Try running that. If it doesn't work, then copy & paste any error messages (you'll probably need to run it from a command line for this) to your next post here so that we can try to troubleshoot a bit more effectively. Jeff Shannon Technician/Programmer Credit International From wittempj at hotmail.com Tue Jan 25 15:34:33 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 25 Jan 2005 12:34:33 -0800 Subject: __deepcopy__ without recursive copies? In-Reply-To: <1106677008.086803.76270@c13g2000cwb.googlegroups.com> References: <1106677008.086803.76270@c13g2000cwb.googlegroups.com> Message-ID: <1106685273.094802.41440@c13g2000cwb.googlegroups.com> Here I found something on __deepcopy__ http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/c34431c5fd3c223b/427866340239edd7?q=__deepcopy__+example&_done=%2Fgroups%3Fq%3D__deepcopy__+example+%26hl%3Den%26lr%3D%26safe%3Doff%26sa%3DN%26tab%3Dwg%26&_doneTitle=Back+to+Search&&d#427866340239edd7 if applied on your script it gives something like: -import copy -class DeviceManager(object): - def __init__(self,devFile): - DevFile = open(devFile) - devList = [Device(line) for line in DevFile] - #etc, etc... - - def __deepcopy__(self, memo): - x = DeviceManager.__new__(DeviceManager) - memo[id(self)] = x - for n, v in self.__dict__.iteritems(): - setattr(x, n, copy.deepcopy(v, memo)) - return x - -class Device(object): - def __init__(self,line): - self.copies = [] - #do something with line here - - def __deepcopy__(self, memo): - x = Device.__new__(Device) - memo[id(self)] = x - for n, v in self.__dict__.iteritems(): - setattr(x, n, copy.deepcopy(v, memo)) - return x - -DevMan1 = DeviceManager(r'c:\autoexec.bat') -DevMan2 = copy.deepcopy(DevMan1) - -print DevMan1 is DevMan2 it prints False, so the deepcopy seems to work From benn at cenix-bioscience.com Tue Jan 11 11:37:38 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Tue, 11 Jan 2005 17:37:38 +0100 Subject: shutil.move has a mind of its own In-Reply-To: <1d6cdae3050111033379f5ee14@mail.gmail.com> References: <1d6cdae3050111033379f5ee14@mail.gmail.com> Message-ID: <41E400D2.1070903@cenix-bioscience.com> Daniel Bickett wrote: >Oh, I'm sorry, that was my mistake. The example contained that error, >but my code does not. > >Daniel Bickett > > To be fair though - I would have expected the method to throw an error rather than default to cwd. Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From sam.wun at authtec.com Wed Jan 12 02:18:09 2005 From: sam.wun at authtec.com (sam) Date: Wed, 12 Jan 2005 15:18:09 +0800 Subject: Excel module for Python Message-ID: Hi group, I m wondering which Excel module is good to be used by Python? Thanks Sam From steven.bethard at gmail.com Wed Jan 12 20:17:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 18:17:17 -0700 Subject: Why would I get a TypeEror? In-Reply-To: References: Message-ID: <5ZydnVNkUIyAUXjcRVn-pw@comcast.com> It's me wrote: > For this code snip: > > a=3 > .... > b=(1,len(a))[isinstance(a,(list,tuple,dict))] > > Why would I get a TypeError from the len function? You're looking for lazy evaluation or short-circuiting behavior. Python provides one form of short circuiting behavior with 'and' and 'or', though you need to be careful. In your particular circumstances, you could write this code as: b = not isinstance(a, (list, tuple, dict)) and 1 or len(a) Some example code: py> def b(a): ... return not isinstance(a, (list, tuple, dict)) and 1 or len(a) ... py> b(3) 1 py> b([]) 0 py> b([3, 4]) 2 Note however that, due to how 'and' and 'or' short-circuit, you cannot write your code as: b = isinstance(a, (list, tuple, dict)) and len(a) or 1 because when len(a) is 0, 1 will be returned instead of 0: py> def b(a): ... return isinstance(a, (list, tuple, dict)) and len(a) or 1 ... py> b(3) 1 py> b([]) 1 py> b([3, 4]) 2 If you want lazy evaluation, you can do this with lambdas (though I wouldn't advise it): b = (lambda: 1, lambda: len(a))[isinstance(a,(list,tuple,dict))]() Note that I select which function using isinstance as you have before, and then invoke the selected function with the final (). Steve From yunmao at gmail.com Thu Jan 20 20:33:25 2005 From: yunmao at gmail.com (Yun Mao) Date: Thu, 20 Jan 2005 20:33:25 -0500 Subject: problems with duplicating and slicing an array Message-ID: <7cffadfa05012017337858d171@mail.gmail.com> Hi python gurus, I have some questions when I'm using python numeric: 1. When I do v = u[:, :], it seems u and v still point to the same memory. e.g. When I do v[1,1]=0, u[1,1] will be zero out as well. What's the right way to duplicate an array? Now I have to do v = dot(u, identity(N)), which is kind of silly. 2. Is there a way to do Matlab style slicing? e.g. if I have i = array([0, 2]) x = array([1.1, 2.2, 3.3, 4.4]) I wish y = x(i) would give me [1.1, 3.3] Now I'm using map, but it gets a little annoying when there are two dimensions. Any ideas would be deeply appreciated! Thanks!!! -Y From duncan.booth at invalid.invalid Mon Jan 3 04:50:06 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Jan 2005 09:50:06 GMT Subject: Problem remotely shutting down a windows computer with python References: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> <1104726323.505127.139360@c13g2000cwb.googlegroups.com> <1104727810.646660.297480@f14g2000cwb.googlegroups.com> Message-ID: Kartic wrote: > Looks like this is the documented outcome. You could alternatively try > setting a little XML-RPC app to invoke 'shutdown -s' on the remote PC > from your PC (e.g. using Twisted Python). > Or invoke 'shutdown -s -m \\machinename' on the local machine to shutdown a remote machine. From skip at pobox.com Fri Jan 28 10:23:09 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 28 Jan 2005 09:23:09 -0600 Subject: debugging os.spawn*() calls Message-ID: <16890.22749.899414.324589@montanaro.dyndns.org> I have an os.spawnv call that's failing: pid = os.spawnv(os.P_NOWAIT, "ssh", ["ssh", remote, "PATH=%(path)s nice -20 make -C %(pwd)s" % locals()]) When I wait for it the status returned is 32512, indicating an exit status of 127. Unfortunately, I see no way to collect stdout or stderr from the spawned process, so I can't tell what's going wrong. The "ssh remotehost PATH=$PATH nice -20 make ..." command works fine from a similar shell script. Thx, Skip From philippecmartin at sbcglobal.net Tue Jan 18 01:10:51 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Tue, 18 Jan 2005 07:10:51 +0100 Subject: how to find site-packages path (Michael Hoffman) - use distutils Message-ID: <1106028651.6604.11.camel@localhost> >> Why would you want to copy any *.pyc instead of compiling them on site? I know that sounds terrible to the open source community, but I do not intend to release the source code for my product - pls go to philippecmartin.com/applications.html for my _small_ contributions :-)) Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From aleaxit at yahoo.com Mon Jan 31 07:46:38 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 31 Jan 2005 13:46:38 +0100 Subject: variable declaration References: Message-ID: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> Alexander Zatvornitskiy wrote: > Hello All! > > I'am novice in python, and I find one very bad thing (from my point of > view) in language. There is no keyword or syntax to declare variable, like > 'var' in Since the lack of declarations is such a crucial design choice for Python, then, given that you're convinced it's a very bad thing, I suggest you give up Python in favor of other languages that give you what you crave. The suggestions about using pychecker, IMHO, amount to "band-aids" -- the right way to deal with minor annoying scratches, but surely not with seriously bleeding wounds, and your language ("very bad thing", "very ugly errors") indicates this is a wound-level issue for you. Therefore, using Python, for you, would mean you'd be fighting the language and detesting its most fundamental design choice: and why should you do that? There are zillions of languages -- use another one. > Pascal, or special syntax in C. It can cause very ugly errors,like this: > > epsilon=0 > S=0 > while epsilon<10: > S=S+epsilon > epselon=epsilon+1 > print S > > It will print zero, and it is not easy to find such a bug! Actually, this while loop never terminates and never prints anything, so that's gonna be pretty hard to ignore;-). But, assume the code is slightly changed so that the loop does terminate. In that case...: It's absolutely trivial to find this bug, if you write even the tiniest and most trivial kinds of unit tests. If you don't even have enough unit tests to make it trivial to find this bug, I shudder to think at the quality of the programs you code. Even just focusing on typos, think of how many other typos you could have, besides the misspelling of 'epsilon', that unit tests would catch trivially AND would be caught in no other way whatsoever -- there might be a <= where you meant a <, a 1.0 where you meant 10, a - where you meant a +, etc, etc. You can't live without unit tests. And once you have unit tests, the added value of declarations is tiny, and their cost remains. A classic reflection on the subject by Robert Martin, a guru of C++ and other languages requiring declarations, is at: . > Even Visual Basic have 'Option Explicit' keyword! May be, python also have > such a feature, I just don't know about it? Python has no declarations whatsoever. If you prefer Visual Basic, I strongly suggest you use Visual Basic, rather than pining for Visual Basic features in Python. If and when your programming practices ever grow to include extensive unit-testing and other aspects of agile programing, THEN you will be best advised to have a second look at Python, and in such a case you will probably find Python's strengths, including the lack of declarations, quite compelling. Some people claim a language should change the way you think -- a frequent poster, excellent Python contributor, and friend, even has that claim in his signature. That may be alright in the groves of academia. If you program to solve problems, rather than for personal growth, on the other hand, changing "the way you think" with each programming language is a rather steep price to pay. As a pragmatist, I prefer a motto that I've also seen about Python: "it fits your brain". I find it's true: Python gets out of my way and let me solve problems much faster, because it fits my brain, rather than changing the way I think. If Python doesn't fit YOUR brain, for example because your brain is ossified around a craving for the declaration of variables, then, unless you're specifically studying a new language just for personal growth purposes, I think you might well be better off with a language that DOES, at least until and unless your brain changes by other means. Alex From peter at engcorp.com Thu Jan 6 10:54:07 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Jan 2005 10:54:07 -0500 Subject: 2 versions of python on 1 machine In-Reply-To: References: Message-ID: <0fydnX5CmoCCwkDcRVn-2w@powergate.ca> flupke wrote: > I have version 2.3.4 and 2.4 installed on windows and i thought that by > switching the PYTHONPATH parameter to the dir of the 2.4 version that > that would make python 2.4 active. That is not the purpose of PYTHONPATH. I'd suggest removing any definition of this environment variable that you have, unless you have a specific reason to use it and know what it actually does. I believe the docs on it are fairly clear, so reading them again might help. Note that if you have installed both versions of Python using the regular installer, the PYTHONPATH information would be redundant anyway because each version puts the necessary info in the Windows registry. > However when i envoke python from the commandline, it still runs 2.3.4 > Is it possible to have 2 versions installed and switching versions when > you need to? It's quite possible. It sounds like your problem is that you have the c:\python23 folder in your PATH (note, not PYTHONPATH, just the old DOS PATH variable). If that's the case, you should probably remove it and use batch files to invoke the different versions instead. > How can i do that? On my machine, I have a folder called c:\bin where I put useful batch files. I have a python23.bat and a python24.bat file, which basically just call c:\python23\python.exe or c:\python24\python.exe as required. For various reasons which may or may not apply to you as well, I also have each of them set the PYTHONHOME variable to point to the right folder as well. The content of each batch file is like this: @echo off c:\python23\python.exe %1 %2 %3 %4 %5 %6 %7 %8 %9 -Peter From Scott.Daniels at Acm.Org Tue Jan 4 14:03:17 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 04 Jan 2005 11:03:17 -0800 Subject: Pythonic search of list of dictionaries In-Reply-To: References: Message-ID: <41dae5c0$1@nntp0.pdx.net> Skip Montanaro wrote: > ...lotsa great stuff ... > You might want to sort your lists by the 'English' key. I don't know how to > use the new key arg to list.sort(), but you can still do it the > old-fashioned way: > > oldl.sort(lambda a,b: cmp(a['English'], b['English'])) > newl.sort(lambda a,b: cmp(a['English'], b['English'])) To complete the thought, for 2.4 and after the new-fashioned way is: import operator oldl.sort(key=operator.itemgetter('English')) newl.sort(key=operator.itemgetter('English')) > Once sorted, you can then march through the lists in parallel, which should > give you an O(n) algorithm. But overall you will have O(n log n) because of the sorts. --Scott David Daniels Scott.Daniels at Acm.Org From tjreedy at udel.edu Tue Jan 11 15:07:53 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 11 Jan 2005 15:07:53 -0500 Subject: Game programming in Python References: Message-ID: "Baza" wrote in message news:BE09CC52.2E5B%baza at themauvezone.fsnet.co.uk... > I'm looking for any books or on-line resources on game programming using > Python. Does anyone have any advice? Google "Python game programming" From bokr at oz.net Wed Jan 5 12:58:12 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 05 Jan 2005 17:58:12 GMT Subject: Is there any way/where to subscribe for automated PEP status emails? Message-ID: <41dc24f8.68802652@news.oz.net> I find that threads sometimes mention PEPs that I wasn't aware of, or that an interesting one has been updated without my noticing. I should perhaps check the PEP site more regularly, but ISTM it shouldn't be that hard to implement an automated notification of PEP status changes by email. A cron job could just monitor the PEP source directory and watch for new files and last-mod changes, for starters. Maybe that would be sufficient, without going into classifying the changes in more detail. Subscription/unsubscription could be like an ordinary read-only mail list. You could just bounce replies with some advice as to where to go ;-) Googling didn't hit anything obvious for me. Regards, Bengt Richter From chrisdewinN0SPAM at yahoo.com.au Wed Jan 19 15:03:40 2005 From: chrisdewinN0SPAM at yahoo.com.au (Dfenestr8) Date: Thu, 20 Jan 2005 06:03:40 +1000 Subject: python/cgi/html bug References: <1106137924.918776.9090@f14g2000cwb.googlegroups.com> Message-ID: On Wed, 19 Jan 2005 04:32:04 -0800, Fuzzyman wrote: > This looks very good. > I've been looking for a python messageboard CGI for a long time. > Thanx! No glaring security holes that you noticed? Other than being able to hide things in html tags? > If you wanted to add user accounts/login/admin etc. you could use 'Login > Tools'. This is a python module built especially to do that. It also > provides a convenient way of saving user preferences etc. > > http://www.voidspace.org.uk/python/logintools.html > > If you want any help using it then feel free to ask. > > Regards, From lkirsh at cs.ubc.ca Sat Jan 29 21:35:04 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Sat, 29 Jan 2005 18:35:04 -0800 Subject: is this sort method the same as the one in python 2.4 Message-ID: I'm trying to emulate the sorted() method introduced in python 2.4. The only difference is that it takes a sequence as one of its arguments rather than being a method of the sequence class. Does my method do the same as the sorted()? The obvious difference is that my method is called as sort(seq, cmp, key, reverse) rather than seq.sorted(cmp, key, reverse) def sort(seq, cmp=None, key=None, reverse=False): "return a sorted copy of its input" if sys.version_info > (2,4): return sorted(seq, cmp, key, reverse) if key: toreturn = [ (key(elt), elt) for elt in seq ] else: toreturn = seq[:] if cmp: toreturn.sort(cmp) else: toreturn.sort() if key: toreturn = [ b for (a,b) in toreturn ] if reverse: toreturn.reverse() return toreturn Lowell From usenet_spam at janc.invalid Fri Jan 21 21:42:39 2005 From: usenet_spam at janc.invalid (JanC) Date: Sat, 22 Jan 2005 02:42:39 GMT Subject: nntplib: abstraction of threads References: <1105840367.526347.110160@c13g2000cwb.googlegroups.com> <41EAA458.1020501@holdenweb.com> Message-ID: Steve Holden schreef: > Better still, do a Google search on "mail threading algorithm", > implement the algorithm described in > > http://www.jwz.org/doc/threading.html > > and post your implementation back to the newsgroup :-) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From sjmachin at lexicon.net Fri Jan 14 15:32:48 2005 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Jan 2005 07:32:48 +1100 Subject: Pickled text file causing ValueError (dos/unix issue) References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> Message-ID: On Fri, 14 Jan 2005 09:12:49 -0500, Tim Peters wrote: >[Aki Niimura] >> I started to use pickle to store the latest user settings for the tool >> I wrote. It writes out a pickled text file when it terminates and it >> restores the settings when it starts. >... >> I guess DOS text format is creating this problem. > >Yes. > >> My question is "Is there any elegant way to deal with this?". > >Yes: regardless of platform, always open files used for pickles in >binary mode. That is, pass "rb" to open() when reading a pickle file, >and "wb" to open() when writing a pickle file. Then your pickle files >will work unchanged on all platforms. The same is true of files >containing binary data of any kind (and despite that pickle protocol 0 >was called "text mode" for years, it's still binary data). Tim, the manual as of version 2.4 does _not_ mention the need to use 'b' on OSes where it makes a difference, not even in the examples at the end of the chapter. Further, it still refers to protocol 0 as 'text' in several places. There is also a reference to protocol 0 files being viewable in a text editor. In other words, enough to lead even the most careful Reader of TFM up the garden path :-) Cheers, John From orwin42 at mail.be Sun Jan 9 11:20:07 2005 From: orwin42 at mail.be (Nyx42) Date: Sun, 09 Jan 2005 11:20:07 -0500 Subject: Pygame and pyopengl with py2exe ? References: <34crqiF47stihU1@individual.net> Message-ID: <2a89f13576daaaef3f1689eb93a445e8@localhost.talkaboutprogramming.com> Same problem: the window closes immediately. For the first program, I precise that the "pygame window" opens also. From http Sat Jan 8 01:30:32 2005 From: http (Paul Rubin) Date: 07 Jan 2005 22:30:32 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> Message-ID: <7xvfa8l9fb.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > > Usage could be something like: > > >>> res = [ f(i) for i in objects ] where: > > >>> def f(x): > > >>> #do something > > Hmm, this is actually a really interesting idea. Avoiding accidental > namespace conflicts is certainly one of the advantages of using lambdas. I like it too. Seems a little perl-ish, but what the hey. > In fact, any subexpressions in a complicated expression can be > extracted and named for clarity without fear of screwing up the > containing namespace, which would be an enormous boon for software > maintainers. Sure, why not: x = (-b + sqrt(discriminant))/(2*a) where: discriminant = b*b - 4*a*c Maybe you could just have a where: suite that binds variables within the suite: where: def f(x): #do something res = [ f(i) for i in objects ] where: discriminant = b*b - 4*a*c x = (-b + sqrt(discriminant))/(2*a) Syntax is where: suite statement the suite has its own scope so any variable created there is local to the suite plus the following statement. The scope vanishes after the statement. From bulba at bulba.com Sat Jan 8 19:34:38 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 09 Jan 2005 01:34:38 +0100 Subject: Speed revisited References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> Message-ID: <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> On 4 Jan 2005 14:33:34 -0800, "John Machin" wrote: >(b) Fast forwarding 30+ years, let's look at the dictionary method, >assuming you have enough memory to hold all your data at once: > >Step 1: read the "left" table; for each row, if english not in mydict, >then do mydict[english] = MyObject(). In any case, do >mydict[english].left_list.append(row) >Step 2: same for the "right" table. >Step 3: for english, obj in mydict.iteritems(): process(english, obj) >As your datasets are stored in MS Excel spreadsheets, N < 64K so >whether your solution is O(N) or O(N*log(N)) doesn't matter too much. >You are however correct to avoid O(N**2) solutions. Following advice of two posters here (thanks) I have written two versions of the same program, and both of them work, but the difference in speed is drastic, about 6 seconds vs 190 seconds for about 15000 of processed records, taken from 2 lists of dictionaries. I've read "Python Performance Tips" at http://manatee.mojam.com/~skip/python/fastpython.html ..but still don't understand why the difference is so big. Both versions use local variables, etc. Both have their lists initially sorted. Both essentially use a loop with conditional for comparison, then process the record in the same way. The overhead of second version is that it also uses cmp() function and two additional integer variables - that should not slow the program _so much_. I have measured the run of snippet 2 with time checkpoints written to a log (write time delta to log every 200 records), even made a graph of time deltas in spreadsheet and in fact snippet 2 seems after initial slowdown looks exactly linear, like that: ^ (time) | | /----------- | / |/ ---------------> (# of records written) So yes, it would scale to big files. However, why is it so frigging slow?! # snippet 1, this runs in about 6 seconds !def prepend(l): ! map = {} ! for d in l: ! key = d['English'] ! map[key] = d ! return map ! !old_map = prepend(oldl) !new_map = prepend(newl) ! !for engphrase in old_map: ! if engphrase in new_map: ! o = old_map[engphrase] ! n = new_map[engphrase] ! cm.writerow(matchpol(o,n)) # snippet 2, this needs 190 seconds !while 1: ! if len(oldl) == 0 or len(newl) == 0: ! break ! if oldl[o]['English'] == newl[n]['English']: ! cm.writerow(matchpol(oldl[o], newl[n])) ! del oldl[o] ! del newl[n] ! o, n = 0, 0 ! continue ! elif cmp(oldl[o]['English'], newl[n]['English']) < 0: ! if o == len(oldl): ! cm.writerow(newl[0]) ! del(newl[0]) ! o, n = 0, 0 ! continue ! o+=1 ! elif cmp(oldl[o]['English'], newl[n]['English']) > 0: ! if n == len(newl): ! cm.writerow(newl[0]) ! del(oldl[0]) ! o, n = 0, 0 ! continue ! n+=1 -- It's a man's life in a Python Programming Association. From aahz at pythoncraft.com Tue Jan 4 12:52:36 2005 From: aahz at pythoncraft.com (Aahz) Date: 4 Jan 2005 12:52:36 -0500 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1104831798.408560.228940@c13g2000cwb.googlegroups.com> <1104852554.684821.297400@f14g2000cwb.googlegroups.com> Message-ID: In article <1104852554.684821.297400 at f14g2000cwb.googlegroups.com>, wrote: >Aahz: >> >> The first three PSF grants were all in some way not directly related to >> changing the core language. One was for a library, one for improving >> Jython, and one for improving docs. Giving the PSF more money increases >> the chances for additional work. > >Here is the link you forgot to post ;-) > >http://www.python.org/psf/grants/ Didn't forget, was lazy and short of time. >The one about the docs seems more about teaching scientists how to use >Python. True, but that's still an expansion of Python's usability as opposed to changing the core language. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From luismgz at gmail.com Sun Jan 9 15:20:40 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 9 Jan 2005 12:20:40 -0800 Subject: else condition in list comprehension Message-ID: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Hi there, I'd like to know if there is a way to add and else condition into a list comprehension. I'm sure that I read somewhere an easy way to do it, but I forgot it and now I can't find it... for example: z=[i+2 for i in range(10) if i%2==0] what if I want i to be "i-2" if i%2 is not equal to 0? From elephantum at dezcom.mephi.ru Sun Jan 9 06:01:03 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 14:01:03 +0300 Subject: python3: 'where' keyword In-Reply-To: References: <3480qqF46jprlU1@individual.net> Message-ID: <34ch7gF45vrjoU1@individual.net> Peter Hansen wrote: >> >>> print words[3], words[5] where: >> >>> words = input.split() >> >> - defining variables in "where" block would restrict their visibility >> to one expression > > Then your example above doesn't work... print takes a > sequence of expressions, not a tuple as you seem to think. sorry, I used "expression" carelessly. I mean that >>> print words[3], words[5] is a single expression (and that would be in Python 3, when print would be subtituted with write()/writeln()). From pycon at python.org Thu Jan 20 19:06:07 2005 From: pycon at python.org (Steve Holden) Date: Fri, 21 Jan 2005 01:06:07 +0100 (CET) Subject: PyCon Preliminary Program Announced! Message-ID: <20050121000607.DE1261E4010@bag.python.org> Dear Python Colleague: You will be happy to know that the PyCon Program Committee, after lengthy deliberations, has now finalized the program for PyCon DC 2005. I can tell you that the decision-making was very difficult, as the standard of submissions was even higher than last year. You can see the preliminary program at http://www.python.org/pycon/2005/schedule.html and it's obvious that this year's PyCon is going to be even fuller than the last. On innovation is that there will be activities of a more social nature on the Wednesday (and perhaps the Thursday) evening, as well as keynote speeches from Guido and two other luminaries. Remember that the early bird registration rates end in just over a week, so hurry on down to http://www.python.org/pycon/2005/register.html to be sure of your place in what will surely be the premier Python event of the year. As always, I would appreciate your help in getting the word out. Please forward this message to your favorite mailing lists and newsgroups to make sure that everyone has a chance to join in the fun! regards Steve Holden Chairman, PyCON DC 2005 -- PyCon DC 2005: The third Python Community Conference http://www.pycon.org/ http://www.python.org/pycon/ The scoop on Python implementations and applications From news+0409 at henrikholm.com Wed Jan 12 11:24:58 2005 From: news+0409 at henrikholm.com (Henrik Holm) Date: Wed, 12 Jan 2005 10:24:58 -0600 Subject: Iteration over two sequences References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> Message-ID: <1gq9u7n.1msmhzw1wzq5alN%news+0409@henrikholm.com> Richard Brodie wrote: > "Henrik Holm" wrote in message > news:1gq9qs9.3snutr1s4mcn2N%news+0409 at henrikholm.com... > > > I suppose I could also use a lambda here -- but is there a different, > > efficient, and obvious solution that I'm overlooking? > > Check the itertools recipes in the library documentation. Thanks, the itertools seem to contain several useful functions. -- "On some great and glorious day the plain folks of the land will reach in their heart's desire at last and the White House will be adorned by a downright moron." -H.L. Mencken (1880-1956) American Writer From tjreedy at udel.edu Thu Jan 6 19:35:29 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Jan 2005 19:35:29 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com><25mlt05vtce42ohljk32qish66oj9bq049@4ax.com><7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: "Steve Holden" wrote in message news:rZbDd.68969$Jk5.62111 at lakeread01... > Absolutely not. Some people want to share under very specific conditions, > hence the proliferation of licenses in the open source world. Indeed, Prof. Lessig at Standford University, I believe, recently designed the Creative Commons license with a checklist of options with the intention of allowing and thereby encouraging people to share under the specific conditions they are willing to share under. http://creativecommons.org/licenses/ Terry J. Reedy From aleaxit at yahoo.com Sat Jan 22 03:50:37 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 09:50:37 +0100 Subject: Reload Tricks References: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> Message-ID: <1gqsb7j.1tbzcqn1f431kdN%aleaxit@yahoo.com> Kamilche wrote: > I want my program to be able to reload its code dynamically. I have a > large hierarchy of objects in memory. The inheritance hierarchy of > these objects are scattered over several files. Michael Hudson has a nice custom metaclass for that in Activestate's online cookbook -- I made some enhancements to it as I edited it for the forthcoming 2nd edition of the cookbook (due out in a couple of months), but the key ideas are in the online version too (sorry, no URL at hand). Alex From roland.heiber at web.de Tue Jan 11 06:07:20 2005 From: roland.heiber at web.de (Roland Heiber) Date: Tue, 11 Jan 2005 12:07:20 +0100 Subject: here document In-Reply-To: References: Message-ID: harold fellermann wrote: > f = open("/bin/exe.x","w") > print >>f , """CategoryY = GRIB > etc. > """ This would overwrite the existing /bin/exe.x ... HtH, Roland From steve at holdenweb.com Sat Jan 22 23:04:28 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 22 Jan 2005 23:04:28 -0500 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> Message-ID: Doug Holton wrote: > Fredrik Lundh wrote: > >> and trust me, when things are hard to get right for developers, users >> will >> suffer too. > > > That is exactly why YAML can be improved. But XML proves that getting > it "right" for developers has little to do with getting it right for > users (or for saving bandwidth). What's right for developers is what > requires the least amount of work. The problem is, that's what is right > for end-users, too. Yet again I will interject that XML was only ever intended to be wriiten by programs. Hence its moronic stupidity and excellent uniformity. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From skip at pobox.com Sat Jan 29 08:28:48 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 29 Jan 2005 07:28:48 -0600 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <41fb646a$0$31784$9b622d9e@news.freenet.de> References: <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> Message-ID: <16891.36752.154869.431676@montanaro.dyndns.org> >> What matters is the code complexity, not whether something is in a >> separate module or not. Martin> A module *is* typically more complex than a single function. And one that deals with cryptography is likely to be even more complex. Skip From francis.girard at free.fr Fri Jan 21 11:54:47 2005 From: francis.girard at free.fr (Francis Girard) Date: Fri, 21 Jan 2005 17:54:47 +0100 Subject: need help on generator... In-Reply-To: <1106325287.19065.50.camel@bucket.localnet> References: <63b5e209.0501210558.686f5c10@posting.google.com> <200501211654.52900.francis.girard@free.fr> <1106325287.19065.50.camel@bucket.localnet> Message-ID: <200501211754.47176.francis.girard@free.fr> Thank you, I immediately download version 2.4, switching from version 2.3. Francis Girard FRANCE Le vendredi 21 Janvier 2005 17:34, Craig Ringer a ?crit?: > On Fri, 2005-01-21 at 16:54 +0100, Francis Girard wrote: > > First, I think that you mean : > > > > consecutive_sets = [ x[offset:offset+subset_size] > > for subset_size in xrange(2, len(x)) > > for offset in xrange(0, len(x) + 1 - subset_size)] > > > > (with square brackets). > > > > I'm just trying to understand and obviously I'm missing the point. > > Yep. This: > > ( x for x in xrange(10) ) > > will return a generator that calculates things as it goes, while this: > > [ x for x in xrange(10) ] > > will return a list. > > Check out: > http://www.python.org/peps/pep-0289.html > http://docs.python.org/whatsnew/node4.html > http://www.python.org/dev/doc/newstyle/ref/genexpr.html > for details. > > -- > Craig Ringer From phr040919 at sympatico.ca Fri Jan 14 01:25:17 2005 From: phr040919 at sympatico.ca (Peter Renzland) Date: Fri, 14 Jan 2005 06:25:17 GMT Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: In <1105495569.479185.166340 at z14g2000cwz.googlegroups.com> On 2005-01-12 humblythegreatest at usa.com wrote: > python.org = 194.109.137.226 > > 194 + 109 + 137 + 226 = 666 > > What is this website with such a demonic name and IP address? What > evils are the programmers who use this language up to? What is the simplest/fastest Python program to determine how many IP addresses sum up to 666? The simplest/fastest enumerator? The simplest/fastest that determines which ones of them are home pages? BTW, www.churchofsatan.org is 216.168.224.70 That adds up to 666 + 12 Are they hedging their bets? :-) -- Peter From vincent at visualtrans.de Tue Jan 25 15:09:31 2005 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 25 Jan 2005 21:09:31 +0100 Subject: Open Folder in Desktop In-Reply-To: References: Message-ID: Jimmy Retzlaff wrote: > Kamilche wrote: > > Folders like My Documents, My Pictures, etc. are special and you need to > determine their actual path before you can open them. The pywin32 > extensions > (https://sourceforge.net/project/showfiles.php?group_id=78018) include a > way to get at this: > > from win32com.shell import shellcon, shell > path = shell.SHGetFolderPath(0, shellcon.CSIDL_MYPICTURES, 0, 0) > os.startfile(path) > > Google for CSIDL to find the constants to use for other special folders. Here's the exact link you'll need (warning, long url ahead ;) http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/enums/csidl.asp -- Vincent Wehren > > Jimmy From sjmachin at lexicon.net Fri Jan 21 18:48:59 2005 From: sjmachin at lexicon.net (John Machin) Date: 21 Jan 2005 15:48:59 -0800 Subject: why am I getting a segmentation fault? In-Reply-To: <1106330476.419418.46920@f14g2000cwb.googlegroups.com> References: <1106330476.419418.46920@f14g2000cwb.googlegroups.com> Message-ID: <1106351339.457714.214940@f14g2000cwb.googlegroups.com> Jay donnell wrote: > I have a short multi-threaded script that checks web images to make > sure they are still there. I get a segmentation fault everytime I run > it and I can't figure out why. Writing threaded scripts is new to me so > I may be doing something wrong that should be obvious :( > def run(self): try: self.site = urllib.urlopen(self.url) self.f=open(self.filename, 'w') self.im = Image.open(self.filename) self.size = self.im.size self.flag = 'yes' self.q = "yadda yadda" That's SIX names that don't need to be attributes of the object; they are used _only_ in this method, so they can be local to the method, saving you a whole lot of typing "self." and saving puzzlement & careful scrutiny by those trying to read your code. Back to your real problem: does it work when you set maxThreads to 1? did it work before you added the threading code? what does your debugger tell you about the location of the seg fault? MOST IMPORTANTLY, sort this mess out: self.q = "update item set goodImage = '" + self.flag + "' where productId='" + str(self.id) + "'" print self.q self.cursor.execute(query) ############################### ### "query" is a global variable[YUK!] (see below) which isn't going to do what you want. Looks like you meant "self.q". self.db.close() db = MySQLdb.connect(host="localhost", user="xxx", passwd="xxx", db="xxx") cursor = db.cursor() query = "select * from item order by rand() limit 0, 100" ### Have you looked in your database to see if the script has actually updated item.goodImage? Do you have a test plan? From adamhum at gmail.com Sat Jan 1 10:58:43 2005 From: adamhum at gmail.com (adamhum at gmail.com) Date: 1 Jan 2005 07:58:43 -0800 Subject: want some extra cash, try this Message-ID: <1104595123.745484.183540@c13g2000cwb.googlegroups.com> want some extra cash, try this THIS REALLY CAN MAKE YOU EASY MONEY!! A little while back, I was on my computer having a grand old time, just like you are now and came across an article similar to this that said you could make thousands dollars within weeks with only an initial investment of $6.00! So I thought, "Yeah, right, this must be a scam", but like most of us, I was curious, so I kept reading. Anyway, it said that you send $1.00 to each of the 6 names and address stated in the article. You then place your own name and address in the bottom of the list at #6, and post the article in at least 200 newsgroups. No catch, that was it. So after thinking it over, and talking to few people first, I thought about trying it. I figured what have I got to lose except 6 stamps and $6.00, right? Like most of us I was a little skeptical and a little worried about the legal aspects of it all, So I checked it out with the U.S. Post Office (1-800-725-2161) and they confirmed that it is indeed legal! Then I invested the measly $6.00. Well GUESS WHAT!!?. Within 7 days, I started getting money in the mail! I was shocked! I figured it would end soon, but the money just kept coming in. In my first week, I made about $25.00. By the end second week I had made a total over $1,000.00! In the third week I had over $10,000.00 and it's still growing. Its Certainly worth $6.00, and 6 stamps, I have spent more than that on the lottery!! Let me tell you how this works and most importantly, why it works?.STEP 1: Get 6 separate pieces of paper and write the following on each piece of paper "PLEASE PUT ME ON YOUR MAILING LIST." Now get 6 US $1.00 bills and place ONE inside EACH of the 6 pieces of paper so the bill will not be seen through the envelope to prevent thievery. Next, place one paper in each stating the above phrase, your name and address, and a $1.00 bill. What you are doing is creating a service by this. THIS IS ABSOLUTELY LEGAL! Mail the 6 envelopes to the following addresses: #1) Jason Barone P.O. Box 1015 Glen Burnie, MD 21060-1015 #2) Jonathon Markwood 3308 Birdsong Way Birmingham, AL 35242 #3) Eben Mcgee 1876 #C Locust, Las Cruces, NM 88001 #4) Ricky DeMaio 471 McCutcheon rd, Hudson WI 54016 #5) P. Ortner 29 Briarlee Dr. Tonawanda, NY 14150 #6) O. Humphrey 8452 E. Louise Dr, Tucson, AZ 85730 STEP 2: Now take the #1 name off the list that you see above, move the other names up and add YOUR Name as number 6 on the list. STEP 3: Change anything you need to, but try to keep this article as close to original as possible. Now, post your amended article to at least 200 newsgroups, message board. All you need is 200, but remember, the more you post, the more money you make!---- Just copy this message, paste it in Word or Notepad, find message boards like this and paste away. Congratulations? THAT'S IT! All you have to do is jump to different newsgroups and post away, after you get the hang of it, and it will take about 30 seconds for each newsgroup! * REMEMBER, THE MORE NEWSGROUPS OR MESSAGE BOARD YOU POST IN, THE MORE MONEY YOU EILL MAKE!! BUT YOU HAVE TO POST A MINIMUM OF 200* That's it! You will begin receiving money from around the world within days! From whereU at now.com Sun Jan 2 06:20:53 2005 From: whereU at now.com (Eric Pederson) Date: Sun, 2 Jan 2005 03:20:53 -0800 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <20050102032053.1006135324.whereU@now.com> Cameron Laird wrote: > > Let me add a cautionary note, though: Big Companies, > including Oracle, Software AG, IBM, Cisco, and so on, have > adopted Tcl over and over. All of them still rely on Tcl > for crucial products. All of them also have employees who > sincerely wonder, "Tcl? Isn't that dead?" > > I offer this as a counter-example to the belief that Adop- > tion by a heavyweight necessarily results in widespread > acceptance. > -- I think the adoption of computer languages is quite complex, but one useful metaphorical model may be gravity, e.g. the clumpy universe of stars, with gravity working on different scales to shape the overall distribution of matter. Adoption by a heavyweight may have some effect if that force is allowed to operate on other bodies, but the overall distribution of "mass" is complex. In the practice of business, companies generally find a need to consciously limit methodological diversity as they grow in size. Control is usually made more centralized, but becomes more distant from the atom (programmer writing code) as the firm grows large, and entropy becomes the enemy, lower level entropy a source of uncertainty and risk. If so, there is some legitimate reason for trying to "standardize" on tools (i.e. programming languages). Less sophisticated business minds may latch onto the notion of gains from economies of scale, which is usually an easy sell (and good route for a fast career rise) but an overly simple optimization. Not to say that such restrictive mindsets and policies are inevitable, but they seem the prevailing wind. Preserving intellectual diversity and innovation may be critical to a big company in the long run, and allowing the use of (for example) Python would seem very in tune with those goals. It might be nice if it was widely understood (in IT) that Python was a language any competent programmer could pick up in an afternoon, such that Java, C, and Perl shops would not be concerned about the need for their staff to learn a new language. Eric Pederson "Linear? What is linear?" Digital M4 (music) http://www.songzilla.blogspot.com ::::::::::::::::::::::::::::::::::: domainNot="@something.com" domainIs=domainNot.replace("s","z") ePrefix="".join([chr(ord(x)+1) for x in "do"]) mailMeAt=ePrefix+domainIs ::::::::::::::::::::::::::::::::::: From andymac at bullseye.apana.org.au Tue Jan 4 06:12:32 2005 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Tue, 4 Jan 2005 22:12:32 +1100 (EST) Subject: ODBC Connection on Windows XP In-Reply-To: <41D99AB3.5090601@novasyshealth.com> References: <41D99AB3.5090601@novasyshealth.com> Message-ID: <20050104220934.E12542@bullseye.apana.org.au> On Mon, 3 Jan 2005, Greg Lindstrom wrote: > I am running Python 2.3 on Windows XP and am trying to connect to an > ODBC datasource. I have done this many times on this same box but this > time I get an error message saying > > dbi.operation-error: [WSOCK32.DLL]Connection refused, is the host > listener running? (#10061) in LOGIN > > Not having seen this before, and having used the odbc module for about a > year now, I'm at a quandary; what does this mean and what do I do to fix it? Exactly what it says... the host you're trying to connect to has refused your connection attempt (at the TCP level). At a guess, the database is down. ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From jlenton at gmail.com Wed Jan 12 18:27:07 2005 From: jlenton at gmail.com (John Lenton) Date: 12 Jan 2005 15:27:07 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: <1105572427.761562.135250@f14g2000cwb.googlegroups.com> > If you could help me figure out how to code a solution > that won't be a resource whore, I'd be _very_ grateful. (I'd prefer to > keep it in Python only, even though I know interaction with a > relational database would provide the fastest method--the group I'm > trying to write this for does not have access to a RDBMS.) You don't need a RDBMS; I'd put it in a DBM or CDB myself. From evan at tokenexchange.com Thu Jan 13 18:03:56 2005 From: evan at tokenexchange.com (Evan Simpson) Date: Thu, 13 Jan 2005 17:03:56 -0600 Subject: News Reader In-Reply-To: <41E6F97A.9010100@bowettsolutions.com> References: <41E6F97A.9010100@bowettsolutions.com> Message-ID: <41E6FE5C.6020804@tokenexchange.com> Daniel Bowett wrote: > OK, ask a stupid question.... I wasn't aware I needed a Usenet account. ...and if you don't have one, like me, there's always GMane (http://www.gmane.org/, nntp://news.gmane.org/). Cheers, Evan @ 4-am From PeterMayne at ap.spherion.com Wed Jan 5 20:28:29 2005 From: PeterMayne at ap.spherion.com (PJDM) Date: 5 Jan 2005 17:28:29 -0800 Subject: Import binary extensions from zipfiles, windows only References: <1104809102.966779.18480@f14g2000cwb.googlegroups.com> Message-ID: <1104974909.307793.173930@c13g2000cwb.googlegroups.com> Thomas Heller wrote: > zipextimporter, as published, doesn't handle extensions in packages. > The patch I attached at the end, may fix this - I tested it with PIL. Thanks, that works fine. However, ZopeX3 itself still won't run. As part of the startup, it attempts to load some files relative to imported classes. Since the path dives into a zip file, opening a file such as file://///C|/tmp/zope.zip/zope/app/server/schema.xml doesn't work. Patching things up to avoid this just leads deeper into the mire, so it looks like this avenue is closed. Things would probably be easier if Python had something like Java's Class.getResourceAsStream(), where a resource is found by the class loader. This means that is doesn't matter if the class came from a directory, a JAR file, or a network: if the class loader could load the class, it could also load the resource from the same place. The __loader__ attribute from PEP 302 seems to be the equivalent, but the standard importer doesn't provide it. maynp at nessus:~> python Python 2.3.4 (#1, Jul 31 2004, 11:22:19) [GCC 3.3.1 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.__loader__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute '__loader__' >>> Oh well. PJDM From francis.girard at free.fr Mon Jan 24 10:24:41 2005 From: francis.girard at free.fr (Francis Girard) Date: Mon, 24 Jan 2005 16:24:41 +0100 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <200501241409.25598.francis.girard@free.fr> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> Message-ID: <200501241624.41889.francis.girard@free.fr> The following implementation is even more speaking as it makes self-evident and almost mechanical how to translate algorithms that run after their tail from recursion to "tee" usage : *** BEGIN SNAP from itertools import tee, imap import sys def imerge(xs, ys): x = xs.next() y = ys.next() while True: if x == y: yield x x = xs.next() y = ys.next() elif x < y: yield x x = xs.next() else: yield y y = ys.next() def hamming(): def _hamming(): yield 1 hamming2 = hammingGenerators[0] hamming3 = hammingGenerators[1] hamming5 = hammingGenerators[2] for n in imerge(imap(lambda h: 2*h, iter(hamming2)), imerge(imap(lambda h: 3*h, iter(hamming3)), imap(lambda h: 5*h, iter(hamming5)))): yield n hammingGenerators = tee(_hamming(), 4) return hammingGenerators[3] for i in hamming(): print i, sys.stdout.flush() *** END SNAP Here's an implementation of the fibonacci sequence that uses "tee" : *** BEGIN SNAP from itertools import tee import sys def fib(): def _fib(): yield 1 yield 1 curGen = fibGenerators[0] curAheadGen = fibGenerators[1] curAheadGen.next() while True: yield curGen.next() + curAheadGen.next() fibGenerators = tee(_fib(), 3) return fibGenerators[2] for n in fib(): print n, sys.stdout.flush() *** END SNAP Francis Girard FRANCE Le lundi 24 Janvier 2005 14:09, Francis Girard a ?crit?: > Ok, I think that the bottom line is this : > > For all the algorithms that run after their tail in an FP way, like the > Hamming problem, or the Fibonacci sequence, (but unlike Sieve of > Eratosthene -- there's a subtle difference), i.e. all those algorithms that > typically rely upon recursion to get the beginning of the generated > elements in order to generate the next one ... > > ... so for this family of algorithms, we have, somehow, to abandon > recursion, and to explicitely maintain one or many lists of what had been > generated. > > One solution for this is suggested in "test_generators.py". But I think > that this solution is evil as it looks like recursion is used but it is not > and it depends heavily on how the m235 function (for example) is invoked. > Furthermore, it is _NOT_ memory efficient as pretended : it leaks ! It > internally maintains a lists of generated results that grows forever while > it is useless to maintain results that had been "consumed". Just for a > gross estimate, on my system, percentage of memory usage for this program > grows rapidly, reaching 21.6 % after 5 minutes. CPU usage varies between > 31%-36%. Ugly and inefficient. > > The solution of Jeff Epler is far more elegant. The "itertools.tee" > function does just what we want. It internally maintain a list of what had > been generated and deletes the "consumed" elements as the algo unrolls. To > follow with my gross estimate, memory usage grows from 1.2% to 1.9% after 5 > minutes (probably only affected by the growing size of Huge Integer). CPU > usage varies between 27%-29%. > Beautiful and effecient. > > You might think that we shouldn't be that fussy about memory usage on > generating 100 digits numbers but we're talking about a whole family of > useful FP algorithms ; and the best way to implement them should be > established. > > For this family of algorithms, itertools.tee is the way to go. > > I think that the semi-tutorial in "test_generators.py" should be updated to > use "tee". Or, at least, a severe warning comment should be written. > > Thank you, > > Francis Girard > FRANCE > > Le dimanche 23 Janvier 2005 23:27, Jeff Epler a ?crit?: > > Your formulation in Python is recursive (hamming calls hamming()) and I > > think that's why your program gives up fairly early. > > > > Instead, use itertools.tee() [new in Python 2.4, or search the internet > > for an implementation that works in 2.3] to give a copy of the output > > sequence to each "multiply by N" function as well as one to be the > > return value. > > > > Here's my implementation, which matched your list early on but > > effortlessly reached larger values. One large value it printed was > > 6412351813189632 (a Python long) which indeed has only the distinct > > prime factors 2 and 3. (2**43 * 3**6) > > > > Jeff > > > > from itertools import tee > > import sys > > > > def imerge(xs, ys): > > x = xs.next() > > y = ys.next() > > while True: > > if x == y: > > yield x > > x = xs.next() > > y = ys.next() > > elif x < y: > > yield x > > x = xs.next() > > else: > > yield y > > y = ys.next() > > > > def hamming(): > > def _hamming(j, k): > > yield 1 > > hamming = generators[j] > > for i in hamming: > > yield i * k > > generators = [] > > generator = imerge(imerge(_hamming(0, 2), _hamming(1, 3)), > > _hamming(2, 5)) generators[:] = tee(generator, 4) > > return generators[3] > > > > for i in hamming(): > > print i, > > sys.stdout.flush() From francis.girard at free.fr Fri Jan 21 10:05:38 2005 From: francis.girard at free.fr (Francis Girard) Date: Fri, 21 Jan 2005 16:05:38 +0100 Subject: need help on need help on generator... In-Reply-To: <1106318290.19065.11.camel@bucket.localnet> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> Message-ID: <200501211605.40696.francis.girard@free.fr> Hi, I recently read David Mertz (IBM DeveloperWorks) about generators and got excited about using lazy constructs in my Python programming. But besides the fact that generators are either produced with the new "yield" reserved word or by defining the __new__ method in a class definition, I don't know much about them. In particular, I don't know what Python constructs does generate a generator. I know this is now the case for reading lines in a file or with the new "iterator" package. But what else ? Does Craig Ringer answer mean that list comprehensions are lazy ? Where can I find a comprehensive list of all the lazy constructions built in Python ? (I think that to easily distinguish lazy from strict constructs is an absolute programmer need -- otherwise you always end up wondering when is it that code is actually executed like in Haskell). Thank you Francis Girard FRANCE Le vendredi 21 Janvier 2005 15:38, Craig Ringer a ?crit?: > On Fri, 2005-01-21 at 17:14 +0300, Denis S. Otkidach wrote: > > On 21 Jan 2005 05:58:03 -0800 > > > > joh12005 at yahoo.fr (Joh) wrote: > > > i'm trying to understand how i could build following consecutive sets > > > from a root one using generator : > > > > > > l = [1,2,3,4] > > > > > > would like to produce : > > > > > > [1,2], [2,3], [3,4], [1,2,3], [2,3,4] > > > > > >>> def consecutive_sets(l): > > > > ... for i in xrange(2, len(l)): > > ... for j in xrange(0, len(l)-i+1): > > ... yield l[j:j+i] > > Since you have a much faster brain than I (though I ended up with > exactly the same thing barring variable names) and beat me to posting > the answer, I'll post the inevitable awful generator expression version > instead: > > consecutive_sets = ( x[offset:offset+subset_size] > for subset_size in xrange(2, len(x)) > for offset in xrange(0, len(x) + 1 - subset_size) ) > > -- > Craig Ringer From jelle.feringa at ezct.net Thu Jan 20 14:38:35 2005 From: jelle.feringa at ezct.net (Jelle Feringa // EZCT / Paris) Date: Thu, 20 Jan 2005 20:38:35 +0100 Subject: building extensions: ming & python mathlink for win32 Message-ID: <20050120193521.37C7A2800129@mwinf1007.wanadoo.fr> Have been trying to build python extensions from the C libs ming & mathlink. I have been able to produce a .pyd object after studying Mike Fletchers excellent: http://www.vrplumber.com/programming/mstoolkit/ which is a terrific tutorial for anyone trying to compile .pyd on win32! Building mathlink (communicating with mathematica from python!) was semi successful in the sense that it did build a .pyd, Semi, since importing it gave: >>> import mathlink Fatal Python error: Error initializing mathlink extension module This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information. Has anyone been able to compile this extension for python? Same thing goes for Ming (c lib for compiling flas .swf files), such a pity no disutils script is included in this very powerful library! ##if you succeeded to build this, please consider sharing it with me! (2.3 is fine as well!) What struck me while trying to compile is that instead of the Active Python 2.4 version I was running I downloaded and installed the python.org version (as recommended by Fletcher), and while launching it, I stated ActivePython 2.4 Build 243 (ActiveState Corp.) based on Python 2.4 HUH! WHAT! No actual difference between the python.org & activestate version??? Cheers, Jelle. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Serge.Orlov at gmail.com Mon Jan 17 04:04:50 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: Mon, 17 Jan 2005 12:04:50 +0300 Subject: how to print unicode structures? References: Message-ID: Serge Orlov wrote: >>>> print unicode([u'???']) > [u'\u0430\u0431\u0432'] > Oops, Outlook Express has screwed the encoding, one more evidence that printing unicode is hard :) I hope this time, the message will be with real Russian characters instead of Latin ones. Serge. From aleaxit at yahoo.com Sat Jan 22 06:00:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 12:00:36 +0100 Subject: need help on need help on generator... References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> Message-ID: <1gqsffz.vgl2rr78gx4xN%aleaxit@yahoo.com> Francis Girard wrote: ... > > A 'def' of a function whose body uses 'yield', and in 2.4 the new genexp > > construct. > > Ok. I guess I'll have to update to version 2.4 (from 2.3) to follow the > discussion. It's worth upgrading even just for the extra speed;-). > > Since you appear to conflate generators and iterators, I guess the iter > > built-in function is the main one you missed. iter(x), for any x, > > either raises an exception (if x's type is not iterable) or else returns > > an iterator. > > You're absolutly right, I take the one for the other and vice-versa. If I > understand correctly, a "generator" produce something over which you can > iterate with the help of an "iterator". Can you iterate (in the strict sense > of an "iterator") over something not generated by a "generator" ? A generator function (commonly known as a generator), each time you call it, produces a generator object AKA a generator-iterator. To wit: >>> def f(): yield 23 ... >>> f >>> x = f() >>> x >>> type(x) A generator expression (genexp) also has a result which is a generator object: >>> x = (23 for __ in [0]) >>> type(x) Iterators need not be generator-iterators, by any means. Generally, the way to make sure you have an iterator is to call iter(...) on something; if the something was already an iterator, NP, then iter's idempotent: >>> iter(x) is x True That's what "an iterator" means: some object x such that x.next is callable without arguments and iter(x) is x. Since iter(x) tries calling type(x).__iter__(x) [[slight simplification here by ignoring custom metaclasses, see recent discussion on python-dev as to why this is only 99% accurate, not 100% accurate]], one way to code an iterator is as a class. For example: class Repeater(object): def __iter__(self): return self def next(self): return 23 Any instance of Repeater is an iterator which, as it happens, has just the same behavior as itertools.repeat(23), which is also the same behavior you get from iterators obtained by calling: def generepeat(): while True: yield 23 In other words, after: a = Repeater() b = itertools.repeat(23) c = generepeat() the behavior of a, b and c is indistinguishable, though you can easily tell them apart by introspection -- type(a) != type(b) != type(c). Python's penchant for duck typing -- behavior matters more, WAY more than implementation details such as type() -- means we tend to consider a, b and c fully equivalent. Focusing on ``generator'' is at this level an implementation detail. Most often, iterators (including generator-iterators) are used in a for statement (or equivalently a for clause of a listcomp or genexp), which is why one normally doesn't think about built-in ``iter'': it's called automatically by these ``for'' syntax-forms. In other words, for x in <<>>: ...body... is just like: __tempiter = iter(<<>>) while True: try: x = __tempiter.next() except StopIteration: break ...body... ((Simplification alert: the ``for'' statement has an optional ``else'' which this allegedly "just like" form doesn't mimic exactly...)) > You're right. I was much more talking (mistakenly) about lazy evaluation of > the arguments to a function (i.e. the function begins execution before its > arguments get evaluated) -- in such a case I think it should be specified > which arguments are "strict" and which are "lazy" -- but I don't think > there's such a thing in Python (... well not yet as Python get more and more > akin to FP). Python's strict that way. To explicitly make some one argument "lazy", sorta, you can put a "lambda:" in front of it at call time, but then you have to "call the argument" to get it evaluated; a bit of a kludge. There's a PEP out to allow a ``prefix :'' to mean just the same as this "lambda:", but even though I co-authored it I don't think it lowers the kludge quotient by all that much. Guido, our beloved BDFL, is currently musing about optional typing of arguments, which might perhaps open a tiny little crack towards letting some arguments be lazy. I don't think Guido wants to go there, though. My prediction is that even Python 3000 will be strict. At least this makes some things obvious at each call-site without having to study the way a function is defined, e.g., upon seeing f(a+b, c*d) you don't have to wonder, or study the ``def f'', to find out when the addition and the multiplication happen -- they happen before f's body gets a chance to run, and thus, in particular, if either operation raises an exception, there's nothing f can do about it. And that's a misunderstanding I _have_ seen repeatedly even in people with a pretty good overall grasp of Python, evidenced in code such as: self.assertRaises(SomeError, f(23)) with astonishment that -- if f(23) does indeed raise SomeError -- this exception propagates, NOT caught by assertRaises; and if mistakenly f(23) does NOT raise, you typically get a TypeError about None not being callable. The way to do the above call, _since Python is strict_, is: self.assertRaises(SomeError, f, 23) i.e. give assertRaises the function (or other callable) and arguments to pass to it -- THIS way, assertRaises performs the call under its own control (inside the try clause of a try/except statement) and can and does catch and report things appropriately. The frequency of this misunderstanding is high enough to prove to me that strictness is not FULLY understood by some "intermediate level" Pythonistas. However, I doubt the right solution is to complicate Python with the ability to have some arguments be strict, and other lazy, much as sometimes one might yearn for it. _Maybe_ one could have some form that makes ALL arguments lazy, presenting them as an iterator to the function itself. But even then the form _should_, I suspect, be obvious at the call site, rather than visible only in the "def"... Alex From carribeiro at gmail.com Sun Jan 9 03:51:42 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sun, 9 Jan 2005 06:51:42 -0200 Subject: python3: 'where' keyword In-Reply-To: <41E0C700.8080604@iinet.net.au> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <7xhdlsw6ov.fsf@ruckus.brouhaha.com> <41E0C700.8080604@iinet.net.au> Message-ID: <864d3709050109005131f943ee@mail.gmail.com> On Sun, 09 Jan 2005 15:54:08 +1000, Nick Coghlan wrote: > Here's another nice one if 'where' is added to compound statements as well: > > @dbc(pre, post) > def foo(): > pass > where: > def pre(): > pass > def post(): > pass Interesting. It solves some of the issues with chosing a clear syntax for "design by contract" and other similar features that were being debated lately. I also thought about his one: ! def foo(x=calculate_default_value()): ! pass ! where: ! def calculate_default_value(): ! ... ! return -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From mcturra2000 at yahoo.co.uk Tue Jan 4 10:52:03 2005 From: mcturra2000 at yahoo.co.uk (Mark Carter) Date: Tue, 04 Jan 2005 15:52:03 +0000 Subject: How can engineers not understand source-code control? In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41da713a$0$610$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: <41dabba1$0$47624$ed2619ec@ptn-nntp-reader02.plus.net> ;; This buffer is for notes you don't want to save, and for Lisp evaluation. ;; If you want to create a file, first visit that file with C-x C-f, ;; then enter the text in that file's own buffer. Cameron Laird wrote: > Well *that* certainly made my morning unpleasant. Then let's see if I can spoil you afternoon, too ... I was working on a project (that used Excel, alas) that checked the daily allocation of oil and gas. The calculations were very complicated, and liable to error. I thought it would be a good idea if I serialised intermediate calculations so they could be checked. My solution was to save them as a CSV file, with array name in the first column, index variables in subsequent columns, and array value in the last column. That way, they could be checked manually. The standard approach at my company would have been to create honking big spreadsheets to house these values. Anyway, time went on, it was decided that these daily calculations needed to be aggregated to monthly values. Well, it turned out that the solution I had adopted was quite good, because one could just suck the file in, read off the relevant variables, and populate an array. To be compared with what would normally happen of creating a nexus of links to a disk-busting collection of spreadsheets. I shall have my revenge, though. The file serve hierarchy that we have is very complicated, and is due for simplification in the very near future. So all those peeps who did spreadsheets, with hard links to other spreadsheets, are in for a bit of a surprise. I think the I-Ching expressed it better than I ever could: The bird's nest burns up. The wanderer laughs at first, Then must needs lament and weep. Through carelessness he loses his cow. Misfortune. Source: http://www.eclecticenergies.com/iching/hexagram.php?nr=56 I'm thinking that the I-Ching is a vast untapped resource for programming wisdom, plus it makes it funny. Or haikus, maybe they'd be good. From roy at panix.com Sun Jan 23 16:04:41 2005 From: roy at panix.com (Roy Smith) Date: Sun, 23 Jan 2005 16:04:41 -0500 Subject: What is print? A function? References: Message-ID: Frans Englich wrote: > Nah, I don't think it's a function, but rather a builtin "statement". But > it's possible to invoke it as an function; print( "test" ) works fine. That's not calling it as a function. The parens in this case are simply evaluated as grouping operators around the string literal. > So I wonder, what _is_ exactly the print statement? The untraditional way of > invoking it(without paranteses) makes me wonder. It's a statement, just like "write" in Fortran. When C came around, the idea of a language having no built-in print statement and having to call a function to generate output was "untraditional". The function was named "printf" (with an "f" at the end) to emphasize that it was a function call, not a built-in language keyword. Java, and many other quasi-C-based languages also use print functions, and this has become so common that people have come to expect it. It's even a function in Perl, although that language's devil-may-care attitude about punctuation makes it difficult to tell for sure :-) > The reason I thinks about this is I need to implement a debug print for my > program; very simple, a function/print statement that conditionally prints > its message whether a bool is true. Not overly complex. You can certainly define a function which conditionally calls print, you just can't call it "print", because that's a reserved word. But, before you get too far down that path, you might want to explore the logging module. It suffers from a bit of kitchen-sink syndrome, so it may be more complicated than you want to deal with, but it's worth taking a look at. You may discover that what you want to do is already done for you. From mhartl at post.harvard.edu Fri Jan 28 12:13:15 2005 From: mhartl at post.harvard.edu (Michael Hartl) Date: 28 Jan 2005 09:13:15 -0800 Subject: a sequence question In-Reply-To: References: Message-ID: <1106932395.158158.149060@c13g2000cwb.googlegroups.com> For problems like this I use a partition function defined in a utils.py file that I use (based on Peter Norvig's utils file at http://aima.cs.berkeley.edu/python/utils.py). Using partition, the problem you posed can be solved by writing #for a, b in partition([1, 2, 3, 4], 2): # print a, b The implementation of partition I use is simple-minded; the previous posts in this thread suggest some more sophisticated ways to attack it using generators. #def partition(seq, partsize): # """Partition a sequence into subsequences of length partsize.""" # ls = len(seq) # assert ls % partsize == 0, ('length %s, partition size %s\n' # % (ls, partsize)) # return [seq[i:(i+partsize)] for i in range(0, ls, partsize)] Michael From kartic.krishnamurthy at gmail.com Sun Jan 9 19:12:03 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 9 Jan 2005 16:12:03 -0800 Subject: path to python file given module In-Reply-To: <1105315568.887724.260370@c13g2000cwb.googlegroups.com> References: <1105315568.887724.260370@c13g2000cwb.googlegroups.com> Message-ID: <1105315923.520581.280580@c13g2000cwb.googlegroups.com> Try this:; >>> import filegen >>> import inspect >>> print inspect.getsourcefile(filegen.SomeClass) 'C:\\Python23\\Lib\\site-packages\\filegen\filegen.py' Cheers, --Kartic From ialbert at mailblocks.com Thu Jan 27 14:10:06 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 27 Jan 2005 14:10:06 -0500 Subject: python memory blow out In-Reply-To: References: Message-ID: Simon Wittber wrote: > Does anyone have ideas on why this is occuring, or how I might > otherwise prevent memory blow out? I don't know it this is a decent enough solution but if I were you I would try running the SQL service in a subshell. Within this subshell I would terminate then restart the program after a large query and keep it going after small ones. The clients then would need to have some tolerance for the service being offline for short periods. Just a guess. Istvan. From ncoghlan at iinet.net.au Sun Jan 9 06:36:18 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 21:36:18 +1000 Subject: python3: 'where' keyword In-Reply-To: <7xr7ku26zs.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> Message-ID: <41E11732.7@iinet.net.au> Paul Rubin wrote: > Nick Coghlan writes: > >>Trying to push it a level further (down to expressions) would, IMO, be >>a lot of effort for something which would hurt readability a lot. > > > I think we should just try to do things in a simple and general way > and not try to enforce readability. Trying to embed a suite in a Python expression is anything but simple, though :) Attaching an optional local suite to every statement can actually be done quite cleanly (so long as the parser is up to the job). Doing the substitutions on the whole statement using distinct names will work just as well as doing the substitutions directly on the subexpressions using duplicate names, and moves the 'unimportant' bits after the whole thing, instead of sprinkling them throughout the statement. It seems a statement based approach would be: 1. Easier to read 2. Less work to implement 3. Consistent with the rest of the language 4. Works for any statements, including compound statements The only disadvantage relative to expression local namespaces would be that you would still have to watch for namespace conflicts within the statement - and I have grave doubts about the structure of any statement which has that problem. If statement local namespaces were pursued, I would see expression local namespaces as something which hurt readability a lot without providing any new functionality. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From skip at pobox.com Fri Jan 14 05:03:28 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 14 Jan 2005 04:03:28 -0600 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: <16871.39152.202342.414779@montanaro.dyndns.org> Fredrik> no, expressions CAN BE USED as statements. that doesn't mean Fredrik> that they ARE statements, unless you're applying belgian logic. Hmmm... I'd never heard the term "belgian logic" before. Googling provided a few uses, but no formal definition (maybe it's a European phrase so searching for it in English is futile). The closest thing I found was Or is it another case of Belgian logic, where you believe it because theres no evidence or motive whatsoever? Fredrik> no, it's Python, and it's designed this way on purpose. go Fredrik> read the language reference. What he said... While Python borrows stuff from other languages where they fit, it has a few core syntactic features that taken together distinguish it from other languages. Not allowing any statements to be used as expressions is one of them. Note that both "expression" and "statement" are context-sensitive terms. Fredrik applied them in their Python sense ("go read the language reference"), while Paul (perhaps naively, perhaps provocatively) seems bent on forcing a more general definition of the two words on the thread. Skip From fredrik at pythonware.com Mon Jan 24 11:04:22 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 17:04:22 +0100 Subject: Right place for third party modules (here: fixedpoint) References: <35kj2iF4n6sokU1@news.dfncis.de> Message-ID: Sibylle Koczian wrote: > for the first time since getting Python I can't get a third party module to work. > > I got fixedpoint.0.1.2.tar.gz from SourceForge for use with KinterbasDB. After unpacking I had a > directory called "fixedpoint" which I put under my site-packages directory. There are no > installation instructions and just the one module fixedpoint.py (and some documentation and > examples). > > All of this under Windows XP, with Python 2.4. > > Now I try to use the module, but > > import fixedpoint > > says "ImportError: No module named fixedpoint". > > I suppose fixedpoint is no package as described in the tutorial and so "site-packages" might not > be the right place for it. site-packages sure works on my windows xp / python 2.4 configuration. what is your sys.path set to? >>> import sys >>> sys.path ['', 'C:\\WINDOWS\\system32\\python24.zip', ... 'C:\\python24', 'C:\\python24\\lib\\site-packages', ... ] if you fire up a command window and run python -v -v -c "import fixedpoint" you get a list of places where python looks for that module. does it look in right directory? (this can be very verbose; you might wish to do python -v -v -c "import fixedpoint" 2> out notepad out instead) From db3l at fitlinxx.com Thu Jan 6 13:15:01 2005 From: db3l at fitlinxx.com (David Bolen) Date: 06 Jan 2005 13:15:01 -0500 Subject: Another PythonWin Excel question References: <1104968382.403653.267060@f14g2000cwb.googlegroups.com> Message-ID: "It's me" writes: > Yes, I read about that but unfortunately I have no experience with VBA *at > all*. :=( You don't really have to know VBA, but if you're going to try to interact with COM objects from Python, you'll find it much smoother if you at least use any available reference information for the COM object model and interfaces you are using. In the Excel case, that means understanding - or at least knowing how to look in a reference - its object model, since that will tell you exactly what parameters an Add method on a worksheet object will take and how they work. For excel, online documentation can be found in a VBAXL9.CHM help file (the "9" may differ based on Excel release), but it might not always be installed depending on what options were selected on your system. In my English, Office 2000 installation, for example, the files are located in: c:\Program Files\Microsoft Office\Office\1033 You can load that file directly, or Excel itself will reference it from within the script editor help (Tools->Macro->Visual Basic Editor, then F1 for help). If you methods or classes and have the help installed it'll bring in the reference. You can also find it on MSDN on the web, although it can be tricky to navigate down to the right section - the top of the Office 2000 object documentation should be available at: http://msdn.microsoft.com/library/en-us/odeomg/html/deovrobjectmodelguide.asp This is mostly reference information, but there are some higher level discussions of overall objects (e.g., worksheets, workbooks, cells, etc...) too. -- David From kartic.krishnamurthy at gmail.com Thu Jan 6 07:16:25 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 6 Jan 2005 04:16:25 -0800 Subject: navigating/changing directories In-Reply-To: <1105013445.219752.99060@z14g2000cwz.googlegroups.com> References: <1105013445.219752.99060@z14g2000cwz.googlegroups.com> Message-ID: <1105013785.465364.18070@f14g2000cwb.googlegroups.com> Hmmm... I take it back... that is not working! I think it changes the path only during execution time. From tundra at tundraware.com Thu Jan 20 05:53:57 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 20 Jan 2005 05:53:57 EST Subject: [ANN] tconfpy 2.112 Released And Available Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 'tconfpy' Version 2.112 is now released and available for download at: ~ http://www.tundraware.com/Software/tconfpy The last public release was 1.185 (5-2-2004) This is a significant bugfix and feature upgrade release. Existing users are strongly encouraged to upgrade. Be aware that the passed and returned API parameters have changed, as have some of the semantics of the configuration language, so existing code and/or configuration files may need to be edited accordingly. Complete details can be found in the WHATSNEW.txt file included in the distribution. Users are strongly encouraged to join the tconfpy-users mailing list as described in the documentation. What Is 'tconfpy'? - ------------------ 'tconfpy' is an advanced configuration file parser and validator for Python programs. By using 'tconfpy', Python programmers can provide their users with an external configuration file for setting program options, defining defaults, and so on. 'tconfpy' offloads the responsibility for parsing and validating a configuration file from the main application. The Python programmer need only deal with the results and any errors or warnings generated during the parsing process. 'tconfpy' recognizes a rich configuration language and provides a number of sophisticated programming features including: ~ - The ability to breakup large configurations into smaller pieces ~ via the '.include' directive. ~ - Support for string substitution and concatenation throughout the ~ configuration file via string variables. Variables may be ~ locally declared, a reference to a symbol already in the ~ symbol table, or a reference to an environment variable. ~ - A complete set of conditional directives for selective ~ processing of configuration options. Both existential ("If ~ variable exists ...") and comparison ("if string equals/does not ~ equal string ...") forms are provided, as is an '.else' ~ directive. ~ - The ability to instantiate program options prior to reading a ~ configuration file and make them mandatory by declaring those ~ options as Read-Only. ~ - Optional type validation to ensure that a user enters a value ~ appropriate for boolean, integer, floating point, string, or ~ complex data. ~ - Optional value validation to ensure that a configuration option ~ is either within a specified range or one of an enumerated set ~ of possible values. For configuration options which are string ~ types, 'tconfpy', can optionally specify min/max string lengths ~ and enumerate a set of legitimate regular expressions that the ~ string must match. ~ - The ability to define an arbitrary number of lexical namespaces. ~ - The ability to use the various features of 'tconfpy' as a pre- ~ processor for any other text (including source code for other ~ programming languages and Python itself) via the '.literal' ~ directive. ~ - The ability to "template" classes of variables, thereby predefining ~ the type and value restrictions for such variables. This makes ~ 'tconfpy' useful as a building block for data validation tools. ~ - An optional debug capability which returns detailed information ~ about each line parsed. ~ - Includes a test driver program for learning how to program with ~ 'tconfpy' and for debugging and testing your own configuration ~ files. ~ - Comes with approximately 40 pages of documentation including a ~ Programmer's API Reference and a User's Guide to the 'tconfpy' ~ configuration language. Documentation is provided in several ~ formats including Unix 'man', Plain Text, html, pdf, and ~ Postscript. 'tconfpy' is a Pure Python module and is platform-independent. It should work identically on any platform on which Python runs. - ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.6 (Cygwin) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFB744ayjgA+Mact+YRAopHAJ952scQ/LVBz5ye+VARvuhsKk+9cgCfYNSQ LLuefsso1mXxdh38EEovuCo= =ojco -----END PGP SIGNATURE----- From timr at probo.com Fri Jan 21 02:58:10 2005 From: timr at probo.com (Tim Roberts) Date: Thu, 20 Jan 2005 23:58:10 -0800 Subject: global variable, ok for string, bad for int References: <41f07e65$1_2@aeinews.> Message-ID: francisl wrote: > >I have a problem when I declare global variable. >If it is string, dict, array or tuple, everything goes fine, but with int, I get an "used before declaration" error. Excuse me for being dubious, but I don't believe you. Both of the examples you posted work fine in Python 2.3 on Windows XP. Please type the EXACT script you ran, and show us the EXACT error message you get. You can cut-and-paste from the cmd shell script to make sure we see the right output. >here a sample : > >vardict = {'un':1, 'deux':2} > >def print_value(): > print vardict['un'] >######### ok, that works > >-------------------- > >#!/bin/python >varint = 1 > >def print_value(): > print varint >######### ok, that failed > >python 2.3.4 - windows2000 > >(it works in linux!) -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com Sun Jan 9 11:34:11 2005 From: jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com (Miklós P) Date: Sun, 9 Jan 2005 17:34:11 +0100 Subject: Guild of Python consultants? Message-ID: Hello freelancers out there, Is there such a thing somewhere? Yes, I'm aware of the Python Business Forum. But I mean something specifically for (individual) consultants. By searching on Google, I couldn't find a "virtual guild" of consultants who try to make a living from Python and technologies built around it (like Zope, Plone, etc.) I'm thinking of providing mutual marketing help like a webring, passing info about projects and clients, discussing business related issues and technical issues in deploying Python in the enterprise, etc. Any thoughts? Best, Mikl?s --- Jegenye 2001 Bt. Egyedi szoftverk?sz?t?s, tan?csad?s | Custom software development, consulting Magyarul: http://jegenye2001.parkhosting.com In English: http://jegenye2001.parkhosting.com/en From bokr at oz.net Sat Jan 8 05:55:36 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 08 Jan 2005 10:55:36 GMT Subject: Other notes References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> <41DD40F1.5030301@holdenweb.com> <41dda7c5.167823026@news.oz.net> <41def1ea.252340977@news.oz.net> Message-ID: <41dfa77b.298821542@news.oz.net> On Sat, 08 Jan 2005 18:22:53 +1000, Nick Coghlan wrote: >Bengt Richter wrote: >> IOW, I think there is a fix: keep tokenizing greedily and tokenize floating point as >> a sequence of integers and operators, and let be translated by >> the compiler to floating point, and be translated to the >> appropriate generator expression implementation. > >That would be: > > -> float( + "." + ) > -> getattr(int(), ) > -> xrange(, ) > >However, the problem comes when you realise that 1e3 is also a floating point >literal, as is 1.1e3. > Ok, that requires a little more imagination ;-) I think it can be solved, but I haven't explored it all the way through ;-) The key seems to be to be to condition the recognition of tokens as if recognizing an old potentially floating point number, but emitting number-relevant separate tokens so long as there is no embedded spaces. When a number ends, emitting an end marker should permit the compiler to deal with the various compositions. We still aren't looking ahead more than one, but we are carrying context, just as we do to accumulate digits of an integer or characters of a name, but the context may continue and determine what further tokens are emitted. E.g. the 'e' in the embedded numeric context, becomes rather than a name. In the following, :== end of number token 1.1 -> <1><1> 1 .1 -> <1><1> 1.e1 -> <1><1> 1 .e1 -> <1> 1.2e3 -> <1><2><3> 1..2 -> <1><1> 1. .2 -> <1><2> (syntax error) 1 ..2 -> <1><1> I just have the feeling that there is a solution, whatever the hiccups ;-) Regards, Bengt Richter From aahz at pythoncraft.com Thu Jan 6 20:07:19 2005 From: aahz at pythoncraft.com (Aahz) Date: 6 Jan 2005 20:07:19 -0500 Subject: The Industry choice References: <7xhdluxh4i.fsf@ruckus.brouhaha.com> Message-ID: In article , Bulba! wrote: > >Nope. That is not what I'm arguing. Really, I think you have >jumped to conclusion about that: I merely pointed out that >I don't like what I perceive as end effect of what GPL license >writers are attempting to achieve: vendor lock-in. > >I think I stated that clearly. And my counter-argument is that I believe your perception is wrong. If I agreed with your focus on lock-in, I'd say that what the GPL is trying to lock in is a specific legal philosophy by subverting the existing system. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From beliavsky at aol.com Mon Jan 17 10:47:06 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 17 Jan 2005 07:47:06 -0800 Subject: dynamic data types References: <1105969253.296411.301760@f14g2000cwb.googlegroups.com> Message-ID: <1105976826.510706.114900@z14g2000cwz.googlegroups.com> rbt wrote: >I've always thought of it like this... in C, we have to do something >like this when declaring a variable: >int x = 0; >We had to specifically tell the language compiler that x is an integer. >In Python, all we have to do is: >x = 0 >The interpretor knows that x is an integer. We can also change the type >like this: >str(x) >float(x) >long(x) Just to clarify, str(x) does not change x, but x = str(x) does. Probably rbt knows this. I wonder how often this feature should be employed. In my Python programs, most variables keep the same type throughout. This makes a code easier for me to understand, and this constraint should facilitate translation of the code to a statically typed language (perhaps even a variant of Python) in the future, if necessary. The ability to grow a list with "append" is a very convenient feature of Python. The C++ vector is similar but stores elements of the same type, whereas a Python list or tuple can store elements of different types. From deetsNOSPAM at web.de Mon Jan 10 08:21:29 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 10 Jan 2005 14:21:29 +0100 Subject: Port blocking References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> Message-ID: <34fabdF49gjh1U1@individual.net> > Usually you wouldn't run a public corba or pyro service over the > internet. You'd use something like XMLRPC over HTTP port 80 partly > for the precise purpose of not getting blocked by firewalls. What exactly makes sending bytes over port 80 more secure than over any other port? It has always been my impression that this was to create less administrative troubles for firewall admins. But its not inherently more secure. That's a property of the application running. -- Regards, Diez B. Roggisch From ncoghlan at iinet.net.au Sat Jan 8 00:06:44 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 15:06:44 +1000 Subject: What could 'f(this:that=other):' mean? In-Reply-To: <41DF05DC.9060004@pytex.org> References: <41DC52CA.5070104@pytex.org> <10toomjdjcs5v21@corp.supernews.com> <41DCE28B.70806@pytex.org> <10tr8eo5skqo2a3@corp.supernews.com> <41DF05DC.9060004@pytex.org> Message-ID: <41DF6A64.3060000@iinet.net.au> If the caller is meant to supply a namespace, get them to supply a namespace. def f(ns1, ns2): print ns1['a'], ns1['b'], ns2['a'], ns2['b'] f(ns1 = dict(a=1, b=2), ns2 = dict(a=3, b=4)) Hey, where's Steve? Maybe his generic objects should be called namespaces instead of bunches. . . def f(ns1, ns2): print ns1.a, ns1.b, ns2.a, ns2.b f(ns1 = namespace(a=1, b=2), ns2 = namespace(a=3, b=4)) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From sjmachin at lexicon.net Fri Jan 21 23:59:39 2005 From: sjmachin at lexicon.net (John Machin) Date: 21 Jan 2005 20:59:39 -0800 Subject: getting file size In-Reply-To: References: Message-ID: <1106369979.460268.116610@z14g2000cwz.googlegroups.com> Bob Smith wrote: > Are these the same: > > 1. f_size = os.path.getsize(file_name) > > 2. fp1 = file(file_name, 'r') > data = fp1.readlines() > last_byte = fp1.tell() > > I always get the same value when doing 1. or 2. Is there a reason I > should do both? When reading to the end of a file, won't tell() be just > as accurate as os.path.getsize()? > Read the docs. Note the hint that you get what the stdio serves up. ftell() can only be _guaranteed_ to give you a magic cookie that you may later use with fseek(magic_cookie) to return to the same place in a more reliable manner than with Hansel & Gretel's non-magic bread-crumbs. On 99.99% of modern filesystems, the cookie obtained by ftell() when positioned at EOF is in fact the size in bytes. But why chance it? os.path.getsize does as its name suggests; why not use it, instead of a method with a side-effect? As for doing _both_, why would you?? From kartic.krishnamurthy at gmail.com Wed Jan 5 19:31:27 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 5 Jan 2005 16:31:27 -0800 Subject: Another PythonWin Excel question In-Reply-To: References: <1104968382.403653.267060@f14g2000cwb.googlegroups.com> Message-ID: <1104971487.590817.172620@f14g2000cwb.googlegroups.com> Sorry, I was thinking of the move() method. Move() takes the after= argument. See this link for usage. (The left nav bar has all other method of the worksheets collection, so bookmark this page :-) http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_wrcore/html/wrtskhowtoaddnewworksheetstoworkbooks.asp Thanks From yyusenet at yahoo.com Mon Jan 31 18:10:20 2005 From: yyusenet at yahoo.com (YYusenet) Date: Mon, 31 Jan 2005 16:10:20 -0700 Subject: [perl-python] find & replace strings for all files in a dir In-Reply-To: <1107203410.397877.309750@c13g2000cwb.googlegroups.com> References: <1107203410.397877.309750@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > suppose you want to do find & replace of string of all files in a > directory. > here's the code: [snip] > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html > When are you going to take the hint (from everybody in comp.lang.perl.misc and comp.lang.python) to stop posting! Your posts do not help anybody and will only hurt a beginner. *PLEASE STOP POSTING*! -- k g a b e r t (@at@) x m i s s i o n (.dot.) c o m * After "extensive" research, I noticed * that yyusenet at yahoo.com received 12 * spam e-mail messages after just two * posts on usenet groups. If you want * to email me, use the "encrypted" * email address at the beggining of my * signature. From swaroopch at gmail.com Tue Jan 25 15:54:41 2005 From: swaroopch at gmail.com (Swaroop C H) Date: Wed, 26 Jan 2005 02:24:41 +0530 Subject: MySQLdb In-Reply-To: <41F6AF8A.3040102@bowettsolutions.com> References: <41F6AF8A.3040102@bowettsolutions.com> Message-ID: <351e8871050125125434eb6d2@mail.gmail.com> On Tue, 25 Jan 2005 20:43:54 +0000, Daniel Bowett wrote: > I have just started playing around with MySQLdb for a project I am planning. > > As a test I have written a script that executes 3000 insert statements > on a table. The table contains 10 fields with a mix of text and numbers > - its a product table for a website eg UPC, ProductName, Price etc. > > The problem I have is that it takes just over two minuted to execute the > 3000 insert statements which seems really slow! I am running it on a > machine with a 1.5 Ghz Pentium M Processor and Gig Of Ram. I dont think > the machine is to blame for the speed because during execution the > processor sits at about 10% and there is loads of free RAM. I think a better option is to have the rows in a text file and then use `mysqlimport` or 'load data infile' SQL[1] [1]: http://dev.mysql.com/doc/mysql/en/load-data.html -- Swaroop C H Blog: http://www.swaroopch.info Book: http://www.byteofpython.info From grante at visi.com Thu Jan 13 17:31:55 2005 From: grante at visi.com (Grant Edwards) Date: 13 Jan 2005 22:31:55 GMT Subject: how to control the mouse pointer with python? References: <1105650438.311153.167410@f14g2000cwb.googlegroups.com> <34o9npF4et4hiU1@individual.net> <1105654593.637145.321290@z14g2000cwz.googlegroups.com> Message-ID: <41e6f6db$0$5416$a1866201@visi.com> On 2005-01-13, oglycans at yahoo.com wrote: > Sorry, I should have mentioned it's linux (debian). > Thanks. What environment? Console? X11? MGR? ??? -- Grant Edwards grante Yow! My ELBOW is a remote at FRENCH OUTPOST!! visi.com From gh at ghaering.de Tue Jan 4 12:52:16 2005 From: gh at ghaering.de (Gerhard Haering) Date: Tue, 4 Jan 2005 18:52:16 +0100 Subject: DB-API 2.0 in pysqlite and pgdb In-Reply-To: References: Message-ID: <20050104175216.GA830@mylene.ghaering.de> On Sat, Jan 01, 2005 at 06:33:24PM +0300, Roman Suzi wrote: > > Happy New Year to all Pythoneers! > > I am playing with pysqlite and pgdb and their DB-API conformancy. > It was quite interesting to know: > > - sqlite doesn't have mandatory helper-functions Date, Tim, etc. > (due to an error int it's __init__, but this is quite obvious to correct > or just to use mx.Date, mx.Time) Yes, that's an oversight. > more serious mishaps with pgdb (postgresql-python): > it doesn't know how to quote date-time data for the objects > it has constructors itself. [...] You may have better luck with pyPgSQL or psycopg. -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From darrinbaggs at --spamreallysucks--rogers.com Fri Jan 7 19:08:15 2005 From: darrinbaggs at --spamreallysucks--rogers.com (Baggs) Date: Fri, 07 Jan 2005 19:08:15 -0500 Subject: Help uninstalling/installing Python 2.4 Message-ID: Guys/Gals I've messed up my Python 2.4 install. I'm really new to Python (and Linux for that matter) and really wanted to try Python out. I have mandrake 10.1. The first thing I did was uninstalled via rpm Python 2.3 and Tkinter 8.3 (I now realize that was a mistake, since I could have both version installed with no problems). I then downloaded Python2.4 ran ./configure make and make install... voila I had Python installed... Tk calls did not work, the output from Python when running a program stated that I probably did not have TK installed. I got and installed TK 8.4 and the problem persisted (I know I should have written down the exact error, but I didn't... but the story gets worse!) Here is the really stupid part... I figured if I uninstalled and re-installed everything would be ok.... the bad part is I could not find an uninstaller for TK or Python, so I just searched and delted the files and directorys from /usr/local.... when I re-installed I still have problems.. everything installs ok, but now I get the following errors with Python... bash: /usr/bin/python: No such file or directory The interesting thing is the python executable is in /usr/local/bin when I go to /usr/local/bin and type ./python I get Python 2.4 (#6, Jan 7 2005, 18:44:57) [GCC 3.4.1 (Mandrakelinux 10.1 3.4.1-4mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. Traceback (most recent call last): File "/etc/pythonrc.py", line 2, in ? import readline ImportError: No module named readline I think some paths are screwed up.. can someone take pity on me and give me a hand. Thanks Darrin PS -- if you want to mail me directly remove the --spamreallysucks-- in my email address. From stephen.thorne at gmail.com Wed Jan 12 22:26:54 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 13:26:54 +1000 Subject: pyserial and com port interrupts In-Reply-To: <41e5e4e2.707756109@news.oz.net> References: <41e5e4e2.707756109@news.oz.net> Message-ID: <3e8ca5c805011219265626a9f8@mail.gmail.com> On Thu, 13 Jan 2005 03:11:23 GMT, Bengt Richter wrote: > On Wed, 12 Jan 2005 14:24:48 -0800, engsol wrote: > > >Has anyone done a script that will rspond to the serial com port(s) > >receive buffer interrupt, as opposed to polling and timeouts? > >Win2000 is the main interest right now. > > Have you looked into letting the OS do it? I.e., reading from COM4: > or whatever port in a thread maybe one byte at a time? Maybe you can > get your end functionality without writing low levels stuff, depending ;-) > > I haven't done this, but it seems an easy thing to try a few experiments with. > The control panel should let you set baud rates and handshaking etc. I would think. PySerial[1] is more than capable of handling all the low level operations with little more than 's.baud = 9600'. The OP was more interested in how to write his program so he could react to com port input in a timely manner in the face of having blocking procedures elsewhere in his code. Regards, Stephen Thorne [1] http://pyserial.sourceforge.net/ From markfanty at yahoo.com Mon Jan 24 22:24:43 2005 From: markfanty at yahoo.com (Mark Fanty) Date: Tue, 25 Jan 2005 03:24:43 GMT Subject: best way to do a series of regexp checks with groups References: Message-ID: <%ZiJd.5729$cx2.3209@trndny03> This is the kind of thing I meant. I think I have to get used to writing small, light-weight classes. You inspired this variation which is a little more verbose in the class definition, but less so in the use: class Matcher: def search(self, r,s): self.value = re.search(r,s) return self.value def __getitem__(self, i): return self.value.group(i) m = Matcher() if m.search(r'add (\d+) (\d+)', line): do_add(m[1], m[2]) elif m.search(r'mult (\d+) (\d+)', line): do_mult(m[1], m[2]) elif m.search(r'help (\w+)', line): show_help(m[1]) As for using regular expressions too much... they are why I've liked perl so much for quick file processing for years. I don't like perl objects at all, which is why I'm trying python, but the re package has not been my favorite so far... "Nick Craig-Wood" wrote in message news:slrncv8ar0.m68.nick at irishsea.home.craig-wood.com... > > There was a thread about this recently under the title > > "regular expression: perl ==> python" > > Here is a different solution... > > class Result: > def set(self, value): > self.value = value > return value > > m = Result() > > if m.set(re.search(r'add (\d+) (\d+)', line)): > do_add(m.value.group(1), m.value.group(2)) > elif m.set(re.search(r'mult (\d+) (\d+)', line)): > do_mult(m.value.group(1), m.value.group(2)) > elif m.set(re.search(r'help (\w+)', line)): > show_help(m.value.group(1)) > > -- > Nick Craig-Wood -- http://www.craig-wood.com/nick From bokr at oz.net Thu Jan 13 19:08:09 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 14 Jan 2005 00:08:09 GMT Subject: newbie q References: <34mgq0F4dq4buU1@individual.net> <34mku4F4c8bdkU1@individual.net> Message-ID: <41e7098e.782680124@news.oz.net> On Thu, 13 Jan 2005 09:16:40 -0500, Steve Holden wrote: [...] > >Any statement of the form > > for i in [x for x in something]: > >can be rewritten as > > for i in something: > >Note that this doesn't mean you never want to iterate over a list >comprehension. It's the easiest way, for example, to iterate over the >first item of each list in a list of lists: > > for i in [x[0] for x in something]: > As I'm sure you know, with 2.4's generator expressions you don't have to build the temporary list. Which could be important if 'something' is (or generates) a huge sequence. for i in (x[0] for x in something): >>> something = ([x] for x in xrange(10,20)) >>> something >>> list(something) [[10], [11], [12], [13], [14], [15], [16], [17], [18], [19]] >>> for i in (x[0] for x in something): print i, ... oops, that list() used it up ;-) >>> something = [[x] for x in xrange(10,20)] >>> for i in (x[0] for x in something): print i, ... 10 11 12 13 14 15 16 17 18 19 Really nice. Regards, Bengt Richter From fuzzyman at gmail.com Fri Jan 28 04:03:37 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 28 Jan 2005 01:03:37 -0800 Subject: urllib2 and proxy question In-Reply-To: References: <1106575675.520424.155310@f14g2000cwb.googlegroups.com> Message-ID: <1106903017.560210.67150@c13g2000cwb.googlegroups.com> rbt wrote: > Fuzzyman wrote: > > urllib2 (under windows) will auto-detect your proxy settings and use > > those. > > > > Normally that's a good thing (I guess), except when it's not ! > > > > How do I switch off this behaviour ? I'm behind a censoring proxy and > > wanting to test things *locally*. IE is set to not use the proxy when > > fetching local adresses, but urllib2 ignores that part of the setting > > and uses the proxy for everything. > > > > The only way I can test are changing my IE settings back and forth > > every time. Most annoying. > > > > I can see how to *add* a new proxy to urllib2, but not how to force it > > to not use a proxy. I may well be missing something obvious though. > > Anyone able to help ? > > Regards, > > > > Fuzzy > > http://www.voidspace.org.uk/python/index.shtml > > > > "Alternatively, the optional proxies argument may be used to explicitly > specify proxies. > It must be a dictionary mapping scheme names to proxy URLs, where an > empty dictionary causes no proxies to be used" > > # Don't use any proxies > filehandle = urllib.urlopen(some_url, proxies={}) The correct equivalent for urllib2 (in answer to my question !) is : >>> proxy_support = urllib2.ProxyHandler({}) >>> opener = urllib2.build_opener(proxy_support) >>> urllib2.install_opener(opener) which is slightly more complicated but does exactly the same job ! Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From wittempj at hotmail.com Wed Jan 12 13:56:52 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 12 Jan 2005 10:56:52 -0800 Subject: Refactoring; arbitrary expression in lists In-Reply-To: References: Message-ID: <1105556212.036972.160470@z14g2000cwz.googlegroups.com> I can not break the original code in 2.4, if I try this: import os, sys class NoMimeError(Exception): pass def detectMimeType( filename ): extension = filename[-3:] basename = os.path.basename(filename) if extension == "php": return "application/x-php" elif extension == "cpp" or extension.endswith("cc"): return "text/x-c++-src" elif extension == "1": return 'BlahBlah' elif extension == "2": return 'BlahBlah' elif extension == "3": return 'BlahBlah' elif extension == "4": return 'BlahBlah' elif extension == "5": return 'BlahBlah' elif extension == "6": return 'BlahBlah' elif extension == "7": return 'BlahBlah' elif extension == "8": return 'BlahBlah' elif extension == "9": return 'BlahBlah' elif extension == "10": return 'BlahBlah' elif extension == "11": return 'BlahBlah' elif extension == "12": return 'BlahBlah' elif extension == "13": return 'BlahBlah' elif extension == "14": return 'BlahBlah' elif extension == "15": return 'BlahBlah' elif extension == "16": return 'BlahBlah' elif extension == "17": return 'BlahBlah' elif extension == "18": return 'BlahBlah' elif extension == "19": return 'BlahBlah' elif extension == "20": return 'BlahBlah' elif extension == "xsl": return "text/xsl" elif basename.find( "Makefile" ) != -1: return "text/x-makefile" else: raise NoMimeError try: print detectMimeType(r'c:\test.php') print detectMimeType('c:\test.xsl') print detectMimeType('c:\test.xxx') except Exception, e: print >> sys.stderr, '%s: %s' %(e.__class__.__name__, e) I get >>> application/x-php text/xsl NoMimeError: >>> So although the dictionary solution is much nicer nothing seems wrong with your code as it is - or am I missing something? From mmokrejs at ribosome.natur.cuni.cz Fri Jan 14 11:12:32 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?UTF-8?B?TWFydGluIE1PS1JFSsWg?=) Date: Fri, 14 Jan 2005 17:12:32 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <1f7befae0501101245679b26f2@mail.gmail.com> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> <41E2E69C.7080104@ribosome.natur.cuni.cz> <1f7befae0501101245679b26f2@mail.gmail.com> Message-ID: <41E7EF70.1020505@ribosome.natur.cuni.cz> Tim Peters wrote: > [Martin MOKREJ?] > >>... >> >>I gave up the theoretical approach. Practically, I might need up >>to store maybe those 1E15 keys. > > > We should work on our multiplication skills here . You don't > have enough disk space to store 1E15 keys. If your keys were just one > byte each, you would need to have 4 thousand disks of 250GB each to > store 1E15 keys. How much disk space do you actually have? I'm > betting you have no more than one 250GB disk. > > ... > > [Istvan Albert] > >>>On my system storing 1 million words of length 15 >>>as keys of a python dictionary is around 75MB. > > >>Fine, that's what I wanted to hear. How do you improve the algorithm? >>Do you delay indexing to the very latest moment or do you let your >>computer index 999 999 times just for fun? > > > It remains wholly unclear to me what "the algorithm" you want might > be. As I mentioned before, if you store keys in sorted text files, > you can do intersection and difference very efficiently just by using > the Unix `comm` utiltity. This comm(1) approach doesn't work for me. It somehow fails to detect common entries when the offset is too big. file 1: A F G I K M N R V AA AI FG FR GF GI GR IG IK IN IV KI MA NG RA RI VF AIK FGR FRA GFG GIN GRI IGI IGR IKI ING IVF KIG MAI NGF RAA RIG file 2: W W W W W W W W W W AA AI FG FR GF GI GR IG IK IN IV KI MA NG RA RI VF AAAAA AAAAA AAAAA AAAAA AAAAA AAAAA AAAAA AAAAA AAAAA AAAAA AAAAA AAAAA From michele.simionato at gmail.com Thu Jan 6 10:15:20 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 6 Jan 2005 07:15:20 -0800 Subject: parameterized metaclass (or metametaclass) In-Reply-To: References: Message-ID: <1105024520.193968.70120@f14g2000cwb.googlegroups.com> > I was wondering if there is some simpler way of building parameterized > metaclasses ? Why not just a function returning metaclasses? def metaFactory(*args): dic = return type("somemetaclass", (type,), dic) Alternatively, a metaclass classmethod returning a metaclass, so that you can use something like __metaclass__ = MyMetaclass.with(*args) # classmethod returning a metaclass Michele Simionato From jeff at ccvcorp.com Fri Jan 7 16:15:13 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 07 Jan 2005 13:15:13 -0800 Subject: sorting on keys in a list of dicts In-Reply-To: References: <10tr9ejf05pv660@corp.supernews.com> Message-ID: <10ttukogfl43p62@corp.supernews.com> Nick Coghlan wrote: > Jeff Shannon wrote: > >> I suppose that your version has the virtue that, if the sortkey value >> is equal, items retain the order that they were in the original list, >> whereas my version will sort them into an essentially arbitrary order. >> Is there anything else that I'm missing here? > > > Stability in sorting is a property not to be sneezed at [...] Agreed. I'd started typing before I realized that it'd provide a stable sort, which pretty much answered my own question, but decided to send it anyhow in case I'd missed anything else... :) Jeff Shannon Technician/Programmer Credit International From cookedm+news at physics.mcmaster.ca Tue Jan 11 16:11:07 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 11 Jan 2005 16:11:07 -0500 Subject: readline, rlcompleter References: <1105429869.770262.14360@c13g2000cwb.googlegroups.com> Message-ID: michele.simionato at gmail.com writes: > This a case where the documentation is lacking. The standard library > documentation > (http://www.python.org/dev/doc/devel/lib/module-rlcompleter.html) gives > this example > try: > import readline > except ImportError: > print "Module readline not available." > else: > import rlcompleter > readline.parse_and_bind("tab: complete") > > but I don't find a list of recognized key bindings. For instance, can I > would > like to bind shift-tab to rlcompleter, is that possible? Can I use > function > keys? I did various attempt, but I did not succed :-( > Is there any readline-guru here with some good pointers? > Michele Simionato Basically, you could use any key sequence that is sent to the terminal. So shift-tab is out (that's not sent as a key to any terminal program). Function keys would have to be specified as the key sequence sent by a function key ("\e[11~" for F1, for instance). Have a look at the readline info page, or the man page. The syntax of readline.parse_and_bind is the same as that of an inputrc file. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From newsgroups at jhrothjr.com Sun Jan 9 17:08:21 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 9 Jan 2005 16:08:21 -0600 Subject: Python3: on removing map, reduce, filter References: <34csn1F4a46hqU1@individual.net> Message-ID: <10u3areb0r8c93b@news.supernews.com> "Andrey Tatarinov" wrote in message news:34csn1F4a46hqU1 at individual.net... > Hi. > > How does GvR suggestions on removing map(), reduce(), filter() correlate > with the following that he wrote himself (afaik): > > http://www.python.org/doc/essays/list2str.html This is fairly old. Note that the fastest version uses the array module, and is quite comprehensible - if you know the array module and how it works. It doesn't use the map function. John Roth > > ? From craig at postnewspapers.com.au Thu Jan 27 01:27:19 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Thu, 27 Jan 2005 14:27:19 +0800 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <1106807239.8583.12.camel@bucket.localnet> On Wed, 2005-01-26 at 22:28 -0500, Davor wrote: > I browsed docs a bit today, and they also confirm what I have believed - > that OO is totally secondary in Python. In fact, > object/classes/metaclasses are nothing but *dictionaries with identity* > in python. Love this approach. I was really impressed with the design of the language, especially this bit. I first "got" it when reading Learning Python 2nd Ed (well *after* I'd been using Python for a while, but it's always good to read even intro books to fill out "obvious" things you might've missed). I love the way the same "It's just a dictionary search" principle applies to inheritance, scoped variable lookups, etc. In Python, even metaclasses just operate on the class dictionary. How pleasantly simple :-) - especially how the step from class factory to metaclass is so small and approachable. I also love the way I can chuck a bunch of objects into a functionally styled processing pipeline, say a series of functions that each just return the result of a listcomp/genexp. -- Craig Ringer From john at grulic.org.ar Thu Jan 13 18:39:00 2005 From: john at grulic.org.ar (John Lenton) Date: Thu, 13 Jan 2005 20:39:00 -0300 Subject: XPath and XQuery in Python? In-Reply-To: References: Message-ID: <20050113233900.GA3727@grulic.org.ar> On Wed, Jan 12, 2005 at 12:09:58AM +0000, Nelson Minar wrote: > Could someone help me get started using XPath or XQuery in Python? I'm > overwhelmed by all the various options and am lacking guidance on what > the simplest way to go is. What library do I need to enable three line > Python programs to extract data with XPath expressions? > > I have this problem a lot with Python and XML. Even with Uche's > excellent yearly roundups I have a hard time finding how to do fancy > things with XML in Python. I think it's a bit like web server > frameworks in Python - too many choices. my own favorite is libxml2. Something like the following: #!/usr/bin/env python import libxml2 import sys def grep(what, where): doc = libxml2.parseDoc(where) for found in doc.xpathEval(what): found.saveTo(sys.stdout, format=True) if __name__ == '__main__': try: what = sys.argv[1] except IndexError: sys.exit("Usage: %s pattern file ..." % sys.argv[0]) else: for where in sys.argv[2:]: grep(what, file(where).read()) although you might want to be smarter with the errors... -- John Lenton (john at grulic.org.ar) -- Random fortune: The whole world is a scab. The point is to pick it constructively. -- Peter Beard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From tom at dtsam.com Tue Jan 4 10:30:09 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Tue, 4 Jan 2005 09:30:09 -0600 Subject: Reaching the real world References: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> Message-ID: "Fuzzyman" wrote in message news:1104850540.610295.152240 at f14g2000cwb.googlegroups.com... > I have a friend who would like to move and program lights and other > electric/electro-mechanical devices by computer. I would like to help - > and needless to say Python would be an ideal language for the > 'programmers interface'. > > What I'd like is an electronic interface that connects to several > relays and a python extension module to switch on and off the relays. > I've had a quick google and can't see anything too similar to what I > want. pyro (python robotics) seems to require expensive (relatively) > robotic equipment. Loosely, what you are looking for is Data Acquisition (DAQ) , Digital I/O, and control that you can do from your pc. Those are the keywords you want to google. Look at www.ni.com and poke around. They will have some introductory material. Look at www.circuitcellar.com . It may look a bit overwhelming at first but look at the ads for pc equipment. These should also lead you to some tutorials. You are looking for simple digital output. You can use an existing serial or parallel port with a bit of external hardware from radio shack to control relays on the cheap. OR You can purchase a Digital I/O adaptor that will plug into your computer bus and give you outputs to control your relays. You will also get instructions and some software to interface (talk!) to the adaptor. Typically you will read and write to the I/O ports on your computer to flip the switches. OR perhaps the easiest and most effective These would be smart devices that talk to your Python (or whatever!) software via the serial port. You would throw simple string commands (eg "ChannelB ON") at the serial port and the microprocessor based controller will turn on the appropriate relay. Your challenge from Python will be to control the computers I/O ports or to communicate with one of the serial ports. I'm sure someone else will point to libraries that will help you with this. Much *much* more but you have to start somewhere :-) Thomas Bartkus From none at none.net Tue Jan 4 02:48:25 2005 From: none at none.net (Iwan van der Kleyn) Date: Tue, 04 Jan 2005 08:48:25 +0100 Subject: Python evolution: Unease Message-ID: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> Please ignore if you are allergic to ramblings :-) Despite a puritan streak I've always tried to refrain from language wars or syntax bickering; call it enforced pragmatism. That's the main reason why I've liked Python: it's elegant and simple and still dynamic and flexible. You could do worse for a clean and pragmatic language. I do know my Smaltalk from my Common Lisp and my Ruby from my C#, so I think I'm quite capable of escaping the "Blub paradox" http://c2.com/cgi/wiki?BlubParadox. I do miss some slick features in Python. But the nice thing about Python is that in those cases I can use its dynamism to implement it myself (and usually somebody else has done it for me, of course). In the end I'm not a language guru nor a framework wizard, but a mere mortal who designs and writes programs for end-users. For that task I need: a better standard ide, an integrated db interface with a proper set of db drivers (!!), a better debugger, a standard widget/windows toolkit, something akin to a standard for web programming, better documentation, a standard lib which is better organized, a formalized set of protocols and patterns for program construction. And an interpreter which is fast enough to avoid using C or Pyrex in most obvious cases. Many will say that Van Rossum's brainstorms/proposals as depicted in http://www.artima.com/weblogs/viewpost.jsp?thread=86641 will help in the above mentioned. And I'm certainly not against Optional ype checking. But I see little to no efforts from the core python team to address my needs as listed above. They seem mainly to focus on the core attributes and syntax of the language. Very little or no efforts are taken to improve the infrastructure around the language. And then I read the following sentence by Van Rossum: "In order to make type inferencing a little more useful, I'd like to restrict certain forms of extreme dynamic behavior in Python" In the end, it's mindset which counts. And I think that mindset is going to be determine the way foreward for Python: more features, increased complexity, less dynamism. Lots of syntax crud, without addressing the need to improve the infrastructure around the language. In short: I symphatize Patrick Logan's feeling: http://patricklogan.blogspot.com/2005/01/road-to-ruin.html Regards, Iwan van der Kleyn From aleaxit at yahoo.com Thu Jan 27 08:29:57 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 27 Jan 2005 14:29:57 +0100 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106814263.835719.181360@z14g2000cwz.googlegroups.com> <1106826024.655143.227050@c13g2000cwb.googlegroups.com> Message-ID: <1gr1xay.2ym8rg9jui8uN%aleaxit@yahoo.com> wrote: ... > Some complexity is not needed, and I am sure even in Python > something could be dropped. But it is difficult to find what can > be removed. Remember that Saint-Exupery quote? Something > like "a work of art is finished when there is nothing left to remove?" Saint-?xupery was an engineer (and a pioneer of flight) and so he was referring to a designer (and no doubt had in mind those planes...), not to an artist (not his fault if he's better remembered as a novelist;-). As for what can be removed from Python, one could start at -- while each of us will find there some "complexity" one loves and uses often (be it lambda, buffer, reload, ...), it's a good start. Alex From grahamd at dscpl.com.au Fri Jan 28 20:33:27 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 28 Jan 2005 17:33:27 -0800 Subject: Who should security issues be reported to? In-Reply-To: References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> Message-ID: <1106962407.019438.87470@z14g2000cwz.googlegroups.com> > OP: Did you discover this supposed security hole from black-box observation > of behavior or by being one of the 'lots of people being able to look at > source code', thereby giving evidence to the point? The technique used which is the source of the problem was actually first discovered in a separate package to the Python distribution, but it was known that the same technique was used in a module within the Python distribution. It is quite possible that other third party packages might use it as well, although a few of the main stream packages have been checked and they don't use exactly the same technique so are okay. I could have just ignored the fact that the Python distribution had the problem and worried about the other package only. > a) The OP has provided no info about his/her claim. Since the problem at least affects two packages and because of the potential for mischief, I am hardly about to identify the packages concerned, nor describe anything that is going to allow people to work out what the issue is. > b) The OP's original post is a classical troll: blast volunteer developers > for not having anticipated and planned for a novel situation; argue against > things not said, at least now here, not recently; imply that volunteers own > him something. Most people with the expertise to detect a security hole > would know better. And the reaction is what I have more and more been seeing in Open Source circles. That, is either treat posters like ignoreant newbies who know no better, or assume they are a trolls trying to discredit Open Source. Quite sad really, one tries to do the right thing and gets abused for it. It doesn't matter if a large project may be perceived as being mostly immune to security problems, one could still occur and if it isn't simple to raise such an issue I am sure than some people wouldn't even bother. > c) The noise generated because of b) has alerted any malware writers > monitering c.l.p for hints about exploitable security holes that there > might be one in one of the few modules where such could reasonably be. With approx 200+ modules in the Python distribution I can hardly see how this helps. If I had done what you had wanted in (a) and gave actual information about the problem I would have been narrowing down the problem to less than a dozen modules. You can't have it both ways. > OP: If my doubts are wrong and you really do have something to quietly > report to the 'authority', then do so, and quit making a noise about it. And so it is was and knowledgeable people are looking at the issue. It should not though have necessitated me making a noise in order to find someone to deal with it in a timely manner. When a proprietary company doesn't have an easy way of reporting problems or seems not to care too much, Open Source people are on top of them like wolves. Why can't Open Source people hold themselves to the same standard. Not sure why I have even bothered to respond to you as it is probably just the sort of attention you want. You even appear to have some history of taking issue with people, even though in one of your own posts you state: > Responding to trollish postings. (Jan 26) > > My personal strategy is to read only as much of trollish > threads as I find interesting or somehow instructive, almost never respond, > and then ignore the rest. I also mostly ignore discussions about such > threads. > > Terry J. Reedy Maybe you should simply have not responded. Lets see if you now ignore the followup discussion. :-) From ncoghlan at iinet.net.au Fri Jan 7 12:49:01 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 03:49:01 +1000 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> Message-ID: <41DECB8D.40507@iinet.net.au> Jacek Generowicz wrote: > Yes, I was wondering whether I should add lots of caveats to the above. I thought that might be the case. When teaching, I guess I can understand the need to avoid "well, technically, this isn't always true". It sounds like the students were having a tough enough time of it already :) > Usually one or two have trouble grasping that "int" would be perfectly > adequate in this situation. The ability to pass around functions at run-time was probably the hardest thing to get my head around when I started with Python, after a history of working in languages where "the compiler knows about types and functions, and the runtime knows about variables and instances". Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ml at dynkin.com Fri Jan 28 15:18:28 2005 From: ml at dynkin.com (George Yoshida) Date: Sat, 29 Jan 2005 05:18:28 +0900 Subject: Proccess termination In-Reply-To: <1106917700.730538.80320@f14g2000cwb.googlegroups.com> References: <1106917700.730538.80320@f14g2000cwb.googlegroups.com> Message-ID: alexrait1 wrote: > I use popen.popen2 or popen.popen3 to start a new process and read from > it's stdout/ write to it's stdin. > But I need a way to know when a process terminates. > Do you know about a library that provides these tools other then the > standard os module... or should I use it otherwise? popen2.Popen3, popen2.Popen4 and subprosess.Popen have poll/wait methods. These will do what you're looking for. -- George From danperl at rogers.com Wed Jan 5 12:48:19 2005 From: danperl at rogers.com (Dan Perl) Date: Wed, 5 Jan 2005 12:48:19 -0500 Subject: Cookbook 2nd ed Credits References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> Message-ID: "Alex Martelli" wrote in message news:1gpvtjk.3jf7dc1cch7yfN%aleaxit at yahoo.com... > Premshree Pillai wrote: >> Btw, is there a comprehensive list of ALL contributors put up anywhere? > > Not yet -- do you think I should put it up on my website? Updating the status of the recipes on the web site would be nice. Dan > > Alex From bulba at bulba.com Thu Jan 6 19:04:31 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 01:04:31 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> <1gpwrh7.b7z8qtablx7gN%aleaxit@yahoo.com> <41DD4E62.1020404@holdenweb.com> <10tr15fabtpnf97@corp.supernews.com> Message-ID: On Thu, 06 Jan 2005 10:38:53 -0800, Jeff Shannon wrote: >It's also noteworthy to consider that many times, waste happens not >because of corruption or self-interest, but simply because of errors >of judgement. Precisely. That is one of the main points I was trying to get across in discussion with Alex. I have no reason to make conspiracy theories that bribes were involved in that bad decision at that German company. No, it _seemed_ like it was simple mistake, because somebody responsible for this did not research the issue in enough depth. And note that it was definitely not in his personal interest, whoever that was, a person or group of persons, as he/they risked getting fired for that. >Humans being as we are, it's inevitable that over time, >some "obvious" important details will escape our attention, and the >resulting imperfect information will result in poor decisions. This >is a simple fact of human nature, and (ob-Python ;) ) it's one of the >reasons that Python is designed as it is -- it makes a serious effort >to reduce the number of details that might escape detection. I suspect it is one of the reasons why many people switch from learning Perl to learning Python (at least I did - I simply could not remember after a month or two what the hell I concocted in this place in Perl program, it felt as if this were somebody else's code). >(One should also consider that many business failures are a case of >simply having played the odds and lost. Many ventures depend on >outside events playing in a certain way; when by chance those events >happen, the decision-makers are called "bold and insightful", but if >things don't work out, they're called foolish or misguided. Again, I agree with you - all that I can add is that it this is what may be a rational element in the otherwise irrational decisionmaking process - managers may get hit if it goes wrong, but not rewarded if it goes right. Consider this: "Moreover the fact that a CEO can command does not mean that other employees will obey. Instructions can be given, but they need to be obeyed enthusiastically by others for them to mean anything. CEOs have tools to win the enthusiasm of their subordinates: the rhetoric of shared accomplishment of action and vision; the carrots of promotions, salary increases, and bonuses; the sticks of demotion and dismissal. But even with these tools, managing a large bureaucratic organization is a difficult task. And changing its direction away from that of mere business-as-usual requires great skill and luck." http://www.j-bradford-delong.net/Econ_Articles/Command_Corporations.html -- It's a man's life in a Python Programming Association. From ncoghlan at iinet.net.au Fri Jan 7 12:17:23 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 03:17:23 +1000 Subject: sorting on keys in a list of dicts In-Reply-To: References: <10tr9ejf05pv660@corp.supernews.com> Message-ID: <41DEC423.3030506@iinet.net.au> It's me wrote: > What does it mean by "stability in sorting"? > > Can somebody please give a sample for using the code posted? I am a little > lost here and I like to know more about the use of keys.... It's the jargon for what Jeff said - if you are sorting by some value calculated from each list entry, and different list entries may give the same value, then a stable sort guarantees that the order of entries giving the same value will be preserved from the original list. Consider: Py> from operator import itemgetter as item Py> seq = [(1, 1), (2, 1), (2, 3), (1, 5)] Py> seq.sort(key=item(1)) Py> seq #1 [(1, 1), (2, 1), (2, 3), (1, 5)] Py> seq.sort(reverse=True) Py> seq #2 [(2, 3), (2, 1), (1, 5), (1, 1)] Py> seq.sort(key=item(1)) Py> seq #3 [(2, 1), (1, 1), (2, 3), (1, 5)] This snippet sorts the tuples according to the second item, then sorts them in reverse order of the whole tuple, then resorts them according to the second item. Notice that the order of the first two items is different between point #1 and point #3. This is because sorting by the second item makes no distinction between these two tuples, and they retain whatever order they had before the sort began. This is what it means to have a stable sort, and it makes expressing complex sorting quite easy by chaining different sort operations together. Python 2.3 has a stable sort, and Python 2.4 brought the guarantee that it shall remain that way. I'm not sure about Python 2.2 and earlier. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From siona at chiark.greenend.org.uk Tue Jan 25 07:19:34 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 25 Jan 2005 12:19:34 +0000 (GMT) Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> <7xoefhtavd.fsf@ruckus.brouhaha.com> Message-ID: Fredrik Lundh wrote: >Sion Arrowsmith wrote: >> I'm probably not thinking deviously enough here, but how are you >> going to exploit an eval() which has very tightly controlled >> globals and locals (eg. eval(x, {"__builtins__": None}, {}) ? >try this: > > eval("'*'*1000000*2*2*2*2*2*2*2*2*2") No thanks. I guess my problem is a tendency view security issues from the point of view of access to data rather than access to processing. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From vishnube at acmet.com Thu Jan 6 01:33:27 2005 From: vishnube at acmet.com (Vishnu) Date: Thu, 6 Jan 2005 12:03:27 +0530 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> Message-ID: <003801c4f3b9$af17fa20$0800a8c0@vishnu> logfile = file(r'test.txt','w') logfile.write('datetime') logfile.close() # <- close the file logfile = file(r'test.txt','r') # <- Open the file in read mode test=logfile.readlines() ~Vishnu. -----Original Message----- From: python-list-bounces+vishnube=acmet.com at python.org [mailto:python-list-bounces+vishnube=acmet.com at python.org] On Behalf Of wordsender at gmail.com Sent: Thursday, January 06, 2005 11:53 AM To: python-list at python.org Subject: file.readlines() - gives me error (bad file descriptor) Hey guys, I can't figure this one out, why is this simple script giving me problems? logfile=file(r'test.txt','w') logfile.write('datetime') test=logfile.readlines() When I run it I get the error message: Traceback (most recent call last): File "C:\Documents and Settings\Gregory\My Documents\Get New Great Job\testfile.py", line 3, in ? test=logfile.readlines() IOError: [Errno 9] Bad file descriptor I'm running Windows XP, Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Any help would be greatly appricated. Thanks, Greg -- http://mail.python.org/mailman/listinfo/python-list From marklists at mceahern.com Mon Jan 17 15:25:00 2005 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 17 Jan 2005 14:25:00 -0600 Subject: FTPLIB - retry files? In-Reply-To: References: Message-ID: <41EC1F1C.8020900@mceahern.com> Peter A.Schott wrote: > Is there any way to retry sending files with some delay up to a set > number on > failure? Sometimes we encounter a locked file on our server or the > destination > server and we want to retry that file in X seconds. > > In general, what's wrong with this: import time retryCount = 10 retrySleep = 5 for x in range(retryCount): try: [ftp commands] except [ftp exceptions]: time.sleep(retrySleep) else: break // m From sp1d3rx at gmail.com Tue Jan 25 16:31:00 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 25 Jan 2005 13:31:00 -0800 Subject: Question Regarding SocketServer References: <1106684900.771730.218060@f14g2000cwb.googlegroups.com> Message-ID: <1106688660.694617.290330@c13g2000cwb.googlegroups.com> I tried to reply earlier... basically your "SocketServer.py" file is messed up. That line "AF_INET{,6}: IP (Internet Protocol) sockets (default)" should be commented out. It should be part of a block of lines that are all commented out. From tim.peters at gmail.com Fri Jan 14 09:12:49 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 14 Jan 2005 09:12:49 -0500 Subject: Pickled text file causing ValueError (dos/unix issue) In-Reply-To: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> Message-ID: <1f7befae05011406127d76759e@mail.gmail.com> [Aki Niimura] > I started to use pickle to store the latest user settings for the tool > I wrote. It writes out a pickled text file when it terminates and it > restores the settings when it starts. ... > I guess DOS text format is creating this problem. Yes. > My question is "Is there any elegant way to deal with this?". Yes: regardless of platform, always open files used for pickles in binary mode. That is, pass "rb" to open() when reading a pickle file, and "wb" to open() when writing a pickle file. Then your pickle files will work unchanged on all platforms. The same is true of files containing binary data of any kind (and despite that pickle protocol 0 was called "text mode" for years, it's still binary data). From Serge.Orlov at gmail.com Tue Jan 11 08:56:19 2005 From: Serge.Orlov at gmail.com (Serge.Orlov at gmail.com) Date: 11 Jan 2005 05:56:19 -0800 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> Message-ID: <1105451779.544442.204920@f14g2000cwb.googlegroups.com> Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle. wrote: > Hi ! > > >>> and plain Latin letters > > But not all letters (no : ? ? ? ? ? ? ? etc.) > > > > Therefore, the Python's support of Unicode is... limited. > So is the support of Unicode in virtually every computer language because they don't support ... digits except 0..9. Does anyone know a language that supports? Serge. From fredrik at pythonware.com Sun Jan 30 13:15:15 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 30 Jan 2005 19:15:15 +0100 Subject: Disassembling strings and turning them into function parameters References: <1107107283.694377.286360@c13g2000cwb.googlegroups.com> Message-ID: wrote: > I'm pretty new to Python, to programming overall...so how would I make > something where the user inputs multiple words in a string - like > "connect 123.123.123.123 21 user password" or similar, and then I can > split this string up to pass these arguments to a function like > ftp_connect(ip, port, user, pw) etc...? I have no idea how to "break" > the string up so I can get these out of it.. you can use the split() method to split on whitespace: >>> s = "connect 123.123.123.123 21 user password" >>> s.split() ['connect', '123.123.123.123', '21', 'user', 'password'] btw, the cmd module might be useful for your project: http://effbot.org/librarybook/cmd.htm http://docs.python.org/lib/module-cmd.html From http Sat Jan 22 11:38:25 2005 From: http (Paul Rubin) Date: 22 Jan 2005 08:38:25 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> Message-ID: <7xvf9p2zcu.fsf@ruckus.brouhaha.com> "A.M. Kuchling" writes: > It was discussed in this thread: > http://mail.python.org/pipermail/python-dev/2003-April/034959.html > > Guido and M.-A. Lemburg were leaning against including crypto; everyone else > was positive. But Guido's the BDFL, so I interpreted his vote as being the > critical one. That's interesting, so it's an export issue after all. But export from the US is handled by sending an email to the DOC, and Martin mentions that's already been done for some Python modules. I had been under the impression was that the concern was over causing possible problems for users in some destination countries, and possibly having to maintain separate distros for the sake of users like that. But maybe I was wrong about that. From craig at postnewspapers.com.au Mon Jan 3 06:09:00 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Mon, 03 Jan 2005 19:09:00 +0800 Subject: Developing Commercial Applications in Python In-Reply-To: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: <1104750540.26918.5.camel@rasputin.localnet> On Mon, 2005-01-03 at 19:00, eeykay at gmail.com wrote: > Hello All, > I am trying to convince my client to use Python in his new product. He > is worried about the license issues. Can somebody there to point me any > good commercial applications developed using python ?. The licence > clearly says Python can be used for commercial applications. Is there > any other implications like that of GPL to make the source open ? My understanding is that you're dead safe with Python its self, as AFAIK you can even bundle (possibly modified) the Python sourcecode into your application. You'd simply need to keep an eye on the licenses of any extensions you used, like ReportLab, PIL, mx, database interfaces, twisted, etc. Many are licensed under the same license as Python or an MIT-like license, but of course some Python extensions are not and you would need to consider that. -- Craig Ringer From breamoreboy at aol.com Sat Jan 15 12:47:46 2005 From: breamoreboy at aol.com (BrainDead) Date: 15 Jan 2005 09:47:46 -0800 Subject: 20050115, for statement In-Reply-To: <41E9397A.90301@holdenweb.com> References: <1105783084.748174.307680@f14g2000cwb.googlegroups.com> <41E9397A.90301@holdenweb.com> Message-ID: <1105811266.627500.64590@z14g2000cwz.googlegroups.com> Steve Holden wrote: > Michael Hoffman wrote: > > > Xah Lee wrote: > > > >> ? a = range(1,51) > >> ? for x in a: > >> ? if x % 2 == 0: > >> ? print x, 'even' > > > > > > Now he's mixing tabs and spaces. Hideous. > > > > Are you doing things wrong on purpose? > > Actually Xah is to be commended, since he's united the Perl and Python > camps. Both agree he's a nuisance who is ill-informed about Perl *and* > Python ;-) > > I can only presume it's egocentricity that keeps him cross-posting this > nonsense to c.l.py and c.l.pe.misc despite the many deficiencies that > have been remarked upon in both newsgroups. > > fraternal-greetings-to-the-perl-wordl-ly y'rs - steve > -- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/ > Holden Web LLC +1 703 861 4237 +1 800 494 3119 I humbly suggest that Xah Lee Foxtrot Oscar, failing that would he/she stand up as the voice is rather muffled. Hardly original I know, but this crap is getting up my nose. I would much rather read the Timbot discussing things which mention the best operating system in the world, i.e. VMS, which for the uninitiated stands for Very Much Safer. Mark Lawrence. From venkatbo at yahoo.com Thu Jan 13 17:59:01 2005 From: venkatbo at yahoo.com (Venkat B) Date: Thu, 13 Jan 2005 14:59:01 -0800 Subject: newbie ?s Message-ID: <1105656971.768148@sj-nntpcache-5> Hi folks, I'm looking build a CGI-capable SSL-enabled web-server around Python 2.4 on Linux. It is to handle ~25 hits possibly arriving "at once". Content is non-static and built by the execution of py cgi-scripts talking to a few backend processes. 1) I was wondering if anyone has opinions on the ability of CGIHTTPServer (a forking variant) to be able to handle this. 2) If so, would something like pyOpenSSL be useful to make such a webserver SSL-enabled. I checked out John Goerzen's book: Foundations of Python Network Programming (ISBN 1590593715) and searched around. While I found how one can write py scripts that could communicate with SSL-enabled webservers, tips on building SSL-enabled webservers isn't obvious. I was hoping to build a cleaner solution around the CGIHTTPServer variant instead of say something like mini-httpd/OpenSSL/Python. I'd appreciate any pointers. TIA, /venkat From steven.bethard at gmail.com Fri Jan 21 19:37:29 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 17:37:29 -0700 Subject: Unbinding multiple variables In-Reply-To: <1gqrkce.1jtex3qfem7tkN%aleaxit@yahoo.com> References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> <35bnkeF4jpeetU1@individual.net> <1106334800.868412.27650@f14g2000cwb.googlegroups.com> <1gqrkce.1jtex3qfem7tkN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Nevertheless, any modifications to locals() are utterly > futile (within a function). Evil hack that makes modifications to locals() not quite as futile: py> import sys py> import ctypes py> def f(): ... x = 1 ... locals()['x'] = 2 ... ctypes.pythonapi.PyFrame_LocalsToFast( ... ctypes.py_object(sys._getframe()), 0) ... return x ... py> f() 2 Warning! NEVER do this! ;) (Also note that you can't del or add variables in this manner -- only modify them.) Steve From zyqnews at 163.net Sat Jan 29 23:03:28 2005 From: zyqnews at 163.net (zyqnews at 163.net) Date: 29 Jan 2005 20:03:28 -0800 Subject: cx_freeze error In-Reply-To: References: <1107048210.548048.152870@z14g2000cwz.googlegroups.com> <1107054796.999110.18380@c13g2000cwb.googlegroups.com> Message-ID: <1107057808.297752.168780@z14g2000cwz.googlegroups.com> Thanks for your answer. I tried it and the result is: [cxfreeze]$ python Python 2.2.3 (#1, Oct 15 2003, 23:33:35) [GCC 3.3.1 20030930 (Red Hat Linux 3.3.1-6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> re.compile >>> re.__file__ '/usr/lib/python2.2/re.pyc' >>> Is there any hint? From http Sun Jan 2 20:00:58 2005 From: http (Paul Rubin) Date: 02 Jan 2005 17:00:58 -0800 Subject: Continuations Based Web Framework - Seaside. References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <7aTBd.11928$H%6.521997@twister1.libero.it> <7xhdlz8jv6.fsf@ruckus.brouhaha.com> <1gpshts.1o7ja8jqfh5moN%dial#####$#$#NOSPAM####$$##$tone@gmail.com> Message-ID: <7xd5wn1g39.fsf@ruckus.brouhaha.com> dial#####$#$#NOSPAM####$$##$tone at gmail.com (Valentino Volonghi aka Dialtone) writes: > Since I've already said Nevow with wolf works the same as borges. > The only thing that wouldn't work without continuations is the back > button. With greenlet module (from Armin Rigo) also the back button will > work. Thanks, I'm not familiar with wolf, borges, or greenlet. I've also been wondering what Rails is. Maybe some configuration of PyPy can supply first-class continuations like the old Stackless did. That would be really cool for all sorts of reasons. Then again, maybe it's reasonable to just fake it all, using ordinary threads and queues. I might try coding something that way. From abpillai at gmail.com Thu Jan 6 04:49:27 2005 From: abpillai at gmail.com (Anand) Date: 6 Jan 2005 01:49:27 -0800 Subject: Cookbook 2nd ed Credits In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> Message-ID: <1105004967.147430.128140@f14g2000cwb.googlegroups.com> Yes, such a list is available. I have uploaded a tentative list of contributors at http://harvestman.freezope.org . The original list is courtesy Alex. For the impatient, here are the direct links... List of first authors: http://harvestman.freezope.org/cookbook/credau.html List of all authors: http://harvestman.freezope.org/cookbook/creds.html Hope this helps! Regards -Anand From rschroev_nospam_ml at fastmail.fm Thu Jan 6 03:39:11 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 06 Jan 2005 08:39:11 GMT Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: Bulba! wrote: > If GPL folks had their way, it would not be possible not to "share" > _anything_ you create. That's generally the goal of the Free Software Foundation: they think all users should have the freedom to modify and/or distribute your code. Most people who use the GPL don't feel that way; they think that each author should have the freedom to choice if and how he chooses to share code. They just see the GPL as an appropriate way to share their code. > It is widely acknowledged that GPL license has the "viral" aspect of > extending itself on your software - can you point to closed-source > licenses that would have this aspect? Can you point to closed-source licenses that allow using the code *at all*? With GPL, you have the choice: either you agree with its terms on distributing the code and then you can use the code, or you don't agree with it and you don't use (which is still no worse than closed source). Some people call that viral, but I think it's a distortion of the truth. > None of the licenses I've read except GPL has > this aspect. LGPL is still a different story, though. Of course, different licenses have different terms. That's why there are different licenses. -- "Codito ergo sum" Roel Schroeven From ncoghlan at iinet.net.au Fri Jan 21 10:21:14 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 22 Jan 2005 01:21:14 +1000 Subject: Dynamic properties In-Reply-To: References: Message-ID: <41F11DEA.4050702@iinet.net.au> michael wrote: > My first try is : > > fget = lambda self: mygetattr(self, attrname) > fset = lambda self, value: mysetattr (self, attrname, value) > fdel = lambda self: mydelattr(self, attrname) > > # fget, fset, fdel are used to reconstruct the byte field > > setattr (self, key, property (fget, fset, fdel)) setattr creates entries in the instance dictionary of the object that is passed in. Properties need to be stored in the object type's dictionary in order to work their magic. I also believe it is required that the class be a new-style class. So try something like (Python 2.4): Py> def mygetattr(self, attr): ... print "Getting %s from %s" % (str(attr), str(self)) ... Py> def mysetattr(self, attr, value): ... print "Setting %s to %s on %s" % (str(attr), str(value), str(self)) ... Py> def mydelattr(self, attr): ... print "Deleting %s from %s" % (str(attr), str(self)) ... Py> class C(object): ... @classmethod ... def make_properties(cls, attrs): ... for attr in attrs: ... # Use default arguments to bind attr *now*, not at call time ... def _get(self, attr=attr): ... return mygetattr(self, attr) ... def _set(self, value, attr=attr): ... mysetattr(self, attr, value) ... def _del(self, attr=attr): ... mydelattr(self, attr) ... setattr(cls, attr, property(_get, _set, _del)) ... Py> properties = ["x", "y"] Py> C.make_properties(properties) Py> C.x Py> c = C() Py> c.x Getting x from <__main__.C object at 0x00A9A990> Py> c.x = 1 Setting x to 1 on <__main__.C object at 0x00A9A990> Py> del c.x Deleting x from <__main__.C object at 0x00A9A990> Py> c.y Getting y from <__main__.C object at 0x00A9A990> Py> c.y = 1 Setting y to 1 on <__main__.C object at 0x00A9A990> Py> del c.y Deleting y from <__main__.C object at 0x00A9A990> The decorator syntax is the only 2.4'ism I'm aware of in that code, so porting to 2.3 or even 2.2 shouldn't be an issue. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From grig.gheorghiu at gmail.com Mon Jan 10 15:11:21 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 10 Jan 2005 12:11:21 -0800 Subject: Importing Problem on Windows References: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> <1105385451.560381.57650@c13g2000cwb.googlegroups.com> Message-ID: <1105387881.581610.17840@f14g2000cwb.googlegroups.com> I normall set PYTHONPATH to the parent directory of my module directory tree. If I have my module files in C:\home\mymodules and below, then I set PYTHONPATH to C:\home. This way, I can do "import mymodules" in my code. From http Wed Jan 19 15:25:07 2005 From: http (Paul Rubin) Date: 19 Jan 2005 12:25:07 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41ee6551$1@nntp0.pdx.net> Message-ID: <7xis5tyxng.fsf@ruckus.brouhaha.com> Scott David Daniels writes: > I understand this to be true. Since I am trying to address encryption > in the zipfile module, and I know you actually follow a bit of the > encryption stuff, can you answer a question or two for me? Sure, I can try, so go ahead. There's more crypto expertise in sci.crypt though. Zipfile encryption is totally incompatible with the rotor module, by the way, and traditionally it didn't use AES. There are a couple of replacements for the traditional method that do use AES but that I think are somewhat incompatible with each other. > > The Python maintainers didn't want to deal with imagined legal hassles > > that might develop from including good crypto functions in the > > distribution. Then it became obvious that the same imagined hassles > > could also befall the rotor module, so that was removed. > > Are you saying these hassles are, in fact, imaginary rather than real? Well, I didn't want to say that the hassles were real, but I wasn't trying to insinuate quite as much as it may have sounded. Like, I don't drive my car at 100 mph on Main Street because I can imagine what would happen and it's not pretty. The imagined carnage is a good enough reason not to drive that way. However, I do feel that the Python distributors are being over-cautious, see below. > Is this because you feel python is over-cautious about the USA, or is > this an opinion on "essentially all countries?" This is not a quibble > or a kvetch; I would like your understanding about the world legal > state of dealing with encryption (which, I assure you, I won't take as > definitive). I would hate to think someone in, for example, the UAE, > was busted for downloading or republishing python "out-of-the-box." I think the Python maintainers were more concerned about that UAE situation. However, the most widely deployed encryption software is the SSL stack in just about every web browser (MSIE, Firefox, etc.) and I'm sure lots of people are using those browsers in the UAE. The Mozilla foundation isn't hestitating to ship the encryption as far as I can tell. See http://www.bxa.doc.gov/Encryption for the USA rules. Basically for a free encryption program on the web, you're supposed to notify the Dept. of Commerce by sending them an email when you publish it, telling them where they can get it (address is on that site). As far as anyone can tell, the DOC never does anything with those emails. The rules are more complicated for nonpublished commercial programs, crypto hardware, etc. > Don't get me wrong, I'd love the answer to be "sure its fine," but my > current plans are to provide a way to connect a crypto package to > zipfile without providing any such package myself. I'd say provide a package if you can, unless you have realistic concern about getting in trouble. From erikbethke at gmail.com Sun Jan 2 04:17:41 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 2 Jan 2005 01:17:41 -0800 Subject: Python! Is! Truly! Amazing! Message-ID: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Hello Everyone, I have to say: Python! Is! Truly! Amazing! So I started with python about a month ago and put in 24 hours across three weekends. My first project was to recreate a simple maze-let thingie that I remember as my first program way back on the Vic-20. That was a quick snap and a pleasure. Since then I have settled down into working on a Mahjong game. I have uploaded a current version at my personal website: www.erikbethke.com/Python/mahjong.zip also note screenshots: www.erikbethke.com/Python/screenshot01.jpg www.erikbethke.com/Python/screenshot02.pg www.erikbethke.com/Python/screenshot03.pg www.erikbethke.com/Python/screenshot04.pg www.erikbethke.com/Python/screenshot05.pg So I have been using Python 2.3.4 as that is what was compatible with the excellent PyGame last month. After reading the posts here I am using wing IDE, and over all I like it... some minor issues and I am sure if I RTFM I would have these handled. I will be buying a bunch of licenses for us. I also used this project to learn a little about XML, so I used XML to fully describe the UI, the tilesets and the tile layouts and have it able to go back and forth between 3 different tilesets, and backgounds. The XML is crappy as you can see I am experimenting with putting some data in attributes and elsewhere in elements. So now I have it laying out the tiles, tile picking correctly, and I was even able to write many new little feature-ettes in wickedly fast single edit-run passes such as this to highlight the currently available matches: def findMatchingTiles(self): matchList = [] visibleTiles = [] for i, c in enumerate ( self.tiles ): if c.state != 'clear': visibleTiles.append( c ) for i, c in enumerate ( visibleTiles ): if self.testForClear( c ): for j, d in enumerate ( visibleTiles ): if d != c and d.tileNum == c.tileNum and self.testForClear( d ): matchList.append( [c, d] ) return matchList def showHint(self): matchList = self.findMatchingTiles() for i, c in enumerate( matchList ): c[0].state='clicked' c[1].state='clicked' self.draw() I have NEVER experienced this kind of programming joy. I am a 33 year-old professional game developer (www.gopetslive.com) and have been in the industry for 11 years, and have been programming since 4th grade like all the rest of you guys. And I am not saying all this to brag, no seriously I am delirious in joy right now. I have a bad cold and went to sleep at 1am last night and woke at 5am just to get back to playing with Python! I have been looking into Python to see if it is a good answer for getting a lot of new fresh mini-game and UI work done for our project GoPets, and clearly it is. I haven't yet explored the server-side but I will. The Mahjong game in the future will take its tile art dynamically from the portraits of the users that are your friends and the people your GoPet has visited recently. Anyways, I am now a super gushing fan-boy. I have worked my way up from a scripter working in crappy proprietary languages to a c++ programmer, to now biz guy. But when I walked away from programming I gave it a grim farewell, c++ work is good, but so much mind goes into it to make progree compared to other creative uses of the mind. But Python rocks, it makes programming very fun again and now I finding myself coming home earlier so I can get to work on Python and I have an entire heap of new projects I wanted to get done. Anyways, the Mahjong game code is quite crappy. No effort has been made to optimize it, nor have I handled any sorts of errors whatsoever. I know it sucks. But I posted the code there anyways in case any one else is just coming along and wants some more example code. I also have no real UI going on. Hit R to randomize the tiles, M to try to setup a solvable game (but my algorithm for this is not very effective yet), and H for hints on tiles that can be matched. Other than the tile art anyone can do what the feel with it. Thank you all for posting here, you have already solved dozens and dozens of questions for me with a little help of google groups. Truly thank you. -Erik From jerf at jerf.org Tue Jan 18 16:28:53 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 18 Jan 2005 16:28:53 -0500 Subject: macros (was: RE: generator expressions: performance anomaly?) References: Message-ID: On Tue, 18 Jan 2005 12:59:07 -0800, Robert Brewer wrote: > Especially since you can already do it explicitly with Raymond > Hettinger's cookbook recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 You know, Guido might as well give in now on the Macro issue. If he doesn't come up with something himself, apparently we'll just hack bytecode. I'm not sure that's a gain. (To be fair, I can see some arguments that it is, so that "I'm not sure" isn't a passive-aggressive/sarcastic snipe like most people use it in this context; I mean it literally.) (I expect if we ever do see them, this will be the basic argument used. I guess you could call it Historic Inevitably. :-) ) I'm not just basing it on this one thing, I'm basing this on all the bytecode hacks I've seen. From petite.abeille at gmail.com Wed Jan 26 15:44:43 2005 From: petite.abeille at gmail.com (PA) Date: Wed, 26 Jan 2005 21:44:43 +0100 Subject: python without OO In-Reply-To: <200501262135.30872.francis.girard@free.fr> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <200501262039.23260.francis.girard@free.fr> <1993411a01509c62cae1715b62fe16f5@gmail.com> <200501262135.30872.francis.girard@free.fr> Message-ID: On Jan 26, 2005, at 21:35, Francis Girard wrote: >> Project fails for many reasons but seldomly because one language is >> "better" or "worst" than another one. > > I think you're right. But you have to choose the right tools that fit > your > needs. But I think that's what you meant anyway. Yes. But even with the "best" tool and the "best" intents, projects still fail. In fact, most IT projects are considered failures: http://www.economist.com/business/PrinterFriendly.cfm?Story_ID=3423238 Cheers -- PA http://alt.textdrive.com/ From a.newmane.remove at eastcoastcz.com Mon Jan 10 12:51:28 2005 From: a.newmane.remove at eastcoastcz.com (Alfred Z. Newmane) Date: Mon, 10 Jan 2005 09:51:28 -0800 Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: <34ftl8F48t3b9U1@individual.net> J|rgen Exner wrote: > xah at xahlee.org wrote: >> #python supports complex numbers. > [...] > > So? > >> # Perl doesn't support complex numbers. But there are packages that >> supports it. > > The Math::Complex module is part of the standard installation > already, no need for any "packages" (whatever that might be). 'package' is a keyword, you should know this :-) Thats an important part of most modules. Actually it seems a lot of people use 'module' and 'package' interchangably, both refering to libraries, if you will, the one can include in a script, or another package. From aleaxit at yahoo.com Fri Jan 7 05:45:08 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 11:45:08 +0100 Subject: Excluded and other middles in licensing References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> <75r0b2-ohg.ln1@lairds.us> <1gq0jpn.1es49j7jrk3k5N%aleaxit@yahoo.com> <7x3bxd5ywz.fsf@ruckus.brouhaha.com> Message-ID: <1gq0o3c.1lnjwhxjgcefmN%aleaxit@yahoo.com> Paul Rubin wrote: > Note also from the Heine-Borel theorem that every closed source > program can be covered by some finite collection of open source > programs. Every _compact_ one, surely? Quoting by heart from old memories, but, isn't Heine-Borel about (being able reduce any open covering of X to a finite subcovering) <-> (X is compact) ...? Alex From wittempj at hotmail.com Mon Jan 17 13:58:53 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 17 Jan 2005 10:58:53 -0800 Subject: Assigning to self In-Reply-To: References: <200501171845.46766.frans.englich@telia.com> Message-ID: <1105988333.379592.327600@z14g2000cwz.googlegroups.com> An implementation of what you want can be found here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52558 From dave.benjamin at gmail.com Sat Jan 22 02:24:07 2005 From: dave.benjamin at gmail.com (Dave Benjamin) Date: Sat, 22 Jan 2005 00:24:07 -0700 Subject: Zen of Python In-Reply-To: <7xfz0uqe1d.fsf@ruckus.brouhaha.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Tim Peters writes: > >>But at that time, Python didn't have lexical scoping, and it wasn't >>clear that it ever would. So what's the bigger wart? Making >>listcomps exactly equivalent to an easily-explained Python for-loop >>nest, or introducing a notion of lexical scope unique to listcomps, >>hard to explain in terms of the way the rest of the language worked? > > Oops, I'd gotten confused and thought lexical scope came first and > listcomps afterwards. If lexical scope came afterwards, then > implementing listcomps as a for-loop at that time makes more sense. > > Of course in that case, since the absence of lexical scope was a wart > in its own right, fixing it had to have been on the radar. So turning > the persistent listcomp loop var into a documented feature, instead of > describing it in the docs as a wart that shouldn't be relied on, > wasn't such a hot idea. Adding lexical scope and listcomps at the > same time might have also been a good way to solve the issue. Can we get a show of hands for all of those who have written or are currently maintaining code that uses the leaky listcomp "feature"? I guess I've been peripherally aware of it, but I almost always use names like "x" for my loop variables, and never refer to them afterwards. If Python were to change in this regard, I don't think it would break any Python code that I've ever written or maintained... Dave From http Fri Jan 28 17:59:11 2005 From: http (Paul Rubin) Date: 28 Jan 2005 14:59:11 -0800 Subject: Elliptic Code References: Message-ID: <7x3bwl9n40.fsf@ruckus.brouhaha.com> Nick Craig-Wood writes: > > I understand the algorithm quite well but how to code the multiplication > > stage most efficiently in python eludes me. > > You might want to look at > > http://gmpy.sourceforge.net/ > > It has very fast multiplication up to any size you like! I think he's talking about point multiplication on the elliptic curve group, not integer multiplication. From jack at performancedrivers.com Fri Jan 7 17:42:32 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 7 Jan 2005 17:42:32 -0500 Subject: "A Fundamental Turn Toward Concurrency in Software" In-Reply-To: References: Message-ID: <20050107224232.GM1404@performancedrivers.com> On Fri, Jan 07, 2005 at 01:35:46PM -0800, aurora wrote: > Hello! > > Just gone though an article via Slashdot titled "The Free Lunch Is Over: A > Fundamental Turn Toward Concurrency in Software" > [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that the > continous CPU performance gain we've seen is finally over. And that future > gain would primary be in the area of software concurrency taking advantage > hyperthreading and multicore architectures. It got most things right, AMD & Intel are moving towards multiple cores on a chip so programmers will adapt. I don't see this as a big deal, the current trend is rack farms of cheap boxes for heavy computing needs. Multi-core CPUs will help those kinds of applications more than single threaded ones. Existing threaded apps don't have to worry at all. His picking on Intel to graph CPU speeds was a mistake (I'll be generous and not say deliberate). Intel screwed up and pursued a megahertz-at-all-costs strategy for marketing reasons. AMD didn't worry about MHz, just about CPUs that did more work and so AMD is eating Intel's lunch. Intel has abandoned their "faster" line of processors and is using their CPUs that are slower in MHz but get more work done. So the author's "MHz plateau" graph isn't all Moore's law breaking down, it is the result of Intel's marketing dept breaking down. -Jack ps, I started a python corner to my blog, http://jackdied.com/python Only one substantial post yet, and the RSS feed isn't up, but there ya go. From phil_nospam_schmidt at yahoo.com Mon Jan 31 12:45:14 2005 From: phil_nospam_schmidt at yahoo.com (phil_nospam_schmidt at yahoo.com) Date: 31 Jan 2005 09:45:14 -0800 Subject: how to access class methods via their name-as-string Message-ID: <1107193514.516478.155440@f14g2000cwb.googlegroups.com> I'd like to be able to look up a method name by passing a string with the method name. I thought I could use self.__dict__ to get at the method names, but as my example shows, this is obviously not working. I've also tried self.__class__.__dict__ without success. Can anyone point me in the right direction to make this work? Thanks, Phil >>> class a: def m1(self): print 'm1' def __getitem__(self, k): return self.__dict__[k] >>> class b(a): def m2(self): print 'm2' >>> z=b() >>> dir(z) ['__doc__', '__getitem__', '__module__', 'm1', 'm2'] >>> z['m1'] Traceback (most recent call last): File "", line 1, in ? z['m1'] File "", line 5, in __getitem__ return self.__dict__[k] KeyError: 'm1' >>> From peter at engcorp.com Thu Jan 6 10:58:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Jan 2005 10:58:00 -0500 Subject: File Handling Problems Python I/O In-Reply-To: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> Message-ID: Josh wrote: > I am having a problem with Python. I am new to Python as a programming > language, but I do have experience in other languages. I am > experiencing strange problems with File handling and wonder if anyone > else has seen this or knows what I am doing wrong. I am simply trying > to open a file for read and iterate through until the end of file. I am > able to do so without a problem, but here's the catch: The open > statement is only working on certain files. I open a simple text file > say file1.txt without any issues, but I change the open statement to > another text file and it error's out stating the file doesn't exist. The usual rookie mistake here is to fail to recognize that backslashes in strings are interpreted as special escape sequences if they precede certain characters such as "t" or "b". You probably have a path that looks like this: "c:\temp\myfile.txt", right? The \t is actually being converted into a TAB character. You can use *forward* slashes in most cases in Windows, except on the command line. The simplest fix is just to convert your backslashes to forward slashes: "c:/temp/myfile.txt" Another approach, somewhat less desirable, is to use "raw" strings instead, to prevent the escape sequences from being recognized: r"c:\temp\myfile.txt" Finally, and by far least desirable, use double-backslashes to escape each backslash and in effect nullify the usual escape handling: "c:\\temp\\myfile.txt" Much less readable that way, but sometimes the right thing to do... -Peter From sylvain.thenault at nospam.logilab.fr Wed Jan 26 04:03:47 2005 From: sylvain.thenault at nospam.logilab.fr (Sylvain Thenault) Date: Wed, 26 Jan 2005 10:03:47 +0100 Subject: Maximum Number of Class Attributes References: Message-ID: On Wed, 26 Jan 2005 02:03:12 +0000, Bob Parnes wrote: > In its default configuration, my version of pylint (0.5.0) sets the > maximum number of class attributes at 7. This seems low to me, but I can > see how an excessive number might make maintenance more difficult. Is this > indeed the best value for a maximum under ordinary conditions? If not, can > anyone suggest a more reasonable value? well, this value is very subjective, and may change from one context to another... For instance at some point I hope that pylint will detect "GUI" classes and allow more attributes (and methods?) to those. Anyway that's just an indicator, not a rule of thumb (and pylint itself has some class with more than 7 attributes...). And FYI, this value has been taken from a post to the testdrivendevelopment at yahoogroups (as most others default values in the "design analysis" checker). Hum, well... After checking it seems that the post said 20 attributes. I don't remember why did i get this number down to 7. If this discussion leads to an agreement for a better number, I can change the default value. -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From smitsky at mindspring.com Sat Jan 8 21:03:07 2005 From: smitsky at mindspring.com (Smitsky) Date: Sun, 09 Jan 2005 02:03:07 GMT Subject: Windows XP Installation References: Message-ID: Thanks Folks. Yes, I did visit the Python site. I just wasn't sure what to try first. :O) Steve From steven.bethard at gmail.com Fri Jan 21 22:09:38 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 20:09:38 -0700 Subject: finding name of instances created In-Reply-To: References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> Message-ID: Andr? Roberge wrote: > Behind the scene, I have something like: > robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') } > and have mapped move() to correspond to > robot_dict['robot'].move() > (which does lots of stuff behind the scene.) > > I have tested robot_dict[] with more than one robot (each with > its own unique name) and am now at the point where I would like > to have the ability to interpret something like: > > alex = CreateRobot() > anna = CreateRobot() > > alex.move() > anna.move() > > etc. Since I want the user to learn Python's syntax, I don't > want to require him/her to write > alex = CreateRobot(name = 'alex') > to then be able to do > alex.move() If you have access to the user module's text, something like this might be a nicer solution: py> class Robot(object): ... def __init__(self): ... self.name = None ... def move(self): ... print "robot %r moved" % self.name ... py> class RobotDict(dict): ... def __setitem__(self, name, value): ... if isinstance(value, Robot): ... value.name = name ... super(RobotDict, self).__setitem__(name, value) ... py> user_code = """\ ... alex = Robot() ... anna = Robot() ... alex.move() ... anna.move()""" py> robot_dict = RobotDict() py> robot_dict['Robot'] = Robot py> exec user_code in robot_dict robot 'alex' moved robot 'anna' moved Note that I provide a specialized dict in which to exec the user code -- this allows me to override __setitem__ to add the appropriate attribute to the Robot as necessary. Steve From b at b.b Sat Jan 8 23:27:32 2005 From: b at b.b (Roose) Date: Sun, 09 Jan 2005 04:27:32 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> Message-ID: OK I've heard of that. But the original poster didn't ask to make a Python machine and then a Python OS. My point was that you can't do a lot of hardware interface programming in pure Python -- there would be so much non-trivial code in C that it would be hard to call it a Python OS. So this basically proves my point -- that you need different hardware altogether in order to make an OS in a high level language like Lisp or Python. And if that Lisp OS on a PC simulator works... that still wouldn't disprove what I'm saying. What does the PC simulator run on? An OS? or it part of the OS? Either way you've got tons of non-trivial code in C/C++/assembly. "Paul Rubin" wrote in message news:7x8y734jlq.fsf at ruckus.brouhaha.com... > "Roose" writes: > > > Is an OS written in Lisp also ludicrous? Because it's been done. > > > > Can you point me to this? I'd like to see how "truly" Lisp it is. > > http://en.wikipedia.org/wiki/Lisp_machine > > > My first guess would be -- not very. And I'd like to install it on my PC. > > Although written with federal funds at a university, it was never > released to the public, but was instead offered for sale from some > companies. The conflicts over this led to the birth of the free > software movement. > > Also, it was never intended to run on PC's (which didn't exist at that > time). It needed special hardware that was built for the purpose of > running Lisp. Lately there are people trying to program PC's to > simulate the Lisp hardware and to get the Lisp Machine software > released (now that the commercial market for it has long since dried > up). However, both of those projects have a ways to go. From phr at localhost.localdomain Mon Jan 24 17:56:55 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Mon, 24 Jan 2005 22:56:55 GMT Subject: simultaneous multiple requests to very simple database References: Message-ID: I agree with you, there's a crying need for something like that and there's no single "one obvious way to do it" answer. Have you looked at bsddb? See also www.sleepycat.com. From gurpreet.sachdeva at gmail.com Thu Jan 6 02:00:03 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Thu, 6 Jan 2005 12:30:03 +0530 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: References: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> <003801c4f3b9$af17fa20$0800a8c0@vishnu> Message-ID: logfile=file(r'test.txt','a+') logfile.write('datetime') logfile.flush() test=logfile.readlines() print test I added logfile.flush(), the 'datetime' was written in the file correctly but I couldn't get any result... Crazy! Garry From johng2001 at rediffmail.com Sat Jan 22 21:13:04 2005 From: johng2001 at rediffmail.com (johng2001 at rediffmail.com) Date: 22 Jan 2005 18:13:04 -0800 Subject: embedding jython in CPython... In-Reply-To: References: Message-ID: <1106446384.384110.25150@z14g2000cwz.googlegroups.com> > As for using JPype ... well it depends on what you want to script. if > you Java code is the main app, I'd eschew CPython completely and use > Jython to script. If you main app is in Python, and the Java code is > "simply" libraries you wish to use, then I'f go with CPython + Jpype. It > is very easy to manipulate Java objects that way, even to receive callbacks. > > I guess it all comes down to what you mean by scripting, and exaclt what > the structure of your application (as far as what is java and non-java). > If you care to explain your situation a bit more, we'll be better able > to help you. > > Steve Menard > Maintainer of http://jpype.sourceforge.net While we are on topic, I am having some trouble understanding JPype classpath. How do I init the JVM with the folder in which the Python program is located included in the classpath? I tried t = JPackage('.').test That did not work. My environment variable includes current folder in the classpath I tried passing it as an argument to startJVM. Didn't help. I think my main use is going to be using CPython with a few Java custom classes and if anyone has a snippet on this it would really help me. Thanks From craig at postnewspapers.com.au Thu Jan 27 01:47:49 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Thu, 27 Jan 2005 14:47:49 +0800 Subject: exclude binary files from os.walk In-Reply-To: References: <41f8167b$0$8648$a1866201@visi.com> Message-ID: <1106808469.8583.14.camel@bucket.localnet> On Wed, 2005-01-26 at 17:32 -0500, rbt wrote: > Grant Edwards wrote: > > On 2005-01-26, rbt wrote: > > > > > >>Is there an easy way to exclude binary files (I'm working on > >>Windows XP) from the file list returned by os.walk()? > > > > > > Sure, assuming you can provide a rigorous definition of 'binary > > files'. :) > > non-ascii That's not really safe when dealing with utf-8 files though, and IIRC with UCS2 or UCS4 as well. The Unicode BOM its self might (I'm not sure) qualify as ASCII. -- Craig Ringer From bokr at oz.net Mon Jan 17 16:13:06 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 17 Jan 2005 21:13:06 GMT Subject: news feed problem -- anyone else? Message-ID: <41ec1b57.1114913110@news.oz.net> I can see postings on google, but my news service is having a problem since sometime during the weekend. Can get old stuff from other n.g., but no new. Wondering whether I'll see this via google. Regards, Bengt Richter From jstroud at mbi.ucla.edu Sun Jan 9 21:50:40 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 9 Jan 2005 18:50:40 -0800 Subject: a new Perl/Python a day In-Reply-To: References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: <200501091850.40179.jstroud@mbi.ucla.edu> On Sunday 09 January 2005 05:31 pm, Scott Bryce wrote: > Xah Lee wrote: > > frustrated constantly by its inanities and incompetences.) > > I don't see what this has to do with Perl. On Sunday 09 January 2005 04:28 pm, Matt Garrish wrote: > What language are you an expert at? It certainly isn't Perl. Very dry humor indeed! bob = [1,2,3,4] carol = [bob,bob] # not inane dereferencing print carol[1][3] $bob = [1,2,3,4] ; $carol = [ $bob, $bob ] ; # inane dereferencing print "$carol->[1][3]\n" ; -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics 611 Charles E. Young Dr. S. MBI 205, UCLA 951570 Los Angeles CA 90095-1570 http://www.jamesstroud.com/ From yaipa at yahoo.com Wed Jan 19 16:08:57 2005 From: yaipa at yahoo.com (yaipa) Date: 19 Jan 2005 13:08:57 -0800 Subject: finding/replacing a long binary pattern in a .bin file References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> Message-ID: <1106168937.821814.217110@f14g2000cwb.googlegroups.com> John, Thanks for reminding me of the mmap module. The following worked as expected. #-------------------------------------------------------- import mmap source_data = open("source_file.bin", 'rb').read() search_data = open("search_data.bin", 'rb').read() replace_data = open("replace_data.bin", 'rb').read() # copy source.bin to modified.bin open("modified.bin", 'wb').write(open("source_file.bin", 'rb').read()) fp = open("modified.bin", 'r+') mm = mmap.mmap(fp.fileno(), 0) start_addr = mm.find(search_data) end_addr = start_addr + len(replace_data) mm[start_addr:end_addr] = replace_data mm.close() #-------------------------------------------------------- Although, I choose impliment string method approach in the build tool because there are two occurances of *Pattern* in the .bin file to be updated and the string method did both in one shot. Cheers, --Alan John Lenton wrote: > On Wed, Jan 12, 2005 at 10:36:54PM -0800, yaipa wrote: > > What would be the common sense way of finding a binary pattern in a > > .bin file, say some 200 bytes, and replacing it with an updated pattern > > of the same length at the same offset? > > > > Also, the pattern can occur on any byte boundary in the file, so > > chunking through the code at 16 bytes a frame maybe a problem. The > > file itself isn't so large, maybe 32 kbytes is all and the need for > > speed is not so great, but the need for accuracy in the > > search/replacement is very important. > > ok, after having read the answers, I feel I must, once again, bring > mmap into the discussion. It's not that I'm any kind of mmap expert, > that I twirl mmaps for a living; in fact I barely have cause to use it > in my work, but give me a break! this is the kind of thing mmap > *shines* at! > > Let's say m is your mmap handle, a is the pattern you want to find, > b is the pattern you want to replace, and n is the size of both a and > b. > > You do this: > > p = m.find(a) > m[p:p+n] = b > > and that is *it*. Ok, so getting m to be a mmap handle takes more work > than open() (*) A *lot* more work, in fact, so maybe you're justified > in not using it; some people can't afford the extra > > s = os.stat(fn).st_size > m = mmap.mmap(f.fileno(), s) > > and now I'm all out of single-letter variables. > > *) why isn't mmap easier to use? I've never used it with something > other than the file size as its second argument, and with its access > argument in sync with open()'s second arg. > > -- > John Lenton (john at grulic.org.ar) -- Random fortune: > If the aborigine drafted an IQ test, all of Western civilization would > presumably flunk it. > -- Stanley Garn From FBatista at uniFON.com.ar Wed Jan 5 14:40:15 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 5 Jan 2005 16:40:15 -0300 Subject: Python evolution: Unease Message-ID: [John Roth] #- I would like to contribute some documentation to Python. #- I've got the time, I write quite a bit, etc. I've got fairly #- strong opinions about some things that need to be documented, #- (such as all the new style class descriptor stuff from 2.2) #- and I have relatively little difficulty matching the existing style. #- #- However, I don't #- know TEX, Latex, CVS or Sourceforge. (The latter two are #- on my "learn sometime soon so I can put PyFIT where it belongs" #- list.) The easiest way to contribute with documentation is the following: 1. You found something badly documented. 2. You write/correct the docs as you think they should be. 3. Open a bug in SF and attach your text (just plain text if you don't want to produce something more elaborate). Of course, for step 3 you need a SF account: that's only five minutes. . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From danb_83 at yahoo.com Thu Jan 13 21:33:19 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 13 Jan 2005 18:33:19 -0800 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> <1105500724.648914.213880@z14g2000cwz.googlegroups.com> Message-ID: <1105669999.844853.137340@z14g2000cwz.googlegroups.com> DogWalker wrote: > "Luis M. Gonzalez" said: > > >humblythegreat... at usa.com wrote: > >> python.org = 194.109.137.226 > >> > >> 194 + 109 + 137 + 226 = 666 > >> > >> What is this website with such a demonic name and IP address? What > >> evils are the programmers who use this language up to? > >You dared to unveil our secret. > >Now we'll have to kill you... > > > But is 194.109.137.226 the only one? What other sites are in league > with the python? There are 6 853 010 possible dotted quads that add up to 666. Surely python.org is not the only one. From bvande at po-box.mcgill.ca Fri Jan 7 23:07:32 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 07 Jan 2005 23:07:32 -0500 Subject: DOS problem (simple fix??) In-Reply-To: References: Message-ID: <41DF5C84.7010002@po-box.mcgill.ca> Gavin Bauer said unto the world upon 2005-01-07 15:47: > My DOS window (running in windows ME) closes the second it finishes > running my programs. As you can imagine, this makes it hard to see the > Thank you, and please make all answers simple enough to be understood > by a highschool student and his father :) . Hi Gavin, you received some solutions. I have another, and a warning about Paul's. The warning: Paul suggested looking at IDLE. You should; it's a big improvement over notepad or the console. But, do you plan to make GUI application with Tkinter? If so, they will have troubles under IDLE. IDLE itself is a Tkinter application, so if it runs another Tkinter app, the poor beast gets confused about which Tkniter commands go where. (If that doesn't make sense, then you probably aren't yet at a place where it will matter. So, don't worry about it now.) Another popular alternative is SciTe. If you are doing your code in notepad or an interactive window, you really do want to look into an alternative! The other solution: The exact procedure is Windows version specific, but you can change the behaviour of .py files when they are double clicked. Here's what I do on my Win version (ME), which, sadly for both of us, we share: 1) Open a file explorer window. 2) Pick Tool->Folder Options from the menu. 3) Select the File Types tab. 4) Select the .py file type in the alphabetical list of file types that pops up. 5) Click on the Advanced button. 6) Select the Open action. 7) It will start out with something like: "C:\Python24\python.exe" Put a -i immediately thereafter. Mine looks like this "C:\Python24\python.exe" -i "%1" %* The -i makes .py files when double-clicked within Windows. The rest has to do with sending command line parameters, but I'd muff it if I tried to say more ;-) HTH, Brian vdB From martin at v.loewis.de Thu Jan 27 18:22:49 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 28 Jan 2005 00:22:49 +0100 Subject: Missing _bssd in Python 2.4 In-Reply-To: <1106864043.734366.315660@c13g2000cwb.googlegroups.com> References: <1106864043.734366.315660@c13g2000cwb.googlegroups.com> Message-ID: <41F977C9.4020400@v.loewis.de> jalil at feghhi.com wrote: > I compiled and installed python 2.4 on Redhat Linux using default > options but don't seem to be getting _bsddb. I get an error message > that _bssd cannot be imported. > > Does anybody know why this might happen? Do I need to do any special > customization or install any other software? You need to install the bsddb header files and development libraries when building Python from source. Regards, Martin From pyguy2 at gmail.com Wed Jan 5 11:47:28 2005 From: pyguy2 at gmail.com (pyguy2 at gmail.com) Date: 5 Jan 2005 08:47:28 -0800 Subject: Cookbook 2nd ed Credits (was Re: The Industry choice) In-Reply-To: <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> Message-ID: <1104943648.570355.179840@c13g2000cwb.googlegroups.com> Wow I didn't realize that I made that significant of a contribution :-) > 3: 9 u'John Nielsen' Well, I guess I did and I didn't. I worked hard to put postings up before I started taking classes again at a university last fall (with little kids and working full time, classes are a frustrating timesink). I am glad I could make a difference and proud to see what the community could put together. And of course, thanks to Alex and all the editors for their hard work. The cookbook site is, of course, among my default startup pages, so I can peruse what new things pop up there :-) I am slowly building up ideas on more things to post. This spring break, hopefully I'll get my mind enough together to put it all down coherently. john From merkosh at hadiko.de Fri Jan 28 17:18:06 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Fri, 28 Jan 2005 23:18:06 +0100 Subject: example needed: sip + Qt In-Reply-To: <39688.82.68.80.137.1106920041.squirrel@82.68.80.137> References: <39688.82.68.80.137.1106920041.squirrel@82.68.80.137> Message-ID: <200501282318.13918.merkosh@hadiko.de> On Friday 28 January 2005 14:47 pm, Phil Thompson wrote: > > The QLabel example in the SIP reference manual yields syntax errors for > > me. > > What syntax errors? If there is a documentation bug then I'll fix it. I'll come to that a little later, that happened in the simple c++ word example. I am currently fiddling around with the QLabel example. I copied the example and tried it out. First problem was that the generated makefile does not attempt to compile the original hello.cpp sources. So I wrote a configure script and a Makefile.am for that. It was not clear to me what type of archive or object was needed, so I first tried creating a normal object file, then libtool archives and then normal archives. It turned out I needed a normal archive an the library search path has to be extended to include the current directory (-L.), i.e. where the libhello.a lies. My only way of doing so was edditing the Makefile generated by configure.py. Is there a way of telling that to configure.py? So now the hello.cpp example compiles. I fire up python: >>> import hello Traceback (most recent call last): File "", line 1, in ? ImportError: ./hello.so: undefined symbol: _ZTV5Hello $ c++filt _ZTV5Hello vtable for Hello The compilation did not give any warnings or error messages. Any ideas? Thanks Uwe -- It would seem that evil retreats when forcibly confronted. -- Yarnek of Excalbia, "The Savage Curtain", stardate 5906.5 -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 492 bytes Desc: not available URL: From david at graydragon.net Sat Jan 8 11:34:05 2005 From: david at graydragon.net (David Brown) Date: Sat, 8 Jan 2005 10:34:05 -0600 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: <10u02s3deapvkd8@corp.supernews.com> So how would I make an OS Shell? From harold.fellermann at upf.edu Mon Jan 3 08:39:58 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Mon, 3 Jan 2005 14:39:58 +0100 Subject: cosmetic Tkinter question In-Reply-To: References: Message-ID: On 26.12.2004, at 16:38, Sean McIlroy wrote: > I've got a bunch of Frames, all packed into the root window with > side=TOP, and in each Frame I've got a Checkbutton packed with > side=LEFT. I expected the Checkbuttons to be flush with the left edge > of the window, but they're not, and it looks a little gross. How do I > get them to align? if you pack the frames with option fill=X they should be well aligned -- This commands the frame to use all available space in the horizontal direction: your_frame.pack(side=TOP,fill=X) your_button.pack(side=LEFT) - harold - -- What is mind? -- Doesn't matter. What is matter? -- Never mind! -- From anno4000 at lublin.zrz.tu-berlin.de Tue Jan 11 14:00:29 2005 From: anno4000 at lublin.zrz.tu-berlin.de (Anno Siegel) Date: 11 Jan 2005 19:00:29 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: It's me wrote in comp.lang.perl.misc: [reply moved into context] > "Anno Siegel" wrote in message > news:cs145l$8d6 > > > > > > > Like this? > > > > use Math::Complex; > > > > my $z = sqrt( -1); > > print 1 + $z, "\n"; # prints "1+i" > > > > Operator overloading makes it possible to work with complex numbers as if > > they were a native data type. > Operator overloading (and function overloading) helps but not enough. You > have to be aware of the complex type *everywhere* you go and that's very > annoying and error prone. I've been the works with C++, and later with > Modelica. I am very happy that Python included *native* complex number > support. What kind of awareness do you mean? There are some operations (as comparison) that work for reals, but not for complex numbers. If you want your program to run with complex input, you have to avoid such operations, whether the data type is native or not. What other considerations are there? A typical numeric program should just run and give complex output when fed complex input. I made the experiment with the Perl module Statistics::Descriptive, which was certainly written without concern for complex input, and it works without a hitch. I'm not sure if the (complex) variance of several complex numbers is a reasonably interpretable quantity, but I'm certain the maths is done right. What else do you want? Anno From http Wed Jan 5 06:52:47 2005 From: http (Paul Rubin) Date: 05 Jan 2005 03:52:47 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <1104910363.381748.105670@z14g2000cwz.googlegroups.com> Message-ID: <7xzmzo6qk0.fsf@ruckus.brouhaha.com> michele.simionato at gmail.com writes: > Dunno about Fedora, I stopped using Red Hat just because they were > *not* using the standard Python distribution, and the version they > shipped was cripped in various ways. Eh? I used Red Hat for a long while and don't remember their crippling the Python distribution. I do remember their believing the Python advocates that Python was a stable language, and therefore building critical features around it, and being unwilling to upgrade between major Python releases during minor Red Hat release cycles. The result was that RH 7.x shipped with Python 1.5.x for quite a long time after Python 2.x had been released. However I don't remember anything being crippled about the 1.5.x installations. From aahz at pythoncraft.com Mon Jan 31 16:22:59 2005 From: aahz at pythoncraft.com (Aahz) Date: 31 Jan 2005 16:22:59 -0500 Subject: Want to meet any of these people? They are registered for PyCon References: Message-ID: In article , Steve Holden wrote: > >Note that the sort order isn't perfect - I just sorted on the second >"word" in each name. PyCon is a *great* place to meet people and discuss >ideas. Hope to see you there. Good thing I'm not coming this year, eh? ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger." --Roy Smith, c.l.py, 2004.05.23 From swaroopch at gmail.com Tue Jan 25 14:45:10 2005 From: swaroopch at gmail.com (Swaroop C H) Date: Wed, 26 Jan 2005 01:15:10 +0530 Subject: How to input one char at a time from stdin? In-Reply-To: References: Message-ID: <351e887105012511457b494894@mail.gmail.com> On Tue, 25 Jan 2005 12:38:13 -0700, Brent W. Hughes wrote: > I'd like to get a character from stdin, perform some action, get another > character, etc. If I just use stdin.read(1), it waits until I finish typing > a whole line before I can get the first character. How do I deal with this? This is exactly what you need: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 Title: "getch()-like unbuffered character reading from stdin on both Windows and Unix" This recipe was a lifesaver for me once :-) Regards, -- Swaroop C H Blog: http://www.swaroopch.info Book: http://www.byteofpython.info From snacktime at gmail.com Wed Jan 26 16:54:08 2005 From: snacktime at gmail.com (snacktime) Date: Wed, 26 Jan 2005 13:54:08 -0800 Subject: XOR on string In-Reply-To: References: Message-ID: <1f060c4c05012613541abf5417@mail.gmail.com> > lrc == Linear Redundancy Check? or Longitudinal? Note that > such terms are not precisely defined... generally just acronyms > people make up and stick in their user manuals for stuff. :-) > Longitudinal > import operator > lrc = reduce(operator.xor, [ord(c) for c in string]) That's better than what I had, which as it turned out was working I was just calculating the lrc on one extra digit that I should have been. Chris From aleaxit at yahoo.com Sun Jan 9 06:01:47 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 9 Jan 2005 12:01:47 +0100 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> Message-ID: <1gq4ebf.17qqy8dk9ccr6N%aleaxit@yahoo.com> AdSR wrote: > I don't know haskell, but it looks SQL-ish to me (only by loose Indeed, the fact that many MANY more people are familiar with SQL than with Haskell may be the strongest practical objection to this choice of syntax sugar; the WHERE clause in an SQL SELECT has such wildly different semantics from Haskell's "where" that it might engender huge amounts of confusion. I.e., reasoning by analogy with SQL only, one might reasonably expect that minor syntax variations on: print a, b where a = b could mean roughly the same as "if a==b: print a, b", rather than roughly the same as: a = b print a, b I wonder if 'with', which GvR is already on record as wanting to introduce in 3.0, might not be overloaded instead. Alex From aleaxit at yahoo.com Wed Jan 5 05:19:56 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 5 Jan 2005 11:19:56 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> Message-ID: <1gpwrh7.b7z8qtablx7gN%aleaxit@yahoo.com> Bulba! wrote: ... > First, even though I disagree with you in places, thanks for > this reply - it enhanced my knowledge of the topic in some You're welcome! > What you wrote regards especially strong the industries you pointed > at: fashion, jewellery, esp. I think in those industries those factors > may be decisive. When this street is renown in the city to have > "good jewellers" located there, the choice for a new jeweller in this > city is almost like this: get located there or die. > > However, I'd argue that industries with those kinds of dependencies > are actually pretty rare. And yet the phenomenon appears in quantitatively similar ways (to different scales) in many industries where either the supply side or demand side benefits of clustering apply. > >Now consider a new company Z set up to compete with X, Y and Z. Where Ooops, typo, sorry, call the new company T!-) > >will THEY set up shop? Quarter Q has the strong advantage of offering > >many experienced suppliers nearby -- and in many industries there are > >benefits in working closely with suppliers, too (even just to easily > >have them compete hard for your business...). > > I grant that this model is neat and intuitive - but I'd argue it is > not very adequate to real world. Read on. Apart from its being exogenous (the model does not try to explain why X Y and Z were already located in Q -- only why, given this state of affair, T has advantages to setting things up in Q, too, which may well offset the costs such as higher rents), I don't think so -- but, I _am_ reading;-). > >YOU going to set up shop? Rents in that piazza are high, BUT - that's > >where people who want to buy new hats will come strolling to look at the > >displays, compare prices, and generally shop. > > That will only be true if the hats from Piazza dell'Orologio are much > better than elsewhere. No, this is not necessary (it's not even strictly necessary that they're _believed_ to be better, say because they traditionally were). A sufficient inducement to the would-be customers to go shopping there rather than elsewhere is that in that Piazza they get more choices for the same effort, so shopping there is more effective. Say that the city has ten hat shops of the same quality. One is in Piazza dell'Unita`, all the way to the Northern border of the city. One is in Piazza Saragozza, all the way to the Southern border. The other eight are in Piazza dell'Orologio, smack in the middle of downtown. Each shop offers hats taken from the same random distribution: we can say that a normal curve measuring the utility function for the customer (some function of price, quality, looks, fit, ...), with identical average and variance, represents the best hat available today from a given shop from the POV of a given customer. Say that a customer has one day to shop for their new hat, and the locations are too far apart for a customer to visit more than one location within that day. If a customer chooses to visit the one southern shop, or the one northern shop, the customer expects to be presented with the choice of hat from said normal curve. If the customer goes downtown, they expect a choice which overall lies along a DIFFERENT curve -- the best-of-eight samples from the normal curve. Sorry I can't model that analytically, but both intuitively and from any little simulation (easy to code in Python) you can see the customer's expectations are much better if they choose the location where they can do more comparison shopping! If you change this handwaving into numbers you can model this demand-side push of hatsellers towards clustering vs the forces pushing in the other direction, such as the supply-side issue of higher rents which may be assumed, all other things being equal, to make each shop's curve slightly _worse_ in the downtown location (higher costs, all other things being equal, must mean higher prices). It's not just fashion. I can look at the historical location of fishmongers in Bologna, still to some extent observable today, and I see them generally spread all over BUT with two obvious centers of downtown aggregation: a minor one at the Mercato delle Erbe (center-south side of downtown) and a major one at via Pescherie Vecchie (which just happens to mean "street of the Old Fishmongers" -- that concentration goes back many, many centuries). When I'm just getting, say, some fresh anchovies to fry for a pasta sauce, I'm likeliest to shop at a fishmonger near my home (the University side of downtown, northerly) or get them as part of a generic grocery shopping trip at a supermarket. But sometimes I'm preparing for a meal where fish plays a big role, maybe with company, and then I want the best, and then I head for Pescherie Vecchie. It's always very crowded with shoppers there, particularly at the times when people are likeliest to be shopping for fresh fish. It's obvious to even the most casual observer that just the same mechanism is at play: there are demand-driven centripetal forces because shoppers sometimes like to comparison-shop and get a lot of choice. This demand-side process doesn't operate much for "commodities" -- goods with quality and prices so flat and standardized that comparison shopping does not matter much. Much fashion-industry ware is that way, spewed out at commodity levels by the same factories. Some concentration may nevertheless remain for purely historical reasons: I'm thinking for example of the concentration of bookstores in Charing Cross Road, and of electronics shops in the nearby Tottenham Court Road, in London. Being in London only rarely nowadays, if I'm shopping for books I'm likely to head for Charing Cross, because I know I'll get choice; if I was a resident, though, and shopped for books often enough, I guess I'd find out about other places that may be cheaper or otherwise better. In any case, this more detailed demand-side sketch already shows that transaction costs are the key consideration in explaning clustering. Considering that they're also key in the very EXISTENCE of firms, according to standard economic theory, it's hardly surprising that they should play a large role in shaping the firm's foundational decisions, including, of course, location. But the demand-side model focuses on the _customers_' transaction costs, their advantage in comparison shopping. Similarly, a supply-side model can focus on suppliers' issues. Focusing within the firm, we can get insight on the pluses and minuses to the firm of being in a single place vs spreading itself around, but clustering of separate firms is clearly a different issue. > If the quality and prices of products converged, the gain for the > customers to go there isn't high. And the prices for customers > have to be higher, as the high rents drive some suppliers out, > so the supply of hats is lower, ergo customer prices are higher. ...which is why you know a priori that some equilibrium point is likely: there are costs as well as advantages to clustering (rents can often be an important slice of the costs, but other inputs that are costly to transport could also become scarce, though maybe not to the same point as land and suitable buildings and other fixed infrastructure). But there's nothing intrinsic to predict that the amount of clustering at equilibrium will be low. Transaction costs are often connected to acquiring and checking information; "knowing" (or believing one knows) where the hatsellers are may be enough of an advantage to maintain a clustering, once it's historically formed, even when you can hardly find any more present evidence of materials-costs advantage to it... the information-cost part of the transaction costs may well suffice. > >That's close to where > >felt-makers are, since they sell to other hat-makers. Should your > >business soon flourish, so you'll need to hire a worker, that's where > >you can soon meet all the local workers, relaxing with a glass of wine > >at the local osteria after work, and start getting acquainted with > >everybody, etc, etc... > > That is true in the model. However, I don't find it very true > in practice in a lot of industries: > > - "physical proximity" in this city very often means navigating > through jammed roads, so the transportation costs in terms of > time and money may very well increase rather than decrease by > locating "in a cluster", even though physical distance may > be smaller. physical distance != temporal distance & a cost > of getting there. Congestion can be a part of transaction costs, sure, just as higher rents can. But if your suppliers or customers are clustered in Hollywood, or the City of London, etc, etc, you don't diminish your congestion-driven costs much by going elsewhere, as you still need to see your customers or suppliers often -- you just add the costs of getting to LA / London / etc to those of moving within it -- in this sense congestion costs behave very differently from rents. > - since everything is more expensive, so is labor; even > if you pay this worker a little bit less elsewhere, he might > find it more attractive to commute shortly to work and > have lower costs of living in a different area, so this very > well may work as a motivation to relocate Sure, you get more competition: just as it's easier for you to get your competitors' best people, it's easier for your competitors to get yours (to some extent this applies to other inputs, and customers too, but highly skilled labor is the key component in many industries). This raises general costs, roughly equally for all clustered competitors, but another factor may be more prevalent because it differentiates among competitors: if you think you're among the best company in your sector, a more desirable place for your competitors' best personnel to work, then you perceive clustering as desirable because of that; if you think you're an inferior company, so your best people are likely to want to flee, then you perceive clustering as undesirable. Thus, seeking clusters can send the message "we're the best"; avoiding clusters can send the message "we're not so hot". That's how situations of asymmetric information tend to work in economics -- and since Akerlof's seminal work "The Market for Lemons" is 35 years old, and he got the Nobel prize for it (and related work, of course) in 2001, I believe we can call this field reasonably classic by now. Note that I'm not saying there are no forces pushing against clustering: of course there are, varying by industry etc. But they're easy to overstate. Consider the highly skilled worker who has a choice: they can stay in some crowded cluster, say Silicon Valley, and keep facing congestion, high rents, etc, for high salaries and great opportunities to keep hopping to the highest bidder; or, they can accept an offer at a lower salary in some more isolated area, say a minor cluster such as Austin, Tx, and get less congestion, cheaper housing, etc, although also less opportunity to keep enhancing their careers. Which kind of worker will tend to pick which of the two? Somebody who thinks they may be past the peak of their career, and won't get many more lucrative offers in the future anywa, might be more tempted by (say) Austin, while somebody who's keenly competitive and on a sharp upwards path may keep braving the congestion for the (to them) attractive lures and challenges of Silicon Valley. Of course there are a zillion other factors, but in as much as we're talking about factors strictly related to clustering, this is the bias, and therefore (in an Akerlovian model) this is the message which tends to be sent by such choices. I.e., seeking clusters send a message "I'm the best", avoiding them sends "I'm not so hot", for the individual highly skilled worker as much as for the firm in some highly competitive industry. In as much as we live in a "superstar economy" clustering becomes more desirable because of such competitive pressures and messages. > - few large businesses nowadays have customers neatly > clustered in one location, they tend to sell countrywide > or worldwide; so the premium for getting into this expensive > place is low and the costs are high There are exceptions (monopsonies or oligopsonies) but for _large_ firms this generally holds. But a _branch_ of a large firm may be set up specifically to serve a geographically identified market, so the location decision for the branch need not reflect the overall firm's issues, but rather only those specific to said market. > - production nowadays tends to be geographically > distributed as well Not as much as you might think. For example, people who worry about programming jobs moving to India may not realize a vast majority of such jobs go to a SINGLE tiny "spot" within the huge expanse of India, for all of the usual reasons promoting clustering. > - communication costs and transportation costs are DRAMATICALLY > lower nowadays than they used to be (today it costs 1/80 [one > eightieth] to transport a kg of mass using an aircraft in > comparison to what it cost in 1930s; ditto for telecommunication). ...so in the '30s very VERY few goods moved by plane. Not that it's exactly _common_ nowadays to move most goods by plane, mind you; but sure, it's conceivable in some cases. But there are other transaction costs, mostly connected to the need for face-to-face interaction as being the most effective form. I've worked for a SW development firm which tried to coordinate development distributed across many locations via cheap video-based teleconferences spanning timezones from California all the way to India; I've done way more than my share of telecommuting and airport- and plane-hopping for development projects geographically distributed and/or mostly located far from the customers and/or other stakeholders; I know whereof I speak... > Consider real world examples: Microsoft in Redmond or Boeing in > Seattle. Microsoft needs quite a lot of programmers. It would be > rather hard to find enough programmers born and educated in > Redmond, wouldn't it? Of course, or, at MS's scale, in any other single location. So, as they grew, they had to face the usual within-firm tension between the advantages of a single location and that of many; right now, quoting their careers webpage, they "employ more than 50,000 people worldwide, including offices in every major U.S. metropolitan city, and subsidiary offices in more than 60 countries.". For example, to attract the kind of highly competitive top-of-career high-tech worker that just will NOT leave the cluster of Silicon Valley, they chose to set up a new campus in Mountain View, CA, focusing on the convergence of entertainment and information technologies and industries; to attract the kind of European scholar who considers living in Europe a must and/or has no patience for the silly hassles put up by the US to keep foreigners out, Microsoft has an excellent Research laboratory at Cambrige, UK; and so on, and so forth. Of course, management-wise, there would be some great advantages to MS to having everybody at the Redmond campus, but even MS must deal with the real world, and the job market in particular: they're very pragmatic, so they get things in the Campus where they can, elsewhere when they must. How a large firm internally decides to site its various locations is really a separate issue from that of how different firms cluster, though of course there are many connections, particularly when you study the siting of one particular location. The two examples I give here are reasonably typical of a focus on supply-side and particularly the availability of highly skilled workers in high-tech areas... and then they show, again, the pluses of clustering. If Microsoft had found it easier to attract the kind of people they wanted, and build the needed connections to other firms in entertainment/information merging, outside the Silicon Valley cluster, there would be no reason for them to site there -- and instead you find them smack in the middle at Mountain View. > Boeing: Seattle?! Why Seattle? Doesn't Boeing sell most of its > new aircrafts in Washington? Obviously they agree with you, since their World Headquarters are in Chicago since over 3 years ago -- not exactly all that near to Washington, DC, but way closer than Seattle;-) "Why Seattle" has obvious purely historical answers -- they were born there, etc, etc. "Why Chicago" is a far more interesting question, since clearly the choice was way more open once they had decided that to keep expanding in Seattle was too costly or inopportune. You can find a lot about that specific decision on the web, of course. > AFAIK, in Europe Boeing does much of its production in > cooperation with Alena in Italy. From this viewpoint it really The spelling is "Alenia" (just in case somebody wants to google for more info). > doesn't matter much if Boeing is located in Seattle or anywhere > else in America really, does it? Not much, though flying to Chicago is marginally easier than flying to Seattle, it's not enough to matter;-) > Right here (Poland), most of the foreign corporations set up their > call centers in Warsaw, which is totally ridiculous given how > expensive that city is. Oh I can understand setting up a warehouse > by HP there because it's close to its biggest customers. But > I really see no good reason behind HP call center being located in > Warsaw, too, AFAIK (or at least that's the city code when I have > to call them sometimes). > > Most of the successful domestic companies I have observed here > have started and still operate in some God-forgotten provincial > towns, where land and labor is cheap and when it comes to > highly skilled professionals, you have to "import" some or all of > them from elsewhere anyway, because not even a big city is > likely to have precisely all the kinds of ultra-specialized > professionals that you may need. And there's less crime, and > shuttling kids to school isn't a nightmare, and the costs of living > are lower. Plus there's less of other things to do, so your workers > tend to focus more on work. :-) I remember glancing at some costly booklet called something like "Poland Infrastructure Report" back when an employer was considering setting up a branch office somewhere in Poland (selling and customizing SW for the mechanical industry), and back then issues such as internet and other telecom access, easy availability of top graduates, ease for expatriates from Italy to live in the place for a while knowing only English and Italian, at most German and French, and not Polish or Russian, closeness to good international airports and other good transportation, closeness to partner firms and potential customers' decision-makers, all appeared to point to Warsaw, if I recall correctly. Mechanical engineers with some programming experience or viceversa, good translators, and good salespeople with connections in the mechanical industry, are not as ultra-specialized as all that, after all. > >Risk avoidance is quite a secondary issue here (except if you introduce > >in your model an aspect of imperfect-information, in which case, > >following on the decisions made by locals who may be presumed to have > >better information than you is an excellent strategy). Nor is there any > >"agency problem" (managers acting for their interests and against the > >interest of owners), not a _hint_ of it, in fact -- the hatmaker acting > >on his own behalf is perfectly rational and obviously has no agency > >problem!). > > I find no justification in most of foreign companies setting up their > call centers in a ridiculously overpriced capital city - so from > my viewpoint the risk avoidance is the only explanation that is > left. The firm I was working for had a consensus decision-making process (even I was involved) and managers (and other employees) and stockholders were mostly the same people -- it wasn't all that large a firm at the time. Nobody needed to practice risk avoidance. The infrastructure advantages of Warsaw vs other locations loomed HUGELY large, judging of course from some consultants' reports purchased for the purpose -- it may look different to people living in the place, although I'd like to get a second opinion from Warsaw's Chamber of Commerce since you appear to have a very specific individual bone to pick (and I can sympathize: even though Milan may be the economically correct choice for foreign investors, I'd never want to LIVE there myself, being a Bolognese... but I must admit that Milan's infrastructure, connections, location, etc, etc, may in several cases drive a rational decision to set up there). > Not all corporations do that: in this country Coca-Cola has made > their big "green field" investment almost in the middle of nowhere > in this country. GM, Volkswagen, FIAT, and most of other carmakers > have made similar decisions. Doesn't seem like those were bad business > decisions for them. If their needs were for cheap land for greenfield factories, and cheap workers for said factories, then they were acting under very different forces than a midsize company looking to set up a mostly-sales branch office, not an industrial factory. > The cluster I've seen - an IT "corporate area" in Dublin, > Ireland - was specifically created not due to "natural clustering", > but due to govt policy of tax breaks and preparing good > infrastructure in this place rather than some inter-business and > inter-customer dependencies, since e.g. Microsoft (where the company > sent me for training) neither is able to get all the workers it needs > just from this city, nor it sells mostly to local customers, but it > sells all over Europe. That's addressing only the issue of endogenous vs exogenous original causes for clustering. Many attempts to create clusters artificially have happened ever since the economical advantages of clusters were discussed in the literature, together with the crucial point that WHERE the cluster originally happens is in most cases almost random, it's self-reinforcing once it's properly underway. Most such attempts have failed, because governments' powers aren't unlimited; Dublin is a good example of this strategy succeeding. No matter WHY the good infrastructure is there, the tax breaks, the thriving community of high-tech workers, etc, a firm deciding where to set up may perfectly well find it rational to have all of these advantages overwhelm the issues of rents, congestion, competition for good workers. In other words, my disagreement with your thesis that, because the government lowered taxes, taking advantage of that is NOT in the best interests of a firm's stockholders, is now maximal: I find your thesis not just wrong, but by now outright silly. > To me, the issue of manager having to face their superiors > asking him a question - "why on Earth have you decided > to locate our branch in the middle of nowhere in this country? > Why not in capital city? Can't you look at the map? Read some > stats how many inhabitants this city has and what is the > income level there?" is overwhelming: it would take long > time to explain for this manager who e.g. may have already You are wrong, because the same decisions get rationally made by sole-owner sole-manager companies where these considerations cannot apply. Deciding where to site an imporant branch is a BIG decision: of course it takes a long time, *DUH*, and all sorts of factors are taken into consideration. > got his hands dirty in this industry in that country to know > that say, there's little revenue increase to be gained in > locating the facility in capital city, the needed workers are > actually hard to find there, etc. So all of these factors are folded into a huge pile of reports in companies where such decisions are at all likely to be challenged later, and sign-off on the folders is carefully obtained for cover-up purposes. If the local development agencies of the "middles of nowhere in that country" don't do their job, including showering managers planning such decisions with supporting materials, that's a bad sign: maybe due to cultural influences foreign capital, professionals, and managers are NOT welcome there as they would be in a relative metropolis, for example. This is (or was not too long ago) surely the case for some rural parts of the British Islands, and Italy too. It's perfectly rational and consone to stocholders' interests to take this into account and site where you KNOW you'll be welcome. > To me, this is much like decision whether do much of > development in Python or MS VS / VB. "But everybody's > using VisualStudio / VB" is a simple and compelling argument: > "so many people can't be wrong", while explanations that > going Python may actually be better decision in this context > requires long and complex explanations and managers oft can > not even be bothered to read executive summaries. The issue of parallels or otherwise is by now totally secondary, to me, to the main issue that I find your approach to explaining regional clustering problems across industries totally, irredeemably, and horribly WRONG. So, I'm not going to make the post even longer by even trying to address this part. Few, besides the two of us, can be left reading by now, and clearly our disagreements on economics are so total that it's unlikely we can get anywhere by our discussions anyway. > I feel econ models frequently are elegantly designed > abstractions of elegantly designed problems; the problem > is how close those are to the real-world problems. At > the end of the day, it's "human action" that gets all > of that implemented. I've seen too much resources > going down the drain in completely idiotic projects > and decisions to believe managers are rational beings. When you claim managers are acting rationally (if selfishly) to avoid risk to themselves, you can't then justify this claim by adding that they aren't rational at all. Economics does cover, in its modern form, both issues of agency problems (misalignment of incentives between agent and owner) AND ones of "bounded rationality" (all the way from asymmetric information, to transaction costs relating to acquiring and processing information). Trying to throw economics overboard because you can't be bothered to understand it is a kind of behavior that reminds me closely of the "leftists" you excoriate in your signature. Alex From andre.roberge at gmail.com Sun Jan 23 07:40:45 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 23 Jan 2005 04:40:45 -0800 Subject: finding name of instances created In-Reply-To: <41f28f16@nntp0.pdx.net> References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> <41f28f16@nntp0.pdx.net> Message-ID: <1106484045.503918.82350@f14g2000cwb.googlegroups.com> Scott David Daniels wrote: > Andr? Roberge wrote: > > Craig Ringer wrote: > > > >> On Fri, 2005-01-21 at 16:13 -0800, Andr? wrote: > >> > >>> Short version of what I am looking for: > >>> > >>> Given a class "public_class" which is instantiated a few times e.g. > >>> > >>> a = public_class() > >>> b = public_class() > >>> c = public_class() > >>> > >>> I would like to find out the name of the instances so that I could > >>> create a list of them e.g. > >>> ['a', 'b', 'c'] > > > > ... > > Behind the scene, I have something like: > > robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') } > > and have mapped move() to correspond to robot_dict['robot'].move() > > (which does lots of stuff behind the scene.) > > ...[good explanation]... > > Does this clarify what I am trying to do and why? > > Yup. Would something like this help? > > parts = globals().copy() > parts.update(locals()) > names = [name for name, value in parts.iteritems() > if isinstance(value, Robot)] # actual class name here > > Note, however, that > > a = b = CreateRobot() > > will give two different names to the same robot. > > And even: > > Karl = CreateRobot() > Freidrich = CreateRobot() > for robot in (Karl, Freidrich): > robot.move() > > Will have two names for "Freidrich" -- Freidrich and robot > > --Scott David Daniels Thanks for your suggestion. It might have been interesting to try, but I am going to try and implement a suggestion given by Nick Coghlan instead. Andr? From claird at lairds.us Mon Jan 3 10:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Mon, 03 Jan 2005 15:08:03 GMT Subject: Industrial organization (was: The Industry choice) References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> Message-ID: <0u1oa2-qk4.ln1@lairds.us> In article <1gpsbr7.1otvj5mkq1l96N%aleaxit at yahoo.com>, Alex Martelli wrote: >Bulba! wrote: > >> True. I have a bit of interest in economics, so I've seen e.g. >> this example - why is it that foreign branches of companies >> tend to cluster themselves in one city or country (e.g. > >It's not just _foreign_ companies -- regional clustering of all kinds of >business activities is a much more widespread phenomenon. Although I'm >not sure he was the first to research the subject, Tjalling Koopmans, as >part of his lifework on normative economics for which he won the Nobel >Prize 30 years ago, published a crucial essay on the subject about 50 >years ago (sorry, can't recall the exact date!) focusing on >_indivisibilities_, leading for example to transportation costs, and to >increasing returns with increasing scale. Today, Paul Krugman is >probably the best-known name in this specific field (he's also a >well-known popularizer and polemist, but his specifically-scientific >work in economics has mostly remained in this field). . . . clp actually dropped related names back in April , but I think that was during one of your sabbaticals from the group. The work of Vernon Smith, the unconventionally conventional Nobel co-recipient of 2002, can be viewed as a commentary on clustering and other non-homogeneities. Many US readers have encountered Jane Jacobs, who has made a career (and spawned a following) exploring the significance of cities as economic clusters. From janeaustine50 at hotmail.com Sun Jan 9 06:09:27 2005 From: janeaustine50 at hotmail.com (janeaustine50 at hotmail.com) Date: 9 Jan 2005 03:09:27 -0800 Subject: time module precision In-Reply-To: References: Message-ID: <1105268967.629064.154850@c13g2000cwb.googlegroups.com> Tim Peters wrote: [snip] > Python's time.sleep() calls the Win32 API Sleep() function on Windows. > All behavior is inherited from the latter. See MS's docs: > > Oh, after a short research, I found that time.sleep uses its customized way of sleeping using "select". http://groups.google.com/groups?threadm=ud7i1c9ck.fsf%40ctwd0143.fitlinxx.com So I think its behaviour is more complicated than single MS Sleep call, I suppose. > In particular, MS Sleep() takes an integer argument, giving the number > of milliseconds to sleep. Your 0.0001 case falls under the special > Sleep(0) case due to truncation in float->int conversion. > Oh, I see. > Also Google on > > sleep thread deviation > > to find an interesting CodeProject article quantifying behavior on one > particular tester's Windows box. Also see an article it references > for approaches to the question "how do I handle small intervals?" > (short course: you probably can't, unless we're willing to throw > money at it). Thanks for the references. What I want to do is waiting(not busy-delaying) for a few tens to hundreds of microseconds in some threads. The closet solution I got is using windows QueryPerformanceCounter (in Python, time.clock) with busy looping checking if we have past the target time. However, that makes the cpu usage upto almost 100%. So the problem (waiting tens to hundreds of us without busy looping) still remains... From a at a.invalid Thu Jan 27 20:36:19 2005 From: a at a.invalid (Timo Virkkala) Date: Fri, 28 Jan 2005 01:36:19 GMT Subject: [perl-python] 20050127 traverse a dir In-Reply-To: <1106875259.426213.252030@z14g2000cwz.googlegroups.com> References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> <1106875259.426213.252030@z14g2000cwz.googlegroups.com> Message-ID: The Flow wrote: > Do you want to be taken seriously? > First, stop posting. > Second, learn perl. > Third, learn python. No. Second, learn Python. Third, learn Perl (optional). :) But we do agree on the first. -- Timo Virkkala From deetsNOSPAM at web.de Fri Jan 21 06:45:47 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 21 Jan 2005 12:45:47 +0100 Subject: Class introspection and dynamically determining function arguments References: Message-ID: <35c890F4jse0nU1@individual.net> > The classes I'm dealing with do have attributes since they're > C-Extension types with attributes provided in the "tp_getset" slot. So > this is one case where I can query the class for attributes without > having to create an instance. Thanks for making me think of that, since > looking in the class's __dict__ pretty much gives me what I want. I'm > not sure that that's something I can rely on though which is exactly the > sort of issue where I'd like to know if there's a right way (e.g. an > existing module) to ask a class for its attributes, without poking > around in __dict__ directly and doing some type checking. I guess in a > way I'm asking for introspection with a greater degree of granularity > than "dir". According to this http://www-106.ibm.com/developerworks/library/l-pyint.html not really - and there are no special moduls neccessary, as everything is at your hands using __dict__ and so on. -- Regards, Diez B. Roggisch From http Thu Jan 13 14:18:17 2005 From: http (Paul Rubin) Date: 13 Jan 2005 11:18:17 -0800 Subject: sorted (WAS: lambda) References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <7x7jmh1eek.fsf@ruckus.brouhaha.com> <7xpt09xizb.fsf@ruckus.brouhaha.com> Message-ID: <7xy8exgmti.fsf@ruckus.brouhaha.com> "Fredrik Lundh" writes: > > Oh, same difference. I thought it was a method because I'm not using > > 2.4 yet. The result is the same > > nope. sorted works on any kind of sequence, including forward-only > iterators. sorted(open(filename)) works just fine, for example. Oh cool. However I meant the result is the same in my example, where assigning the temporary result to a variable stopped memory from getting reclaimed until after the function exits. From jelle.feringa at ezct.net Wed Jan 19 05:17:33 2005 From: jelle.feringa at ezct.net (Jelle Feringa // EZCT / Paris) Date: Wed, 19 Jan 2005 11:17:33 +0100 Subject: python & iges (nurbs file format) Message-ID: <20050119101739.E9B0E1C001B7@mwinf0402.wanadoo.fr> Is anyone aware of a module allowing you to read / write .iges data? Currently I'm trying to figure a way of writing out my nurbs data generated in python, but if such a package exists, that would be great, haven't been able to find anything so far. Cheers, Jelle. -------------- next part -------------- An HTML attachment was scrubbed... URL: From MrJean1 at gmail.com Sun Jan 9 14:42:36 2005 From: MrJean1 at gmail.com (python) Date: 9 Jan 2005 11:42:36 -0800 Subject: printing line numbers for debugging purpose In-Reply-To: <41e06e72$1_1@omega.dimensional.com> References: <41e06e72$1_1@omega.dimensional.com> Message-ID: <1105299756.717486.151500@c13g2000cwb.googlegroups.com> Below is a function to get the current line number and file name. /Jean Brouwers - # dashes added to preserve indentation. - - import traceback - - def caller(up=0): - '''Get file name, line number, function name and - source text of the caller's caller as 4-tuple: - (file, line, func, text). - - The optional argument 'up' allows retrieval of - a caller further back up into the call stack. - - Note, the source text may be None and function - name may be '?' in the returned result. In - Python 2.3+ the file name may be an absolute - path. - ''' - try: # just get a few frames - f = traceback.extract_stack(limit=up+2) - if f: - return f[0] - except: - if __debug__: - traceback.print_exc() - pass - # running with psyco? - return ('', 0, '', None) - - - if __name__ == '__main__': - print caller() - From evan at tokenexchange.com Mon Jan 17 12:56:07 2005 From: evan at tokenexchange.com (Evan Simpson) Date: Mon, 17 Jan 2005 11:56:07 -0600 Subject: Producer/consumer Queue "trick" In-Reply-To: <34s541F4f5gqiU1@individual.net> References: <34s541F4f5gqiU1@individual.net> Message-ID: <41EBFC37.5030309@tokenexchange.com> Jon Perez wrote: > If the consumer and the producer are separate threads, > why does the consumer thread block when the producer > thread is generating a new board? Or why does it > take forever for the producer thread to be pre-empted? > > Also, I don't understand why the solution works. > How does sleeping for .001 seconds right after putting > a new board on the queue solve the problem? I'm guessing at how things work, and may be totally wrong, but here's what I think happens: In the Queue get() code, the consumer releases the 'fsema' lock. Directly or indirectly, this wakes up and hands control to the producer thread, which was blocked trying to acquire 'fsema'. The sleep() hands control back to the scheduler immediately, which appears to wake up the consumer and let it get on with things. It doesn't take "forever" for the producer to be preempted, just the normal preemption interval. I was bothered, though, by the idea of having it take even a few dozen milliseconds out of the middle of a request that's at most a millisecond or two away from finishing anyway. Cheers, Evan @ 4-am From newsgroups at jhrothjr.com Mon Jan 10 18:14:55 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 10 Jan 2005 17:14:55 -0600 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> Message-ID: <10u6347j23enuc3@news.supernews.com> It doesn't work because Python scripts must be in ASCII except for the contents of string literals. Having a function name in anything but ASCII isn't supported. John Roth "Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle." wrote in message news:41e30aab$0$6434$8fcfb975 at news.wanadoo.fr... Hi ! If Python is Ok with Unicode, why the next script not run ? # -*- coding: utf-8 -*- def ?????(toto): return(toto*3) aret = ?????(4) @-salutations -- Michel Claveau From newsgroups at jhrothjr.com Mon Jan 17 18:19:15 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 17 Jan 2005 17:19:15 -0600 Subject: Assigning to self References: <10uo6hbn040qt24@news.supernews.com> Message-ID: <10uoi0hfluhk0b6@news.supernews.com> "Frans Englich" wrote in message news:mailman.816.1105995336.22381.python-list at python.org... > On Monday 17 January 2005 20:03, John Roth wrote: >> "Frans Englich" wrote in message > > > >> In other words, you're trying to create a singleton. In general, >> singletons are frowned on these days for a number of reasons, >> not least because of the difficulty of testing them. > > Then I have some vague, general questions which perhaps someone can reason > from: what is then the preferred methods for solving problems which > requires > Singletons? Is it only frowned upon in Python code? I don't know of any generic methods that will work in all cases _and_ are easy to apply. There are really two issues: testing and abuse of the pattern. There really are some places where you want a single instance of something that is globally visible. Things that leap immediately to mind include the connection to a data base and a logger facility. However, in a lot of cases, you find singletons used as an "object oriented" substitute for a global variable, which stinks just as badly as a global would. Since Python is a multi-paradigm language, just put in a global at the module level. It's clearer. Otherwise redesign. There are several ways of getting around the testing difficulty. One is the "toolbox" pattern that appears in a number of places. The idea there is to have a single object that proxies all of the singletons so that they can be replace by testing versions at initialization time. A neater and more modern method is to use an IOC (Inversion of Control) container, or at least the pattern involved. All IOC containers I'm aware of support singletons and make testing them almost trivially easy. A third way is to simply take advantage of Python's dynamic nature and have your tests stuff the testing instance into the class object before the first call. This is an ad-hoc variation on the IOC principle. HTH John Roth > > > Cheers, > > Frans > From vincent at visualtrans.de Tue Jan 18 14:06:52 2005 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 18 Jan 2005 20:06:52 +0100 Subject: how to find site-packages path (Michael Hoffman) - use distutils In-Reply-To: References: Message-ID: Philippe C. Martin wrote: >>>Why would you want to copy any *.pyc instead of compiling them on > > site? > I know that sounds terrible to the open source community, but I do not > intend to release the source code for my product That's not why I asked. I'll leave the politics up to you. The thing is, that the path info gets cached in the *.pyc file. This may lead to confusing tracebacks - might they occur - when the user does not install to the exact same drive/path as you did. Additionally: if you *do* want to distribute *.pyc only, I personally wouldn't find it terribly neat if you stuck those into the site-packages directory of my Python installation. I - for one - would want to know what kind of source code you place along *my* sys.path. Maybe you should consider using py2exe to distribute - keeping your *.pyc out of the user's Python directory tree, if any, entirely. Also, you may want to consider using Inno Setup as deployment tool (if Windows is your target platform). Using distutils for a *.py-less installer seems pretty pointless. Regards, -- Vincent Wehren - pls go to > philippecmartin.com/applications.html for my _small_ contributions :-)) > > Regards, > > Philippe > > > From bj_666 at gmx.net Sat Jan 8 16:54:20 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 08 Jan 2005 22:54:20 +0100 Subject: Documenting data members References: Message-ID: In , Frans Englich wrote: > I have a custom module which among others contains a dictionary, acting as a > "constant". I want to document it, but no matter what I do, it doesn't show > up in `pydoc`. For example, the following doesn't work: I'm using epydoc_ for my documentation and there the module level and class level variables are documented in the module/class docstring with special markup. > """ > A dictionary of the namespaces. > """ > xmlns = { > ... > } Will become: """ (Module description) :var xmlns: A dictionary of the namespaces. """ Ciao, Marc 'BlackJack' Rintsch .. _epydoc: http://epydoc.sourceforge.net/ From samantha7395 at hotmail.com Wed Jan 19 11:32:51 2005 From: samantha7395 at hotmail.com (Samantha) Date: Wed, 19 Jan 2005 08:32:51 -0800 Subject: Print to Windows default Printer References: Message-ID: Thanks Tim. I didn't realize it would be so difficult. S "Tim Golden" wrote in message news:mailman.889.1106123987.22381.python-list at python.org... From tdelaney at avaya.com Wed Jan 26 17:24:30 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 27 Jan 2005 09:24:30 +1100 Subject: On benchmarks, heaps, priority queues Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE025202DC@au3010avexu1.global.avaya.com> aaronwmail-usenet at yahoo.com wrote: > PQPython23 - the Lib implementation > PQ0 - my insertion sort based variant > PQueue - my "heap" based variant > (like PQPython23, but different). First of all, you should be running these benchmarks using Python 2.4. heapq is considerably faster there ... (Raymond Hettinger rewrote it all in C). http://www.python.org/2.4/highlights.html Tim Delaney From peter at engcorp.com Sun Jan 9 13:37:13 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jan 2005 13:37:13 -0500 Subject: Python Installation In-Reply-To: <41E15306.7090108@holdenweb.com> References: <1105220812.579690.292260@c13g2000cwb.googlegroups.com> <1105232505.142279.85810@c13g2000cwb.googlegroups.com> <41E15306.7090108@holdenweb.com> Message-ID: Steve Holden wrote: > Peter Hansen wrote: > >> Simon John wrote: >> >>> I would say install on one machine, then just copy the C:\Python24 >>> directory, but then you'd have to deal with the missing Registry >>> entries.... >> >> >> >> That part is pretty trivial to automate as well. Fredrik >> Lundh has a useful utility on his web site that will do much >> of what is required. Google for his name and "python registry" >> to find out more. >> > Hmm, effbot.org seems to be down just now. Sure it'll be back soon, though. Still down, but clicking on the second link in the result, on the "cached" link, then on the "cached text only" link in the header, will get the relevant source code for you. -Peter From carribeiro at gmail.com Wed Jan 5 14:17:03 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 5 Jan 2005 17:17:03 -0200 Subject: Python evolution: Unease In-Reply-To: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> References: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> Message-ID: <864d370905010511177a231a96@mail.gmail.com> On Wed, 5 Jan 2005 19:25:37 +0100, Alex Martelli wrote: > Carlos Ribeiro wrote: > ... > > > - IDE: Better than what? Than IDLE? Than Eclipse? Than SPE? Than Pythonwin? > > > > I would like to seee Eric3, with some polish & opensourced on Win > > (which means solving the Qt licensing problem). Perhaps someone could > > convince Trolltech to release a special Qt Win version just for it > > (Eric3). Eclipse is also an interesting approach. > > I love eric3, but if you're an eclipse fan, look at enthought's > "envisage" IDE -- it seems to me that it has superb promise. Hint noted. > > wish I could simply plug & play DBAPI modules in a totally seamlessly > > way. Anyone who tried know how far are we of this dream. > > If you manage to get there, you'll start fighting against the different > dialects of SQL supported by the various back-ends, as is well known by > anybody who tried, say, ODBC or ADO, which do manage good plug&play of > their components but still can't solve the real hard one:-( Ian Bicking's SQLObject goes a long way to solve this problem. It's a ORM, not a complete relational solution, mind you. However, while it's architecturally oriented towards solving the high-level SQL-to-object mapping issues, a good deal of time is spent solving things that a common plug & play API could solve. IOW: the hard problem really does exist. However, we never come to face it because we're still stuck in the "easy" one. :-( -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Thu Jan 6 13:46:05 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 6 Jan 2005 19:46:05 +0100 Subject: File Handling Problems Python I/O References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> <1105034402.428393.283930@c13g2000cwb.googlegroups.com> Message-ID: <1gpzg5n.1ylh8m21c0o5jN%aleaxit@yahoo.com> Josh wrote: ... > He is the function where I am making the call. If I change the open > statment to another file, say "c:\test.txt", a file I know exists, it Are you sure a file exist whose name is, c, colon, tab, e, s, t ...? \t is an escape sequence and it means TAB (character of ascii code 9). Try 'c:/test.txt' -- using normal slash instead the backslash -- and you should be fine. You mention you have some experience with other languages: if those languages include C, or Java, or C++, and many others besides (all which use backslashes for escape sequences in strings), you'd have exactly the same issues. Alex From fuzzyman at gmail.com Fri Jan 14 07:11:59 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 14 Jan 2005 04:11:59 -0800 Subject: huygens lands on titan In-Reply-To: References: Message-ID: <1105704719.374905.239790@f14g2000cwb.googlegroups.com> John Thingstad wrote: > -- > huygens lands on titan > Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/ I bet it didn't....... Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From roy at panix.com Wed Jan 12 22:37:33 2005 From: roy at panix.com (Roy Smith) Date: Wed, 12 Jan 2005 22:37:33 -0500 Subject: why are people still using classic classes? References: Message-ID: Simon Wittber wrote: > Is there a legitimate use for classic classes that I am not aware of? Is there a reason NOT to use them? If a classic class works fine, what incentive is there to switch to new style classes? I realize it's not much effort to put "(object)" after your class name, but I'm lazy and don't bother. I don't see how I've been hurt by that. Obviously, if there was some feature of new style classes I wanted to use, it would be a different story. From tom at dtsam.com Tue Jan 4 14:19:39 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Tue, 4 Jan 2005 13:19:39 -0600 Subject: Reaching the real world References: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> Message-ID: "Fuzzyman" wrote in message news:1104850540.610295.152240 at f14g2000cwb.googlegroups.com... > I have a friend who would like to move and program lights and other > electric/electro-mechanical devices by computer. I would like to help - > and needless to say Python would be an ideal language for the > 'programmers interface'. > > What I'd like is an electronic interface that connects to several > relays and a python extension module to switch on and off the relays. > I've had a quick google and can't see anything too similar to what I > want. pyro (python robotics) seems to require expensive (relatively) > robotic equipment. Loosely, what you are looking for is Data Acquisition (DAQ) , Digital I/O, and control that you can do from your pc. Those are the keywords you want to google. Look at www.ni.com and poke around. They will have some introductory material. Look at www.circuitcellar.com . It may look a bit overwhelming at first but look at the ads for pc equipment. These should also lead you to some tutorials. You are looking for simple digital output. You can use an existing serial or parallel port with a bit of external hardware from radio shack to control relays on the cheap. OR You can purchase a Digital I/O adaptor that will plug into your computer bus and give you outputs to control your relays. You will also get instructions and some software to interface (talk!) to the adaptor. Typically you will read and write to the I/O ports on your computer to flip the switches. OR perhaps the easiest and most effective These would be smart devices that talk to your Python (or whatever!) software via the serial port. You would throw simple string commands (eg "ChannelB ON") at the serial port and the microprocessor based controller will turn on the appropriate relay. Your challenge from Python will be to control the computers I/O ports or to communicate with one of the serial ports. I'm sure someone else will point to libraries that will help you with this. Much *much* more but you have to start somewhere :-) Thomas Bartkus From steve at holdenweb.com Tue Jan 18 20:04:15 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Jan 2005 20:04:15 -0500 Subject: file copy portability In-Reply-To: References: Message-ID: Bob Smith wrote: > Is shutil.copyfile(src,dst) the *most* portable way to copy files with > Python? I'm dealing with plain text files on Windows, Linux and Mac OSX. > > Thanks! Yes. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From aleaxit at yahoo.com Sun Jan 9 06:31:47 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 9 Jan 2005 12:31:47 +0100 Subject: Getting rid of "self." References: Message-ID: <1gq4ery.1v79c2t9lsfinN%aleaxit@yahoo.com> BJ?rn Lindqvist wrote: > I think it would be cool if you could refer to instance variables > without prefixing with "self." I know noone else thinks like me so Some do -- Kent Beck's excellent book on TDD-by-example has a specific grouse against that in the chapter where he develops the unittest module (in Python). But that's how comes Kent is a _Smalltalk_ programmer rather than a _Python_ programmer, see?-) > Python will never be changed, but maybe you can already do it with > Python today? Sure. > impressive in this case but much cooler when there is more instance > variables around. But the solution is very ugly because you have to > write exec(magic()) in every method. So I'm asking here if someone > knows a better way, maybe using decorators or metaclasses or other > black magic? A decorator can entirely rewrite the bytecode (and more) of the method it's munging, so it can do essentially anything that is doable on the basis of information available at the time the decorator executes. You do, however, need to nail down the specs. What your 'magic' does is roughly the equivalent of a "from ... import *" (except it "imports", so to speak, from a namespace that's not a module): it makes a local copy of all names defined in the given namespace, and that's all. The names stay local, any rebinding of a name has no non-local effect whatsoever, etc. Is this indeed what you want -- just give a method this kind of copies? And still have to write self.x=23 for re-binding (without effect on the local copy, note...)? Or what else? Then, you must decide whether this applies to all names the method accesses (which aren't already local). For example, if the method has a statement such as: x = len(y) and does not otherwise as locals len nor y, does this mean x = self.len(self.y) or x = len(self.y) or x = self.len(y) or x = len(y) ...? I.e., which of the names len and y is meant to be a global or builtin, which is meant to be an isntance variable? The decorator must know, because it needs to generate different bytecode. Your approach, injecting an exec statement in the method, makes the compiler punt: the compiler knows, seeing 'exec', that it has no idea about which names are locals or globals any more, so it generates horribly-slow code for completely-general accesses instead of normal local-access-is-optimized code. Is that what you want to do -- slow all of your Python code down by an order of magnitude in order to be able to avoid writing 'self.' in a few cases? If you can give totally complete specifications, I can tell you whether your specs are doable (by a decorator, or other means), how, and at what cost. Without knowing your specs, I can't tell; I can _guess_ that the answer is "probably doable" (as long as you're not demanding the code in the decorator to be an oracle for the future, but are content to limit it to information known when it runs; and as long as you don't care how much you slow everything down) and most definitely not WORTH doing for anything except mental gym. Alex From xah at xahlee.org Fri Jan 14 05:42:37 2005 From: xah at xahlee.org (Xah Lee) Date: 14 Jan 2005 02:42:37 -0800 Subject: [perl-python] 20050113 looking up syntax Message-ID: <1105699357.565028.107750@c13g2000cwb.googlegroups.com> while programing in Python, one can lookup syntax or info for keywords or modules within Python. In the command line, type python to get into the python interactive program. then type help() >From there one can type any keyword or module name to find out the syntax or info. Everything is self-contained and self-explanatory. to exit help, type control-d. if you haven't tried already, you can type 1+1 while running python. The result will be displayed interactively. So in this way, Python can be used as a calculator. --------------------- for perl syntax lookup, use perldoc in the command line. For example: perldoc perl use 'perldoc -f functionName' for specific function. example: perldoc -f qq note that keywords cannot be looked up with -f. For basic keywords like if, while..., use perldoc perlop Master 'perldoc perl' as a way to get familiar of what info are available and what subroutine or aspect of perl is in what section of the documentation associated with what documentation name abbreviation. Master 'perldoc perldoc' to know all its power of options and flexibility. If you use emacs, in particular you want to add the -t option. Master the unix text editor vi to learn the navigation system of perldoc. The basics are: control-f for page down, control-v for page up, q for exit. Also, one may wish to peruse 'perldoc perlfaq' to acquaint yourself about the preamble of nine volumes of perl's FAQ. --------------------------- Note: this post is from the Perl-Python a-day mailing list at http://groups.yahoo.com/group/perl-python/ to subscribe, send an email to perl-python-subscribe at yahoogroups.com if you are reading it on a web page, program examples may not run because they've been changed by yahoo.com or google.com. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From aleaxit at yahoo.com Mon Jan 24 03:38:25 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 24 Jan 2005 09:38:25 +0100 Subject: best way to do a series of regexp checks with groups References: Message-ID: <1gqvzm0.htfjsq10h8nruN%aleaxit@yahoo.com> Nick Craig-Wood wrote: > Here is a different solution... > > class Result: > def set(self, value): > self.value = value > return value > > m = Result() > > if m.set(re.search(r'add (\d+) (\d+)', line)): > do_add(m.value.group(1), m.value.group(2)) > elif m.set(re.search(r'mult (\d+) (\d+)', line)): > do_mult(m.value.group(1), m.value.group(2)) > elif m.set(re.search(r'help (\w+)', line)): > show_help(m.value.group(1)) This is roughly the same as my Cookbook recipe for test-and-set, but if all you're using it for is RE search and MO access you might be better off giving more responsibilities to your auxiliary class, such as: class ReWithMemory(object): def search(self, are, aline): self.mo = re.search(are, aline) return self.mo def group(self, n): return self.mo.group(n) m = ReWithMemory() if m.search(r'add (\d+) (\d+)', line): do_add(m.group(1), m.group(2)) elif m.search(r'mult (\d+) (\d+)', line): do_mult(m.group(1), m.group(2)) elif m.search(r'help (\w+)', line): show_help(m.group(1)) Demeter's Law suggests that the 'm.value.group' accesses in your approach are better handled by having m delegate to its `value'; and the repeated m.set(re.search( ... seem to be a slight code smell, violating "once and only once", which suggests merging into a single `set' method. Your approach is more general, of course. Alex From sjmachin at lexicon.net Tue Jan 4 17:33:34 2005 From: sjmachin at lexicon.net (John Machin) Date: 4 Jan 2005 14:33:34 -0800 Subject: Pythonic search of list of dictionaries In-Reply-To: References: Message-ID: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> Bulba! wrote: [big snip] Forget the csv-induced dicts for the moment, they're just an artifact of your first solution attempt. Whether english = csv_row[1], or english = csv_row_dict["english"], doesn't matter yet. Let's take a few steps back, and look at what you are trying to do through a telescope instead of a microscope. Core basic root problem: you have a table with 3 columns, id, english, polish. Nothing is said about id so let's assume nothing. Evidently contents of "english" is the "key" for this exercise, but it's not necessarily unique. You have two instances of the table, and you want to "diff" them using "english" as the key. You want to collect together all rows that have the same value of "english", and then process them somehow. You need to define an object containing a list of all "left" rows and a list of all "right" rows. Processing the contents of the object: do whatever you have to with obj.left_list and obj.right_list depending on the lengths; you have 3 cases of length to consider (0, 1, many). 3 x 3 = 9 but if you get both zero you have a bug (which you should of course assert does not exist), so that leaves 8 cases to think about. Now, how do we get the rows together: (a) The sort method Step 1: sort each dataset on (english, id, polish) or (english, polish, id) -- your choice; sorting on the whole record instead just english makes the ordering predictable and repeatable. Step 2: read the two sorted datasets ("left" and "right") in parallel: when left key < right key: do_stuff(); read another left record when left key > right key: converse when left ley == right key: do_stuff(); read another record for both where do_stuff() includes appending to left_list and right_list as appropriate and at the right moment, process a completed object. This is a little tricky, and handling end of file needs a little care. However this algorithm can be implemented with minimal memory ("core"), no disk drive at all :-O and a minimum of 3 (preferably 4+) serially-readable rewindable re-writable storage devices e.g magnetic tape drives. Once upon a time, it was *the* way of maintaining a database (left = old database, right = transactions, output file -> new database). (b) Fast forwarding 30+ years, let's look at the dictionary method, assuming you have enough memory to hold all your data at once: Step 1: read the "left" table; for each row, if english not in mydict, then do mydict[english] = MyObject(). In any case, do mydict[english].left_list.append(row) Step 2: same for the "right" table. Step 3: for english, obj in mydict.iteritems(): process(english, obj) As your datasets are stored in MS Excel spreadsheets, N < 64K so whether your solution is O(N) or O(N*log(N)) doesn't matter too much. You are however correct to avoid O(N**2) solutions. Hoping this sketch of the view through the telescope (and the rear-vision mirror!) is helpful, John From bjourne at gmail.com Fri Jan 7 11:51:13 2005 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Fri, 7 Jan 2005 17:51:13 +0100 Subject: Getting rid of "self." In-Reply-To: References: <740c3aec05010705393048a374@mail.gmail.com> <1105114214.359029.152240@f14g2000cwb.googlegroups.com> Message-ID: <740c3aec050107085166d99e50@mail.gmail.com> Thank you for your replies. But they don't deal with my original question. :) I have read the thousands of posts all saying "self is good" and they are right. But this time I want to be different m-kay? I figure that there might be some way to solve my problem by doing this: .def instancevar2locals(method): . # Do something magic here so that exec(magic()) is automagically run each time . # the function is invoked. . newmethod = method . return newmethod And then in the class definition something like this: .class A: . def __init__(self): . self.hi = "hi" . def meth(self): . print hi . meth = instancevar2locals(meth) But beyond that, I have no idea and I would be grateful if someone would like to help me with it. -- mvh Bj?rn From hwlgw at hotmail.com Wed Jan 19 12:04:08 2005 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 19 Jan 2005 09:04:08 -0800 Subject: delay and force in Python References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> Message-ID: <1106154248.364547.301430@c13g2000cwb.googlegroups.com> Yes you are right, if you just want to carry an expression around then lambda does it; but delay was not intended as a top-level function. Perhaps you think that my silly stream implementation in the original post builds the whole list, but it does not: >>> o = stream_enumerate_interval(11,121) >>> print o [11, at 0x00BA8670>] >>> f = o[1] >>> r = f() >>> print r [12, at 0x00BA86B0>] instead it builds a list of lambda's, and that is so desirable Others suggested generators indeed, and I can imagine now a usage pattern like >>> s = stream_generator(initValue, next, stop, other_params) >>> stream_hd(stream_tl(stream_filter(isEven,s))) where the idea is to pass a generator to a function all the time. What I don't like though is that I then, as I understand it, have to code some for-loop inside that function, I try to avoid for-loops. But a functional form defined with a for-loop does not seem all that bad. Anyway I have some reading-up to do, about things some posters use and I forgot to keep up with since I have been coding Python 1.5.2 style for ages now: properties, itertools, ...printed some stuff already, thanks! From jeff at ccvcorp.com Wed Jan 26 19:59:01 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 26 Jan 2005 16:59:01 -0800 Subject: Browsing text ; Python the right tool? In-Reply-To: <1106783975.472873.21420@z14g2000cwz.googlegroups.com> References: <10vdpohm549g44a@corp.supernews.com> <1106707324.874852.208520@z14g2000cwz.googlegroups.com> <10vfqra5knegoa3@corp.supernews.com> <1106783975.472873.21420@z14g2000cwz.googlegroups.com> Message-ID: <10vgerafeom164b@corp.supernews.com> John Machin wrote: > Jeff Shannon wrote: > >>[...] For ~10 or fewer types whose spec >>doesn't change, hand-coding the conversion would probably be quicker >>and/or more straightforward than writing a spec-parser as you >>suggest. > > I didn't suggest writing a "spec-parser". No (mechanical) parsing is > involved. The specs that I'm used to dealing with set out the record > layouts in a tabular fashion. The only hassle is extracting that from a > MSWord document or a PDF. The "specs" I'm used to dealing with are inconsistent enough that it's more work to "massage" them into strict tabular format than it is to retype and verify them. Typically it's one or two file types, with one or two record types each, from each vendor -- and of course no vendor uses anything similar to any other, nor is there a standardized way for them to specify what they *do* use. Everything is almost completely ad-hoc. >>If, on the other hand, there are many record types, and/or those >>record types are subject to changes in specification, then yes, it'd >>be better to parse the specs from some sort of data file. > > "Parse"? No parsing, and not much code at all: The routine to "load" > (not "parse") the layout from the layout.csv file into dicts of dicts > is only 35 lines of Python code. The routine to take an input line and > serve up an object instance is about the same. It does more than the > OP's browsing requirement already. The routine to take an object and > serve up a correctly formatted output line is only 50 lines of which > 1/4 is comment or blank. There's a tradeoff between the effort involved in writing multiple custom record-type classes, and the effort necessary to write the generic loading routines plus the effort to massage coerce the specifications into a regular, machine-readable format. I suppose that "parsing" may not precisely be the correct term here, but I was using it in parallel to, say, ConfigParser and Optparse. Either you're writing code to translate some sort of received specification into a usable format, or you're manually pushing bytes around to get them into a format that your code *can* translate. I'd say that my creation of custom classes is just a bit further along a continuum than your massaging of specification data -- I'm just massaging it into Python code instead of CSV tables. >>I suspect >>that we're both assuming a case similar to our own personal >>experiences, which are different enough to lead to different >>preferred solutions. ;) > > Indeed. You seem to have lead a charmed life; may the wizards and the > rangers ever continue to protect you from the dark riders! :-) Hardly charmed -- more that there's so little regularity in what I'm given that massaging it to a standard format is almost as much work as just buckling down and retyping it. My one saving grace is that I'm usually able to work with delimited files, rather than column-width-specified files. I'll spare you the rant about my many job-related frustrations, but trust me, there ain't no picnics here! Jeff Shannon Technician/Programmer Credit International From fredrik at pythonware.com Mon Jan 24 13:39:24 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 19:39:24 +0100 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> Message-ID: Steven Bethard wrote: >>>>>a = 1, 2, 3 >>>>>b = a[:] >>>>>a is b >> True > > My impression was that full tuple copies didn't actually copy, but that slicing a subset of a > tuple might. Not exactly sure how to test this, but: > > py> a = 1, 2, 3 > py> a[:2] is a[:2] > False yup. and to figure out why things are done this way, consider this case: >>> a = give_me_a_huge_tuple() >>> len(a) (a rather large number) >>> b = a[:2] >>> del a (IIRC, I proposed to add "substrings" when I implemented the Unicode string type, but that idea was rejected, for the very same "and how do you get rid of the original object" reason) From BOOGIEMANPN at YAHOO.COM Mon Jan 3 17:38:32 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Mon, 3 Jan 2005 23:38:32 +0100 Subject: How do I make Windows Application with Python ? References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> Message-ID: <1j5b7xzffmtry$.xdy044lkg71u$.dlg@40tude.net> On Mon, 03 Jan 2005 22:57:22 +0100, Jarek Zgoda wrote: > Close your eyes, see this model-view-controller in your application, > rewrite it in Python using one of its MVC frameworks. > > You see? It's easy, like that! Yes, only if I'd know what you're talking about :( From tds at gmx.de Sun Jan 2 18:07:14 2005 From: tds at gmx.de (Wolfgang) Date: Mon, 03 Jan 2005 00:07:14 +0100 Subject: UserDict deprecated In-Reply-To: <1gpqh6l.65jemkskbo5eN%aleaxit@yahoo.com> References: <1gpqh6l.65jemkskbo5eN%aleaxit@yahoo.com> Message-ID: Hello, Alex Martelli wrote: > The DictMixin class from the UserDict module is *not* deprecated -- only > the UserDict class from the same module. (If you found info saying > otherwise pls provide a URL: the info is wrong and I'll try to get it > fixed -- thanks!). DictMixin's purpose is exactly as you state: letting > you make a complete mapping class out of one which only supplies the > very basics, by mix-in inheritance. If UserDict is deprecated why is it still used in the os module ? (in python V. 2.4) The std lib should be a good example for python coding, if something is deprecated it should not be used in the std lib. Some weeks ago I had ten minutes of spare time and rewrote the 'os' module to use dict and there was no problem with it. But due to lack of time I was not able to run tests and submitted no patch. I will try this next week. bye by Wolfgang From tjreedy at udel.edu Sat Jan 29 20:42:54 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 29 Jan 2005 20:42:54 -0500 Subject: {Spam?} Re: naive doc question References: <5175a81c050129163826fcd734@mail.gmail.com> Message-ID: "Gabriel B." wrote in message news:5175a81c050129163826fcd734 at mail.gmail.com... > I wanted a list of all the methods of dict for example... where can i > find it? Lib Ref 2.3.8 Mapping Types. Do browse chapter 2 so you know what is there. Terry J. Reedy From ovazquez at gmail.SPAM.com Tue Jan 25 00:28:23 2005 From: ovazquez at gmail.SPAM.com (Orlando Vazquez) Date: Tue, 25 Jan 2005 05:28:23 GMT Subject: Retrieving modification time of file class was declared in In-Reply-To: <1IkJd.53158$06.43207@clgrps12> References: <1106627951.152900.135310@z14g2000cwz.googlegroups.com> <1IkJd.53158$06.43207@clgrps12> Message-ID: Actually, what my comment wass supposed to say was "Checking the modification time of the file the Thread class was defined in", but I'm sure you understood what I meant. ;-) Orlando Vazquez wrote: > nathan_kent_bullock at yahoo.ca wrote: > >> Assume I am using a class Foo. I want to find out the modification time >> of the file that that class was defined in. How would I go about this? >> >> If I could find out the name of the file that Foo was defined in then >> it is easy, I could use os.path.getmtime(), but I can't even figure >> that out. >> >> I realize that this wouldn't be a completely accurate way to tell the >> last time this class was modified because it could inherit info from >> other classes, or use functions from other modules that have been >> modified, etc. >> >> Nathan Bullock >> > > Off the top of my head, without having done too much experimentation > here's what you could try. Caveat: there may be a more robust/cleaner > way of doing this: > > # Checking the modificationtime of the Thread class in the threading > # module > > >>> import threading > >>> import time > >>> > >>> module_filename = vars()[threading.Thread.__module__].__file__ > >>> > >>> mtime = os.path.getmtime(module_filename) > >>> > >>> print time.ctime(mtime) > Sun Nov 14 20:29:42 2004 > > > I hope that answer's your question :-) > From bokr at oz.net Wed Jan 12 22:01:33 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 03:01:33 GMT Subject: dict.updated References: <5GiFd.8571$Vj3.3354@newssvr17.news.prodigy.com> Message-ID: <41e5e359.707363114@news.oz.net> On Wed, 12 Jan 2005 23:47:13 GMT, "Rick Morrison" wrote: >I could live with creating a new dict, sure (although it seems wasteful). I >realize that something like this probably doesn't stand a chance of ever >making it into the std library for what might be called "philosophical" >reasons. I just want it for me (my personal philosophy runs more to the >pragmatic -- well at least for coding). > >I suppose the in-place version would be more along the lines of: > >>>> def updated(d, updates): >... d.update(updates) >... return d >... >>>> [updated(d, {'c':3}) for d in [{'a':1, 'b':2}, {'x':10, 'y':'11'}]] >[{'a': 1, 'c': 3, 'b': 2}, {'y': '11', 'x': 10, 'c': 3}] > It's kind of a strange list comp, but I guess you're just illustrating something. But for this case you could just write >>> [d.update({'c':3}) or d for d in [{'a':1, 'b':2}, {'x':10, 'y':'11'}]] [{'a': 1, 'c': 3, 'b': 2}, {'y': '11', 'x': 10, 'c': 3}] taking advantage of normal d.update() returning None and so forcing the 'or' term. Regards, Bengt Richter From bokr at oz.net Fri Jan 7 17:02:19 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 07 Jan 2005 22:02:19 GMT Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> Message-ID: <41df023c.256518524@news.oz.net> On 07 Jan 2005 14:38:01 +0100, Jacek Generowicz wrote: [...] > >[*] Funnily enough, getting them to understand that "lambda x: fn(x)" > is just a very silly way of writing "fn", can be quite a struggle > at times ... but that's probably a consequence of the context in > which lambda is introduced. Actually, it may _usually_ be silly, but it could be a way of deferring a name lookup instead of using the current binding of a name: >>> def bar(): return 'this is bar' ... >>> def foo(f=bar): print f() ... >>> def bar(): return 'this is updated bar' ... >>> foo() this is bar >>> def foo(f=lambda:bar()): print f() ... >>> foo() this is updated bar >>> def bar(): return 'this updated bar was picked up by silly lambda' ... >>> foo() this updated bar was picked up by silly lambda Regards, Bengt Richter From bjourne at gmail.com Sun Jan 9 19:51:07 2005 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 10 Jan 2005 01:51:07 +0100 Subject: Getting rid of "self." In-Reply-To: <10u2dlj4p45psf0@news.supernews.com> References: <1gq4ery.1v79c2t9lsfinN%aleaxit@yahoo.com> <10u2dlj4p45psf0@news.supernews.com> Message-ID: <740c3aec05010916515326ac4a@mail.gmail.com> Thank you for your replies. It is very nice to see that a thread you started is generating so much discussion, but please, I have read the previous debates so I know all about what people think about self. Spare the "you shouldn't do that" and "self is here to stay" replies to the threads in which people are actually suggesting changing the syntax. :) I know the solution I presented is not working ideally, because you have to use self to assign to instance attributes like "self.hi = 'baby'". > Sean Ross: > http://starship.python.net/crew/mwh/hacks/selfless.py That's excellent! There is one small problem with the code though: .class Hi(Selfless): . __attrs__ = ["x"] . def __init__(x): . self.x = x In this case, I think the Python interpreter should realise that the parameter x shadows the attribute x. But the selfless code has problems with that. I want it to work exactly like how the situation is handled in Java and C++. > Alex Martelli: >> Bj?rn Lindqvist: >> I think it would be cool if you could refer to instance variables >> without prefixing with "self." I know noone else thinks like me so > Some do -- Kent Beck's excellent book on TDD-by-example has a specific > grouse against that in the chapter where he develops the unittest module I have to get myself that book. > Alex Martelli: > A decorator can entirely rewrite the bytecode (and more) of the method > it's munging, so it can do essentially anything that is doable on the > basis of information available at the time the decorator executes. Which I believe means that the instance variables have to be declared in the class? I am content with declaring them like the selfless approach does: __attrs__ = ["hi", "foo"] It's not optimal because it would lead to some "name duplication" when a class is __init__:ed. .__attrs__ = ["hi", "foo"] .def __init__(_hi, _foo): . hi = _hi . foo = _foo I guess you can solve that adequately by using one of the recipes from the Cookbook that automagically initialises an objects variable depending on which variables was passed in the parameter list. Another alternative would be not to declare the variables in an __attr__ list, and instead let them be "declared" by having them initialised in the __init__. I.e: .def __init__(hi, foo): . self.hi = hi . self.foo = foo When the metaclass then does it magic, it would go through the code of the __init__ method, see the assignments to "self.hi" and "self.foo", decide that "hi" and "foo" are attributes of the object and replace "hi" and "foo" in all other methods with "self.hi" and "self.foo". The downside is that it probably could never be foolproof against code like this: .def __init__(hi, foo): . if hi: . self.hi = hi . else: . self.foo = foo But AFAIK, that example is a corner case and you shouldn't write such code anyway. :) > Alex Martelli: > You do, however, need to nail down the specs. What your 'magic' does > is roughly the equivalent of a "from ... import *" (except it > ... > Then, you must decide whether this applies to all names the method > accesses (which aren't already local). For example, if the method > has a statement such as: > x = len(y) All names should be checked like this: 1. Is the name in the parameter list? If so, do not rebind it. 2. Is the name in the objects attribute list? If so, prepend "self." 3. Do stuff like normal. Example: .class Foo(Selfless): . def __init__(x): . print x . self.x = x*2 . def meth(): . x = x + 10 . print x . def meth2(x): . print x . print self.x . self.x = x . .o = Foo(50) .print o.x .o.meth() .o.meth2(12) .print o.x Outputs: 50 100 110 12 110 12 > Alex Martelli: > If you can give totally complete specifications, I can tell you > whether your specs are doable (by a decorator, or other means), how, > and at what cost. Without knowing your specs, I can't tell; I can > _guess_ that the answer is "probably doable" (as long as you're not > demanding the code in the decorator to be an oracle for the future, This is promising, I'm content with whatever slowdowns necessary as long as I can prove those who say "you can't do it" wrong. :) It seems to me that it should be doable by having the metaclass that modifies the class go through the class and bytecode-rewrite all its methods. So there has to be a big slowdown when the class is created, but after that, it should execute at pure Python speed? That doesn't seem to hard, and pretty robust too since bytecode doesn't change so often. And THEN I'll rewrite python-mode so that it syntax highlights member attributes! It will be cool. -- mvh Bj?rn From kent3737 at yahoo.com Thu Jan 20 13:59:43 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Thu, 20 Jan 2005 13:59:43 -0500 Subject: Overloading ctor doesn't work? In-Reply-To: References: <35ab8oF4idc25U1@individual.net> Message-ID: <41effd30$1_1@newspeer2.tds.net> > Martin H?cker wrote: > >> Hi there, >> >> I just tried to run this code and failed miserably - though I dunno >> why. Could any of you please enlighten me why this doesn't work? Here is a simpler test case. I'm mystified too: from datetime import datetime class time (datetime): def __init__(self, hours=0, minutes=0, seconds=0, microseconds=0): datetime.__init__(self, 2001, 10, 31, hours, minutes, seconds, microseconds) print time(1,2,3,4) # => 0001-02-03 04:00:00 print time() # => TypeError: function takes at least 3 arguments (0 given) What happens to the default arguments to time.__init__? What happens to the 2001, 10, 31 arguments to datetime.__init__? I would expect the output to be 2001-10-31 01:02:03.000004 2001-10-31 00:00:00.000000 Kent From peter at somewhere.com Wed Jan 26 06:55:38 2005 From: peter at somewhere.com (Peter Maas) Date: Wed, 26 Jan 2005 12:55:38 +0100 Subject: "pickle" vs. f.write() In-Reply-To: References: Message-ID: Johan Kohler schrieb: > class person: > name ="" > age = 0 > friends=[] > comment="""""" > > me = person() > > Otherwise, what is the best "Python" way to write and read this data > structure? import pickle class person: name ="" age = 0 friends=[] comment="""""" me = person() # store pf = file('/tmp/pickletest', 'w') pickle.dump(me, pf) pf.close() # load pf = file('/tmp/pickletest', 'r') me2 = pickle.load(pf) pf.close() This is sequential access. If you want to have random access, look for shelve. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From adam at cognitcorp.com Thu Jan 6 17:58:03 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Thu, 06 Jan 2005 17:58:03 -0500 Subject: Download .jpg from web In-Reply-To: References: Message-ID: <1105052283.3737.9.camel@localhost.localdomain> On Thu, 2005-01-06 at 13:49, GMane Python wrote: > Hello All. > Using a network camera with built-in webserver, I'd like to have a python > program download .jpg files on a local lan. the location is > http:///jpg/image.jpg. > > Currently, I'm importing urllib and using urlopen to the address, then > read()-ing it, saving it to a binary file. All that is working great, but > maybe a bit slowly. I'm getting ~2.3 frames per second, and would like > between 5-10 frames per second. I don't think that connection persistance is the problem you are facing. Perhaps the camera's TCP stack is really slow, but I just don't see the overhead of reconnecting being anywhere near high enough to account for the difference between what you have and what you think you should have. * What kind of camera are you using ... is it capable of handling more frames per second? I sounds like what you really want is a camera that can stream an avi or mpeg. * What is the bandwidth between the camera cluster and your server and what is the average size of an image? Lets be sure you are not bandwidth constrained. * Are you doing any post processing on these images? If all you are doing is: open( "somefilename.jpg").write( urllib.open( ... ).read() ) then what you are looking to do is a premature optimization. Also, you may want to consider saving the images in a format other than a stream or jpegs. The Ogg Vorbis Theora codec is pretty mature right now and, assuming that consequtive images are similar, will compress way better than just saving jpegs. - Adam > > Am I approaching this incorrectly? I have to do a urlopen, then .read() > for each image. Is there any way to 'persist' the urlopen so I just have to > keep read()-ing or maybe is there a type of streaming read? I have many > cameras, so there are many threads simultaneously reading and dropping them > in a central Queue for saving later. > > I appreciate it! > -Dave > > WebImage = urllib.urlopen("http:///jpg/image.jpg").read() > QueuePacket = [] > QueuePacket.append(WebImage) > Adam DePrince From maxm at mxm.dk Fri Jan 14 05:09:12 2005 From: maxm at mxm.dk (Max M) Date: Fri, 14 Jan 2005 11:09:12 +0100 Subject: oddities in the datetime module Message-ID: <41e79a1a$0$264$edfadb0f@dread12.news.tele.dk> # -*- coding: latin-1 -*- """ I am currently using the datetime package, but I find that the design is oddly asymmetric. I would like to know why. Or perhaps I have misunderstood how it should be used? I can make a datetime easily enough >>> datetime(2005, 1, 1) datetime.datetime(2005, 1, 1, 0, 0) What I find odd is that I cannot make a new datetime object from the timetuple() like this: >>> d1 = datetime(2005, 1, 1, 12, 13, 10) >>> d2 = datetime(*d1.timetuple()) Traceback (most recent call last): ... TypeError: function takes at most 8 arguments (9 given) >>> d1.timetuple() (2005, 1, 1, 12, 13, 10, 5, 1, -1) Because if I subclass datetime, I often need to convert between my subclass and the built in datetime module. But there is no direct way to do it. Instead I have to do it in a somewhat more clunky way: >>> datetime(* (d1.timetuple()[:6] + (0, d1.tzinfo))) datetime.datetime(2005, 1, 1, 12, 13, 10) if I want to convert a date to a datetime it is easy, even though I still have to truncate the timetuple. >>> d = date(2005, 1, 1) >>> datetime(*d.timetuple()[:6]) datetime.datetime(2005, 1, 1, 0, 0) The other way around is also easy. >>> dt = datetime(2005, 1, 1, 12, 0, 0) >>> date(*dt.timetuple()[:3]) datetime.date(2005, 1, 1) But it's a clunky design that I have to do it that way. I think it would be nice if date and datetime at least had a pair of datetimetuple() and from_datetimetuple() methods that could be used for easily converting between datetime types. Like the ones I have made below. That would make them a lot more symmetric. >>> datetimetuple = (2005,1,1,12,0,0,0,None) >>> datetime2.from_datetimetuple(datetimetuple) datetime2(2005, 1, 1, 12, 0) >>> dtt = datetime2(2005,1, 1).datetimetuple() >>> dtt (2005, 1, 1, 0, 0, 0, 0, None) >>> d2 = date2.from_datetimetuple(dtt) >>> d2 date2(2005, 1, 1) >>> datetime2.from_datetimetuple(d2.datetimetuple()) datetime2(2005, 1, 1, 0, 0) """ from datetime import datetime, date class datetime2(datetime): def datetimetuple(self): return self.timetuple()[:6] + (0, self.tzinfo) def from_datetimetuple(dt_tuple): return datetime2(*dt_tuple) from_datetimetuple = staticmethod(from_datetimetuple) class date2(date): def datetimetuple(self): return self.timetuple()[:6] + (0, None) def from_datetimetuple(dt_tuple): return date2(*dt_tuple[:3]) from_datetimetuple = staticmethod(from_datetimetuple) #from datetime import datetime # #ical = Calendar() #print ical.ical() if __name__ == "__main__": import os.path, doctest, x # import and test this file doctest.testmod(x) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From chrisdewinN0SPAM at yahoo.com.au Fri Jan 28 17:21:24 2005 From: chrisdewinN0SPAM at yahoo.com.au (Dfenestr8) Date: Sat, 29 Jan 2005 08:21:24 +1000 Subject: An mysql-python tutorial? Message-ID: Hi. Been told by the admin of my (free!) server that he'd rather I should learn to use mysql if I want to continue writing cgi scripts there. Not even sure exactly what mysql is. Is there a simple tutorial anywhere on the web about using python + mysql? From http Fri Jan 7 05:08:02 2005 From: http (Paul Rubin) Date: 07 Jan 2005 02:08:02 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41dcf582.122188317@news.oz.net> <7xd5wh7qdf.fsf@ruckus.brouhaha.com> <7xpt0h66yf.fsf@ruckus.brouhaha.com> Message-ID: <7x65291ri5.fsf@ruckus.brouhaha.com> adamc writes: > I've not experienced problems installing wxPython on Debian (unstable). > It just *works* out of the box with apt-get. Perhaps this is more of a > problem with the package maintainers? I think the problem I encountered was that the version of WxWidgets currently on the WxWidgets.com site was trying to use some obsolete function in GTK. If Debian is using an older version of GTK than what comes with FC3, then it might work. From detlev at die-offenbachs.de Sun Jan 23 10:34:54 2005 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 23 Jan 2005 16:34:54 +0100 Subject: ANN: eric3 3.6.0 released Message-ID: Hi, this is to let you know about a new release of eric3, the Python IDE. It has a bunch of new functions. The most prominent ones are listed below. - added some dialog wrappers that make eric3 use KDE dialogs, if KDE and PyKDE are installed - added a previewer for UI files - added a previewer for translation files - added a "Continue to cursor" command to the debugger - added view profiles and a correspondig configuration dialog - added capability to show the coverage annotations in the editor - added capability to select the protocol of the VCS server at login time - added support for alternative keyboard shortcuts - changed variables viewer to keep the state of the tree while debugging - added multiple selection capabilities to the browsers - added capability to enter variables filter patterns to the variables viewer windows - added an icon previewer to the configuration dialog icons page and some more little things. It is available via http://www.die-offenbachs.de/detlev/eric3.html I hope you enjoy it. What is eric3 ------------- eric3 is Python IDE written using the PyQt wrappers. If the PyKDE wrappers are installed as well, it will work as a KDE application and use KDE dialogs. It has a built in debugger, profiler, help viewer, unlimited number of editors with syntax highlighting, autocompletion and many more. Eric3 interfaces to CVS and subversion and has a built in documentation generation facility. For all the other details and snapshots please see the above URL. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From michele.simionato at gmail.com Tue Jan 11 05:06:06 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 11 Jan 2005 02:06:06 -0800 Subject: python and macros (again) [Was: python3: 'where' keyword] Message-ID: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> Paul Rubin wrote: > How about macros? Some pretty horrible things have been done in C > programs with the C preprocessor. But there's a movememnt afloat to > add hygienic macros to Python. Got any thoughts about that? "Movement" seems quite an exaggeration. Maybe 2-3 people made some experiments, but nobody within the core Python developers seems to be willing to advocate the introduction of macros. > Why should you care whether the output of a macro is ugly or not, > if no human is ever going to look at it? But at least some human eye have to look at it! Did you ever debug a macro? More seriuosly, I have given some thought to the issue, and I am very much against the introduction of macros in Python. Here are a few reasons: 1. I like defmacro in Lisp. Problem is, Lisp is an s-expression based language, Python is not. We cannot implement defmacro in Python and even if we could, if would be too ugly to be used (at least, IMHO). 2. One could proposed hygienic pattern-matching macros in Python, similar to Scheme syntax-rules macros. Again, it is not obvious how to implement pattern-matching in Python in a non-butt-ugly way. Plus, I feel hygienic macros quite limited and not worth the effort. 3. We would add to Python the learning curve of macros and their subtilities and we do not want it. 4. Macros would complicate a lot Python module system. 5. We have Guido providing a good syntax for us all, why we should be fiddling with it? More seriously, if some verbosity is recognized in the language (think to the "raison d'etre" of decorators, for instance) I very much prefer to wait for Guido to take care of that, once and for all, than having 100 different custom made solutions based on macros. I am sure I could find other reasons if I think a bit more, but these should suffice for the moment ;) What I would be interested in is a Lisp/Scheme implementation compiling to Python bytecode, but I am not aware of any project in that direction. Michele Simionato P.S. some pointers for people interested on the topic: http://logix.livelogix.com/ (a Python-like language with macros) https://sourceforge.net/projects/pymac/ (an experimental Dylan-inspired macro system for Python) From Sibylle.Koczian at Bibliothek.Uni-Augsburg.de Mon Jan 24 10:37:54 2005 From: Sibylle.Koczian at Bibliothek.Uni-Augsburg.de (Sibylle Koczian) Date: Mon, 24 Jan 2005 16:37:54 +0100 Subject: Right place for third party modules (here: fixedpoint) Message-ID: <35kj2iF4n6sokU1@news.dfncis.de> Hello, for the first time since getting Python I can't get a third party module to work. I got fixedpoint.0.1.2.tar.gz from SourceForge for use with KinterbasDB. After unpacking I had a directory called "fixedpoint" which I put under my site-packages directory. There are no installation instructions and just the one module fixedpoint.py (and some documentation and examples). All of this under Windows XP, with Python 2.4. Now I try to use the module, but import fixedpoint says "ImportError: No module named fixedpoint". I suppose fixedpoint is no package as described in the tutorial and so "site-packages" might not be the right place for it. But where does it belong? I think it should go somewhere in the Python directory tree, not among my own scripts. Thank you, Koczian -- Dr. Sibylle Koczian Universitaetsbibliothek, Abt. Naturwiss. D-86135 Augsburg Tel.: (0821) 598-2400, Fax : (0821) 598-2410 e-mail : Sibylle.Koczian at Bibliothek.Uni-Augsburg.DE From j-clark at lineone.net Fri Jan 7 13:10:30 2005 From: j-clark at lineone.net (Jonathan Clark) Date: 7 Jan 2005 10:10:30 -0800 Subject: HTML purifier using BeautifulSoup? In-Reply-To: References: Message-ID: <1105121430.950052.97940@z14g2000cwz.googlegroups.com> Dan Stromberg wrote: > Has anyone tried to construct an HTML janitor script using BeautifulSoup? > > My situation: > > I'm trying to convert a series of web pages from .html to palmdoc format, > using plucker, which is written in python. The plucker project suggests > passing html through "tidy", to get well-formed html for plucker to work > with. > > However, some of the pages I want to convert are so bad that even tidy > pukes on them. > > I was thinking that BeautifulSoup might be more tolerant of really bad > html... Which led me to the question this article started out with. :) > > Thanks! I have used BeautifulSoup for screen scraping, pulling html into structured form (using XML). Is that similar to a janitor script? I used it because tidy was puking on some html. BS has been excellent. From xah at xahlee.org Mon Jan 17 12:43:19 2005 From: xah at xahlee.org (Xah Lee) Date: 17 Jan 2005 09:43:19 -0800 Subject: [perl-python] 20050117, filter, map In-Reply-To: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> Message-ID: <1105983799.202346.9710@f14g2000cwb.googlegroups.com> erratum: the Mathematica Apply should've been Select. ... Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From ramen at lackingtalent.com Mon Jan 31 01:57:50 2005 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 31 Jan 2005 06:57:50 -0000 Subject: Nested scopes and class variables Message-ID: I ran into an odd little edge case while experimenting with functions that create classes on the fly (don't ask me why): >>> def f(x): ... class C(object): ... x = x ... print C.x ... >>> f(5) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in f File "", line 3, in C NameError: name 'x' is not defined "x" clearly is defined, but apparently Python is not looking at the nested variable scope to find it. What's stranger is that if I rename the parameter "x" to "y", the error goes away: >>> def f(y): ... class C(object): ... x = y ... print C.x ... >>> f(5) 5 So, it's not like nested scopes aren't supported in the class block. Rather, when it sees "x = x", it seems like Python is determining at that point that "x" is a class variable, and refuses to search any further. At the top-level, it works as expected: >>> x = 5 >>> class C(object): ... x = x ... >>> C.x 5 Any implementation gurus have some insight into what's going on here? -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. "talking about music is like dancing about architecture." From removethis.kartic.krishnamurthy at gmail.com Sat Jan 29 01:41:37 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Sat, 29 Jan 2005 06:41:37 GMT Subject: An mysql-python tutorial? In-Reply-To: References: Message-ID: Dfenestr8 said the following on 1/28/2005 5:21 PM: > Hi. > > Been told by the admin of my (free!) server that he'd rather I should > learn to use mysql if I want to continue writing cgi scripts there. > > Not even sure exactly what mysql is. > > Is there a simple tutorial anywhere on the web about using python + mysql? Did you try googling? There are two items in the very first page that should be of use to you. One is the Python-MySQL module, which you should have installed. http://sourceforge.net/projects/mysql-python There is an examples directory that has some concrete stuff to help you learn. Another hit is a basic tutorial, simple to follow and learn :- http://images.devshed.com/Server_Side/Python/PythonMySQL/PythonMySQL.pdf And here is one more site, good stuff here too:- http://www.kitebird.com/articles/pydbapi.html You might also want to check the "Charming Python" pages at IBM.com but I dont know if they have articles covering mysql. HTH! Thanks, --Kartic From mfuhr at fuhr.org Sat Jan 8 18:36:18 2005 From: mfuhr at fuhr.org (Michael Fuhr) Date: 8 Jan 2005 16:36:18 -0700 Subject: printing line numbers for debugging purpose References: Message-ID: <41e06e72$1_1@omega.dimensional.com> "Philippe C. Martin" writes: > All of the methods from my program return None on error (i.e; I do not > want to assert and have the program exit). > > Is it possible to print the current source file name/line number ? Someone else posted an example using an exception handler. See also the traceback module. -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From jerf at jerf.org Sun Jan 16 08:08:04 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 16 Jan 2005 08:08:04 -0500 Subject: Newbie inheritance question. References: Message-ID: On Sun, 16 Jan 2005 22:08:13 +0800, bwobbones wrote: > Hi all, > > I'm a java programmer struggling to come to terms with python - bear > with me! Christophe already identified the problem, I wanted to address another Javaism in your code, for your educational benefit. Speaking "idiomatically" (since this is all small sample code), in Python you'd normally code your driver as follows: ---------- import two t = two() # or something, there's a name conflict here, too many "two"s t.printHello() t.printTestVar() ---------- Things that aren't objects shouldn't be forced to be objects and I don't think there is any shame in having a non-OO top level. (I go on about this at http://www.jerf.org/writings/bowersLaw.html#4 in more detail.) From arobert at townisp.com Wed Jan 5 10:58:42 2005 From: arobert at townisp.com (Andrew Robert) Date: Wed, 05 Jan 2005 10:58:42 -0500 Subject: screen clear question In-Reply-To: References: <10teqpdvramua3@corp.supernews.com> <8ucft0tf456g07iuuavgu31m6dhrgjbmh3@4ax.com> Message-ID: <10to3kns044v63f@corp.supernews.com> Nick Coghlan wrote: > Alan Gauld wrote: > >> But the bottom line is that there is no builtin command because the >> mechanism is different on each platform. > > > I'd have said it was because the inpreter is line-oriented rather than > screen-oriented, but YMMV. > > Cheers, > Nick. > I would try doing a test against the resident OS the program is running against and set the clear command based on that. -- Thank you, Andrew Robert E-mail: arobert at townisp.com Ur: http://shardservant.no-ip.info From skip at no-spam.net Thu Jan 6 04:24:02 2005 From: skip at no-spam.net (skip) Date: Thu, 6 Jan 2005 04:24:02 -0500 Subject: navigating/changing directories Message-ID: A simple script like the one below lets me jump through a directory structure. However, if I run it from /this/directory and within it to go to /a/totally/different/directory... I'm still actually going to be in /this/directory when I exit the script. Is it possible to have a script that can drop me off into a different directory than where I initiated it from? import os process = 1 while (process): # Display directories for i in os.listdir(os.getcwd()): if (os.path.isdir(os.path.join(os.getcwd(),i))): print i # Change directory goto_dir = raw_input(": ") if (goto_dir in os.listdir(os.getcwd())): os.chdir(os.path.join(os.getcwd(),goto_dir)) else: process = 0 # Exit From Dennis.Benzinger at gmx.net Tue Jan 25 18:42:40 2005 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Wed, 26 Jan 2005 00:42:40 +0100 Subject: string.atoi and string.atol broken? In-Reply-To: References: Message-ID: <41f6d96f$1@news.uni-ulm.de> Mike Moum wrote: > I think there may be a bug in string.atoi and string.atol. Here's some > output from idle. > > >>Python 2.3.4 (#2, Jan 5 2005, 08:24:51) >>[GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2 >>Type "copyright", "credits" or "license()" for more information. >> >> **************************************************************** >> Personal firewall software may warn about the connection IDLE >> makes to its subprocess using this computer's internal loopback >> interface. This connection is not visible on any external >> interface and no data is sent to or received from the Internet. >> **************************************************************** >> >>IDLE 1.0.4 >> >>>>>import string as s >>>>>s.atoi('2',3) >> >>2 >> >>>>>s.atoi('4',3) >> >>Traceback (most recent call last): >> File "", line 1, in -toplevel- >> s.atoi('4',3) >> File "/usr/lib/python2.3/string.py", line 220, in atoi >> return _int(s, base) >>ValueError: invalid literal for int(): 4 >> >>>>>s.atoi('12',11) >> >>13 >> >>>>>s.atoi('13',4) >> >>7 >> >>>>>s.atoi('12',4) >> >>6 >> >>>>>s.atoi('8',4) >> >>Traceback (most recent call last): >> File "", line 1, in -toplevel- >> s.atoi('8',4) >> File "/usr/lib/python2.3/string.py", line 220, in atoi >> return _int(s, base) >>ValueError: invalid literal for int(): 8 >> > > s.atoi('4',3) should result in 11 > > s.atoi('13',4) should result in 31 > > s.atoi('12',4) should result in 30 > > s.atoi('8',4) is legitimate, but it generates an error. > > Is this a bug, or am I missing something obvious? > [...] That's not a bug, you'r missing something obvious. The second parameter of string.atoi (or the int builtin) is the base (or radix) in which the number you want to convert is given. For example string.atoi("777", 8) results in 511, because 7 * 8**2 + 7 * 8**1 + 7 * 8**0 = 511. Just out of curiosty: What did you think what atoi does? I don't understand how you came to expect that atoi('4',3) should result in 11. Bye, Dennis From http Tue Jan 11 01:46:01 2005 From: http (Paul Rubin) Date: 10 Jan 2005 22:46:01 -0800 Subject: reference or pointer to some object? References: Message-ID: <7x4qhoh39y.fsf@ruckus.brouhaha.com> Torsten Mohr writes: > i'd like to pass a reference or a pointer to an object > to a function. The function should then change the > object and the changes should be visible in the calling > function. Normally you would pass a class instance or boxed object, and let the function change the instance or object: def bump(b): b[0] += 123 # change x = [5] bump(x) print x # prints [128] From flamesrock at gmail.com Thu Jan 27 14:03:11 2005 From: flamesrock at gmail.com (flamesrock) Date: 27 Jan 2005 11:03:11 -0800 Subject: Question about 'None' Message-ID: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Well, after playing with python for a bit I came across something weird: The statement (1 > None) is false (or any other value above 0). Why is this? (The reason I ask is sortof unrelated. I wanted to use None as a variable for which any integer, including negative ones have a greater value so that I wouldn't need to implement any tests or initializations for a loop that finds the maximum of a polynomial between certain x values. Anything is greater than nothing, no?) From chris.cavalaria at free.fr Sat Jan 29 18:05:41 2005 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Sun, 30 Jan 2005 00:05:41 +0100 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) References: Message-ID: <362j65F4qsgbiU1@individual.net> Steven Bethard wrote: > Fuzzyman wrote: > > Cameron Laird wrote: > > [snip..] > > > >>This is a serious issue. > >> > >>It's also one that brings Tcl, mentioned several > >>times in this thread, back into focus. Tcl presents > >>the notion of "safe interpreter", that is, a sub- > >>ordinate virtual machine which can interpret only > >>specific commands. It's a thrillingly powerful and > >>correct solution to the main problem Jeff and others > >>have described. > > > > A better (and of course *vastly* more powerful but unfortunately only > > a dream ;-) is a similarly limited python virutal machine..... > > Yeah, I think there are a lot of people out there who would like > something like this, but it's not quite clear how to go about it. If > you search Google Groups, there are a lot of examples of how you can use > Python's object introspection to retrieve "unsafe" functions. > > I wish there was a way to, say, exec something with no builtins and with > import disabled, so you would have to specify all the available > bindings, e.g.: > > exec user_code in dict(ClassA=ClassA, ClassB=ClassB) > > but I suspect that even this wouldn't really solve the problem, because > you can do things like: > > py> class ClassA(object): > ... pass > ... > py> object, = ClassA.__bases__ > py> object > > py> int = object.__subclasses__()[2] > py> int > > > so you can retrieve a lot of the builtins. I don't know how to retrieve > __import__ this way, but as soon as you figure that out, you can then > do pretty much anything you want to. > > Steve Wouldn't it be better to attach to all code objets some kind of access right marker and to create an opcode that calls a function while reducing the access rights ? After all, security would be easier to achieve if you prevented the execution of all the dangerous code rather than trying to hide all the entry points to it. From tim.peters at gmail.com Fri Jan 21 10:24:16 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 21 Jan 2005 10:24:16 -0500 Subject: PyCon Preliminary Program Announced! In-Reply-To: References: <20050121000607.DE1261E4010@bag.python.org> <41F061C3.3000802@gmail.com> Message-ID: <1f7befae0501210724627c0f14@mail.gmail.com> [A.M. Kuchling] > Suggestions for improvement are welcome. Perhaps the Wiki version of > the schedule, at http://www.python.org/moin/PyConDC2005/Schedule, > may be better. It is, but the 2004 schedule was really what I had in mind (very readable!): http://www.python.org/pycon/dc2004/schedule.html From aahz at pythoncraft.com Sat Jan 29 11:57:45 2005 From: aahz at pythoncraft.com (Aahz) Date: 29 Jan 2005 11:57:45 -0500 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <41FB080E.1070308@iinet.net.au> Message-ID: In article , Skip Montanaro wrote: > > Nick> Upgrading your Python interpreter (even to a new maintenance > Nick> branch release) in a production environment is usually a fairly > Nick> involved exercise requiring a significant amount of testing, and > Nick> the fact of the matter is, you're unlikely to do so unless there > Nick> is some feature or bug-fix in a new version that you really > Nick> need. (I'm still using Python 2.2.2 at work - it's entirely > Nick> adequate for our needs, so there's no real pressure to upgrade on > Nick> the current project. For a new project, I'd probably start with > Nick> 2.4, planning to go to 2.4.1 in a couple of months time, but there > Nick> aren't really any post-2.2 additions to Python that I can't handle > Nick> living without). > >Still, if a security bug was serious enough, my guess is that someone would >step up to supply patches (or Windows installers) for any of a number of >versions that were affected by the bug, even 2.1 or 1.5.2. That someone >might or might not be part of the core development team. That nothing like >that has been done before doesn't preclude it being done in the future. While true, such coordination also requires public discussion, given the way the Python community works. Which obviates the OPs request for private correspondence. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From http Sat Jan 29 21:34:23 2005 From: http (Paul Rubin) Date: 29 Jan 2005 18:34:23 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <7xzmysqmxk.fsf@ruckus.brouhaha.com> <41fbcc01$0$12030$9b622d9e@news.freenet.de> Message-ID: <7xoef71w7k.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > mxCrypto is primarily unsuitable for the core because Marc-Andre Lemburg > will never ever contribute it. He is very concerned about including > crypto code with the Python distribution, so he certainly won't > contribute his own. Oh wait, I confused mxcrypto and m2crypto. Sorry. Anyway, the technical considerations are similar. From wordsender at gmail.com Thu Jan 6 01:22:48 2005 From: wordsender at gmail.com (wordsender at gmail.com) Date: 5 Jan 2005 22:22:48 -0800 Subject: file.readlines() - gives me error (bad file descriptor) Message-ID: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> Hey guys, I can't figure this one out, why is this simple script giving me problems? logfile=file(r'test.txt','w') logfile.write('datetime') test=logfile.readlines() When I run it I get the error message: Traceback (most recent call last): File "C:\Documents and Settings\Gregory\My Documents\Get New Great Job\testfile.py", line 3, in ? test=logfile.readlines() IOError: [Errno 9] Bad file descriptor I'm running Windows XP, Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 Any help would be greatly appricated. Thanks, Greg From alan.gauld at btinternet.com Fri Jan 7 19:36:43 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Jan 2005 00:36:43 +0000 (UTC) Subject: Securing a future for anonymous functions in Python References: Message-ID: On Fri, 07 Jan 2005 08:44:57 -0700, Steven Bethard wrote: > > The unfamiliar argument doesn't work for me. After all most > > people are unfamiliar with complex numbers (or imaginary) numbers > > complex numbers. Lambdas, on the other hand, show up in all kinds of > code, and even though I hardly ever use them myself, I have to > understand them because other people do (over-)use them. That's a fair point I suppose but I still don't see much point in introducing new names and syntaxes when the existing name is a sensible one, even if unfamiliar to many. After all it works in Lisp and Haskell - Haskell even uses Lambda as its emblem... And besides it may just encoursage some to go and explore Lambda calculus, it did for me... And my programing improved enormously as a result. So maybe having the name as a stimulant to research is a good thing... OTOH I do accept the point made by another poster that Pythons single expression limitations mean that they are a poor imitation of lambdas in other languages. And provided I get some kind of anonymous code block to pass around I don't care too much if the name lambda disappears, provided the concept remains! And the syntax is reasonably simple to use where lambdas get used now. (Without lambdas of any kind I might finally make the jump to Ruby that I've been toying with for a while but I just hate those Perl-like @ symbols...) We often see people stating that programming shouldn't be called a science because there is no mathematical basis, such claimants usually haven't seen Predicate or Lambda calculus. I know, I used to be in that category and while I don't explicitly use either when programming (or only rarely) awareness of the principles suddenly made a lot of the "rules of programming" that I'd been taught make perfect sense (no side-effects, avoid globals, etc) Its like the fact that I rarely use Maxwell's equations when designing electronic circuits - but its nice to know what the underlying theory is actually based on! All IMHO of course! :-) Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From francis.girard at free.fr Wed Jan 26 17:41:07 2005 From: francis.girard at free.fr (Francis Girard) Date: Wed, 26 Jan 2005 23:41:07 +0100 Subject: Classical FP problem in python : Hamming problem In-Reply-To: References: <63b5e209.0501210558.686f5c10@posting.google.com> <200501241624.41889.francis.girard@free.fr> Message-ID: <200501262341.07327.francis.girard@free.fr> Le mardi 25 Janvier 2005 09:01, Michael Spencer a ?crit?: > Francis Girard wrote: > > The following implementation is even more speaking as it makes > > self-evident and almost mechanical how to translate algorithms that run > > after their tail from recursion to "tee" usage : > > Thanks, Francis and Jeff for raising a fascinating topic. I've enjoyed > trying to get my head around both the algorithm and your non-recursive > implementation. > Yes, it's been fun. > Here's a version of your implementation that uses a helper class to make > the algorithm itself prettier. > > from itertools import tee, imap > > def hamming(): > def _hamming(): > yield 1 > for n in imerge(2 * hamming, imerge(3 * hamming, 5 * hamming)): > yield n > > hamming = Tee(_hamming()) > return iter(hamming) > > > class Tee(object): > """Provides an indepent iterator (using tee) on every iteration > request Also implements lazy iterator arithmetic""" > def __init__(self, iterator): > self.iter = tee(iterator,1)[0] > def __iter__(self): > return self.iter.__copy__() > def __mul__(self, number): > return imap(lambda x: x * number,self.__iter__()) > > def imerge(xs, ys): > x = xs.next() > y = ys.next() > while True: > if x == y: > yield x > x = xs.next() > y = ys.next() > elif x < y: > yield x > x = xs.next() > else: # if y < x: > yield y > y = ys.next() > > >>> hg = hamming() > >>> for i in range(10000): > > ... n = hg.next() > ... if i % 1000 == 0: print i, n > ... > 0 1 > 1000 51840000 > 2000 8100000000 > 3000 279936000000 > 4000 4707158941350 > 5000 50960793600000 > 6000 409600000000000 > 7000 2638827906662400 > 8000 14332723200000000 > 9000 68024448000000000 > > Interesting idea. > Regards > > Michael From invalidemail at aerojockey.com Thu Jan 6 19:12:54 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 6 Jan 2005 16:12:54 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: <1105056774.393244.199250@f14g2000cwb.googlegroups.com> Arich Chanachai wrote: > But > then again, if you don't like C++, you probably won't like Java. They > can be very different languages, but in my experience, the reasons why > one does not like C++ is usually due to a quality/flaw that can also be > found in Java. Oh, brother. The Zen of Python says that "simple is better than complex" and "complex is better than complicated". Java does pretty well here. C++ didn't even get "complicated is better than convoluted" right. There's are a ton of flaws in C++ not found in Java. -- CARL BANKS From cam.ac.uk at mh391.invalid Mon Jan 17 18:38:28 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 17 Jan 2005 23:38:28 +0000 Subject: how to find site-packages path In-Reply-To: References: Message-ID: Philippe C. Martin wrote: > I am using my own install script for my software and am looking for a > flawless way to figure out where python, and more specifically > site-packages is installed. The flawless way would be to use distutils. In fact you shouldn't even need your own install script--it should do most of the work for you. -- Michael Hoffman From tundra at tundraware.com Sat Jan 22 06:08:21 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 22 Jan 2005 06:08:21 EST Subject: Comments in configuration files In-Reply-To: <41f20f4a$0$6599$8fcfb975@news.wanadoo.fr> References: <41f20f4a$0$6599$8fcfb975@news.wanadoo.fr> Message-ID: Pierre Quentel wrote: > Bonjour, > > I am developing an application and I have a configuration file with a > lot of comments to help the application users understand what the > options mean > > I would like it to be editable, through a web browser or a GUI > application. With ConfigParser I can read the configuration file and > edit the options, but when I write the result all the comments are lost > > Are there modules that work on the same kind of ini files (for the needs > of my application, I prefer this format to XML or YAML) and don't remove > the comments ? > > TIA, > Pierre The latest incarnation of 'tconfpy' I just released will get you close: http://www.tundraware.com/Software/tconfpy This program can read a configuration either from memory (a list) or a file. So you could: 1) Read the file into an in-memory list (including the comments). 2) Pass the list to the parser, which would return a populated symbol table. 3) Use your application to read the current values of the symbols from the symbol table. 4) Modify the values in the symbol table as desired. 5) Map the new values in the symbol table back into the original list where the values were set intitially (this is the part that would take some work). 6) Write the list back to disk. Note that the semantics of feature of 'tconfpy' are substantially different than 'ConfigParser', and the languages recognized by each are quite different as well. It is probably fair to say that 'tconfpy' recognizes a superset of the language recognized by 'ConfigParser'. But you have to be careful because the semantics are somewhat different. -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From a at b.c Sat Jan 1 21:13:12 2005 From: a at b.c (Doug Holton) Date: Sat, 01 Jan 2005 20:13:12 -0600 Subject: What can I do with Python ?? In-Reply-To: <1bkzoh3dskuit$.ppe264krg156$.dlg@40tude.net> References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> <1bkzoh3dskuit$.ppe264krg156$.dlg@40tude.net> Message-ID: BOOGIEMAN wrote: > Thanks everybody, I downloaded latest windows version and > Python-Docs-2.4 archive. Is that enough for absolute beginner. > Is there any e-book, step by step guide ... etc for download, > or anything else important what I have to know before I start > learning Python ? The main thing I would do is subscribe to the python-tutor list. It is the best place by far to ask any questions when you are learning to use python: http://mail.python.org/mailman/listinfo/tutor Second, here are some of the best tutorials specifically designed for people with little or no previous programming experience: http://www.honors.montana.edu/~jjc/easytut/easytut/ http://www.freenetpages.co.uk/hp/alan.gauld/ http://www.dickbaldwin.com/tocpyth.htm http://www.ibiblio.org/obp/pyBiblio/ And lastly, really a great way to learn is to look at what's already out there in python. Try out some of the many 3rd party libraries and programs for python: For games: http://pygame.org/ For GUI applications: http://www.wxpython.org/ and others: http://www.python.org/pypi From itsme at yahoo.com Wed Jan 5 13:31:03 2005 From: itsme at yahoo.com (It's me) Date: Wed, 05 Jan 2005 18:31:03 GMT Subject: win32com.client problem Message-ID: I've been using the win32com module with very good success in placing data onto an Excel spreadsheet. However, whenever I have an error in my script (like mapping a non-square array onto the spreadsheet), something breaks. After fixing my error and restart the Python program again, Excel would start up a window with a "Microsoft Excel - BookX" where X is a increasing number (1,2,3,4,....) instead of just 1. Then, the spreadsheet portion of the screen is hidden - I can only see the menu bars (on top). If I restart the computer, run the Python script again and Excel would behave fine and it would start with "Microsoft Excel - Book1" everytime. My guess is that there is a zombie Excel process that got stuck in the system. However I couldn't tell for sure by looking at the Process Manager list. Any idea how I can prevent this? Thanks, -- Me From peter at somewhere.com Thu Jan 6 10:05:50 2005 From: peter at somewhere.com (Peter Maas) Date: Thu, 06 Jan 2005 16:05:50 +0100 Subject: Embedding a restricted python interpreter In-Reply-To: References: <41db7e8f$1@news.unimelb.edu.au> Message-ID: Craig Ringer schrieb: > That is my understanding. In fact, I'd say with Python it's nearly > impossible given how dynamic everything is and the number of tricks that > can be used to obfuscate what you're doing. Think of the fun that can be > had with str.encode / str.decode and getattr/hasattr . It would certainly be difficult to track all harmful code constructs. But AFAIK the idea of a sandbox is not to look at the offending code but to protect the offended objects: files, databases, URLs, sockets etc. and to raise a security exception when some code tries to offend them. Jython is as dynamic as C-Python and yet it generates class files behaving well under the JVM's security regime. > > I looked into this, and my conclusion ended up being "Well, I'm using > Python because I want it's power and flexibilty. If I want a secure > scripting environment, I should use something like Lua or Qt Script for > Applications instead." It would be good for Python if it would offer a secure mode. Some time ago I asked my hosting provider whether I could use mod_python with apache to run Python scripts in the same way as PHP scripts. He denied that pointing to Python security issues and to PHP safe. mode. Python IS powerful but there are many areas where it is of vital interest who is allowed to use its power and what can be done with it. I think it would be a pity to exclude Python from these areas where a lot of programming/computing is done. Python is a very well designed language but progress is made by criticism not by satisfaction ;) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From steven.bethard at gmail.com Wed Jan 12 13:49:14 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 11:49:14 -0700 Subject: Iteration over two sequences In-Reply-To: <1gq9z5q.1x7si1us4kgmcN%news+0409@henrikholm.com> References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> <1105549514.563799.307030@z14g2000cwz.googlegroups.com> <1gq9z5q.1x7si1us4kgmcN%news+0409@henrikholm.com> Message-ID: <1oOdnQ8ciYG07HjcRVn-gQ@comcast.com> Henrik Holm wrote: > John Lenton wrote: > > >>>def dotproduct(a, b): >>> psum = 0 >>> for i in range(len(a)): >>> psum += a[i]*b[i] >>> return psum >> >>for this particular example, the most pythonic way is to do nothing at >>all, or, if you must call it dotproduct, >> >>>>>from Numeric import dot as dotproduct > > > Downloading, installing, and getting to know numerical modules for > Python is mext on my list :). However, I was under the impression that > Numarray is preferred to Numeric -- is that correct? Are these two > competing packages? (Hopefully this is not flame war bait...) > Numarray is the replacement for Numeric. Some people are still using Numeric for a variety of reasons, e.g. they use a package that has not been updated to use numarray, they can't afford the performance penalty that numarray has for small arrays, etc. Steve From generate at gmail.com Tue Jan 4 15:52:54 2005 From: generate at gmail.com (generate at gmail.com) Date: 4 Jan 2005 12:52:54 -0800 Subject: Working with flat files [LDIF]. In-Reply-To: <33A3E2B3.7F5CF6F0@whoi.edu> References: <33A3E2B3.7F5CF6F0@whoi.edu> Message-ID: <1104871974.248122.102230@f14g2000cwb.googlegroups.com> Scott A. McIntyre wrote: > > I looked around but didn't see any LDIF tools for perl or python... > > Any assistance or advice is appreciated!! > > Scott Hello Scott, Did you ever get this issue resolved? I have a similar need to merge two LDIF files. I did find a program called mmldif, but I believe it is proprietary to Sun. Cheers, Charles From rroberts at adobe.com Thu Jan 27 15:47:46 2005 From: rroberts at adobe.com (Read Roberts) Date: Thu, 27 Jan 2005 12:47:46 -0800 Subject: Problem with win32net on Windows 2K Message-ID: I am trying to use win32net on a Windows 2000 Japanese system, and discover that it won't import. I found a message describing the problem (see below) but can't find any response, and don't see a bug report on the SourceForge site for this. . Can anyone tell me if this has ben fixed? An early message in 2000 said that win32net is supposed to run on Windows 2000 I find the same problem reported, with more detail, on the py2exe user list, where Thomas Heller commented on 2004-08-26 : > Here"s the rest of the trackback: > File "netbios.pyc", line 1, in ? > File "win32wnet.pyc", line 9, in ? > File "win32wnet.pyc", line 7, in __load > ImportError: DLL load failed: The specified procedure could not be found. The procedure entry point LsaLookupNames2 could not be located in the dynamic link library ADVAPI32.dll This looks like the win32net Python extension requires the LsaLookupNames2 function in ADVAPI32, but this is only available in WinXP and Win2003 Server, according to MSDN, preventing to use win32net on win2k. You should report this to Mark Hammond, and maybe use a later version of pywin32 for now. Thomas From http Fri Jan 28 04:23:51 2005 From: http (Paul Rubin) Date: 28 Jan 2005 01:23:51 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> Message-ID: <7x4qh13o0o.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > And I still stand by those blanket statements. Any new module (i.e. > specific code) should see real users for some time before it can > be incorporated into Python. Let's see, the urandom module was recently released in 2.4, I think initially at my urging. I believe it was written just for 2.4, combining a Windows function used only (as far as I know) by its author, and a wrapper to read /dev/urandom on Posix systems. It didn't have any wide distribution or use before incorporation, and didn't need it. It was simple enough that a reasonable code review and some testing on the relevant platforms was enough to make make sure it worked properly. > > I would say the first thing I'd request would be your sense of how > > plausible it is that the current no-crypto policy might be relaxed. > > There is no such policy in force. Different people have different > opinions, and those opinions change over time. I cannot speak for others. If you can't speak for others, how can you say there's no policy in force? If Guido says "no crypto", is that something other than a policy? And are you speaking for him when you say that? > proposed feature is good, and I said that, for an example, IETF even > requires *two* implementations before deciding that the feature is good. No, that's completely wrong. IETF requires two implementations before publishing a specification--a precise description--as a draft standard, which means agreeing on how the feature should work at the finest level of detail. That's much different than merely deciding that a feature is good and inviting people to work on it. IETF often decides and announces that a feature is good long before any such details are decided or agreed on. For example, they decided that IP connection encryption was a good feature, and appointed a working group a general mandate to go figure out the details (IPSEC) and write a spec. See? IETF announced in advance that IPSEC was a good feature, and the working group members knew of that decision before they committed the resources needed to write the draft. And when they started, there were zero actual IPSEC implementations, because nobody knew what precise characteristics IPSEC would eventually have. The implementations got written in the process of developing the spec and presenting it as a standard. The two-implementation policy means there has to be two implementations before the draft is finally declared complete, not before the IETF can announce that it wants a standard to be written and intends to use whatever the working group comes up with once the draft and two implementations are done. That is what happens in any normal professional process. Nobody commits resources to develop something (other than for experimentation) unless they think the end result will actually be used. Are you really having trouble understanding this? > >>That's not true. PyCrypto does have AES support. > > That's not in any Python distro that I know of. > > Sure, but "Python" is more than the Python core. Tell me again what "batteries included" means. I personally interpret "included" as meaning "included". That means when I install Python, the module is right there in the distro. So if it's not in the distro, Python itself doesn't have it. "Batteries included" is an expression of Pythonic philosophy that says: putting components that end-users need in the distro is superior to making the users get them from somewhere else separately. I realize that the difference might not matter to you, but it does matter to a heck of a lot of other users. > With that attitude, the patches tracker on SF would grow unbounded, > because we *continuously* get patches that no core developer has > any personal interest in. Obviously those require a different type of consideration. I'm talking about patches where there's a core developer with an interest. Let's say the cmath module doesn't exist and someone submits it. It computes functions like cos(z) for complex arguments. If Tim, the numerics expert, then says "this is worth having and I've examined the code and it looks good, let's put it in", I'd say that takes care of it, and I think that's what typically happens with real modules. If nobody on the core team has an informed opinion, then it has to be decided some slower and more formal way. From steve at holdenweb.com Mon Jan 17 12:50:06 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 12:50:06 -0500 Subject: How to prevent the script from stopping before it should In-Reply-To: <1105982387.852448.298900@c13g2000cwb.googlegroups.com> References: <1105981979.853318.269300@c13g2000cwb.googlegroups.com> <1105982387.852448.298900@c13g2000cwb.googlegroups.com> Message-ID: wittempj at hotmail.com wrote: > #import urllib, sys > #pages = ['http://www.python.org', 'http://xxx'] > #for i in pages: > # try: > # u = urllib.urlopen(i) > # print u.geturl() > # except Exception, e: > # print >> sys.stderr, '%s: %s' % (e.__class__.__name__, e) > will print an error if a page fails opening, rest opens fine > More generally you may wish to use the timeout features of TCP sockets. These were introduced in Python 2.3, though Tim O'Malley's module "timeoutsocket" (which was the inspiration for the 2.3 upgrade) was available for earlier versions. You will need to import the socket module and then call socket.setdefaulttimeout() to ensure that communication with non-responsive servers results in a socket exception that you can trap. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From peter at engcorp.com Sun Jan 23 19:12:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jan 2005 19:12:00 -0500 Subject: Set parity of a string In-Reply-To: References: Message-ID: snacktime wrote: > Is there a module that sets the parity of a string? I have an > application that needs to communicate with a host using even parity > So what I need is before sending the message, convert it from space to > even parity. And when I get the response I need to convert that from > even to space parity. By what means are the messages being delivered? I've rarely seen parity used outside of simple RS-232-style serial communications. Certainly not (in my experience, though it's doubtless been done) in TCP/IP based stuff. And if it's serial, parity can be supplied at a lower level than your code. As to the specific question: a module is not really required. The parity value of a character depends only on the binary value of that one byte, so a simple 128-byte substitution table is all you need, plus a call to string.translate for each string. -Peter From news at outbacklinux.com Tue Jan 11 03:25:48 2005 From: news at outbacklinux.com (Adrian Casey) Date: Tue, 11 Jan 2005 17:55:48 +0930 Subject: Command line and GUI tools : need a single threading solution References: <41e26e79@duster.adelaide.on.net> <34f9lfF4af717U1@individual.net> Message-ID: <41e38d8c@duster.adelaide.on.net> Diez B. Roggisch wrote: >> I'm thinking it may be possible to modify the command line tools to use >> qt >> threads instead of native python threads. Is this the way to go? Are >> there other options? > > Why don't you use python threads in qt - I do so and so far it didn't make > any troubles for me. And I would strongly advise against using qthreads > with your commandline-tools, as these then would only run on machines > where pyqt is installed - which opens a small part of "dependency hell" > for your users. > I have a QThread which polls a queue object via queue.get(). The command line tools spawn a number of threads each of which writes its output to this queue using queue.put(). As soon as the gui gets something off the queue, it creates a QCustomEvent and sets the data property with the data read from the queue. My application has a customEvent() method which reads the data item from the customEvent and processes it accordingly. The odd thing is, I have a non-threaded version of the command line tools which work 100% with the gui. The multi-threaded version of the command line tools all work OK at the console - just not with the gui. I will try your suggestion and replace my QCustomEvent mechanism with a plain python queue. From dalke at dalkescientific.com Fri Jan 7 01:04:01 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 07 Jan 2005 06:04:01 GMT Subject: Other notes References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> <41DD40F1.5030301@holdenweb.com> <41dda7c5.167823026@news.oz.net> Message-ID: Bengt Richter: > But it does look ahead to recognize += (i.e., it doesn't generate two > successive also-legal tokens of '+' and '=') > so it seems it should be a simple fix. But that works precisely because of the greedy nature of tokenization. Given "a+=2" the longest token it finds first is "a" because "a+" is not a valid token. The next token is "+=". It isn't just "+" because "+=" is valid. And the last token is "2". Compare to "a+ =2". In this case the tokens are "a", "+", "=", "2" and the result is a syntax error. > >>> for t in tokenize.generate_tokens(StringIO.StringIO('a=b+c; a+=2; x..y').readline):print t > ... This reinforces what I'm saying, no? Otherwise I don't understand your reason for showing it. > (51, '+=', (1, 8), (1, 10), 'a=b+c; a+=2; x..y') As I said, the "+=" is found as a single token, and not as two tokens merged into __iadd__ by the parser. After some thought I realized that a short explanation may be helpful. There are two stages in parsing a data file, at least in the standard CS way of viewing things. First, tokenize the input. This turns characters into words. Second, parse the words into a structure. The result is a parse tree. Both steps can do a sort of look-ahead. Tokenizers usually only look ahead one character. These are almost invariably based on regular expressions. There are many different parsing algorithms, with different tradeoffs. Python's is a LL(1) parser. The (1) means it can look ahead one token to resolve ambiguities in a language. (The LL is part of a classification scheme which summarizes how the algorithm works.) Consider if 1..3 were to be legal syntax. Then the tokenizer would need to note the ambiguity that the first token could be a "1." or a "1". If "1." then then next token could be a "." or a ".3". In fact, here is the full list of possible choices <1.> <.> <3> same as getattr(1., 3) <1> <.> <.> 3 not legal syntax <1.> <.3> not legal syntax <1> <..> <3> legal with the proposed syntax. Some parsers can handle this ambiguity, but Python's deliberately does not. Why? Because people also find it tricky to resolve ambiguity (hence problems with precedence rules). After all, should 1..2 be interpreted as 1. . 2 or as 1 .. 2? What about 1...2? (Is it 1. .. 2, 1 .. .2 or 1. . .2 ?) Andrew dalke at dalkescientific.com From aldo at nullcube.com Tue Jan 18 19:36:36 2005 From: aldo at nullcube.com (Aldo Cortesi) Date: Wed, 19 Jan 2005 11:36:36 +1100 Subject: inbuilt function buffer() In-Reply-To: <20050120101006.GA1496@mrna.tn.nic.in> References: <20050120101006.GA1496@mrna.tn.nic.in> Message-ID: <20050119003636.GA26701@nullcube.com> Thus spake km (km at mrna.tn.nic.in): > I which context is the inbuilt function buffer() used ? It's an efficiency measure. Say you have a string x. Taking a slice of the string - x[a:a+10] - will implicitly create a new string containing the specified data. Doing the same using buffer - buffer(x, a, 10) - will not. Essentially, buffer() gives you a window into a piece of contiguous data, without the cost of making a copy of the data you want to extract. To see how this might be useful, consider writing a simple web server. The web server reads a local file into memory, and then feeds it bit by bit to a socket until the data is exhausted. Without using buffer, the server would have to create a copy of each snippet of data fed to the socket. Using buffer, however, the copies are avoided, and the data can be consumed more efficently. The code below demonstrates this idea in an elementary fashion - on my system, "takebuf" runs about twice as fast as "take". ------ #!/usr/bin/env python2.3 import time SIZE = 1024*1024*50 data = "O"*SIZE def take(data): for i in range(0, SIZE, 1024): yield data[i:i+1024] def takebuf(data): for i in range(0, SIZE, 1024): yield buffer(data, i, 1024) def main(): start = time.time() for i in take(data): pass print "Plain:\t", time.time()-start start = time.time() for i in takebuf(data): pass print "Buffer:\t", time.time()-start if __name__ == "__main__": main() Cheers, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com Off: (02) 9283 1131 Mob: 0419 492 863 From tzot at sil-tec.gr Wed Jan 26 12:09:29 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 26 Jan 2005 19:09:29 +0200 Subject: string.atoi and string.atol broken? References: <0ttev01qgb9k6a9f34g185lhohkn2p3evq@4ax.com> <4mffv0dqtj0dpjtsqn7lcf46ndc4ei9bc5@4ax.com> Message-ID: On Wed, 26 Jan 2005 18:07:39 +0100, rumours say that "Fredrik Lundh" might have written: >> You're messing with the time machine again, right? > >no, it was a subversion pilot error, this time. but now that you remind me, >I have to say that this > > http://mail.python.org/pipermail/python-list/2005-February/030720.html > >is a bit scary. I wonder from where I was posting that? And this post is what I was referring to with "again". -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From f18m_cpp217828 at yahoo.it Fri Jan 14 10:01:13 2005 From: f18m_cpp217828 at yahoo.it (Francesco Montorsi) Date: Fri, 14 Jan 2005 16:01:13 +0100 Subject: How to list the global functions from a C program Message-ID: <001101c4fa49$e545a5c0$5c673452@genius> Hi all, I'm a Python newbie and I'm trying to add to my C++ program a limited support for scripts written in python. In particular, I'd like to load user scripts written in python, list all the functions he defined in the script file and then call them. To begin I wrote into my C++ program (correctly linked to python 2.3.2): ============================================== /* create the main module */ m_pModule = PyImport_AddModule("__main__"); m_pDict = PyModule_GetDict(m_pModule); m_pGlobals = m_pDict; m_pLocals = m_pDict; // is this right (globals==locals) ?? /* to try out python, I want just to force the creation of a simple function and then call it from C */ PyRun_StringFlags("def donothing():\n\treturn 'hello'\n", Py_file_input, m_pGlobals, m_pLocals, 0); /* scan all the contents of the __main__ module... */ PyObject *list = PyObject_Dir(m_pGlobals); if (!list || PyList_Check(list) == FALSE) return; for (int i=0,max=PyList_Size(list); i Hi there, I just tried to run this code and failed miserably - though I dunno why. Could any of you please enlighten me why this doesn't work? Thanks a bunch. --- snip --- import unittest from datetime import datetime class time (datetime): def __init__(self, hours=0, minutes=0, seconds=0, microseconds=0): print "blah" datetime.__init__(self, 1, 1, 1, hours, \ minutes, seconds, microseconds) class Test (unittest.TestCase): def testSmoke(self): # print time() # bombs, and complains that # the time ctor needs at least 3 arguments self.assertEquals(datetime(1,1,1,1,2,3,4),time(1,2,3,4)) if __name__ == '__main__': unittest.main() --- snap --- The reason I want to do this is that I want to work with times but I want to do arithmetic with them. Therefore I cannot use the provided time directly. Now I thought, just overide the ctor of datetime so that year, month and day are static and everything should work as far as I need it. That is, it could work - though I seem to be unable to overide the ctor. :( Why is that? cu Martin -- Reach me at spamfaenger (at) gmx (dot) net From yuzx at livedoor.cn Fri Jan 14 02:54:13 2005 From: yuzx at livedoor.cn (yuzx) Date: Fri, 14 Jan 2005 15:54:13 +0800 Subject: test Message-ID: <1105689253.3167.0.camel@linux.tister.com> test From cce at clarkevans.com Thu Jan 13 23:37:23 2005 From: cce at clarkevans.com (Clark C. Evans) Date: Thu, 13 Jan 2005 23:37:23 -0500 Subject: file uploading via urllib2 (multipart/form-data) Message-ID: <20050114043723.GA42184@prometheusresearch.com> Hello. I was wondering if anyone has built a module that works with urllib2 to upload file content via POST multipart/form-data. I'm aware of ASPN 146306, however, I need to use urllib2 beacuse I'm using HTTP Digest over SSL. Cheers, Clark From me at no-spam.org Fri Jan 7 23:12:59 2005 From: me at no-spam.org (Michael) Date: Fri, 07 Jan 2005 21:12:59 -0700 Subject: Python/Qt Problem Message-ID: Hi, I am experiencing something very weird with PyQt. I have created several windows based on QWidget using Designer. I can easily hide and show these with the hide and show methods. However I have just created a new window with Designer and the show method works in my main script but not inside the button action method (not using proper temrinology, sorry) of another window. Why is that? This works fine for the other windows. Have I explained my problem properly? Thanks for any advice, Michael From tim.peters at gmail.com Mon Jan 10 21:15:50 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 10 Jan 2005 21:15:50 -0500 Subject: Securing a future for anonymous functions in Python In-Reply-To: <1oFEd.71967$Jk5.45632@lakeread01> References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <1105381339.922714.23200@c13g2000cwb.googlegroups.com> <1oFEd.71967$Jk5.45632@lakeread01> Message-ID: <1f7befae0501101815572999ae@mail.gmail.com> ... [Anna] >> BTW - I am *quite* happy with the proposal for "where:" syntax - I >> think it handles the problems I have with lambda quite handily. [Steve Holden] > Whereas I find it to be an excrescence, proving (I suppose) that one > man's meat is another person's poison, or something. I've been waiting for someone to mention this, but looks like nobody will, so I'm elected. Modern functional languages generally have two forms of local-name definition, following common mathematical conventions. "where" was discussed here. The other is "let/in", and seems a more natural fit to Python's spelling of block structure: let: suite in: suite There's no restriction to expressions here. I suppose that, like the body of a class, the `let` suite is executed starting with a conceptually empty local namespace, and whatever the suite binds to a local name becomes a temporary binding in the `in` suite (like whatever a class body binds to local names becomes the initial value of the class __dict__). So, e.g., i = i1 = 3 let: i1 = i+1 from math import sqrt in: print i1, sqrt(i1) print i1, print sqrt(i1) would print 4 2 3 and then blow up with a NameError. LIke it or not, it doesn't seem as strained as trying to pile more gimmicks on Python expressions. From steve at holdenweb.com Wed Jan 12 18:46:32 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 12 Jan 2005 18:46:32 -0500 Subject: Why would I get a TypeEror? In-Reply-To: References: Message-ID: It's me wrote: > For this code snip: > > a=3 > ..... > b=(1,len(a))[isinstance(a,(list,tuple,dict))] > > Why would I get a TypeError from the len function? > > Thanks, > > because the interpreter evaluates the tuple (1, len(a)) before applying the indexing to it. You are trying to be far too clever. The standard way to write this would be: a = 3 .... b = 1 if isinstance(a,(list,tuple,dict)): b = len(a) Is code length *really* so important? Think carefully ... regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From dscottr at bellatlantic.net Fri Jan 7 16:08:46 2005 From: dscottr at bellatlantic.net (Scott Robinson) Date: Fri, 07 Jan 2005 21:08:46 GMT Subject: The Industry choice References: <10trej2fl8dip65@corp.supernews.com> <10ttqk8k1e64495@corp.supernews.com> Message-ID: On Fri, 07 Jan 2005 12:06:42 -0800, Jeff Shannon wrote: >Bulba! wrote: > >> On 6 Jan 2005 19:01:46 -0500, aahz at pythoncraft.com (Aahz) wrote: >> >> >>>>Note that the so-called 'viral' nature of GPL code only applies to >>>>*modifications you make* to the GPL software. The *only* way in which >>>>your code can be 'infected' by the GPL is if you copy GPL source. >> >> >>>That's not true -- consider linking to a GPL library. >> >> >> Will someone please explain to me in simple terms what's >> the difference between linking to LGPLed library and linking >> to GPLed library - obviously in terms of consequences of >> what happens to _your_ source code? >> >> Because if there isn't any, why bother with distinguishing >> between the two? > >Releasing a product in which your code is linked together with GPL'ed >code requires that your code also be GPL'ed. The GPL goes to some >lengths to define what exactly "linked together" means. That looks like a typo. The LGPL goes to great length to how you can link to LGPL software without using either the LGPL or GPL. The GPL (linked to by fsf.org) merely states: 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: Note that the conditions are all those of any program released under the GPL. Whatever "forming a work based on the Program" means is whatever you and the copyright owner agree to, or whatever copyright law considers a derived work in areas you wish to release your code into. I would suggest consulting a lawyer before getting close to the line, but you can expect that any legally enforceable restrictions claimed by FSF and/or RMS to be legally binding on all software released under the (L)GPL that the FSF owns the copyright of (they encourage programmers to sign over copyright to the FSF itself). > >Releasing a product in which your code is linked together with LGPL'ed >code does *not* require that your code also be (L)GPL'ed. Changes to >the core library must still be released under (L)GPL, but application >code which merely *uses* the library does not. (I've forgotten, now, >exactly how LGPL defines this distinction...) > >Jeff Shannon >Technician/Programmer >Credit International Scott Robinson From news at NOwillmcguganSPAM.com Mon Jan 31 13:12:29 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Mon, 31 Jan 2005 18:12:29 +0000 Subject: stop program in komodo In-Reply-To: <1107194102.482439.272480@c13g2000cwb.googlegroups.com> References: <1107194102.482439.272480@c13g2000cwb.googlegroups.com> Message-ID: <41fe750e$0$327$db0fefd9@news.zen.co.uk> ajikoe at gmail.com wrote: > Hello, > How can we stop this peace of code in KOMODO: > while 1: > print "helo" > > I can't stop it, even using Ctrl+C Are you sure that is what is happening? When I tried it, it appeared as though nothing had happened after pressing the break button. But it was just that the buffer had filled up with a squillion "helo"'s and was busy scrolling away.. Regards, Will McGugan From bob_smith_17280 at hotmail.com Sun Jan 16 11:53:11 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Sun, 16 Jan 2005 11:53:11 -0500 Subject: protecting the python code. In-Reply-To: <1105893393.214111.227550@f14g2000cwb.googlegroups.com> References: <1105884196.461107.28120@z14g2000cwz.googlegroups.com> <41EA92A7.3080706@holdenweb.com> <1105893393.214111.227550@f14g2000cwb.googlegroups.com> Message-ID: nell wrote: > Hi Steve, > First the "10x in advance" means thanks in advance. > The main importance of protecting my code is to save headache of > customers that want to be smart and change it and then complain on bugs > and problems. > > 10x > I'd say that's more of a policy issue than a technical issue. You have a contract or agreement with your customers, right? Just place a cluase in it that addresses your concerns. You don't have to support people who have altered your code... nor should they expect to be supported. From cartermark46 at ukmail.com Mon Jan 10 08:15:19 2005 From: cartermark46 at ukmail.com (Mark Carter) Date: Mon, 10 Jan 2005 13:15:19 +0000 Subject: Port blocking In-Reply-To: <34f8ovF47d783U1@individual.net> References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> <34f8ovF47d783U1@individual.net> Message-ID: <34fdf6F4a7t7uU1@individual.net> Mark Carter wrote: > Paul Rubin wrote: >> Usually you wouldn't run a public corba or pyro service over the >> internet. You'd use something like XMLRPC over HTTP port 80 partly >> for the precise purpose of not getting blocked by firewalls. I'm not sure if we're talking at cross-purposes here, but the application isn't intended for public consumption, but for fee-paying clients. From newgene at bigfoot.com Wed Jan 12 21:54:30 2005 From: newgene at bigfoot.com (Newgene) Date: 12 Jan 2005 18:54:30 -0800 Subject: Dynamically add class method causes "SystemError: ... bad argument to internal function" References: <1105572079.630658.242210@c13g2000cwb.googlegroups.com> Message-ID: <1105584870.519768.17210@f14g2000cwb.googlegroups.com> I have noticed that the exception was caused by the call of "self.f()" within my "_generic" function. It will raise SystemError exception whenever I refer to any method or attribute of "self" within "_generic" function. Otherwise, dynamically adding method works fine. I cannot figure out what's the reason there. CW From dbickett at gmail.com Sun Jan 23 07:56:45 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 23 Jan 2005 07:56:45 -0500 Subject: What YAML engine do you use? In-Reply-To: <_cSdnRo1keDOzm7cRVn-ug@comcast.com> References: <35a6tpF4gmat2U1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fpq0F4mh1ffU1@individual.net> <_cSdnRo1keDOzm7cRVn-ug@comcast.com> Message-ID: <1d6cdae3050123045614dfa11@mail.gmail.com> Doug Holton wrote: > You might like programming in XML then: http://www.meta-language.net/ > :) http://www.meta-language.net/sample.html#class-metal I'm not so sure ;-) Daniel Bickett From rowen at cesmail.net Mon Jan 24 15:20:43 2005 From: rowen at cesmail.net (Russell E. Owen) Date: Mon, 24 Jan 2005 12:20:43 -0800 Subject: tkinter socket client ? References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> <1106311130.446259.30710@f14g2000cwb.googlegroups.com> <1106318469.311179.126140@c13g2000cwb.googlegroups.com> <1106319270.932204.180590@c13g2000cwb.googlegroups.com> Message-ID: In article <1106319270.932204.180590 at c13g2000cwb.googlegroups.com>, "Tonino" wrote: >yeah - had a look at createfilehandler() - was a bit confusing - but >your example helps ;) Be warned that createfilehandler does not work on Windows, though it works well on unix and MacOS X. So my suggestion is one to try any of these (any of which are preferable to threads): - file handlers for non-Windows code - use tcl sockets for cross-platform code. - use Twisted Framework (some work to learn, but supposedly very solid; I confess I've never used it myself). There is a bit of info on the first two options (including a link to the RO package that includes a python interface to tcl sockets) here: -- Russell From adam at cognitcorp.com Tue Jan 4 22:38:12 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Tue, 04 Jan 2005 22:38:12 -0500 Subject: what is lambda used for in real code? In-Reply-To: References: Message-ID: <1104892918.5050.7.camel@localhost.localdomain> On Fri, 2004-12-31 at 17:36, Steven Bethard wrote: > Adam DePrince wrote: > > Lets not forget the "real reason" for lambda ... the elegance of > > orthogonality. Why treat functions differently than any other object? > > > > We can operate on every other class without having to involve the > > namespace, why should functions be any different? > > Yup. I think in most of the examples that I didn't know how to rewrite, > this was basically the issue. On the other hand, I do think that > lambdas get overused, as indicated by the number of examples I *was* > able to rewrite.[1] > > Still, I have to admit that in some cases (especially those involving > reduce), I wish the coder had named the function -- it would have given > me a little bit more documentation as to what the code was trying to do. This is a long standing philosophical issue that really shouldn't impose itself on the language. Do you document, and risk that the documentation doesn't match the code, or do you use the code itself as documentation. Leaving, or even expanding upon, anonymous functions permits the programmer to choose their stance in the above debate; you can still write # If I had to give this function a name, it would be ... before or after the lambda to elect the former option. The removal of anonymous functions, however, forces the former option. Even if option latter is misguided, one of the guiding principles of Python is that we are all consenting adults free to do dumb things. - Adam Adam DePrince From ola.natvig at infosense.no Wed Jan 12 11:39:06 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Wed, 12 Jan 2005 17:39:06 +0100 Subject: Removing M2Crypto debug data in production code Message-ID: <41E552AA.70001@infosense.no> Hi all I'm writing a SSL server and we are using M2Crypto as our SSL engine. What bothers me is that on every accept it prints a lot of 'junk-data' to my stdout. It would be nice if someone knew a way to get M2Crypto out of debug mode and into a more silent mode. LOOP: SSL accept: before/accept initialization LOOP: SSL accept: SSLv3 read client hello A LOOP: SSL accept: SSLv3 write server hello A LOOP: SSL accept: SSLv3 write certificate A LOOP: SSL accept: SSLv3 write key exchange A LOOP: SSL accept: SSLv3 write server done A LOOP: SSL accept: SSLv3 flush data LOOP: SSL accept: SSLv3 read client key exchange A LOOP: SSL accept: SSLv3 read finished A LOOP: SSL accept: SSLv3 write change cipher spec A LOOP: SSL accept: SSLv3 write finished A LOOP: SSL accept: SSLv3 flush data INFO: SSL accept: SSL negotiation finished successfully regards Ola Natvig -- -------------------------------------- Ola Natvig infoSense AS / development From carribeiro at gmail.com Tue Jan 4 12:22:28 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 4 Jan 2005 15:22:28 -0200 Subject: How can engineers not understand source-code control? In-Reply-To: <41dabba1$0$47624$ed2619ec@ptn-nntp-reader02.plus.net> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41da713a$0$610$ed2619ec@ptn-nntp-reader03.plus.net> <41dabba1$0$47624$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <864d3709050104092224047787@mail.gmail.com> On Tue, 04 Jan 2005 15:52:03 +0000, Mark Carter wrote: > I'm thinking that the I-Ching is a vast untapped resource for > programming wisdom, plus it makes it funny. LOL! +1 QOTW! -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From aleaxit at yahoo.com Thu Jan 27 13:09:57 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 27 Jan 2005 19:09:57 +0100 Subject: Please suggest on the book to follow References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> Message-ID: <1gr29gd.nnwb87holh83N%aleaxit@yahoo.com> wrote: > "santanu" writes: > > I know a little python (not the OOP part) learnt by studying the online > > tutorial. Now I would like to learn it more thoroughly. > > I think there's supposed to be a new version of Python in a Nutshell Just a 2nd edition. I'm just starting to write it. By the time it's done and out in print, say six months if you're a VERY optimistic guy, I'm pretty sure "santanu" will be an experienced Pythonista and quite ready to take advantage, if he chooses, of the Nutshell's 2nd edition as a convenient desktop reference, which is its main intended role. > coming. That's a more serious book than Learning Python. Speaking as the author of the Nutshell, and a TR for Learning, I think I'm reasonably unbiased (or, equally biased in favor of both;-), and I don't think of Learning as ``less serious'' -- it does have a different role, of course. If a book whose title is "Learning X" (for any X) does its job well, then when you're done with it you can probably put it aside -- as Wittgenstein said of the learner, "he must so to speak throw away the ladder, after he has climbed up on it". A book that is meant mostly as a convenient reference, if _it_ does its job, keeps being useful for a longer time. On the other hand, using the Nutshell for the purpose of learning Python, while certainly feasible if you're well skilled in computer programming (in other languages), may not be as easy as using "Learning Python" for that purpose! All in all, while I'm of course gladder the more copies of the Nutshell are sold, I still think that, for the _learning_ part, most people might be better served by "Learning Python" -- or, for that matter, the already recommended "Practical Python" (it has many significant completely worked-out example programs -- I was a TR for it, too) or "Dive into Python" (VERY fast and meant for already-experienced programmers -- I wasn't a TR for it, but, my _wife_ was...;-) Alex From fpm at u.washington.edu Mon Jan 31 11:02:24 2005 From: fpm at u.washington.edu (Frank Miles) Date: Mon, 31 Jan 2005 16:02:24 +0000 (UTC) Subject: Best python postgres module? References: Message-ID: In article , Robert Brewer wrote: >Roland Heiber wrote: >> i recently migrated from mysql to postgresql and did use >> severel python >> postgres-modules. All do what they are designed for, so >> which one would >> you use? psycopg, pygresql, pypgsql? psycopg seems to be the best >> solution for heavy traffic/multiple connections .... i have no real >> testing environment, so any advice which one to use for different >> usecases would be nice. > >If your "use cases" involve cross-platform development (i.e. Linux and >Windows), pypgsql seems to fit the bill nicely. psycopg is available for WinXX as well, though I'm not sure how long it takes for bleeding-edge (development versions) to get to WinXX. -frank -- From apardon at forel.vub.ac.be Mon Jan 17 09:51:55 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Jan 2005 14:51:55 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-17, Just schreef : > In article , > Antoon Pardon wrote: > >> Op 2005-01-17, Steve Holden schreef : > >> > There you go with the minutiae again. How about: >> > >> > "Don't use mutables as hash keys"? >> >> That sounds too dogmatic to my ears. I also find it >> too selective. The problem with mutables as dictionary >> keys is not specific to dictionaries. Everywhere you >> have mutables in a container, it is possible that >> mutating the object in the container will cause >> problem. > > The main difference is: if you mutate a dict key you *always* have a > problem. So don't do that. Mutating (say) a list item *only* is a > problem if you (say) need that list to remain sorted. That is not true. It is a problem every time I expect the list items to remain the same. > Lists don't > magically remain sorted, so people generally sort it before they do some > operation that expects a sorted list. > >> Heck even using mutables as arguments can >> cause trouble. Why else the specific advice against >> >> def foo(p = []) >> >> type of arguments. So should we adopt the principles: >> >> Don't use mutables in containers > > Nonsense. > >> Don't use mutables as default values for parameters > > That's good advice in general. > >> Don't use mutables as arguments. > > Nonsense. > >> Don't assign one mutable to an other. > > Nonsense. Some newbies get surprised by Python's assignment-doesn't-copy > semantics, but it's such basic knowledge (as well as a useful feature) > that I simply don't understand you saying this. Well it is this same sematics that causes the problems with mutable dictionary keys. If it is such basic knowledge then what is the problem with mutable dictionary keys? >> I don't see a big difference between these principles >> and the hash key principle, > > Than you haven't looked hard enough. All of these can get unexpected behaviour because of the assignment-doesn't-copy semantics. The same semantics that can cause problems if you work with mutable dictionary keys. >> so in the end may be we >> should just stick with the more general principle: >> >> Don't use mutables! >> >> and be done with it. > > Ok, so you're indeed a troll. The problems with mutables as dictionary keys is just one particulary case of the problems you can have when your assignmentxs semantics just creates a new reference to the same object. As such it is no different from the problem of mutating one object and finding out this object was also reference through an other name you expected to remain the same or finding out this object was also in a list you expected to remain stable etc. -- Antoon Pardon From ncoghlan at iinet.net.au Fri Jan 21 08:33:04 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 21 Jan 2005 23:33:04 +1000 Subject: Class introspection and dynamically determining function arguments In-Reply-To: <359nmoF4koiepU1@individual.net> References: <359lfnF4hd6e3U1@individual.net> <359nmoF4koiepU1@individual.net> Message-ID: <41F10490.2070805@iinet.net.au> Diez B. Roggisch wrote: > Nick Coghlan wrote: > >>If this only has to work for classes created for the purpose (rather than >>for an arbitrary class): >> > > > Certainly a step into the direction I meant - but still missing type > declarations. And that's what at least I'd like to see - as otherwise you > don't know what kind of editing widget to use for a property. Hmm, true. You really need a name:type dict to define each class that is going to be generated. Perhaps the simplest way is to require all such classes to have a "getExample" class method that produces a fully populated example instance (making it a class method means that you shouldn't need to override it in a subclass if you don't change the signature of __init__). Then the widget generator doesn't need to care about *how* that default example gets generated, and can be something simple like: build_widget(name, data_type): ... build_widget_list(cls): example = cls.getExample() widgets = [] for attr, value in example.__dict__: widgets.append(build_widget(attr, type(value))) return widgets Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ssaeed1973 at yahoo.com Sun Jan 30 15:30:34 2005 From: ssaeed1973 at yahoo.com (ssaeed1973 at yahoo.com) Date: 30 Jan 2005 12:30:34 -0800 Subject: Need programming tip In-Reply-To: <1gr74ck.kncteuqczambN%aleaxit@yahoo.com> References: <1107071340.486489.146580@f14g2000cwb.googlegroups.com> <1gr74ck.kncteuqczambN%aleaxit@yahoo.com> Message-ID: <1107117034.953473.12670@c13g2000cwb.googlegroups.com> Alex, Thanks, I will try this. Salman From peter at engcorp.com Sun Jan 9 13:59:12 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jan 2005 13:59:12 -0500 Subject: windows mem leak In-Reply-To: References: <41XDd.70234$Jk5.40626@lakeread01> <41E06C18.6050407@hotmail.com> Message-ID: Bob Smith wrote: > Peter Hansen wrote: [snip details of Bob's platform] > WinXP Home, Service Pack 2, AMD 1400MHz proc, 256MB Ram That's not really much RAM for a WinXP box. Do you have lots of physical memory available before running? >> (I presume you're using a version of nmap that's compiled >> for Windows XP then? > Yes, I am. > >> It's certainly not standard. > That's a matter of opinion. Nmap works fine on the WinXP machine. Perhaps my use of "standard" was obscure, since it's definitely not a matter of opinion, the way I intended it. What I meant was "nmap is certainly not included in the standard Win XP distribution". >> How have >> you proven that it is not *that* program which is at fault?) > > I have not. All I know is that on WinXP, the program uses 100% CPU at > times and consumes more Ram than is available (the page file grows to > 700 or 800MB). It runs OK for a few hours and then produces a 'not > enough resources' error. Is it certain that this memory is being consumed by the Python process? I could imagine, for example, there being dozens of new processes spawned with os.system. Does the Task Manager back up the theory that this "python.exe" instance is the one causing the trouble? Presumably it should be clear even before the machine grows unusable. Note that you can select which columns are shown in the "Processes" tab of the Task Manager window, to get more detail on a given process. (The Performance Monitor found under Control Panel, Administrative Tools can be even more useful and precise.) > And, the machine is generally unuserable. On > Linux, it has no impact whatsoever on resources. Granted, the Linux > machine is much more robust, but one wouldn't expect this great a > difference. I can rewrite it so that it's pure Pyhton (no calling nmap) > if you think that would be a good idea. Perhaps that would at least > remove nmap from the equation. A simpler test might be to change the nmap call to something guaranteed benign, like a call to "dir", and try with that. That's assuming you don't actually need the output of nmap to reproduce the problem, which of course isn't sure. Still, it would be an easy test, and might show a problem elsewhere. > I can run it if you like and take a screen shot of the error. You'll > have to give me a few hours though ;) I trust that you are getting the error dialog you say you are. :-) I have a feeling that the message by itself helps little, however, and that you'll have to try a few different approaches to observe the problem as it grows, via Task Manager or another tool, rather than just trying to guess what happened after the machine is already effective kaput. -Peter From deetsNOSPAM at web.de Thu Jan 20 07:12:39 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 20 Jan 2005 13:12:39 +0100 Subject: Class introspection and dynamically determining function arguments References: Message-ID: <359lfnF4hd6e3U1@individual.net> Mark English wrote: > The only way I can imagine to do this is to create an instance of the > class in question, and then start poking around in its attributes > dictionary (initially just using dir). So firstly, if there is instead a > way to do this without creating an instance I'd be interested. This is the only way to go, as python has no attribute declarations as static compiled languages have. But of course not all classes may feature default constructors so that creating an instance is impossible. Or you create unwanted sideeffects - think of the notorious class DeleteMyHarddisk.... As youself already mentioned that maybe you have to impose certain prerequisites, you maybe want to extend this to the point where for each class you want to make dynamically instantiatable you need some declaration. This of course depends on your desired application - whatfor is it planned? -- Regards, Diez B. Roggisch From sjmachin at lexicon.net Sun Jan 23 04:49:08 2005 From: sjmachin at lexicon.net (John Machin) Date: 23 Jan 2005 01:49:08 -0800 Subject: getting file size References: <6qc6v0hhfedf0uncp9gieahj38srh46khk@4ax.com> Message-ID: <1106460795.516946.246150@f14g2000cwb.googlegroups.com> Tim Roberts wrote: > Bob Smith wrote: > > >Are these the same: > > > >1. f_size = os.path.getsize(file_name) > > > >2. fp1 = file(file_name, 'r') > > data = fp1.readlines() > > last_byte = fp1.tell() > > > >I always get the same value when doing 1. or 2. Is there a reason I > >should do both? When reading to the end of a file, won't tell() be just > >as accurate as os.path.getsize()? > > On Windows, those two are not equivalent. Besides the newline conversion > done by reading text files, Doesn't appear to me to go wrong due to newline conversion: Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 >>> import os.path >>> txt = 'qwertyuiop\nasdfghjkl\nzxcvbnm\n' >>> file('bob', 'w').write(txt) >>> len(txt) 29 >>> os.path.getsize('bob') 32L ##### as expected >>> f = file('bob', 'r') >>> lines = f.readlines() >>> lines ['qwertyuiop\n', 'asdfghjkl\n', 'zxcvbnm\n'] >>> f.tell() 32L ##### as expected > the solution in 2. will stop as soon as it sees > a ctrl-Z. ... and the value returned by f.tell() is not the position of the ctrl-Z but more likely the position of the end of the current block -- which could be thousands/millions of bytes before the physical end of the file. Good ol' CP/M. > > If you used 'rb', you'd be much closer. And be much less hassled when that ctrl-Z wasn't meant to mean EOF, it just happened to appear in an unvalidated data field part way down a critical file :-( From bj_666 at gmx.net Mon Jan 3 17:59:26 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 03 Jan 2005 23:59:26 +0100 Subject: XML: Better way to accomplish this? References: <1104728060.417168.277780@c13g2000cwb.googlegroups.com> Message-ID: In <1104728060.417168.277780 at c13g2000cwb.googlegroups.com>, flamesrock wrote: > # > # > [...] > # > # > [...] > # > # > [...] > # > # Don't you think it's better to use an attribute for the city nr.? Something like ````. At least if you intent to write a DTD or Schema this might be better. Ciao, Marc 'BlackJack' Rintsch From peter at engcorp.com Tue Jan 4 22:16:32 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 04 Jan 2005 22:16:32 -0500 Subject: Python evolution: Unease In-Reply-To: <7xoeg4txrp.fsf@ruckus.brouhaha.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Jeremy Bowers writes: >>So, nobody should have to write the docs because they should already be >>there, but "somebody" should have to write the docs? >> >>You need to think more clearly about the pronouns you are slinging around. >>Who is this "they" that should write the docs? > > The Python advocates who claim that Python is well-documented and take > exception to when someone say it isn't. Their idea of "it's > well-documented" seems to be "if there's parts that you think are > poorly documented, feel free to document it". What kind of nonsense > is that? "Python code runs just as fast as C code. If you think it's > slower, feel free to speed it up". "Python's standard library > includes a database module. If it isn't there, feel free to add one". > "Programming in Python cures cancer. If your cancer doesn't clear up > when you code in Python, feel free to submit a patch". I think you're throwing out strawman arguments here. The key distinction is that "well-documented" is clearly a judgment call, a personal opinion, while the others are all measurable absolutes. (The "as fast as C" one borders on being an opinion, since most people actually say things that mean something more like "as fast as I need it to, so C has no advantage".) Saying, in effect, as they are, "Python's docs are well enough documented for my purposes and, I believe, for those of many other people" certainly isn't nonsense, and saying "and if you don't agree you should consider improving them yourself instead of asking me or others who feel as I do" is certainly not nonsense. > And no, I don't feel a responsibility to do the missing work, since > I'm not the one making those advocacy claims. So those who claim Python is well-documented are the ones who should improve the documentation, but those claiming that the documentation is poor should feel no responsibility to make the improvements? Does this make any sense to you? To me, *this* is the nonsense. -Peter From fredrik at pythonware.com Mon Jan 17 10:30:24 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Jan 2005 16:30:24 +0100 Subject: Install Python 2.4 on Fedora 3 Core References: <1105975262.047782.6010@z14g2000cwz.googlegroups.com> Message-ID: "Bill" wrote: > 2. I looked in the package editor and there was no way to uninstall > 2.3? Should I? If so, how can I? If not,what are the problems, if > any, of having both. if your OS comes with Python, there's a certain chance that it includes utilities that rely on a specific Python version. removing or replacing that version is usually a rather bad idea. having multiple Python installations on a machine is usually no problem at all. From claird at lairds.us Mon Jan 3 10:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Mon, 03 Jan 2005 15:08:04 GMT Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com><7xekh423b6.fsf@ruckus.brouhaha.com> <_rTBd.66275$Jk5.46@lakeread01> Message-ID: In article , Terry Reedy wrote: > >"Steve Holden" wrote in message >news:_rTBd.66275$Jk5.46 at lakeread01... >> Well clearly there's a spectrum. However, I have previously written that >> the number of open source projects that appear to get stuck somewhere >> between release 0.1 and release 0.9 is amazingly large, and does imply >> some dissipation of effort. > >And how do the failure and effort dissipation rates of open source code >compare to those of closed source code? Of course, we have only anecdotal >evidence that the latter is also 'amazingly large'. And, to be fair, the >latter should include the one-programmer proprietary projects that >correspond to the one-programmer open projects. > >Also, what is 'amazing' to one depends on one's expectations ;-). It is >known, for instance, that some large fraction of visible retail business >fail within a year. And that natural selection is based on that fact that . . . The usual measurements and estimates are generally between 15% and 30%. "Desirable" businesses--restaurants, for example, or computing consultancies--are even more likely to fail. From klingens at web.de Mon Jan 17 09:13:07 2005 From: klingens at web.de (A. Klingenstein) Date: Mon, 17 Jan 2005 15:13:07 +0100 Subject: Native widgets for Python Message-ID: <41EBC7F3.5050807@web.de> Which other GUI library for Python other than wxpython has native widgets for MS Windows ? I know there is MFC and GDI, but I want something easier to use than wx, not harder :) wxpython has to problem that it handles much more like a C++ library than a Python one sometimes. Alex From aahz at pythoncraft.com Sun Jan 2 12:07:57 2005 From: aahz at pythoncraft.com (Aahz) Date: 2 Jan 2005 12:07:57 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xacrs230c.fsf@ruckus.brouhaha.com> Message-ID: In article , Steve Holden wrote: >Aahz wrote: >> In article <7xacrs230c.fsf at ruckus.brouhaha.com>, >> Paul Rubin wrote: >>> >>>I was pretty skeptical of Java's checked exceptions when I first used >>>them but have been coming around about them. There's just been too >>>many times when I wrote something in Python that crashed because some >>>lower-level function raised an exception that the upper level hadn't >>>been expecting, after the program had been in use for a while. I'd >>>sure rather find out about that at compile time. >> >> That's funny -- Bruce Eckel talks about how he used to love checked >> exceptions but has come to regard them as the horror that they are. >> I've learned to just write "throws Exception" at the declaration of >> every method. > >Pretty sloppy, though, no? And surely the important thing is to have a >broad handler, not a broad specification of raisable exceptions? Yes, it's sloppy, but I Don't Care. I'm trying to write usable code while learning a damnably under-documented Java library -- and I'm *not* a Java programmer in the first place, so I'm also fighting with the Java environment. Eventually I'll add in some better code. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From invalidemail at aerojockey.com Fri Jan 28 19:18:48 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 28 Jan 2005 16:18:48 -0800 Subject: what's OOP's jargons and complexities? In-Reply-To: References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> Message-ID: <1106957928.805628.69820@z14g2000cwz.googlegroups.com> Dan Perl wrote: > I will not get into your "history" of the "OOP hype". The best thing to is just ignore him. But, if he bothers you too much to let it slide, then don't take issue with anything he writes. Just post a follow-up warning the newbies that he's a pest, that his claims are untrue and his advice is not good, and that he appears that his posts are just trolling in disguise. (Or, you could do what I do when I feel a need to reply: follow-up with a Flame Warriors link. For Xah, it would probably be this: http://tinyurl.com/4vor3 ) -- CARL BANKS From richie at entrian.com Fri Jan 28 07:26:13 2005 From: richie at entrian.com (Richie Hindle) Date: Fri, 28 Jan 2005 12:26:13 +0000 Subject: Who should security issues be reported to? In-Reply-To: References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> Message-ID: [Duncan] > I'm intrigued how you managed to come up with something you > consider to be a security issue with Python since Python offers no > security. Perhaps, without revealing the actual issue in question, you > could give an example of some other situation which, if it came up in > Python you would consider to be a security issue? I can't speak for the OP, but one hypothetical example might be a buffer overrun vulnerability in the socket module. -- Richie Hindle richie at entrian.com From ola.natvig at infosense.no Thu Jan 27 08:02:19 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Thu, 27 Jan 2005 14:02:19 +0100 Subject: Please suggest on the book to follow In-Reply-To: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> Message-ID: santanu wrote: > Hi all, > > I know a little python (not the OOP part) learnt by studying the online > > tutorial. Now I would like to learn it more thoroughly. > > I have access to 'Programming Python' which I liked (on flipping > through the > pages), but the problem is it deals only with version 2.0 of Phython. > > So, I would be glad if you could suggest me whether it would be really > a good > idea to learn from this book. In other words, will I have to unlearn > too much > after I complete this book (by the time I am done with this book, I > believe > we will be having Python 2.6 or so). > > Please suggest. > > Regards, > Santanu > I realy would recomend Practival Python it's a wery good book which I think it's written for 2.2 or 2.3, but it's got all the basic modern python aspects like new style classes. http://www.amazon.com/exec/obidos/tg/detail/-/1590590066/qid=1106830797/sr=8-1/ref=sr_8_xs_ap_i1_xgl14/104-9460635-7128701?v=glance&s=books&n=507846 -- -------------------------------------- Ola Natvig infoSense AS / development From vincent at visualtrans.de Tue Jan 18 01:08:57 2005 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 18 Jan 2005 07:08:57 +0100 Subject: how to find site-packages path (Michael Hoffman) - use distutils In-Reply-To: References: Message-ID: Philippe C. Martin wrote: >>>The flawless way would be to use distutils. In fact you shouldn't even >>>need your own install script--it should do most of the work for you. > > > The reason I have not so far is I have not found a way to get what I > want done: > > 1) create directories in site-packages (I gather this shoudl be easy > enough) > 2) copy already compiled (.pyc) and source (.py) files to those > directories Why would you want to copy any *.pyc instead of compiling them on site? -- Vincent Wehren > 3) create directories and copy files in a directory kept in an > environment variable > > > Can distutils do this for me? > > > Regards, > > Philippe > > > > > From prakis at gmail.com Sat Jan 22 06:40:57 2005 From: prakis at gmail.com (kishore) Date: 22 Jan 2005 03:40:57 -0800 Subject: dynamic call of a function In-Reply-To: References: <3BCFE666.C8C6136C@c-s.fr> Message-ID: <1106394057.320879.319110@f14g2000cwb.googlegroups.com> Hi Luigi Ballabio, Thankyou very much for your reply, it worked well. Kishore. Luigi Ballabio wrote: > At 10:37 AM 10/19/01 +0200, anthony harel wrote: > >Is it possible to make dynamic call of a function whith python ? > > > >I have got a string that contains the name of the function I > >want to call but I don't want to do something like this : > > > >if ch == "foo" : > > self.foo( ) > >elif ch == "bar" > > self.bar( ) > >.... > > Anthony, > here are two ways to do it---I don't know which is the best, nor > whether the best is yet another. Also, you might want to put in some error > checking. > > class Test: > def foo(self): > print 'Norm!' > def bar(self): > print 'Dum-de-dum' > def dynCall1(self,methodName): > eval('self.%s()' % methodName) > def dynCall2(self,methodName): > method = vars(self.__class__)[methodName] > method(self) > > >>> t = Test() > >>> t.dynCall1('foo') > Norm! > >>> t.dynCall2('bar') > Dum-de-dum > > Bye, > Luigi From Mark.English at liffe.com Mon Jan 24 06:05:34 2005 From: Mark.English at liffe.com (Mark English) Date: Mon, 24 Jan 2005 11:05:34 -0000 Subject: Class introspection and dynamically determining function arguments Message-ID: <40E605146701DE428FAF21286A97D309022FC92E@wphexa02.corp.lh.int> Thanks for the pointers to traits, BasicProperty, and harold fellermann's sample code... ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From FBatista at uniFON.com.ar Mon Jan 24 11:51:13 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 24 Jan 2005 13:51:13 -0300 Subject: Tuple slices Message-ID: [George Sakkis] #- Why does slicing a tuple returns a new tuple instead of a #- view of the existing one, given that #- tuples are immutable ? I ended up writing a custom #- ImmutableSequence class that does this, but I #- wonder why it is not implemented for tuples. What exactly is "a view of the existing one"? And how do you return it without creating a new object? Could you send an example? Thanks. . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pierre.barbier at cirad.fr Tue Jan 18 04:01:02 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Tue, 18 Jan 2005 10:01:02 +0100 Subject: extension module, thread safety? In-Reply-To: References: <41ecbaae$0$1046$626a14ce@news.free.fr> Message-ID: <41eccfe4$0$16621$636a15ce@news.free.fr> Nick Coghlan a ?crit : > Pierre Barbier de Reuille wrote: > >> With the current CPython, it's very hard to mix Python and C in a >> multithreading application (with C-threads, not Python-threads). In >> fact I never really succeeded in that task because of that GIL ! I >> have a multi-thread application but every bit of Python code must be >> run into a Python thread. To be more precise, I wanted to be able to >> call Python code in response to some GUI events, and I didn't want to >> instanciate a new interpreter for I wanted to be able to access the >> environment of my main Python interpreter. > > > I don't understand. This is what PyGILState_Ensure and > PyGILState_Release are for - so C code can leave the GIL unlocked by > default, and only grab it when they want to call into the C/Python API. > > Regards, > Nick. > Ok, I wondered why I didn't know these functions, but they are new to Python 2.4 ( and I didn't take the time to look closely at Python 2.4 as some modules I'm working with are still not available for Python 2.4). But if it really allows to call Python code outside a Python thread ... then I'll surely use that as soon as I can use Python 2.4 :) Thanks for the hint :) Pierre From nick at craig-wood.com Tue Jan 25 03:30:03 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 25 Jan 2005 08:30:03 GMT Subject: Classical FP problem in python : Hamming problem References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> Message-ID: Francis Girard wrote: > def hamming(): > def _hamming(): > yield 1 > hamming2 = hammingGenerators[0] > hamming3 = hammingGenerators[1] > hamming5 = hammingGenerators[2] > for n in imerge(imap(lambda h: 2*h, iter(hamming2)), > imerge(imap(lambda h: 3*h, iter(hamming3)), > imap(lambda h: 5*h, iter(hamming5)))): > yield n > hammingGenerators = tee(_hamming(), 4) > return hammingGenerators[3] If you are after readability, you might prefer this... def hamming(): def _hamming(): yield 1 for n in imerge(imap(lambda h: 2*h, iter(hamming2)), imerge(imap(lambda h: 3*h, iter(hamming3)), imap(lambda h: 5*h, iter(hamming5)))): yield n hamming2, hamming3, hamming5, result = tee(_hamming(), 4) return result PS interesting thread - never heard of Hamming sequences before! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From steven.bethard at gmail.com Thu Jan 20 00:02:51 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 19 Jan 2005 22:02:51 -0700 Subject: list item's position In-Reply-To: References: Message-ID: Bill Mill wrote: > 2 solutions: > > In [98]: bars = ["str", "foobaz", "barbaz", "foobar"] > > In [99]: for bar in bars: > ....: if 'bar' in bar and 'baz' in bar: > ....: print bar > ....: print bars.index(bar) > ....: > barbaz > 2 > > In [100]: for i in range(len(bars)): > .....: if 'bar' in bars[i] and 'baz' in bars[i]: > .....: print bars[i] > .....: print i > .....: > barbaz > 2 > > The first one is slow and pretty, the second one is fast and (a bit) > ugly. I believe that you should avoid range(len(x)) when you can, but > use it when you need to know the index of something without an > additional x.index() call. See Mark's post, if you "need to know the index of something" this is the perfect case for enumerate (assuming you have at least Python 2.3): py> bars = ["str", "foobaz", "barbaz", "foobar"] py> for i, bar in enumerate(bars): ... if 'bar' in bar and 'baz' in bar: ... print bar ... print i ... barbaz 2 The only time where I even consider using range(len(x)) is when I don't also need to look at the item -- which I find to be quite uncommon... Steve From eddie at holyrood.ed.ac.uk Fri Jan 28 12:32:23 2005 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 28 Jan 2005 17:32:23 +0000 (UTC) Subject: HTML Tree View with
    and References: Message-ID: Gregor Horvath writes: >Hi, >Before I reinvent the wheel I`d like to ask if someone has done this >before since I did not find an advice at Google. >The goal is to create a dynamic Tree View in HTML. >Say I have a data strucure like this: >structList = >{'Sun':{'Sun.1':['Sun1.1','Sun1.2'],'Sun.2':['Sun2.1','Sun2.2']},'Kupa':['Kupa1']} >I want to transform this into HTML: >
      >
    1. Sun
    2. >
        >
      1. Sun.1
      2. >
          >
        1. Sun1.1
        2. >
        3. Sun1.2
        4. >
        >
      3. Sun.2
      4. >
          >
        1. Sun2.1
        2. >
        3. Sun2.2
        4. >
        >
      >
    3. Kupa
    4. >
        >
      1. Kupa1
      2. >
      >
    >If the user clicks on a branch-link say 'Sun.1' then the branch below >opens/closes (not printed by the servlet). Like a tree view control in >an native GUI app. >Has this, or a similar approach, been done before in python ( I am using >webware/cheetah)? Here is a browser side solution that you can have a play with: ---------------------------- htmltree.py --------------------------- import sys id = 0 def new_id (): global id id += 1 return id def mk_expander (id, lab='+'): return '%s' % (id,id,lab) def start_invisible (id): return '') def build_tree (dst, node): dst.write ('
      \n') for branch in node: ##sys.stderr.write ('-- %s\n'%branch) id = new_id() if type(node) == type([]): dst.write ('
    1. %s\n' % branch) else: dst.write ('
    2. %s\n%s' % (mk_expander (id,branch), start_invisible(id))) build_tree (dst, node[branch]) finish_invisible (dst) style_stuff = ''' ''' print 'BLAH' print '' print style_stuff print ''' ''' structList = {'Sun':{'Sun.1':['Sun1.1','Sun1.2'],'Sun.2':['Sun2.1','Sun2.2']},'Kupa':['Kupa1']} build_tree (sys.stdout, structList) print '\n\n' ----------------------------------------------------------------- and the javascript file that goes with it ---------------------------------hier.js -------------------------- visibility_state = new Array(); highlighted = new Array(); selected_node = null; selected_id = null; function get_visibility (id) { var m = visibility_state[id]; if (m == undefined) m = "none"; return m; } function set_visibility (id, e, vis) { e.style.display = vis; visibility_state[id] = vis; } function togglen(id) { toggle_branch (id); do_select (id); return false; } function toggle_branch(id) { var e = document.getElementById(id); var m = get_visibility (id); if (m == "none") m = "inline"; else m = "none"; set_visibility (id, e, m); } function show_branch (id) { var e = document.getElementById(id); set_visibility (id, e, "inline"); } function hide_branch (id) { var e = document.getElementById(id); set_visibility (id, e, "none"); } function do_select (id) { if (selected_id != null) { var e = document.getElementById("e."+selected_id); e.style.backgroundColor = 'transparent'; } var n = document.getElementById("e."+id); n.style.backgroundColor = 'red'; selected_node = document.getElementById(id); selected_id = id; } function set_visibility_all (n, vis) { if (n == null) return false; if (n.nodeType == 1) { if (n.tagName == "DIV" && n.id != "") set_visibility (n.id, n, vis); for (var c = n.firstChild; c != null; c = c.nextSibling) set_visibility_all (c, vis); } } ------------------------------------------------------------------- the javascript code is extracted from a larger set of functions that include a popup menu with inbuilt search (which opens tree levels as necessary), if you're interested. Eddie From peter.sch231aefer at gmx.de Thu Jan 20 16:55:36 2005 From: peter.sch231aefer at gmx.de (Peter Schaefer) Date: Thu, 20 Jan 2005 22:55:36 +0100 Subject: Python and SOAP Message-ID: Hello! I'd like to write a SOAP client and a SOAP server in Python. Is SOAPy still the way to go, or are there better methods? Regards, Peter -- Meine E-Mail Adresse enth?lt keine Zahlen. My email address doesn't contain numbers. From steven.bethard at gmail.com Fri Jan 7 17:35:21 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Jan 2005 15:35:21 -0700 Subject: switching an instance variable between a property and a normal value In-Reply-To: References: Message-ID: Robert Brewer wrote: > Steven Bethard wrote: > >>I'd like to be able to have an instance variable that can >>sometimes be >>accessed as a property, and sometimes as a regular value, >>e.g. something >>like: > > ... > >>py> c.x is c.x # I'd like this to be False > > > You'd like 'c.x is c.x' to be FALSE? You can't be serious. Must be a > typo. Hmm... maybe I better give the larger context. The short answer is no, I'm serious. I'm playing around with a mapping type that uses setdefault as suggested in http://www.python.org/moin/Python3_2e0Suggestions. The default value for a missing key is either a simple value, or a value generated from a function. If it's generated from the function, it should be generated new each time so that, for example, if the default is an empty list, d[1] and d[2] don't access the same list. This is why 'c.x is c.x' should be False if I'm using the function. Some more context: Before I added the ability to use a function, my code looked something like: py> class D(dict): ... def __init__(self): ... self._default = None ... def __getitem__(self, key): ... if not key in self: ... self[key] = self._default ... return dict.__getitem__(self, key) ... def setdefaultvalue(self, value): ... self._default = value ... py> d = D() py> d[0] py> d.setdefaultvalue(0) py> d[1] 0 py> d[2] += 1 py> d {0: None, 1: 0, 2: 1} To add the ability to use a function to create the default value, it would have been nice to leave basically the same code I already had and do something like: py> class D(dict): ... def __init__(self): ... self._default = None ... def __getitem__(self, key): ... if not key in self: ... self[key] = self._default ... return dict.__getitem__(self, key) ... def setdefaultvalue(self, value): ... self._default = value ... def setdefaultfunction(self, func, *args, **kwds): ... self._func, self._args, self._kwds = func, args, kwds ... self._default = D._defaultfunc ... def _get(self): ... return self._func(*self._args, **self._kwds) ... _defaultfunc = property(_get) ... Of course, this doesn't work for the reasons that I discussed, but the idea would be that D would use a regular attribute when a simple value was needed, and a property when a value had to be generated by a function each time. The best option I guess is to rewrite this with a _getdefault() function instead of a property: py> class D(dict): ... _undefined = object() ... def __init__(self): ... self._value = None ... self._func = self._undefined ... def __getitem__(self, key): ... if not key in self: ... self[key] = self.getdefault() ... return dict.__getitem__(self, key) ... def getdefault(self): ... if self._value is not self._undefined: ... return self._value ... if self._func is not self._undefined: ... return self._func(*self._args, **self._kwds) ... def setdefaultvalue(self, value): ... self._value = value ... self._func = self._undefined ... def setdefaultfunction(self, func, *args, **kwds): ... self._func, self._args, self._kwds = func, args, kwds ... self._value = self._undefined ... But I was hoping to avoid having two separate attributes (self._value and self._func) when only one should have a value at any given time. Steve From timr at probo.com Fri Jan 7 01:51:13 2005 From: timr at probo.com (Tim Roberts) Date: Thu, 06 Jan 2005 22:51:13 -0800 Subject: smtp question References: Message-ID: "Philippe C. Martin" wrote: >Hi, > >I am testing the smtp module and have the following question: > >in the code below (taken from net sample) prior to adding the "Subject:" >field, the email client found the "From" and the "To". Without the >"Subject:" field on I get this: > >Email client = Evolution: the "From" field is blank >Email client = KMail: the "To" field is blank > >Any clue ? Absolutely. >server = smtplib.SMTP('smtp.sbcglobal.yahoo.com') >server.set_debuglevel(1) >server.login ('xxxxx','yyyyyyy') >server.sendmail(fromaddr, toaddrs, 'Subject:from python\n\n'+msg) >server.quit() You have two newlines following the Subject: line. That inserts a blank line, which terminates the headers. Everything else, including the From: and To: lines, will be taken as part of the message body. I assume you meant to use \r\n, but \n will work just as well and is less error prone. >print "Message length is " + repr(len(msg)) Easier is: print "Message length is", len(msg) More efficient is: print "Message length is %d" % len(msg) -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ysharma at catprosystems.com Thu Jan 13 15:01:39 2005 From: ysharma at catprosystems.com (Yogesh Sharma) Date: Thu, 13 Jan 2005 12:01:39 -0800 Subject: Embedding Multiplr Python interpreter in C++ Message-ID: Hi, I have following setup: OS Linux Fedora Core 3 Python 2.3.4 How can I embed two python interpreters in one C++ program ? Thanks From steven.bethard at gmail.com Tue Jan 25 13:52:15 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Jan 2005 11:52:15 -0700 Subject: Classical FP problem in python : Hamming problem In-Reply-To: References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> Message-ID: <6PKdnVpD-4f3CGvcRVn-gQ@comcast.com> Nick Craig-Wood wrote: > Steven Bethard wrote: > >> Nick Craig-Wood wrote: >> >>>Thinking about this some more leads me to believe a general purpose >>>imerge taking any number of arguments will look neater, eg >>> >>>def imerge(*generators): >>> values = [ g.next() for g in generators ] >>> while True: >>> x = min(values) >>> yield x >>> for i in range(len(values)): >>> if values[i] == x: >>> values[i] = generators[i].next() >>> >> >> This kinda looks like it dies after the first generator is exhausted, >> but I'm not certain. > > > Yes it will stop iterating then (rather like zip() on lists of unequal > size). Not sure what the specification should be! It works for the > hamming problem though. Actually, it stops iterating on lists of equal size too: py> def imerge(*iterators): ... iterators = [iter(i) for i in iterators] ... values = [i.next() for i in iterators] ... while True: ... x = min(values) ... yield x ... for i, val in enumerate(values): ... if val == x: ... values[i] = iterators[i].next() ... py> list(imerge([1, 4, 7], [2, 5, 8], [3, 6, 9])) [1, 2, 3, 4, 5, 6, 7] Note that 8 and 9 are not in the list. Steve From fredrik at pythonware.com Sat Jan 22 07:54:52 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 13:54:52 +0100 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com><797fe3d405011911465ab59acd@mail.gmail.com><1106177050.630141.33090@c13g2000cwb.googlegroups.com><972ec5bd0501191641166972b0@mail.gmail.com><7xis5szpdj.fsf@ruckus.brouhaha.com><7xekggbrns.fsf@ruckus.brouhaha.com><7x651rwbib.fsf@ruckus.brouhaha.com><7xfz0uqe1d.fsf@ruckus.brouhaha.com><1gqsayh.th49i518ixczeN%aleaxit@yahoo.com> <7xpszxljra.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Some languages let you say things like: > for (var x = 0; x < 10; x++) > do_something(x); > and that limits the scope of x to the for loop. depending on the compiler version, compiler switches, IDE settings, etc. From invalidemail at aerojockey.com Sat Jan 8 21:06:23 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 8 Jan 2005 18:06:23 -0800 Subject: python3: accessing the result of 'if' References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> Message-ID: <1105236383.521393.40680@c13g2000cwb.googlegroups.com> Nick Coghlan wrote: > I have a different suggestion for this. > > 'as' is used for renaming in import statements. 'as' will be used for exception > naming in Python 3k. > > So let's use it for expression naming in 'if' statements, too. > > if someregexp.match(s) as m: > # blah using m > elif someotherregexp.match(s) as m: > # blah using m What if the condition you wanted to test wasn't the same as the thing you want to save? In other words, how would you convert this? . where: . m = something() . if m > 20: . do_something_with(m) What you propose works for typical regexps idiom but not for the slightly more general case. However, I could see why some people might not like the where...if syntax I proposed; it's kind of choppy and not exactly easy to follow at a first glance. As a compromise, howabout: . if m > 20 where m=something(): . do_something_with(m) In this case, the m=something() is NOT an assignment statement, but merely a syntax resembling it. The "where m=something()" is part of the if-statement, not the if-expression. It causes m to be visisble in the if-expression and the if-block. It (or your suggestion) could work with a while-loop too. . while line where line=f.readline(): . do_something_with(line) The main problem here (as some would see it) is that you can't do something this: . if m > 20 where (def m(): a(); b()): -- CARL BANKS From jack at performancedrivers.com Mon Jan 24 21:41:31 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Mon, 24 Jan 2005 21:41:31 -0500 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: Message-ID: <20050125024131.GG1607@performancedrivers.com> On Mon, Jan 24, 2005 at 09:17:24PM -0500, Roy Smith wrote: > Rocco Moretti wrote: > > The OP doesn't mention his application, but there is something to be > > said about domain specific scripting languages. A well designed > > domain-specific scripting language(*) with the appropriate high level > > constructs can make script writing simpler. > > This is a bit of a sore point with me. > > I've been involved with several projects where people felt the need to > invent their own scripting languages. It usually starts with "we don't > need the power of a full programming language, we only need to be able > to do X, Y, and Z". So they write a little language which lets them do > X, Y, and Z. > > Then they discover they need more complex data structures than they > originally thought. And nested loops. And functions. And more > sophisticated variable scoping rules. And a regex library. And 47 > other things. So they duct-tape all those into the system. > > A few years later, you end up with most of a real programming language, > except with a whole bunch of warts. > > The syntax is usually quirky (the one I'm working with today does not > allow any space before the open paren of a function call, but requires > it before the opening paren of an "if" statement). It generally has > poor error reporting. It doesn't have the whole family of free tools > that grow up around any real language (editor customization packages, > syntax checkers, debuggers, extensions, etc). You doesn't have a gaggle > of tutorial books written about it that you can buy from your favorite > on-line bookseller. > > Worse, when you need more brains/bodies on the project, you can't put an > add on Hot Jobs for "experienced OurOwnScriptingLanguage programmer" and > expect to get anybody who can be productive quickly. > > What it does have is a body of code dependent on it which is now so > large that porting it to something else is an unthinkably large task. > And it's got a small cadre of language gurus who spend all day defending > the language with answers like, "But, it was never *intended* that > people would do stuff like this with it". > Me Too! I mean, did you used to work at CDNOW too? I don't miss that want-to-gouge-out-your-own-eyes feeling. -Jack From snacktime at gmail.com Sun Jan 23 21:32:10 2005 From: snacktime at gmail.com (snacktime) Date: Sun, 23 Jan 2005 18:32:10 -0800 Subject: Set parity of a string In-Reply-To: References: Message-ID: <1f060c4c05012318322329166d@mail.gmail.com> On Sun, 23 Jan 2005 21:00:25 -0500, Peter Hansen wrote: > Peter Hansen wrote: > > snacktime wrote: > >> Is there a module that sets the parity of a string? > > > > As to the specific question: a module is not really required. > > But here's one for you anyway. It raises an exception if any > input character is non-ASCII, otherwise when you call set_parity() > with a string and a parity parameter of 'even', 'mark', 'none', > 'odd', or 'space', it returns a string of the same length with > the high (parity) bits set appropriately. Thanks for the code example, I'm not quite up to speed on python enough to make this a trivial exercise as of yet. Chris From http Tue Jan 11 02:56:43 2005 From: http (Paul Rubin) Date: 10 Jan 2005 23:56:43 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> <7xllb2f3z4.fsf@ruckus.brouhaha.com> <1105355380.040837.189270@c13g2000cwb.googlegroups.com> <7xis65a5w6.fsf@ruckus.brouhaha.com> <1105357839.696387.309900@c13g2000cwb.googlegroups.com> <7xr7kt314a.fsf@ruckus.brouhaha.com> <1105364925.848973.73080@c13g2000cwb.googlegroups.com> <7xllb1jsdz.fsf@ruckus.brouhaha.com> Message-ID: <7xpt0ciekk.fsf@ruckus.brouhaha.com> Steve Holden writes: > Well I for one disagreed with many of your estimates of the zen's > applicability to macros, but I just couldn't be arsed saying so. Well, I was being somewhat flip with them, as I felt Carl was being snotty in referring me to the Zen list. The point there is that one can interpret each of the Zen points in many ways regarding macros. I don't feel there's a conflict between macros and the Zen list. Macros in Python are a deep subject and gurus have been discussing them for a long time. I think that with PyPy it will become easier to experiment with possible approaches. In other posts I've suggested a moratorium on new Python syntax until after PyPy is deployed. > > An amazing amount of the headaches that both newbies and experienced > > users have with Python, could be solved by macros.... It's not clear > > what the best way to do design them is, but their existence can have a > > profound effect on how best to do these ad-hoc syntax extensions like > > "where". > This is not a justifiable assertion, IMHO, and if you think that > newbies will have their lives made easier by the addition of ad hoc > syntax extensions then you and I come from a different world (and I > suspect the walls might be considerably harder in mine than in yours). I'm saying that many proposals for ad hoc extensions could instead be taken care of with macros. Newbies come to clpy all the time asking how to do assignment expressions, or conditional expressions, or call-by-reference. Sometimes new syntax results. Lots of times, macros could take care of it. > I don't really understand why, if macros are so great (and you are > reading the words of one who was using macros back in the days of > Strachey's GPM) why somebody doesn't produce a really useful set of > (say) M4 macros to prove how much they'd improve Python. You can't really do Python macros with something like M4. How would M4 even generate multi-line output that's indented to the right depth for the place where the macro was called? How would you write an m4 macro like cond(x,y,z) that does the equivalent of (x ? y : z)? Even if you could, it doesn't begin to address the hassle of running Python scripts through m4 before you can execute the scripts, especially in an interactive environment. From c.helmbold at gmx.de Mon Jan 17 03:55:27 2005 From: c.helmbold at gmx.de (Christian Helmbold) Date: Mon, 17 Jan 2005 09:55:27 +0100 Subject: =?iso-8859-15?q?Einrichtung_von_de=2Ecomp=2Elang=2Epython_-_Dein?= =?iso-8859-15?q?e_Stimme_z=E4hlt!?= Message-ID: Hallo, wenn du m?chtest, dass die Gruppe news:de.comp.lang.python eingerichtet wird, bitte ich dich, deine Stimme daf?r abzugeben. Du brauchst dazu nur unten stehenden Wahlschein auszuf?llen und an votetaker at gvv.th-h.de zu schicken. Weitere Einzelheiten zum Verfahren finden sich in news:de.admin.news.anncounce sowie in news:de.admin.news.groups -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 1. CfV (Aufruf zur Abstimmung) zur Einrichtung der Gruppe de.comp.lang.python Programmieren mit Python. Charta - ------ In dieser Gruppe geht es um die Programmiersprache Python und alles, was damit unmittelbar zusammenh?ngt (Installation, alternative Implementierungen, externe Module etc.). Status - ------ unmoderiert Begr?ndung - ---------- In der Diskussion, die mit der Nachricht <314dsqF373djsU1 at individual.net> begann, wurde ?berwiegend Zustimmung zu der Einrichtung ge?u?ert. Proponent - --------- Christian Helmbold Abstimmungsmodalit?ten - ---------------------- Wahlleiter: Thomas Hochstein Abstimmadresse: dclp-0501 at gvv.th-h.de Abstimmungsende: Mit Ablauf des 13. Februar 2005 (MEZ) Wahlschein: Untenstehendes Formular ist zu verwenden. M?glich sind bei jedem Abstimmungspunkt JA, NEIN und ENTHALTUNG. Besonderer Hinweis ------------------ Die am 23.12.2004 begonnene Abstimmung ?ber die Einrichtung der Gruppe de.comp.lang.python wurde am Abend desselben Tages vom Wahlleiter abgebrochen. Die damals abgegebenen Stimmen wurden verworfen und nicht gewertet. Mit diesem 1. CfV beginnt ein neues Abstimmungsverfahren; wer an der Abstimmung teilnehmen m?chte, mu? also jetzt (erneut) abstimmen, auch wenn er schon in dem ersten, abgebrochenen Verfahren eine Stimme abgegeben hat. Es gelten die "Einrichtung von Usenet-Gruppen in de.*" in der bei Beginn der Abstimmung g?ltigen Fassung, die in de.admin.infos und unter auch im WWW ver?ffentlicht sind. Sie erl?utern das Wahlverfahren detailliert und sollten vor der ersten Teilnahme an einer Abstimmung gelesen werden. Gez?hlt werden nur per E-Mail bei der Abstimmadresse eingegangene Stimmen. Diese werden einzeln per E-Mail best?tigt. Das Ergebnis wird nach dem Ende der Wahl ver?ffentlicht. Namen, E-Mail-Adresse und Inhalt der Stimmabgabe aller Abstimmenden werden im Ergebnis genannt. Mit R?cksicht auf das deutsche Datenschutzrecht ist daher die gesonderte Zustimmung zur Speicherung und Ver?ffentlichung der abgegebenen Stimme entsprechend Hinweis im Wahlschein n?tig. Auf die weiteren Hinweise auf sei verwiesen. =-=-=-=-=-=-=-=- Alles vor dieser Zeile bitte loeschen =-=-=-=-=-=-=-=- WAHLSCHEIN fuer Einrichtung der Gruppe de.comp.lang.python Dein Realname, falls nicht im FROM-Header: Wenn du keinen Real-Namen angibst, wird deine Stimme fuer ungueltig erklaert werden. Nr [Deine Stimme] Gruppe/Abstimmungsgegenstand ======================================================================== #1 [ ] Einrichtung von de.comp.lang.python Zur Verarbeitung des Wahlscheines und inbesondere der Veroeffentlichung des Ergebnisses ist deine Zustimmung zur Speicherung, Auswertung und Veroeffentlichung deiner Stimmdaten (Name und E-Mail-Adresse in Verbindung mit dem Stimmverhalten) im Rahmen dieses Verfahrens erforderlich. Wenn du im Feld unterhalb dieses Absatzes "JA" eintraegst, erklaerst du dich damit einverstanden. In allen anderen Faellen wird der Wahlschein mit Ruecksicht auf das deutsche Bundesdatenschutzgesetz verworfen und nicht gewertet. #a [ ] Datenschutzklausel - Zustimmung: Ich bin mit der Verarbeitung meiner Daten wie oben beschrieben einverstanden =-=-=-=-=-=-=-=- Alles nach dieser Zeile bitte loeschen =-=-=-=-=-=-=-=- -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.1 (GNU/Linux) iQCVAwUBQerEb2FKEBFIVyalAQLUvAQAi/S0OSvwYnhkvvlCnYmhVLdi8D4XkMv4 oCYHzADyiNpLDNF3w1dszSL2uXeRuSoXOWd07xcTYS6MpQTWzri8BPyBYyW4Zywz u46rkfDFTpwr5oLHP2Ss3OJr6rqY7zWL28o7bAYdemDd9GIg0vPt4AE8HXyhL5ud CePdwFnaN3s= =z5dB -----END PGP SIGNATURE----- Danke, Christian From asda at sdarta.com Sat Jan 8 21:16:09 2005 From: asda at sdarta.com (worzel) Date: Sun, 9 Jan 2005 10:16:09 +0800 Subject: tuples vs lists References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dff650$0$29357$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41e093e8$0$21144$5a62ac22@per-qv1-newsreader-01.iinet.net.au> yes, "tyoopl" - thats what I meant by 'choo-ple' (not v good at the phonetics) As a scouse git (though living in Australia), I would definitely say 'tyoopl'. "Steve Holden" wrote in message news:w5WDd.69983$Jk5.66802 at lakeread01... > worzel wrote: > >> Cheers - thanks for the feedback guys - pretty much answers the question >> for me. >> >> 'Two-Pull' it is then, thanks. >> > Well, it might be "Two-Pull" in American, but in English it's "tyoopl" -- > NOT "choopl" (blearch!). I've also heard people say "tuppl". > > So, basically, say whatever you want. Language is about communication :-) > > you-say-tomato-ly y'rs - steve > -- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/ > Holden Web LLC +1 703 861 4237 +1 800 494 3119 From frans.englich at telia.com Tue Jan 11 01:54:54 2005 From: frans.englich at telia.com (Frans Englich) Date: Tue, 11 Jan 2005 06:54:54 +0000 Subject: PyChecker messages Message-ID: <200501110654.54193.frans.englich@telia.com> Hello, I take PyChecker partly as an recommender of good coding practice, but I cannot make sense of some of the messages. For example: runner.py:878: Function (main) has too many lines (201) What does this mean? Cannot functions be large? Or is it simply an advice that functions should be small and simple? runner.py:200: Function (detectMimeType) has too many returns (11) The function is simply a long "else-if" clause, branching out to different return statements. What's wrong? It's simply a "probably ugly code" advice? A common message is these: runner.py:41: Parameter (frame) not used But I'm wondering if there's cases where this cannot be avoided. For example, this signal handler: #------------------------------------------- def signalSilencer( signal, frame ): """ Dummy signal handler for avoiding ugly tracebacks when the user presses CTRL+C. """ print "Received signal", str(signal) + ", exiting." sys.exit(1) #------------------------------------------- _must_ take two arguments; is there any way that I can make 'frame' go away? Also, another newbie question: How does one make a string stretch over several lines in the source code? Is this the proper way? print "asda asda asda asda asda asda " \ "asda asda asda asda asda asda " \ "asda asda asda asda asda asda" Thanks in advance, Frans PS. Any idea how to convert any common time type to W3C XML Schema datatype duration? From missiplicity at yahoo.com Tue Jan 25 17:30:28 2005 From: missiplicity at yahoo.com (missiplicity at yahoo.com) Date: 25 Jan 2005 14:30:28 -0800 Subject: Question Regarding SocketServer In-Reply-To: <1106691478.621949.44020@z14g2000cwz.googlegroups.com> References: <1106684900.771730.218060@f14g2000cwb.googlegroups.com> <1106688660.694617.290330@c13g2000cwb.googlegroups.com> <1106691478.621949.44020@z14g2000cwz.googlegroups.com> Message-ID: <1106692228.117977.104720@f14g2000cwb.googlegroups.com> I figured out my problem. I initially had named my program SocketServer.py and then compiled it. It created a file SocketServer.pyc Then I changed the name of the program to TestServer3.py but when I imported SocketServer, it was importing from the compiled file left in the current folder (SocketServer.pyc) I guess. I deleted it and everything worked. Please bear with my ignorance. Thanks once again for the help, Kris From james.keasley at gmail.invalid Mon Jan 17 19:43:24 2005 From: james.keasley at gmail.invalid (James Keasley) Date: 18 Jan 2005 00:43:24 GMT Subject: Fuzzy matching of postal addresses References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 2005-01-18, Andrew McLean wrote: > I have a problem that is suspect isn't unusual and I'm looking to see if > there is any code available to help. I've Googled without success. I have done something very similar (well, near as dammit identical, actually), unfortunately, I did this in Perl[1]. I can give you some general pointers of the way to go about this type of thing, but can't actually provide any code, as it is at work. > Basically, I have two databases containing lists of postal addresses and > need to look for matching addresses in the two databases. More > precisely, for each address in database A I want to find a single > matching address in database B. In my implementation this is the exact same setup, database A (OS/RM addresspoint data) contained a metric shitload of addresses, with addresses to be matched against them coming from client supplied data. > I'm 90% of the way there, in the sense that I have a simplistic approach > that matches 90% of the addresses in database A. But the extra cases > could be a pain to deal with! There is no way to guarantee 100% accuracy if one (or both) of the datasets is collated from a non-authoratative source, ie the actual homeowners. ;) > It's probably not relevant, but I'm using ZODB to store the databases. > The current approach is to loop over addresses in database A. I then > identify all addresses in database B that share the same postal code > (typically less than 50). The database has a mapping that lets me do > this efficiently. Then I look for 'good' matches. If there is exactly > one I declare a success. This isn't as efficient as it could be, it's > O(n^2) for each postcode, because I end up comparing all possible pairs. > But it's fast enough for my application. OK, this is a good start, the first thing to do is to clean the data, especially the postcodes. something along the lines of: (pseudocode, can't remember the exact python implementation I did) postcode = resultarray[postcode] len = length(postcode) for (i = 0; i < len; i++): # if the fourth character is a digit or a space append it to the string if (i == 3 && postcode[i] =~ /(\d|\s)/: cleanPostcode .= postcode[i] # if this isn't the fourth character and it is an aplhanumeric character # append it to the string else if (postcode[i] =~ /(\w|\d): cleanPostcode .= postcode[i] That puts all the postcodes into the format that the Royal Mail uses. Then search on postcode ;) The next thing I did was to split each individual word out fom it field, and matched that in a specific order (I found starting with elements such as house name, number, and street name was the best approach). If a word matched it was assigned a score (1 for a exact match, 0.7 for a metaphone match and 0.6 for a soundex macth IIRC), and when the searching was finished I took the resulting score and divided it by the number of word elements. If that score was higher than any of the prevous scores then it was put in a given variable. If there where a number of equally good(bad?) matches then they were appended onto an array, and if there was no clear winner yb the time that the last of the records for that postcode had been process it spat out a multiple choice list. The trick is picking a threshold level below which no matches are put into the DB, even if they are the best scoring. (I used a threshold of 0.3 This can be refined, the current, extremely baroque, perl script that does this currently drops out certain values from the data array if there is an exact match with certain fields, such as house name. It doesn't reduce the value of the integer that the result is divided by though, thus favouring results that return an exact match on a couple of given fields. > The challenge is to fix some of the false negatives above without > introducing false positives! > > Any pointers gratefully received. Hope this is a) understandable, and b) useful ;) FWIW, the perl script (an I would expect a similarly implemented python script to perform about as well) running a somewhat flaky set of user collated data against the Royal Mail Addresspoint data managed a 75% hit rate, with an additional 5% requiring user intervention, and as near as I have been able to ascertain a >1% false positive count, from a dataset of nearly 17,000 addresses. With cleaner and more up to date data I would expect the results to be noticably better. [1] It is still my main language, I don't use python enough to think in it as easily as I think in perl ;) - -- James jamesk[at]homeric[dot]co[dot]uk "Consistency is the last resort of the unimaginative." - -- Bob Hope -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.5 (GNU/Linux) iD8DBQFB7FurqfSmHkD6LvoRAgdVAJ4t2HCaT52qbuqyT5yN59X+az0ZQwCfZgOH L5nTnPj+TF95Z+FCM65CzV0= =UkeW -----END PGP SIGNATURE----- From xah at xahlee.org Sat Jan 15 04:58:04 2005 From: xah at xahlee.org (Xah Lee) Date: 15 Jan 2005 01:58:04 -0800 Subject: [perl-python] 20050115, for statement Message-ID: <1105783084.748174.307680@f14g2000cwb.googlegroups.com> ? # this is an example of for statement ? # the % symbol calculates the remainder ? # of division. ? # the range(m,n) function ? # gives a list from m to n-1. ? ? a = range(1,51) ? for x in a: ? if x % 2 == 0: ? print x, 'even' ? ? # note that in this example, for goes over a list. ? # each time making x the value of the element. ? ? ------------------------------------ ? # this is similar code in perl ? ? @a=(1..50); ? for $x (@a) { ? if ( $x%2 ==0){ ? print $x, " even\n"; ? }} ? ? # PS each daily tip can be run. Just ? # copy the python part and save to a ? # file and run it as "python ? # file.py". Try it. ? ? ? Note: this post is from the Perl-Python ? a-day mailing list at ? http://groups.yahoo.com/group/perl-python/ ? to subscribe, send an email to ? perl-python-subscribe at yahoogroups.com if ? you are reading it on a web page, ? program examples may not run because ? groups.google.com changes the post slightly. ? ? Xah ? xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html From ianb at colorstudy.com Sun Jan 9 03:51:31 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Sun, 09 Jan 2005 02:51:31 -0600 Subject: The best way to do web apps with Python? In-Reply-To: <41E02FD5.5080703@holdenweb.com> References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41E02FD5.5080703@holdenweb.com> Message-ID: <41E0F093.4090002@colorstudy.com> Steve Holden wrote: > More ways than you can shake a stick at, but nowadays you should > consider using WSGI if you want your code to be portable across many > frameworks. The Web SIG worked very hard last year on defining this > gateway interface, with the intention that it should become widely > available, and implementations are available now on environments as > diverse as mod_python and CherryPy. > > You can read about it in Philip Eby's excellent PEP at > > http://www.python.org/peps/pep-0333.html WSGI isn't really something an application programmer can use; or at least it's not likely to be a very satisfying experience if they do. I'm optimistic that at some point most of the actively developed Python web frameworks we have now will be ported to WSGI. Ultimately, I think WSGI should be something a more casual Python web programmer wouldn't even realize exists. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From ncoghlan at iinet.net.au Tue Jan 11 07:57:59 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 11 Jan 2005 22:57:59 +1000 Subject: "Architecture of Python" was removed ? In-Reply-To: <004801c4f7cb$f62d1d30$1d02a8c0@cr> References: <004801c4f7cb$f62d1d30$1d02a8c0@cr> Message-ID: <41E3CD57.1020904@iinet.net.au> cr999 wrote: > I found the "Architecture of Python" ( http://wiki.cs.uiuc.edu/cs427/PYTHON By Jim Jackson, Kar-Han Tan )is very useful for my understanding of the Python's architecture. But I found the link is not link to that document today. It seems that the document was removed. Who knows what happened? > > Does anyone here have a copy of that document? Or who can tell me what is the email address of Jim Jackson or Kar-Han Tan. http://web.archive.org/web/20031222201953/http://wiki.cs.uiuc.edu/cs427/PYTHON Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ebolonev at mail.ru Sat Jan 15 15:52:54 2005 From: ebolonev at mail.ru (Egor Bolonev) Date: Sun, 16 Jan 2005 06:52:54 +1000 Subject: How can I get the names of the files in a directory? References: Message-ID: On Sat, 15 Jan 2005 15:16:02 GMT, .removethis. <"(.removethis.)kartic.krishnamurthy"@gmail.com> wrote: > Sara Fwd said the following on 1/15/2005 8:10 AM: >> Can you guys also help me find a module that looks in >> a directory and print out the names of the files in there? > > You can use glob: > > >>> import glob > >>> from os.path import isfile > >>> print filter(isfile, glob.glob('/tmp/*')) # can use patterns > > (will print a list of all files in the given directory, matching the > given pattern) > > If you want to traverse a directory tree recursively, please take a look > at this recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/200131 import os, os.path def get_all_files(path): if len(path) > 0: if path[-1] == ':': path = path + '\\' try: for i in os.listdir(path): j = os.path.join(path, i) if os.path.isdir(j): for ii in get_all_files(j): yield ii else: yield j except:pass for i in get_all_files('c:\\'): print i From kartic.krishnamurthy at gmail.com Sun Jan 9 20:10:04 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 9 Jan 2005 17:10:04 -0800 Subject: path to python file given module In-Reply-To: <1105317971.205487.82770@c13g2000cwb.googlegroups.com> References: <1105315568.887724.260370@c13g2000cwb.googlegroups.com> <1105315923.520581.280580@c13g2000cwb.googlegroups.com> <1105317971.205487.82770@c13g2000cwb.googlegroups.com> Message-ID: <1105319404.902746.179690@c13g2000cwb.googlegroups.com> That is because your module in not in a standard location that python can find it in. It is not that inspect.getsourcefile() is not working. Actually if you try reloading your filegen module after the os.chdir(), you will see that import fails. If you copy your filegen directory to the site-packages directory of python, you will get the complete path of the module no matter where you are inside your script. From grante at visi.com Sun Jan 16 21:03:03 2005 From: grante at visi.com (Grant Edwards) Date: 17 Jan 2005 02:03:03 GMT Subject: List problems in C code ported to Python References: <41ead925$0$87061$a1866201@visi.com> Message-ID: <41eb1cd7$0$10879$a1866201@visi.com> On 2005-01-16, Lucas Raab wrote: >>>Please see both the Python and C code at >>>http://home.earthlink.net/~lvraab. The two files are ENIGMA.C >>>and engima.py >> >> http://www.catb.org/~esr/faqs/smart-questions.html > > I didn't expect to get bitched out just because I didn't > follow "protocol." You didn't get "bitched out". You did get some very sound advice. You want help solving a problem, and there are ways you can greatly increase the chances that you'll get help with your problem. After being told the best ways to get help, you whined about it rather than following it. Nobody owes you anything. Remember that. [You're darned lucky somebody did take the time to go to your web site and proof your code for you after your posting said in effect "I'm too lazy to compose and post a precise question, so go look at my program and fix it for me."] Now, go back and read the smart questions reference. -- Grant Edwards grante Yow! Hello? Enema at Bondage? I'm calling visi.com because I want to be happy, I guess... From leyambe at cs.uct.ac.za Tue Jan 11 08:19:59 2005 From: leyambe at cs.uct.ac.za (Linda Eyambe) Date: Tue, 11 Jan 2005 15:19:59 +0200 Subject: including folders with McMillan Installer Message-ID: <001401c4f7e0$40950720$c8619e89@cs.uct.ac.za> Hi everyone, After months of hacking i managed to get my python software to work properly, and have even managed to turn it into an exe with Mcmillan's Installer (ran into a LookupError with py2exe so i tossed it). Anyway, now i'm wondering how to include entire folders and their content into the distribution directory. I created a COLLECT subclass for each folder something like this: coll1 = COLLECT ( [('file1.txt', 'C:/my/folder1/file1', 'DATA')], [('file2.txt', 'C:/my/folder1/file2', 'DATA')], ... name = folder1 ) coll2 = COLLECT ( [('file1.txt', 'C:/my/folder2/file1', 'DATA')], name = folder2 ) I have to do that for each file and each folder i want to include. How can i do this more efficiently? Also, when i run the exe by double-clicking on it directly from within the distribution directory it works fine, but once i create a shortcut or try to access it with the command-line eg C:/project/dist/project.exe it doesnt seem to be able to find the files that i imported with the COLLECT statement, even though in my source code all the file locations are relative. I get an error that goes something like... Cannot find the file or directory named './icons/splash.bmp' although it is clearly there. Any ideas? Thanks, Linda -------------- next part -------------- An HTML attachment was scrubbed... URL: From deetsNOSPAM at web.de Tue Jan 18 07:49:06 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 18 Jan 2005 13:49:06 +0100 Subject: generator expressions: performance anomaly? References: Message-ID: <354esdF4fouh0U1@individual.net> > Something else I was thinking about. I think it would be nice if the > python compilor could figure out whether a genexp in a list or tuple > expression always generates the same list or tuple and then instead > of generating code would generate the list or tuple in place. This won't ever happen in python - at least not in python otherwise similar to the one we know... The thing you're after is known as "common subexpression elemination" and can only be done in purely functional languages. While that certainly is an interesting property of a language, it e.g. forbids functions like time.time() - a too huge paradigm shift for python. -- Regards, Diez B. Roggisch From bvande at po-box.mcgill.ca Tue Jan 4 13:28:42 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue, 04 Jan 2005 13:28:42 -0500 Subject: Cookbook 2nd ed Credits (was Re: The Industry choice) In-Reply-To: <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> Message-ID: <41DAE05A.6000700@po-box.mcgill.ca> Alex Martelli said unto the world upon 2005-01-04 11:15: > wrote: > > >>But then I have THREE published recipes!! >>Does that mean that I get three free copies of the cookbook ? ;-) > > > ...ti piacerebbe eh...?-) Sorry, "one each", even though you have > _five_ credits. For the curious, here's the roster of most credited > contributors (remember, significant comments we merged into other's > recipes also count!-)...: > > > If you wished to count only _authored_ recipes (but that's a bit > misleading, since in several recipes-as-published there is a merge of > two or three separately submitted and accepted recipes, and here I'm > counting only the first-listed-author per published-recipe...): > > 1: 25 u'Luther Blissett' > > ...but each still gets ONE free copy...!-) > > > Alex Since I'm certain Luther won't be claiming his copy ;-) perhaps we could auction it off? Best, Brian vdB From snail at objmedia.demon.co.uk Fri Jan 7 08:49:34 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Fri, 7 Jan 2005 13:49:34 +0000 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <0WlDd.8830$5R.1182@newssvr21.news.prodigy.com> Message-ID: <+wsARHFuNp3BFwz6@objmedia.demon.co.uk> In message , Arich Chanachai writes >think). Or what about D? Digital Mars have a D compiler. http://www.digitalmars.com Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From jeff at ccvcorp.com Fri Jan 7 15:32:44 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 07 Jan 2005 12:32:44 -0800 Subject: The Industry choice In-Reply-To: <1gq0k74.1epsxog1dgcgbsN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <10trej2fl8dip65@corp.supernews.com> <1gq0k74.1epsxog1dgcgbsN%aleaxit@yahoo.com> Message-ID: <10tts536kn15a33@corp.supernews.com> Alex Martelli wrote: > Jeff Shannon wrote: > >>Note that the so-called 'viral' nature of GPL code only applies to >>*modifications you make* to the GPL software. The *only* way in which >>your code can be 'infected' by the GPL is if you copy GPL source. > > ... > >>(Problems may come if someone licenses a library under the GPL; that's >>what the LGPL was invented for. But the issue here is not that the >>GPL is bad, it's that the author used the wrong form of it.) > > > Stallman now says that you should use GPL, not Lesser GPL. > > http://www.gnu.org/licenses/why-not-lgpl.html > > Specifically, he wants library authors to use GPL to impose the viral > nature of GPL on other programs just USING the library -- the very > opposite of what you say about "only applies ... if you copy"! Ah, I haven't kept up on Stallman's current opinions, and was speaking from the understanding I had of GPL/LGPL as of a number of years ago (before that article was written). By "copy", above, I meant "use GPL source in your product". The GPL defines what it means to use source in a rather inclusive way. That inclusiveness means that the standard usage of libraries falls under their definition of "using source". This distinction in the normal terms of "usage" is what impelled the FSF to create the LGPL in the first place... So, I think what I said still (mostly) stands, as long as you look at it in terms of whether object code is copied into your executable. ;) It's still true that one can use (in a consumer sense) GPL software for whatever purpose one wishes, and the restrictions only kick in when one includes GPL code in another product. Indeed, I should have used the word "include" rather than "copy"... (It's hardly surprising that Stallman wants to use whatever leverage he can get to encourage FSF-style free software...) Jeff Shannon Technician/Programmer Credit International From simon.brunning at gmail.com Fri Jan 14 05:25:21 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 14 Jan 2005 10:25:21 +0000 Subject: Octal notation: severe deprecation In-Reply-To: <34o8n7F4e6uduU1@individual.net> References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105575689.335040.174490@c13g2000cwb.googlegroups.com> <34o8n7F4e6uduU1@individual.net> Message-ID: <8c7f10c6050114022561944b6c@mail.gmail.com> On Thu, 13 Jan 2005 16:50:56 -0500, Leif K-Brooks wrote: > Tim Roberts wrote: > > Stephen Thorne wrote: > > > >>I would actually like to see pychecker pick up conceptual errors like this: > >> > >>import datetime > >>datetime.datetime(2005, 04,04) > > > > > > Why is that a conceptual error? Syntactically, this could be a valid call > > to a function. Even if you have parsed and executed datetime, so that you > > know datetime.datetime is a class, it's quite possible that the creation > > and destruction of an object might have useful side effects. > > I'm guessing that Stephen is saying that PyChecker should have special > knowledge of the datetime module and of the fact that dates are often > specified with a leading zero, and therefor complain that they shouldn't > be used that way in Python source code. It would be useful if PyChecker warned you when you specify an octal literal and where the value would differ from what you might expect if you didn't realise that you were specifying an octal literal. x = 04 # This doesn't need a warning: 04 == 4 #x = 09 # This doesn't need a warning: it will fail to compile x= 012 # This *does* need a warning: 012 == 10 -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From rbt at athop1.ath.vt.edu Sun Jan 2 14:28:14 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Sun, 02 Jan 2005 14:28:14 -0500 Subject: arbitrary number of arguments in a function declaration In-Reply-To: References: Message-ID: Nick Coghlan wrote: > rbt wrote: > >> How do I set up a function so that it can take an arbitrary number of >> arguments? For example, I have a bunch of expenses which may grow or >> shrink depending on the client's circumstance and a function that sums >> them up... hard coding them is tedious. How might I make this dynamic >> so that it can handle any amount of expenses? >> >> def tot_expenses(self, e0, e1, e2, e3): >> pass > > > The Python Tutorial is a wonderful thing. . . But so is this list ;) > > Anyway, you can either set up your function to take a proper list, and > then discover that the sum function already exists to add up the > contents of a list: > > def tot_expenses(self, expenses): > self.total_expenses = sum(expenses) > > Or, have the function take a variable number of arguments, and do the > same thing: > > def tot_expenses(self, *args): > self.total_expenses = sum(args) > > Cheers, > Nick. > Many thanks! From grante at visi.com Tue Jan 25 23:49:00 2005 From: grante at visi.com (Grant Edwards) Date: 26 Jan 2005 04:49:00 GMT Subject: py2exe problem References: Message-ID: <41f7213c$0$2343$a1866201@visi.com> On 2005-01-26, Club-B42 wrote: > i've compiled my programm using command "python setup.py py2exe >1" > > python script works fine, but .exe version fails with > LookupError: no codec search functions registered: can't find encoding Googling for the error message will find you the answer. I don't remember what it is, but that's how I found it. IIRC, it's the very first in when you google Usenet. You need to tell py2exe to include some module-or-other that it doesn't by default. I don't remember the exact recipe, but I've got it at work. If you can't figure it out by tomorrow, let me know and I'll post a snippet from my setup.py file. -- Grant Edwards grante Yow! Sometime in 1993 at NANCY SINATRA will lead a visi.com BLOODLESS COUP on GUAM!! From ncoghlan at iinet.net.au Wed Jan 26 06:04:05 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 21:04:05 +1000 Subject: Tuple slices In-Reply-To: <41F7F5CF.5040902@freemail.gr> References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> <1106669254.838248.317170@z14g2000cwz.googlegroups.com> <10vdj4s9ib19fe3@corp.supernews.com> <41F7F5CF.5040902@freemail.gr> Message-ID: <41F77925.1000505@iinet.net.au> jfj wrote: > Jeff Shannon wrote: > >> >> >> So, what problem is it, exactly, that you think you'd solve by making >> tuple slices a view rather than a copy? >> > > I think views are good for > 1) saving memory > 2) saving time (as you don't have to copy the elements into the new tuple) 1. Applies only if you are making large slices, or a lot of slices with each containing at least 3 elements. A view can also *cost* memory, when it looks at a small piece of a large item. The view will keep the entire item alive, even though it needs only a small piece. 2. Hell no. The *elements* aren't copied, pointers to the elements are. If you *don't* copy the pointers, then every item access through the view involves an indirection as the index into the original sequence gets calculated. So views *may* save memory in some applications, but are unlikely to save time in any application (except any saving resulting from the memory saving). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From none.by.e-mail Thu Jan 6 22:31:10 2005 From: none.by.e-mail (Mike Thompson) Date: Fri, 07 Jan 2005 14:31:10 +1100 Subject: Another PythonWin Excel question In-Reply-To: References: <41ddb59e$0$8338$afc38c87@news.optusnet.com.au> Message-ID: <41de0285$0$5108$afc38c87@news.optusnet.com.au> It's me wrote: > Yes, Mike, > > Others pointed that out as well. For good reason. > > The difficulty is that they are all in VBAs. Most of them can be > translated to Python fairly easily, and some I can get from looking at the > recorded macro - but some requires quite a bit of head scratching. > > For instance, I wanted to figure out how create a new window. So, I went > through the record macro process and looked at the VBA code, it says: > > ActiveWindow.NewWindow app.ActiveWindow.NewWindow() > > Okay. Now what??? > > And for switching window, it says: > > Windows("Book1:1").Activate app.Windows.Item("Book1:1").Activate() --------------------------------------------------------------------- from win32com.client import Dispatch, constants app = Dispatch("Excel.Application") app.Visible = True workbook = app.Workbooks.Add() defaultWorksheet = workbook.Worksheets(1) app.ActiveWindow.NewWindow() app.ActiveWindow.NewWindow() # grab the capation (like 'Book1:1') from one of the windows thridWindowsCaption = app.Windows[2].Caption print thridWindowsCaption app.Windows.Item(thridWindowsCaption).Activate() ------------------------------------------------------------------------ Sometimes its useful to look in the file generated by makepy. It details all the classes and their methods AND there are annotations in the form of comments. Having said that, if you've never looked in a makepy generated module before, you're in for a shock - it takes a while before you figure out what you are looking at. When you get stuck, trial & error and a good debuger are your friend. -- Mike From exarkun at divmod.com Thu Jan 6 10:29:39 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 06 Jan 2005 15:29:39 GMT Subject: Embedding a restricted python interpreter In-Reply-To: Message-ID: <20050106152939.25734.439818807.divmod.quotient.3792@ohm> On Thu, 06 Jan 2005 16:05:50 +0100, Peter Maas wrote: >Craig Ringer schrieb: > > That is my understanding. In fact, I'd say with Python it's nearly > > impossible given how dynamic everything is and the number of tricks that > > can be used to obfuscate what you're doing. Think of the fun that can be > > had with str.encode / str.decode and getattr/hasattr . > > It would certainly be difficult to track all harmful code constructs. > But AFAIK the idea of a sandbox is not to look at the offending code > but to protect the offended objects: files, databases, URLs, sockets > etc. and to raise a security exception when some code tries to offend > them. Jython is as dynamic as C-Python and yet it generates class > files behaving well under the JVM's security regime. > > > > > I looked into this, and my conclusion ended up being "Well, I'm using > > Python because I want it's power and flexibilty. If I want a secure > > scripting environment, I should use something like Lua or Qt Script for > > Applications instead." > > It would be good for Python if it would offer a secure mode. Some > time ago I asked my hosting provider whether I could use mod_python > with apache to run Python scripts in the same way as PHP scripts. > He denied that pointing to Python security issues and to PHP safe. > mode. Python IS powerful but there are many areas where it is of > vital interest who is allowed to use its power and what can be done > with it. I think it would be a pity to exclude Python from these > areas where a lot of programming/computing is done. A Python sandbox would be useful, but the hosting provider's excuse for not allowing you to use mod_python is completely bogus. All the necessary security tools for that situation are provided by the platform in the form of process and user separation. Jp From aorfanakos at gmail.com Sun Jan 30 21:53:21 2005 From: aorfanakos at gmail.com (Aggelos I. Orfanakos) Date: 30 Jan 2005 18:53:21 -0800 Subject: Regarding exception handling In-Reply-To: References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> Message-ID: <1107140001.441995.32280@z14g2000cwz.googlegroups.com> I need it because the "various code" may raise other exceptions (not related to sockets). In such case, the "except socket.error, x:" won't catch it, but thanks to the "finally:", it is sure that the socket will close. From tim.golden at viacom-outdoor.co.uk Thu Jan 6 11:11:23 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 6 Jan 2005 16:11:23 -0000 Subject: OT: spacing of code in Google Groups Message-ID: <9A28C052FF32734DACB0A288A3533991035996@vogbs009.gb.vo.local> [Peter Hansen] | [Steve Holden] | > Peter Hansen wrote: | >> But the whole argument is fairly moot... I've needed a rectangle | >> operation only once in the last ten years, and if I hadn't known at | >> the time that my editor could do it (and spent about half an hour | >> figuring out how it worked), I could have written a utility to | >> do the job faster if I'd been using Python at the time... | > | > Or even used cut(1) from the command line. | | Or myybe not :-) | | Microsoft Windows XP [Version 5.1.2600] | (C) Copyright 1985-2001 Microsoft Corp. | | c:\>cut | 'cut' is not recognized as an internal or external command, | operable program or batch file. Thanks goodness for UnxUtils, is what I say: http://unxutils.sourceforge.net/ (But you probably knew that!) Microsoft Windows 2000 [Version 5.00.2195] (C) Copyright 1985-2000 Microsoft Corp. o:\scripts\work_in_progress\tim>c:\tools\cut --help Usage: c:\tools\cut [OPTION]... [FILE]... Print selected parts of lines from each FILE to standard output. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From daranrife at yahoo.com Fri Jan 28 18:15:15 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 15:15:15 -0800 Subject: LinearAlgebra incredibly slow for eigenvalue problems In-Reply-To: References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> <1106952951.834888.65430@f14g2000cwb.googlegroups.com> Message-ID: <1106954115.502875.155450@f14g2000cwb.googlegroups.com> Hi John, I do have more than one version of Python laying around. To do the build and install I am typing: /d2/python/bin/python setup.by build > &! build.out /d2/python/bin/python setup.by install > &! install.out Should I be doing something different? Daran From P at draigBrady.com Tue Jan 11 05:21:16 2005 From: P at draigBrady.com (P at draigBrady.com) Date: Tue, 11 Jan 2005 10:21:16 +0000 Subject: Python & unicode In-Reply-To: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> Message-ID: Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle. wrote: > Hi ! > > If Python is Ok with Unicode, why the next script not run ? > > # -*- coding: utf-8 -*- > > def ?????(toto): > return(toto*3) Because the coding is only supported in string literals. But I'm not sure exactly why. It would be nice to do: import math ? = math.pi -- P?draig Brady - http://www.pixelbeat.org -- From ktm-void at altern.org Wed Jan 12 15:05:15 2005 From: ktm-void at altern.org (Ktm) Date: Wed, 12 Jan 2005 21:05:15 +0100 Subject: m2crypto + asynchronous + stunnel Message-ID: Hello, i tried the demo echod_asyn.py without any certification verification (I modified echod_lib.py) and when I connect on the port with stunnel I've got the following error : error: uncaptured python exception, closing channel <__main__.ssl_echo_channel connected 127.0.0.1:34593 at 0xb7c5560c> (M2Crypto.SSL.SSLError:unexpected record [/usr/lib/python2.3/asyncore.py|write|77] [/usr/lib/python2.3/asyncore.py|handle_write_event|397] [echod-async.py|handle_write|33] [/usr/lib/python2.3/site-packages/M2Crypto/SSL/Connection.py|accept_ssl|84]) Thanks for your help, Ktm From corey.coughlin at attbi.com Wed Jan 5 21:24:33 2005 From: corey.coughlin at attbi.com (corey) Date: 5 Jan 2005 18:24:33 -0800 Subject: Concepts RE: Python evolution: Unease In-Reply-To: References: <20050105002302.542768387.EP@zomething.com> Message-ID: <1104978273.225072.19120@z14g2000cwz.googlegroups.com> Roman Suzi wrote: > On Wed, 5 Jan 2005, EP wrote: > > > I can try to write a PEP "Generic Programming Concepts". > That would be great. It's so hard to get your head around an abstract concept (a thought, not a programming concept) without a concrete example in some form of syntax. I think that's what's throwing off most people from the idea. And if you really do want to get it incorporated into whatever Guido is thinking, it would probably be best to hurry. ;) From newsgroups at jhrothjr.com Sat Jan 8 22:32:44 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 8 Jan 2005 21:32:44 -0600 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <1105219440.064891.199690@c13g2000cwb.googlegroups.com> Message-ID: <10u19fmj9086b8b@news.supernews.com> "jtauber" wrote in message news:1105219440.064891.199690 at c13g2000cwb.googlegroups.com... > My experiment, Cleese, was making progress before I got distracted by > other things. > > The approach was a micro-kernel in C made up of the CPython bytecode > interpreter with the file-related calls to libc ripped out and some > bare-metal port read/writes and memory operations exposed to Python as > built-in functions. > > Everything else could then be written in pure Python. Dave Long was > able to write a VGA driver in Python and an implementation of Sokoban > that used it. You could then boot your machine to Sokoban :-) > > I should probably get back to it at some stage. As my ex-wife was fond of saying, "I wish you'd have told me it was impossible before I did it." John Roth > > see http://cleese.sourceforge.net/ > James Tauber > http://jtauber.com/blog/ > From mirnazim at gmail.com Sun Jan 2 08:30:31 2005 From: mirnazim at gmail.com (mirnazim at gmail.com) Date: 2 Jan 2005 05:30:31 -0800 Subject: Frameworks for "Non-Content Oriented Web Apps" References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <1104672631.884144.294730@c13g2000cwb.googlegroups.com> I have started a topic that is really vauge. I knew that this topic is very general and abstract but I think it turned out to be more general that I had expected. Let me make an attemp at defining "Non-Content Oriented Web Applications". A "Non-Content Oriented Web Application": (1) will be accessed from web browser(obviously). (2) will be developed using 'W3C' and other open standards(STRICTLY, to ensure compatibility and portablity). (3) will expose some kind of functionality to the user, not just some document to read. (4) functionality can be very simple to very complex. I sat down to define what I actually mean by "Non-Content Oriented Web Applications" with a fairly clear idea, But suddenly every thing vanished from my mind, "OH MY GOD, I AM OUT OF WORDS". I think all of you have been i such situation at least once. So please help me in defining these "Non-Content Oriented Web Applications". To give a example, I think GMAIL comes quite close to what I am talking aout. From dalke at dalkescientific.com Mon Jan 3 18:15:23 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Mon, 03 Jan 2005 23:15:23 GMT Subject: input record sepArator (equivalent of "$|" of perl) References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> <1103657476.495700.191020@f14g2000cwb.googlegroups.com> <1103671235.093738.198680@z14g2000cwz.googlegroups.com> <86wtuup21t.fsf@guru.mired.org> Message-ID: Mike Meyer: > Trivia question: Name the second most powerfull country on earth not > using the metric system for everything. The UK? Before going there I thought they were a fully metric country. But I saw weather reports in degrees F, distances in yards and miles, and of course pints of beer. Andrew dalke at dalkescientific.com From eurleif at ecritters.biz Fri Jan 21 02:02:33 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Fri, 21 Jan 2005 02:02:33 -0500 Subject: Unbinding multiple variables In-Reply-To: References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> Message-ID: <35bnkeF4jpeetU1@individual.net> John Hunter wrote: > >>>del locals()['x'] The locals() dictionary will only modify values in a module's top-level code (i.e. when the expression "locals() is globals()" is true). From ncoghlan at iinet.net.au Sat Jan 8 01:52:03 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 16:52:03 +1000 Subject: switching an instance variable between a property and a normal value In-Reply-To: References: Message-ID: <41DF8313.6060106@iinet.net.au> Steven Bethard wrote: > where I also accept *args and **kwds when the default value is to be > called. It's certainly doable with a flag, but note that I have to > check the flag every time in both __getitem__ and setdefault. Alternatively, always use a function for the default value, and set _func to lambda: x when working by value :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tom at dev.null.daemon.de Sun Jan 9 07:32:08 2005 From: tom at dev.null.daemon.de (Thomas Linden) Date: 09 Jan 2005 13:32:08 +0100 Subject: static compiled python modules Message-ID: <87u0pqn5pz.fsf@dev.null.daemon.de> Hi, I made a static version of my python modules (2.4), all modules were build statically. The modules were linked into libpython2.4.a which has ~ 8 MB then. The build process then links the python binary against the libpython2.4.a, the resulting binary has ~ 5 MB afterwards (?). The problem is, that python ignores several modules, it tries to load the dynamic versions. E.g. if I do 'import math', it tells that it cannot find a module 'math'. Of course there is no mathmodule.so somewhere, because it is statically build-in. When I use 'nm' to take a look at the python binary, I can find all functions exported by the math module, so it is there, but python ignores it. In contrast, for example the posix module works. Its also compiled in, and doesn't exist as posixmodule.so. How can I tell python to use the compiled in modules and not try to load them from outside? kind regards, Tom -- Thomas Linden (http://www.daemon.de/) tom at co dot daemon dot de From lee at example.com Sat Jan 8 09:22:30 2005 From: lee at example.com (Lee Harr) Date: Sat, 08 Jan 2005 14:22:30 GMT Subject: "A Fundamental Turn Toward Concurrency in Software" References: <10tu7s9tjnbur81@news.supernews.com> Message-ID: >> [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that the >> continous CPU performance gain we've seen is finally over. And that future >> gain would primary be in the area of software concurrency taking advantage >> hyperthreading and multicore architectures. >> > Well, yes. However, it's not as bad as it looks. I've spent a good part > of my professional life with multiprocessors (IBM mainframes) and > I have yet to write a multi-thread program for performance reasons. > All of those systems ran multiple programs, not single programs > that had to take advantage of the multiprocessor environment. > Your typical desktop is no different. My current system has 42 > processes running, and I'd be willing to bet that the vast majority > of them aren't multi-threaded. > Exactly. If every one of your processes had its own 2 Ghz processor running nothing else, I think you would be pretty happy. Your OS had better be well-written to deal with concurrent access to memory and disks, but I think for general application development there will be huge speed boosts with little need for new programming paradigms. From beliavsky at aol.com Thu Jan 27 08:58:00 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 27 Jan 2005 05:58:00 -0800 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106814263.835719.181360@z14g2000cwz.googlegroups.com> <1106826024.655143.227050@c13g2000cwb.googlegroups.com> Message-ID: <1106834280.360742.116380@c13g2000cwb.googlegroups.com> michele.simionato at gmail.com wrote: > >> There is not much than can be done at the Python level. But I would > >> see with interest a Python spinoff geared towards simplicity. > > >I think this would be useless because advanced concepts exist for > >a reason. A simplified spin-off would aquire advanced concepts > >over time and would just become a clone of Python. > > And then we will need another simplified spinoff ;) > There is always a fight between simplificity and complexity. > Some complexity is not needed, and I am sure even in Python > something could be dropped. But it is difficult to find what can > be removed. Remember that Saint-Exupery quote? Something > like "a work of art is finished when there is nothing left to remove?" > M.S. "Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away." I know this quote because it is the motto of the F programming language http://www.fortran.com/F/ , a "simplified spinoff" of Fortran 95. From reinhold-birkenfeld-nospam at wolke7.net Sat Jan 22 14:45:49 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 22 Jan 2005 20:45:49 +0100 Subject: default value in a list In-Reply-To: References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> <1gqs9gb.1mmtpcit05ruwN%aleaxit@yahoo.com> Message-ID: <35fordF4llio5U1@individual.net> Michael Spencer wrote: > Alex Martelli wrote: > [explanation and the following code:] > >> >>> a, b, c = it.islice( >> ... it.chain( >> ... line.split(':'), >> ... it.repeat(some_default), >> ... ), >> ... 3) >> ... >> ... >> >>> def pad_with_default(N, iterable, default=None): >> ... it = iter(iterable) >> ... for x in it: >> ... if N<=0: break >> ... yield x >> ... N -= 1 >> ... while N>0: >> ... yield default >> ... N -= 1 > > Why not put these together and put it in itertools, since the requirement seems > to crop up every other week? > > >>> line = "A:B:C".split(":") > ... > >>> def ipad(N,iterable, default = None): > ... return it.islice(it.chain(iterable, it.repeat(default)), N) > ... > >>> a,b,c,d = ipad(4,line) > >>> a,b,c,d > ('A', 'B', 'C', None) Good idea! (+1 if this was posted on python-dev!) Reinhold From tom.blackwell at sympatico.ca Tue Jan 4 17:55:15 2005 From: tom.blackwell at sympatico.ca (Tom Blackwell) Date: Tue, 04 Jan 2005 17:55:15 -0500 Subject: Bug in handling of single underscore identifiers? Message-ID: Today I installed the 'mechanoid' package from sourceforge, but the self-test failed. On looking into it, I noticed odd behaviour in the handling of single underscore module names. Importing into the current namespace with 'from' seems to work, but accessing members of the imported module only works if the imported name is qualified by the containing module name. For example: >>> from mechanoid import _mechanoid_Common >>> from _mechanoid_Common import Common Traceback (most recent call last): File "", line 1, in ? ImportError: No module named _mechanoid_Common >>> from mechanoid._mechanoid_Common import Common **succeeds** >>> _mechanoid_Common Is this a bug or a feature? The language reference section 2.3.2 'Reserved classes of identifiers' indicates that identifiers starting with a single underscore are not imported by "from module import *". However I can't find any indication that "from module import _name" should work this way. Thanks Tom From jeff at ccvcorp.com Tue Jan 25 20:43:20 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 25 Jan 2005 17:43:20 -0800 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <10vdt2bpr0m84db@corp.supernews.com> Davor wrote: > [...] what I need that Python has and bash&dos don't is: > > 1. portability (interpreter runs quite a bit architectures) > 2. good basic library (already there) > 3. modules for structuring the application (objects unnecessary) > 4. high-level data structures (dictionaries & lists) > 5. no strong static type checking > 6. very nice syntax But modules, lists, and dictionaries *are* all objects, and one uses standard object attribute-access behavior to work with them. > so initially I was hoping this is all what Python is about, but when I > started looking into it it has a huge amount of additional (mainly OO) > stuff which makes it in my view quite bloated now... If you're basing your opinion of OO off of C++ and Java, then it's not too surprising that you're wary of it. But really, the OO in Python is as simple and transparent as the rest of the syntax. You don't need to define your own classes if you don't want to -- it's quite easy to write modules that contain only simple functions. A trivial understanding of objects & object attributes is needed to use the OO portions of the standard library. If you really want, you can still dictate that your own project's code be strictly procedural (i.e. you can use objects but not define objects). > anyhow, I guess > I'll have to constrain what can be included in the code through > different policies rather than language limitations... You mention elsewhere the fear of some developer with a 50-layer inheritance heirarchy. That's not something that normally happens in Python. Indeed, one of the tenets of the Zen of Python is that "flat is better than nested". But more than that, it's just not necessary to do that sort of thing in Python. In statically typed languages like C++ and Java, inheritance trees are necessary so that you can appropriately categorize objects by their type. Since you must explicitly declare what type is to be used where, you may need fine granularity of expressing what type a given object is, which requires complex inheritance trees. In Python, an object is whatever type it acts like -- behavior is more important than declared type, so there's no value to having a huge assortment of potential types. Deep inheritance trees only happen when people are migrating from Java. ;) Jeff Shannon Technician/Programmer Credit International From nick at craig-wood.com Fri Jan 28 13:30:00 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 28 Jan 2005 18:30:00 GMT Subject: debugging os.spawn*() calls References: <16890.22749.899414.324589@montanaro.dyndns.org> Message-ID: Martin Franklin wrote: > Skip Montanaro wrote: > > I have an os.spawnv call that's failing: > > > > pid = os.spawnv(os.P_NOWAIT, "ssh", > > ["ssh", remote, > > "PATH=%(path)s nice -20 make -C %(pwd)s" % locals()]) > > > > When I wait for it the status returned is 32512, indicating an exit status > > of 127. Unfortunately, I see no way to collect stdout or stderr from the > > spawned process, so I can't tell what's going wrong. > > While not a 'real' answer - I use pexpect to automate my ssh scripts > these days as I had a few problems using ssh with the os.* family > perhaps you may find pexpect a wee bit easier... If using 2.4 the subprocess module is a good solution too. It lets you catch stdout/stderr easily. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From mensanator at aol.com Sun Jan 9 23:51:16 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 9 Jan 2005 20:51:16 -0800 Subject: Old Paranoia Game in Python In-Reply-To: References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> <1105318366.966577.107460@c13g2000cwb.googlegroups.com> Message-ID: <1105332676.467941.155980@c13g2000cwb.googlegroups.com> Paul McGuire wrote: > wrote in message > news:1105318366.966577.107460 at c13g2000cwb.googlegroups.com... > > > > Aahz wrote: > > > Trust the computer, the computer is your friend. > > > > However, the computer isn't a fuckin' mind reader. > > > > If you're going to post source code on the usenet, don't > > have lines longer than 72 characters. Otherwise you'll > > find your code has wrapped lines. This not only causes > > syntax errors in your choose and print statements but > > also fucks up the formatting of of printed paragraphs. > > > > Stupid human. > > > > I copy-and-pasted to a file named para1.py, then wrote the > following python script with pyparsing to fix the erroneous > line breaks. > > -- Paul > > =============================== > from pyparsing import * > > extraLineBreak = White(" ",exact=1) + LineEnd().suppress() > text = file("para1.py").read() > newtext = extraLineBreak.transformString(text) > file("para2.py","w").write(newtext) Damn, that was pretty neat! You learn something new every day. From jarausch at skynet.be Mon Jan 3 11:55:40 2005 From: jarausch at skynet.be (Helmut Jarausch) Date: Mon, 03 Jan 2005 17:55:40 +0100 Subject: Is it possible to open a dbf In-Reply-To: References: <0F3Ad.3192$5R.2578@newssvr21.news.prodigy.com> <7xy8fjywar.fsf@ruckus.brouhaha.com> Message-ID: <41D9790C.4080907@skynet.be> Mikl?s P wrote: >>Paul Rubin wrote: >> >> >>>John Fabiani writes: >>> >>>>I'm wondering if there is a module available that will open a dbf >>> >>So far (more than a minute) I have discovered a reader only. So if you > > have > >>a URL or a search string it would be very helpful. > > >>TIA >>John > > > Yes, "dBase Python" yields only some code for reading dBase ... and lots of > enquires about such a thing... > I've been using http://www.fiby.at/dbfpy/ without any problems including writing/modifying dbf files. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From beliavsky at aol.com Sat Jan 8 09:18:39 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 8 Jan 2005 06:18:39 -0800 Subject: Other notes References: <1104287020.804167.9420@f14g2000cwb.googlegroups.com> <863bxpuhlj.fsf@guru.mired.org> <41d35721.1382016815@news.oz.net> Message-ID: <1105193919.577670.176960@f14g2000cwb.googlegroups.com> Bengt Richter wrote: >OTOH, there is precedent in e.g. fortran (IIRC) for named operators of the >form .XX. -- e.g., .GE. for >= so maybe there could be room for both. Yes, but in Fortran 90 "==", ">=" etc. are equivalent to ".EQ." and ".GE.". It is also possible to define operators on native and user-defined types, so that Y = A .tx. B can be written instead of the expression with the F90 intrinsic functions Y = matmul(transpose(A),B) The Fortran 95 package Matran at http://www.cs.umd.edu/~stewart/matran/Matran.html uses this approach to simplify the interface of the Lapack library and provide syntax similar to that of Matlab and Octave. I don't know if the syntax of your idea clashes with Python, but it is viable in general. From vze4rx4y at verizon.net Tue Jan 4 15:59:24 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 04 Jan 2005 20:59:24 GMT Subject: why does UserDict.DictMixin use keys instead of __iter__? References: <1104836152.639270.196200@z14g2000cwz.googlegroups.com> <1RxCd.847728$8_6.18665@attbi_s04> Message-ID: [Steven Bethard] > Sorry, my intent was not to say that I didn't know from the docs that > UserDict.DictMixin required keys(). Clearly it's documented. My > question was *why* does it use keys()? Why use keys() when keys() can > be derived from __iter__, and __iter__ IMHO looks to be a more basic > part of the mapping protocol. Viewed from the present, __iter__() may seem more basic. However, it is a recent innovation. The keys() method, on the other hand, goes back to the beginning. There were no shortage of mapping-like classes defining keys() but not __iter__(). Still, if __iter__() is provided, UserDict.DictMixin will take advantage of it. The same is also true for __contains__(), and iteritems(). Raymond Hettinger From simoninusa2001 at yahoo.co.uk Sat Jan 8 20:01:45 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 8 Jan 2005 17:01:45 -0800 Subject: Python Installation In-Reply-To: <1105220812.579690.292260@c13g2000cwb.googlegroups.com> References: <1105220812.579690.292260@c13g2000cwb.googlegroups.com> Message-ID: <1105232505.142279.85810@c13g2000cwb.googlegroups.com> brolewis wrote: > I need to install Python on a number of laptop computers (at least a > dozen). I am needing to install Python 2.4, pycrypto, win32all, > wxPython, and pyCurl. You could try the recently-announced MOVPY, or NSIS/InnoSetup as you say. Or simply put the five installers on a disk - if it's only a dozen machines, it's not going to take long if you don't have to download each time. They are simple .exe installers, it's not as if you have to compile and deal with dependancies etc. like on Linux. I would say install on one machine, then just copy the C:\Python24 directory, but then you'd have to deal with the missing Registry entries.... From eric_brunel at despammed.com Fri Jan 7 06:03:14 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 07 Jan 2005 12:03:14 +0100 Subject: Tkinter Puzzler In-Reply-To: References: Message-ID: <41de6aa3$0$3508$8fcfb975@news.wanadoo.fr> Tim Daneliuk wrote: > I am trying to initialize a menu in the following manner: > > for entry in [("Up", KeyUpDir), ("Back", KeyBackDir), ("Home", > KeyHomeDir), ("Startdir", KeyStartDir), ("Root", KeyRootDir)]: > > func = entry[1] > UI.ShortBtn.menu.add_command(label=entry[0], command=lambda: > func(None)) > > However, at runtime, each of the menu options binds to the *last* function > named in the list (KeyStartDir). > > Explicitly loading each entry on its own line works fine: > > UI........command=lambda:KeyWHATEVERDir(None) > > Any ideas why the first form does not fly? This has nothing to do with Tkinter, but only with the way nested scopes work: to put it roughly, your "lambda: func(None)" only knows about the *name* func, which is not actually evaluated until the button is pressed. And when the button is pressed, the name func is bound to the last command in the loop. To do what you want, change your code to: for entry in (...): UI.ShortBtn.menu.add_command( label=entry[0], command=lambda func=entry[1]: func(None) ) This way, the value for the func parameter is evaluated when the function is defined and not when it is called. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From frans.englich at telia.com Mon Jan 17 16:03:11 2005 From: frans.englich at telia.com (Frans Englich) Date: Mon, 17 Jan 2005 21:03:11 +0000 Subject: Assigning to self In-Reply-To: <10uo6hbn040qt24@news.supernews.com> References: <10uo6hbn040qt24@news.supernews.com> Message-ID: <200501172103.11294.frans.englich@telia.com> On Monday 17 January 2005 20:03, John Roth wrote: > "Frans Englich" wrote in message > In other words, you're trying to create a singleton. In general, > singletons are frowned on these days for a number of reasons, > not least because of the difficulty of testing them. Then I have some vague, general questions which perhaps someone can reason from: what is then the preferred methods for solving problems which requires Singletons? Is it only frowned upon in Python code? Cheers, Frans From skip at pobox.com Mon Jan 31 17:48:05 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 31 Jan 2005 16:48:05 -0600 Subject: Request for Feedback; a module making it easier to use regular expressions. In-Reply-To: <310120051504352505%kenneth.m.mcdonald@sbcglobal.net> References: <310120051504352505%kenneth.m.mcdonald@sbcglobal.net> Message-ID: <16894.46501.762775.378035@montanaro.dyndns.org> Ken> rex is a module intended to make regular expressions easier to Ken> create and use... Have you checked out Ping's rxb module? http://lfw.org/python/ Skip From evan at tokenexchange.com Mon Jan 17 12:42:33 2005 From: evan at tokenexchange.com (Evan Simpson) Date: Mon, 17 Jan 2005 11:42:33 -0600 Subject: Producer/consumer Queue "trick" In-Reply-To: References: Message-ID: <41EBF909.9010208@tokenexchange.com> I should clarify up front that I may have given an overblown sense of how long the producer thread typically takes to generate a board; It's usually a few tenths of a second, up to a few seconds for especially fecund boards. My concern was that even a few seconds is long enough for fifty requests to get piled up, and I was experiencing mysterious breakdowns where Apache was suddenly totally clogged up and taking *minutes* to respond. Jeremy Bowers wrote: > Looking over your information about "how to play", my only guess is that > you're generating all possible words that may exist in the board, at the > time of board generation. Yep. I do this in order to minimize the cost of the most common request that WEBoggle handles, which is checking a submitted word to see whether it is a valid word on the board, a valid word not on the board, or an invalid word. With the current code, this averages 1ms. > But it also looks like you score once at the end (as you have to anyhow in > order to cancel out words found by multiple people, according to the rules > of Boggle). WEBoggle is a little different than regular Boggle, in that your score is the plain sum of the scores for all of the words that you found, with no cancellation. I'm planning to add a "vs." feature eventually that will involve cancellation, but even then I'll retain the immediate feedback upon guessing a word. In addition, many players enjoy seeing the list of "Words not found by anyone". > (The other thing I can think of is that you are trying to verify that the > board contains some minimal number of words, in which case I submit that > boards with only 20-ish words is just part of the game :-) I've never sat > down and really studied the Boggle dice, but I've always expected/hoped > that there is at least one or two dice with all vowels; even so the odds > of no vowels are small and easily algorithmically discarded. ) Believe it or not, before I added code to filter them out, I was generating enough boards with *zero* valid words on them to get complaints. > Also, entirely separate plug, you may be interested in my XBLinJS project Very nifty! Well beyond my current needs, but good to know about. Cheers, Evan @ 4-am From roy at panix.com Wed Jan 5 17:05:40 2005 From: roy at panix.com (Roy Smith) Date: 5 Jan 2005 17:05:40 -0500 Subject: Building unique comma-delimited list? Message-ID: I've got a silly little problem that I'm solving in C++, but I got to thinking about how much easier it would be in Python. Here's the problem: You've got a list of words (actually, they're found by searching a data structure on the fly, but for now let's assume you've got them as a list). You need to create a comma-delimited list of these words. There might be duplicates in the original list, which you want to eliminate in the final list. You don't care what order they're in, except that there is a distinguised word which must come first if it appears at all. Some examples ("foo" is the distinguised word): ["foo"] => "foo" ["foo", "bar"] => "foo, bar" ["bar", "foo"] => "foo, bar" ["bar", "foo", "foo", "baz", "bar"] => "foo, bar, baz" or "foo, baz, bar" The best I've come up with is the following. Can anybody think of a simplier way? -------------------- words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"] # Eliminate the duplicates; probably use set() in Python 2.4 d = dict() for w in words: d[w] = w if d.has_key ("foo"): newWords = ["foo"] del (d["foo"]) else: newWords = [] for w in d.keys(): newWords.append (w) s = ', '.join (newWords) print s -------------------- From elephantum at dezcom.mephi.ru Sat Jan 8 06:44:44 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sat, 08 Jan 2005 14:44:44 +0300 Subject: python3: 'where' keyword In-Reply-To: References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> Message-ID: <349vdcF45c9crU2@individual.net> Nick Coghlan wrote: >> It also allows the necessary but uninteresting setup for an expression >> to be moved "out of the way", bringing the expression that does the >> real work to prominence. > Killer app for this keyword: > > class C(object): > > x = property(get, set) where: > def get(self): > return "Silly property" > def set(self, val): > self.x = "Told you it was silly" oh, that's great! I can't imagine prettier example From steve at holdenweb.com Mon Jan 24 10:52:04 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 24 Jan 2005 10:52:04 -0500 Subject: Right place for third party modules (here: fixedpoint) In-Reply-To: <35kj2iF4n6sokU1@news.dfncis.de> References: <35kj2iF4n6sokU1@news.dfncis.de> Message-ID: Sibylle Koczian wrote: > Hello, > > for the first time since getting Python I can't get a third party module > to work. > > I got fixedpoint.0.1.2.tar.gz from SourceForge for use with KinterbasDB. > After unpacking I had a directory called "fixedpoint" which I put under > my site-packages directory. There are no installation instructions and > just the one module fixedpoint.py (and some documentation and examples). > > All of this under Windows XP, with Python 2.4. > > Now I try to use the module, but > > import fixedpoint > > says "ImportError: No module named fixedpoint". > > I suppose fixedpoint is no package as described in the tutorial and so > "site-packages" might not be the right place for it. But where does it > belong? I think it should go somewhere in the Python directory tree, not > among my own scripts. > > Thank you, > Koczian > Instead, just move the "fixedpoint.py" file to your site-packages directory. You can then delete the empty fixedpoint directory, as it won't do anything except get in the way. Packages are implemented as directories, but modules are single Python files. "Site-packages" is a perfectly acceptable place to put "site modules" as well ;-) regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From jelle.feringa at ezct.net Mon Jan 17 09:27:14 2005 From: jelle.feringa at ezct.net (Jelle Feringa // EZCT / Paris) Date: Mon, 17 Jan 2005 15:27:14 +0100 Subject: OCAMl a more natural extension language for python? In-Reply-To: <41ebb95e$0$6625$8fcfb975@news.wanadoo.fr> Message-ID: <20050117142655.8D02C1C001EC@mwinf0203.wanadoo.fr> Hmmmm. Not familiar with erlang at all... > Subject: Re: OCAMl a more natural extension language for python? > > Hi ! > > OCAML is very complementary at Python : > > unreadable vs readable That's depending on how you compare; I find OCAML quite readable compared to C / Fortran > functionnel vs procedural/POO/etc. OCAML is not a true functional language, its also OO > compiled vs interpreted (or compil JIT) > very fast vs mean velocity What I'm looking for! > hard to learn vs easy to easy to learn Is it in comparison to C? > Yes, OCAML is very complementary, too much, much too, complementary at > Python... > > But, C is not complementary to Python (in the same state of mind). So some additional arguments to the hypotheses of OCAMl being a natural extension language to Python? Cheers, Jelle. From perrin.aybara81 at gmail.com Tue Jan 18 10:03:41 2005 From: perrin.aybara81 at gmail.com (Perrin Aybara) Date: Tue, 18 Jan 2005 20:33:41 +0530 Subject: bind error!!!!! Message-ID: hi.. my code was working pretty well until yesterday.suddenly it started giving me bind error: address already in use. but i have logged out and again logged in, but still the problem is not solved can somebody give me solution for this thankx perrin From peter at engcorp.com Sun Jan 9 13:48:57 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jan 2005 13:48:57 -0500 Subject: Guild of Python consultants? In-Reply-To: References: Message-ID: Mikl?s P wrote: > Hello freelancers out there, > > Is there such a thing somewhere? Yes, I'm aware of the Python Business > Forum. But I mean something specifically for (individual) consultants. > By searching on Google, I couldn't find a "virtual guild" of consultants who > try to make a living from Python and technologies built around it The term "consultant" means different things to different people, unfortunately. I know of many people for whom "consultant" is synonymous with "contract programmer", meaning somebody who looks for temporary positions at (usually) an hourly rate somewhat higher than what a permanent employee gets (but without benefits), and who simply joins a team as a regular member, doing whatever they are told. Some have special expertise, many do not. I also know of many people (myself included) who restrict the term to those who have a deep expertise in one or more areas and who look for projects where they can be brought in to apply that expertise, usually by telling the customer what to do (or what not to do any more, perhaps). This sort of work can be hourly, or quite often daily or even at a fixed price (say, for specialized "emergency" troubleshooting, or for a design task). There is obviously overlap between those two descriptions but, in my experience, very little overlap between the sorts of work which those two breeds of "consultants" actually want to perform. (The second type will take on jobs that the former would take, often grudgingly if work is scarce, while the former are rarely qualified to take on the sort of work that interests the latter.) As a result, I suspect that any organization that doesn't make it clear which type of "consultant" is involved could cause a great deal of confusion amongst its members and their clients. Which type do you mean? -Peter From tzot at sil-tec.gr Wed Jan 26 05:51:19 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 26 Jan 2005 12:51:19 +0200 Subject: string.atoi and string.atol broken? References: <1106700417.482871.45140@z14g2000cwz.googlegroups.com> Message-ID: On Wed, 26 Jan 2005 08:58:45 +0100, rumours say that Peter Otten <__peter__ at web.de> might have written: >By the way, does anyone know the Greek name for 36? triakontahexadecimal would be a nice compromise of greek and the "hexadecimal" convention of having six before ten -- "???" ("hexi") is six, "????" ("deka") is ten, "?????????" ("triakonta") is thirty. I think in ancient Greek sometimes units came before tens, just like in German (another similarity is the verb in the end of the sentence, as Mark Twain also noted sometime in a humourous article AFAIR.) In current Greek hexadecimal is "????????????" ("dekaexadikon"). -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From michele.simionato at gmail.com Tue Jan 4 05:55:29 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 4 Jan 2005 02:55:29 -0800 Subject: The Industry choice In-Reply-To: <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> Message-ID: <1104836129.741586.179510@c13g2000cwb.googlegroups.com> But then I have THREE published recipes!! Does that mean that I get three free copies of the cookbook ? ;-) Michele From http Sat Jan 8 05:34:08 2005 From: http (Paul Rubin) Date: 08 Jan 2005 02:34:08 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> Message-ID: <7xhdlsw6ov.fsf@ruckus.brouhaha.com> AdSR writes: > > Killer app for this keyword: > > class C(object): > > x = property(get, set) where: > > def get(self): > > return "Silly property" > > def set(self, val): > > self.x = "Told you it was silly" > > Hey, this is super-elegant! Heh, even further: z = C() where: class C(object): ... Lets you make anonymous classes and singleton objects. From skip at pobox.com Sat Jan 8 08:49:51 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 8 Jan 2005 07:49:51 -0600 Subject: Pre/Postconditions with decorators In-Reply-To: <1105190031.287227.319360@c13g2000cwb.googlegroups.com> References: <1105094828.619317.315340@z14g2000cwz.googlegroups.com> <34814fF43bm4cU1@individual.net> <1105190031.287227.319360@c13g2000cwb.googlegroups.com> Message-ID: <16863.58623.491403.349653@montanaro.dyndns.org> >> Eiffel (language) has both type checking and design by contract. >> Python lacks both. Actually, Python is strongly typed. It's just dynamically instead of statically typed. Skip From cwittern at yahoo.com Wed Jan 12 21:59:14 2005 From: cwittern at yahoo.com (Christian Wittern) Date: 12 Jan 2005 18:59:14 -0800 Subject: Re Wide Unicode build for Windows available somewhere? Message-ID: <5d5d851f.0501121859.56c33f0c@posting.google.com> > Wide unicode is currently not supported on Windows. A number of > internal APIs (in particular for the registry, and for the "mbcs" > codec) assume that sizeof(Py_UNICODE) is 2. Contributions are > welcome. >Even with that fixed, Pythonwin would still need a major rework > to support wide Unicode. Thanks Martin for your reply. So this looks rather dim. I usually work on a Mac, where wide support is just a matter of ./configure --enable-unicode=ucs4 make so I foolishly thought it must be similar on Windows. All the best, chris From skip at pobox.com Sun Jan 2 20:52:05 2005 From: skip at pobox.com (Skip Montanaro) Date: Sun, 2 Jan 2005 19:52:05 -0600 Subject: Calling Function Without Parentheses! In-Reply-To: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> Message-ID: <16856.42309.676788.850210@montanaro.dyndns.org> Kamilche> I called a function without the ending parentheses. I sure do Kamilche> WISH Python would trap it when I try to do the following: Kamilche> MyFunc Kamilche> instead of: Kamilche> MyFunc() Google for pychecker. Skip From kartic.krishnamurthy at gmail.com Wed Jan 12 15:39:05 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 12 Jan 2005 12:39:05 -0800 Subject: encryption/decryption help In-Reply-To: <7xwtuibd26.fsf@ruckus.brouhaha.com> References: <7xwtuibd26.fsf@ruckus.brouhaha.com> Message-ID: <1105562345.525224.319120@z14g2000cwz.googlegroups.com> Hi, Can you use ssh tunneling? You will not be changing anything except add an extra ssh layer to tunnel your data through. There is how-to at http://www.ccs.neu.edu/groups/systems/howto/howto-sshtunnel.html (or you can google for tunneling) Please note you can not use MD5 as it is not reversible. Thanks, --Kartic From marklists at mceahern.com Wed Jan 19 22:29:50 2005 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 19 Jan 2005 21:29:50 -0600 Subject: list item's position In-Reply-To: References: Message-ID: <41EF25AE.6060403@mceahern.com> Bob Smith wrote: > Hi, > > I have a Python list. I can't figure out how to find an element's > numeric value (0,1,2,3...) in the list. Here's an example of what I'm > doing: Use enumerate() (new in Python 2.3, IIRC). Otherwise: for i in range(len(sequence)): item = sequence[i] ... > > for bar in bars: > if 'str_1' in bar and 'str_2' in bar: > print bar > > This finds the right bar, but not its list position. The reason I need > to find its value is so I can remove every element in the list before > it so that the bar I found somewhere in the list becomes element 0... > does that make sense? Sure. You want to slice the list starting at the index of the first occurrence: index = min([i for i, item in enumerate(sequence) if 'str_1' in item and 'str_2' in item]) print sequence[index:] // m From steven.bethard at gmail.com Sun Jan 2 14:30:22 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 02 Jan 2005 19:30:22 GMT Subject: arbitrary number of arguments in a function declaration In-Reply-To: References: Message-ID: rbt wrote: > How do I set up a function so that it can take an arbitrary number of > arguments? If you haven't already, you should check out the Tutorial: http://docs.python.org/tut/node6.html#SECTION006730000000000000000 > How might I make this dynamic so > that it can handle any amount of expenses? > > def tot_expenses(self, e0, e1, e2, e3): > pass py> class C(object): ... def tot_expenses(self, *expenses): ... print expenses ... py> C().tot_expenses(110, 24) (110, 24) py> C().tot_expenses(110, 24, 2, 56) (110, 24, 2, 56) Steve From peter at somewhere.com Wed Jan 26 08:10:47 2005 From: peter at somewhere.com (Peter Maas) Date: Wed, 26 Jan 2005 14:10:47 +0100 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: Davor schrieb: > so initially I was hoping this is all what Python is about, but when I > started looking into it it has a huge amount of additional (mainly OO) > stuff which makes it in my view quite bloated now. So you think f.write('Hello world') is bloated and file_write(f,'Hello world') is not? This is the minimum amount of OO you will see when using Python. But I guess you will use OO in the long run to *avoid* bloated code: --------------snip--------------- print "*** Davor's evolution towards an OO programmer ***" print '\n*** Step 1: OO is evil, have to use atomic variables:' name1 = 'Smith' age1 = 35 sex1 = 'male' name2 = 'Miller' age2 = 33 sex2 = 'female' print name1, age1, sex1, name2, age2, sex2 print '\n*** Step 2: This is messy, put stuff in lists:' p1 = ['Smith', 35, 'male'] p2 = ['Miller', 33, 'female'] for e in p1: print e for e in p2: print e print '\n*** Step 3: Wait ..., p[2] is age, or was it sex? Better take a dict:' p1 = dict(name = 'Smith', age = 35, sex = 'male') p2 = dict(name = 'Miller', age = 33, sex = 'female') for e in p1.keys(): print '%s: %s' % (e, p1[e]) for e in p2.keys(): print '%s: %s' % (e, p2[e]) print '\n*** Step 4: Have to create person dicts, invoice dicts, ...better use dict templates:' class printable: def __str__(self): '''magic method called by print, str() ..''' ps = '' for e in self.__dict__.keys(): ps += '%s: %s\n' % (e, str(self.__dict__[e])) return ps class person(printable): def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex class invoice(printable): def __init__(self, name, product, price): self.name = name self.product = product self.price = price per = person(name = 'Smith', age = 35, sex = 'male') inv = invoice(name = 'Smith', product = 'bike', price = 300.0) print per print inv --------------snip--------------- Either your program is small. Then you can do it alone. Or you will reach step 4. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From jbenson at sextans.lowell.edu Tue Jan 25 23:11:49 2005 From: jbenson at sextans.lowell.edu (Jim Benson) Date: Tue, 25 Jan 2005 21:11:49 -0700 (MST) Subject: OT In-Reply-To: Message-ID: On Wed, 26 Jan 2005 phr at sextans.lowell.edu wrote: > That sounds like you're doing a closed source product and need an ENC > exception or something even worse. Python should qualify for the TSU > exception which only requires sending an email. > > http://www.bxa.doc.gov/encryption/PubAvailEncSourceCodeNofify.html > Sorry for the completely off-topic question. Last night and now tonight i have seen legitimate posts from phr that resolves as: Date: Wed, 26 Jan 2005 03:43:49 GMT From: phr at sextans.lowell.edu To: python-list at python.org Newsgroups: comp.lang.python Subject: Re: Crypto in Python: (Was: What's so funny? WAS Re: rotor replacement) However, i know for a fact that phr is _not_ a user at sextans.lowell.edu. Is this a problem with my dns? Thanks Jim From gdamjan at gmail.com Wed Jan 26 08:13:15 2005 From: gdamjan at gmail.com (Damjan) Date: Wed, 26 Jan 2005 14:13:15 +0100 Subject: execute python code from db References: Message-ID: <35pjbbF4n84hrU1@individual.net> > for python_code in c.fetchall(): > execute (python_code) > > Maybe feed python with stdin??. eval -- damjan From sp1d3rx at gmail.com Tue Jan 18 14:51:59 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 18 Jan 2005 11:51:59 -0800 Subject: Fuzzy matching of postal addresses In-Reply-To: References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <1106077919.685449.81300@c13g2000cwb.googlegroups.com> I think you guys are missing the point. All you would need to add to get a 'probable match' is add another search that goes through the 10% that didnt get matched and do a "endswith" search on the data. From the example data you showed me, that would match a good 90% of the 10%, leaving you with a 1% that must be hand matched. You would have to combine this idea with Jeff Shannon's idea to make it work more efficiently. From tundra at tundraware.com Sun Jan 23 06:52:39 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 23 Jan 2005 06:52:39 EST Subject: Insanity In-Reply-To: References: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> Message-ID: <3sfcc2-b6v1.ln1@eskimo.tundraware.com> Fredrik Lundh wrote: > Tim Daneliuk wrote: > > >>Given an arbitrary string, I want to find each individual instance of >>text in the form: "[PROMPT:optional text]" >> >>I tried this: >> >> y=re.compile(r'\[PROMPT:.*\]') >> >>Which works fine when the text is exactly "[PROMPT:whatever]" > > > didn't you leave something out here? "compile" only compiles that pattern; > it doesn't match it against your string... Sorry - I thought this was obvious - I was interested more in the conceptual part of the contruction of the re itself. > >>but does not match on: >> >> "something [PROMPT:foo] something [PROMPT:bar] something ..." >> >>The overall goal is to identify the beginning and end of each [PROMPT...] >>string in the line. > > > if the pattern can occur anywhere in the string, you need to use "search", > not "match". if you want multiple matches, you can use "findall" or, better > in this case, "finditer": > > import re > > s = "something [PROMPT:foo] something [PROMPT:bar] something" > > for m in re.finditer(r'\[PROMPT:[^]]*\]', s): > print m.span(0) > > prints > > (10, 22) > (33, 45) > > which looks reasonably correct. > > (note the "[^x]*x" form, which is an efficient way to spell "non-greedy match" > for cases like this) > Thanks - very helpful. One followup - your re works as advertised. But if I use: r'\[PROMPT:[^]].*\]' it seems not to. the '.*' instead of just '*' it matches the entire string ... which seems counterintutive to me. Thanks, -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From miki.tebeka at zoran.com Tue Jan 11 08:26:55 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 11 Jan 2005 15:26:55 +0200 Subject: Exception not captured Message-ID: <20050111132654.GP3808@zoran.com> Hello All, Can someone please explain how is the following code fragment possible? (If you're interested I can place the whole project somewhere). def checkout(dest, log): '''Get latest version from SCM client - SCM client to use dest - Destination directory ''' try: SCM.checkout(dest, log) except SCMError, e: raise NightlyError("Checkout") except Exception, e: import inspect file = inspect.getsourcefile(e.__class__) line = inspect.getsourcelines(e.__class__)[1] print "%s:%d" % (file, line) file = inspect.getsourcefile(SCMError) line = inspect.getsourcelines(SCMError)[1] print "%s:%d" % (file, line) print SCMError is e.__class__ raise SystemExit I get to the second "except" clause, and the printout is: /home/mikit/work/nightly/scm/common.py:3 /home/mikit/work/nightly/scm/common.py:3 False How is this possible? Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From fredrik at pythonware.com Sat Jan 29 02:38:38 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 29 Jan 2005 08:38:38 +0100 Subject: Pystone benchmark: Win vs. Linux (again) References: Message-ID: Franco Fiorese wrote: > I am relatively new about Python benchmarks. > After some experiments I found that Python on my PC Windows XP has a relevant higher performance > than on Linux. The simple test using pystone.py shows this: > > * Windows XP Pro: 16566.7 pystones/second > * Linux (kernel 2.6.9 NPTL): 12346.2 pystones/second what Python version are you using for these tests? what Windows build? From jaydonnell at gmail.com Fri Jan 21 20:15:27 2005 From: jaydonnell at gmail.com (Jay donnell) Date: 21 Jan 2005 17:15:27 -0800 Subject: why am I getting a segmentation fault? In-Reply-To: References: <1106330476.419418.46920@f14g2000cwb.googlegroups.com> Message-ID: <1106356527.187742.242380@f14g2000cwb.googlegroups.com> Thank you. I made all the changes you recommended and everything seems to be working. From klachemin at comcast.net Tue Jan 25 22:10:49 2005 From: klachemin at comcast.net (Kamilche) Date: 25 Jan 2005 19:10:49 -0800 Subject: Open Folder in Desktop In-Reply-To: <41f6033a$1@news.uni-ulm.de> References: <1106635751.661619.253930@c13g2000cwb.googlegroups.com> <41f6033a$1@news.uni-ulm.de> Message-ID: <1106709049.277503.10270@z14g2000cwz.googlegroups.com> Thanks, startfile worked great for me! From gsakkis at rutgers.edu Wed Jan 26 10:39:26 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Wed, 26 Jan 2005 10:39:26 -0500 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> <1106669254.838248.317170@z14g2000cwz.googlegroups.com> <10vdj4s9ib19fe3@corp.supernews.com> <41f772b2.1858112584@news.oz.net> Message-ID: <35prt9F4rbhh5U1@individual.net> "Bengt Richter" wrote in message news:41f772b2.1858112584 at news.oz.net... > On Wed, 26 Jan 2005 11:55:59 -0800, jfj wrote: > > >Jeff Shannon wrote: > > > >> > >> > >> So, what problem is it, exactly, that you think you'd solve by making > >> tuple slices a view rather than a copy? > >> > > > >I think views are good for > > 1) saving memory > > 2) saving time (as you don't have to copy the elements into the new tuple) > > > >And they are worth it. However, (as in other cases with slicing), it is > >very easy and fast to create a view for a slice with the default step > >'1', while it's a PITA and totally not worth it to create a view for a > >slice with non default step. I think it would be good to: > > > > if slice_step == 1 > > create_view > > else > > create_new_tuple > > > >Actually, i think that slices with step, is a bad feature in general > >and i think I will write a PEP to suggest their removal in python3k. > > > What's the big deal with other than 1 steps? It is just adjusting a few numbers > so that you can either index the new virtual slice with an integer and return the > element, in which case the index into the original tuple will be > someoffset+i*somefactor once you get past the limit checks for the virtual > slice. By the same token, transforming a few numbers of one virtual slice > into similar numbers for a a new virtual slice of that shouldn't be rocket science. > And it wouldn't have to be done more than once. Don't have time to do it now, > but there are plenty around here that could, I'm sure. > > Regards, > Bengt Richter Here's my (undocumented) version of it: http://rafb.net/paste/results/HkxmHp37.html and its unit test: http://rafb.net/paste/results/2LIInT68.html And some useless timing comparisons (I know it's a stupid example, don't flame me for this): $ python /usr/lib/python2.3/timeit.py \ -s "x=tuple(xrange(10000))" \ "[x[1:-1] for n in xrange(100)]" 10 loops, best of 3: 3.84e+04 usec per loop $ python /usr/lib/python2.3/timeit.py \ -s "from immutableseq import ImmutableSequence" \ -s "x=ImmutableSequence(xrange(10000))" \ "[x[1:-1] for n in xrange(100)]" 100 loops, best of 3: 5.85e+03 usec per loop Feel free to comment or suggest improvements. George From newsgroups at jhrothjr.com Sat Jan 8 12:22:45 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 8 Jan 2005 11:22:45 -0600 Subject: "A Fundamental Turn Toward Concurrency in Software" References: <20050108154453.32125.797079096.divmod.quotient.2429@ohm> <41e0131a$1_3@127.0.0.1> Message-ID: <10u05nrjgcge057@news.supernews.com> "Donn Cave" wrote in message news:41e0131a$1_3 at 127.0.0.1... > Quoth Skip Montanaro : > | > | Jp> How often do you run 4 processes that are all bottlenecked on > CPU? > | > | In scientific computing I suspect this happens rather frequently. > > I think he was trying to say more or less the same thing - responding > to "(IBM mainframes) ... All those systems ran multiple programs ... > My current system has 42 processes running ...", his point was that > however many processes on your desktop, on the rare occasion that > your CPU is pegged, it will be 1 process. The process structure of > a system workload doesn't make it naturally take advantage of SMP. > So "there will still need to be language innovations" etc. -- to > accommodate scientific computing or whatever. Your 4 processes are > most likely not a natural architecture for the task at hand, but > rather a complication introduced specifically to exploit SMP. Exactly. I wasn't addressing some of the known areas where one can take advantage of multiple processors, or where one can take advantage of threading on a single processor to avoid delays. At this point in time, though, I see multithreading for compute intensive tasks to be an intermediate step. The final step is to restructure it so it can take advantage of cluster architectures. Then you can simply ignore all of the complexity of threads. That still leaves putting long running tasks (such as printing) into the background so the UI stays responsive. > > Personally I wouldn't care to predict anything here. For all I know, > someday we may decide that we need cooler and more efficient computers > more than we need faster ones. Chuckle. I basically think of shared memory multiprocessing as being perverse: the bottleneck is memory, not compute speed, so adding more processors accessing the same memory doesn't strike me as exactly sane. Nor does pushing compute speed up and up and up when it just stressed the memory bottleneck. > > Donn Cave, donn at drizzle.com From kohlerj at ukzn.ac.za Wed Jan 26 05:16:01 2005 From: kohlerj at ukzn.ac.za (Johan Kohler) Date: Wed, 26 Jan 2005 12:16:01 +0200 Subject: "pickle" vs. f.write() Message-ID: Hi, I have a class with attributes that are string, integer and list. eg. class person: name ="" age = 0 friends=[] comment="""""" me = person() I want to save a whole bunch of instances to a file, a classic "records" file I/O. To write the file, I can do f.write(str([me.name, me.age, me.friends, me.comment]) + "\n" This works nicely for writing, but when reading, I cannot convert the string easily to a list: list(f.readline()) is not the same as [me.name, me.age, me.friends, me.comment] I was wondering whether pickle might make this easier - an example would be much appreciated. Otherwise, what is the best "Python" way to write and read this data structure? Thanks in advance... Johan __ Yes, I do feel stupid asking this, but time's-a-runnin' out.. -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ -------------------------------------------------------------------- Please find our disclaimer at http://www.ukzn.ac.za/disclaimer -------------------------------------------------------------------- <<<>>> From aleaxit at yahoo.com Tue Jan 4 03:11:12 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 4 Jan 2005 09:11:12 +0100 Subject: input record sepArator (equivalent of "$|" of perl) References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> <1103657476.495700.191020@f14g2000cwb.googlegroups.com> <1103671235.093738.198680@z14g2000cwz.googlegroups.com> <86wtuup21t.fsf@guru.mired.org> Message-ID: <1gpux8t.usezvs17759pwN%aleaxit@yahoo.com> Mike Meyer wrote: ... > Trivia question: Name the second most powerfull country on earth not > using the metric system for everything. Well, then, just name the 2nd most powerful country on earth, period (I'm not going to get myself in trouble by guessing whether said 2nd country is China, Russia, "Europe" [not a country, I know;-)], ...). TVs and other displays are sold as "20 inches" (or whatever) everywhere, printers' resolutions are always given in pixels per inch, etc. Alex From simon.brunning at gmail.com Wed Jan 26 11:21:47 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 26 Jan 2005 16:21:47 +0000 Subject: Help With Python In-Reply-To: References: Message-ID: <8c7f10c605012608213850ecf0@mail.gmail.com> On Wed, 26 Jan 2005 15:55:28 -0000, Judi Keplar wrote: > I am currently taking a course to learn Python and was looking for > some help. I need to write a Python statement to print a comma- > separated repetition of the word, "Spam", written 511 times ("Spam, > Spam, ? Spam"). > > Can anybody help me get started? I am completely new to programming! Well, I don't want to give it to you on a plate, since it's homework, but you might find this page useful: . I'd also suggest that you have a run through the tutorial - . It's time well spent! If you don't get on with that, there's another couple of tutorials available aimed directly at those new to programming - and . Lastly, although neophytes are more than welcome here, you might find the tutor mailing list a good place to ask questions in the early days of your Python experience. You'll find it here - . Good luck, and welcome to Python! -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From sjmachin at lexicon.net Sun Jan 16 15:38:26 2005 From: sjmachin at lexicon.net (John Machin) Date: 16 Jan 2005 12:38:26 -0800 Subject: How to del item of a list in loop? In-Reply-To: References: Message-ID: <1105907906.257801.216630@f14g2000cwb.googlegroups.com> skull wrote: > According to Nick's article, I added three 'reversed' methods to your provided > test prog. and the result turned out method_reversed is faster than others except the 'three' case. > Following is my modified version: [snip] > def method_reversed_idx(lst): > idx = 0 > for i in reversed(lst): > if i == 2: > del lst[idx] > idx += 1 There appears to be a problem with this one: >>> def method_reversed_idx(lst): ... idx = 0 ... for i in reversed(lst): ... if i == 2: ... del lst[idx] ... idx += 1 ... >>> lst=[1,2,3];method_reversed_idx(lst);print lst [1, 3] >>> lst=[2,1,3];method_reversed_idx(lst);print lst [2, 1] >>> lst=[1,3,2];method_reversed_idx(lst);print lst [3] >>> From wnebfynj at mnovryyb.pbz Wed Jan 19 04:33:12 2005 From: wnebfynj at mnovryyb.pbz (JZ) Date: Wed, 19 Jan 2005 10:33:12 +0100 Subject: IronPython, Boo and ASP.NET (web service) Message-ID: Is there any way for preparing a simple web service (ASP.NET) using IronPython or Boo (http://boo.codehaus.org/)? I cannot find any example. C# uses [WebMethod] attribute for marking remote methods. I do not know how IronPython or Boo deals with it. -- JZ ICQ:6712522 http://zabiello.com From rmemmons at member.fsf.org Thu Jan 6 19:08:22 2005 From: rmemmons at member.fsf.org (Rob Emmons) Date: Thu, 06 Jan 2005 18:08:22 -0600 Subject: How do I make Windows Application with Python ? References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> <1104929345.364701.19150@z14g2000cwz.googlegroups.com> Message-ID: On Wed, 05 Jan 2005 04:49:05 -0800, Fuzzyman wrote: > Couple of corrections - neither pypy nor starkiller are compilers. > Starkiller isn't available yet and *may* be helpful in building > compilers. Pyrex is an alternative language - a python/C hybrid that > can be compiled. > > If you want to release an application then innosetup, starkit, and upx > might help - but they're not python related. You will need something > like py2exe, cx_freeze, or mcmillan installer. (Which are specific to > python - py2exe seems to be the more mature tool). > > Alternatively you could consider 'Movable Python' - a frozen > distribution of python that doesn't need isntalling. See > http://sourceforge.net/projects/movpy Great summary. I was hoping someone would fill in the blanks. I've been interested in this area for some time -- but have not had time to look into it more than keep a list of interesting projects I wanted to research in the future. I'll add your comments to my list. Again, thanks. Rob From stephen.thorne at gmail.com Wed Jan 12 18:57:01 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 09:57:01 +1000 Subject: else condition in list comprehension In-Reply-To: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: <3e8ca5c805011215574b35bf91@mail.gmail.com> On 9 Jan 2005 12:20:40 -0800, Luis M. Gonzalez wrote: > Hi there, > > I'd like to know if there is a way to add and else condition into a > list comprehension. I'm sure that I read somewhere an easy way to do > it, but I forgot it and now I can't find it... > > for example: > z=[i+2 for i in range(10) if i%2==0] > what if I want i to be "i-2" if i%2 is not equal to 0? z = [i+2-(i%2)*4 for i in range(10)] C'mon, who needs an 'if' statement when we have maths! Stephen. From bokr at oz.net Wed Jan 5 22:15:41 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 06 Jan 2005 03:15:41 GMT Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> Message-ID: <41dcaa00.102858012@news.oz.net> On 05 Jan 2005 07:18:25 -0800, Paul Rubin wrote: >Ville Vainio writes: >> Paul> I can't parse that. It says two contradictory things. >> Paul> Sentence 2 says that if something essential is not in the >> Paul> (Python) distro then the (Python) distro maintainers have >> Paul> screwed up. Sentence 1 says it's the Fedora maintainer's >> Paul> job to deal with it. Huh? >> >> By "distro" I meant the Linux distribution, not the Python >> distribution. Distro is a customary term for a Linux distribution so I >> didn't qualify the word at the time. > >Oh ok, but it's the Python distribution that's missing components that >are essential to Python. Fedora and other Linux distros are >collections of subsystems like Python. Linux distro maintainers get >asked to include a subsystem, they check that the subsystem has a >reasonable reputation (Python does), they install it in the distro and >run some basic tests, and they ship it. They can't be expected to >immerse themselves in its intricacies and hang out on the user forums >to identify all the missing components that they should also hunt down >and ship. So the Python needs to take care of that stuff. > >I realize that in the old days, people used to write big applications >without makefiles, and later when they started using makefiles, they >didn't use configure scripts. So to install a package, you had to do >a bunch of hand configuration for your particular environment before >you could compile it, and maybe you even had to say > cc -O -Dthisflag=thatnumber xyz.c pqr.c frob.c -o frob >on the command line instead of typing "make" to build the program. >That kind of thing really doesn't fly any more. The standards for >what constitutes a properly engineered release of something have >gotten higher. You really need automatic configuration and build and >installation. Likewise, if you're trying to market something as a >complete drop-in system ("batteries included", to use the Python >terminology), it should not be missing any essential pieces that >the user has to hunt down separately. What do you think of automated secure importing/installing from a remote server? You know, you try to import something and it imports a stub that was included as a battery-place-holder and that has basic help info and will give you reasonable options in directing the installation of the full thing (or subset you are interested in). I don't see why every gee whiz thing has to be on your hard disk from the first. And for those that want a big grabbag, the stubs ought to be designed to to be runnable from a configured script, so you can turn it loose and see what's up IRL. Regards, Bengt Richter From stephen.thorne at gmail.com Mon Jan 17 09:20:02 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Tue, 18 Jan 2005 00:20:02 +1000 Subject: Native widgets for Python In-Reply-To: <41EBC7F3.5050807@web.de> References: <41EBC7F3.5050807@web.de> Message-ID: <3e8ca5c805011706207c70579a@mail.gmail.com> there's someone writing 'dabo', which is apparently "wxpython but more python". Stephen. On Mon, 17 Jan 2005 15:13:07 +0100, A. Klingenstein wrote: > Which other GUI library for Python other than wxpython has native > widgets for MS Windows ? > I know there is MFC and GDI, but I want something easier to use than wx, > not harder :) > wxpython has to problem that it handles much more like a C++ library > than a Python one sometimes. > > Alex > -- > http://mail.python.org/mailman/listinfo/python-list > From reinhold-birkenfeld-nospam at wolke7.net Fri Jan 14 14:10:30 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 14 Jan 2005 20:10:30 +0100 Subject: Octal notation: severe deprecation In-Reply-To: References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105575689.335040.174490@c13g2000cwb.googlegroups.com> <34o8n7F4e6uduU1@individual.net> Message-ID: <34qjp6F4dkctuU1@individual.net> Simon Brunning wrote: > On Thu, 13 Jan 2005 16:50:56 -0500, Leif K-Brooks wrote: >> Tim Roberts wrote: >> > Stephen Thorne wrote: >> > >> >>I would actually like to see pychecker pick up conceptual errors like this: >> >> >> >>import datetime >> >>datetime.datetime(2005, 04,04) >> > >> > >> > Why is that a conceptual error? Syntactically, this could be a valid call >> > to a function. Even if you have parsed and executed datetime, so that you >> > know datetime.datetime is a class, it's quite possible that the creation >> > and destruction of an object might have useful side effects. >> >> I'm guessing that Stephen is saying that PyChecker should have special >> knowledge of the datetime module and of the fact that dates are often >> specified with a leading zero, and therefor complain that they shouldn't >> be used that way in Python source code. > > It would be useful if PyChecker warned you when you specify an octal > literal and where the value would differ from what you might expect if > you didn't realise that you were specifying an octal literal. > > x = 04 # This doesn't need a warning: 04 == 4 > #x = 09 # This doesn't need a warning: it will fail to compile > x= 012 # This *does* need a warning: 012 == 10 Well, this would generate warnings for all octal literals except 01, 02, 03, 04, 05, 06 and 07. However, I would vote +1 for adding such an option to PyChecker. For code that explicitly uses octals, it can be turned off and it is _very_ confusing to newbies... Reinhold From skip at pobox.com Tue Jan 4 13:14:06 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 Jan 2005 12:14:06 -0600 Subject: Pythonic search of list of dictionaries In-Reply-To: References: Message-ID: <16858.56558.9592.366794@montanaro.dyndns.org> Bulba> I put those dictionaries into the list: Bulba> oldl=[x for x in orig] # where orig=csv.DictReader(ofile ... Bulba> ..and then search for matching source terms in two loops: Bulba> for o in oldl: Bulba> for n in newl: Bulba> if n['English'] == o['English']: Bulba> ... Bulba> Now, this works. However, not only this is very un-Pythonic, but Bulba> also very inefficient: the complexity is O(n**2), so it scales up Bulba> very badly. How about using sets? oenglish = set([item['English'] for item in oldl]) nenglish = set([item['English'] for item in newl]) matching = oenglish & nenglish Once you have those that match, you can constrain your outer loop to just those cases where o['English'] in matching If you're not using 2.4 yet, then get sets via: from sets import Set as set That's still not all that Pythonic, but should be a bit faster. You might want to sort your lists by the 'English' key. I don't know how to use the new key arg to list.sort(), but you can still do it the old-fashioned way: oldl.sort(lambda a,b: cmp(a['English'], b['English'])) newl.sort(lambda a,b: cmp(a['English'], b['English'])) Once sorted, you can then march through the lists in parallel, which should give you an O(n) algorithm. Skip From reinhold-birkenfeld-nospam at wolke7.net Sat Jan 15 02:38:34 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 15 Jan 2005 08:38:34 +0100 Subject: How to del item of a list in loop? In-Reply-To: References: Message-ID: <34rvjqF4f6l70U1@individual.net> skull wrote: > Hi everybody, it is my first post in this newsgroup. > I am a newbie for python though I have several years development experience in c++. > recently, I was stumped when I tried to del item of a list when iteration. > > here is the wrong way I did: > > lst = [1, 2, 3] > for i in lst: > print i > if i == 2: > lst.remove(i) > > the result is: > > 1 > 2 >>>> > > as you would see, '3' is missing. this problem is caused by 'lst.remove(i)'. > apparently, 'marked-and-sweep' is a solution to deal with this issue. > but I think there SHOULD BE more 'wise' trick. I want to get your help. Quick solution: for i in lst[:] iterates over a copy. Reinhold From just at xs4all.nl Mon Jan 17 09:28:30 2005 From: just at xs4all.nl (Just) Date: Mon, 17 Jan 2005 15:28:30 +0100 Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: In article , Antoon Pardon wrote: > Op 2005-01-17, Steve Holden schreef : > > There you go with the minutiae again. How about: > > > > "Don't use mutables as hash keys"? > > That sounds too dogmatic to my ears. I also find it > too selective. The problem with mutables as dictionary > keys is not specific to dictionaries. Everywhere you > have mutables in a container, it is possible that > mutating the object in the container will cause > problem. The main difference is: if you mutate a dict key you *always* have a problem. So don't do that. Mutating (say) a list item *only* is a problem if you (say) need that list to remain sorted. Lists don't magically remain sorted, so people generally sort it before they do some operation that expects a sorted list. > Heck even using mutables as arguments can > cause trouble. Why else the specific advice against > > def foo(p = []) > > type of arguments. So should we adopt the principles: > > Don't use mutables in containers Nonsense. > Don't use mutables as default values for parameters That's good advice in general. > Don't use mutables as arguments. Nonsense. > Don't assign one mutable to an other. Nonsense. Some newbies get surprised by Python's assignment-doesn't-copy semantics, but it's such basic knowledge (as well as a useful feature) that I simply don't understand you saying this. > I don't see a big difference between these principles > and the hash key principle, Than you haven't looked hard enough. > so in the end may be we > should just stick with the more general principle: > > Don't use mutables! > > > and be done with it. Ok, so you're indeed a troll. Just From andersjm at inbound.dk Sat Jan 1 08:20:06 2005 From: andersjm at inbound.dk (Anders J. Munch) Date: Sat, 1 Jan 2005 14:20:06 +0100 Subject: Speed ain't bad References: <0189t05r3226bkp5e1vtmp0gd6odcsf2qp@4ax.com> Message-ID: <41d6a39b$0$33656$edfadb0f@dread16.news.tele.dk> "Bulba!" wrote: > > One of the posters inspired me to do profiling on my newbie script > (pasted below). After measurements I have found that the speed > of Python, at least in the area where my script works, is surprisingly > high. Pretty good code for someone who calls himself a newbie. One line that puzzles me: > sfile=open(sfpath,'rb') You never use sfile again. In any case, you should explicitly close all files that you open. Even if there's an exception: sfile = open(sfpath, 'rb') try: finally: sfile.close() > > The only thing I'm missing in this picture is knowledge if my script > could be further optimised (not that I actually need better > performance, I'm just curious what possible solutions could be). > > Any takers among the experienced guys? Basically the way to optimise these things is to cut down on anything that does I/O: Use as few calls to os.path.is{dir,file}, os.stat, open and such that you can get away with. One way to do that is caching; e.g. storing names of known directories in a set (sets.Set()) and checking that set before calling os.path.isdir. I haven't spotted any obvious opportunities for that in your script, though. Another way is the strategy of "it's easier to ask forgiveness than to ask permission". If you replace: if(not os.path.isdir(zfdir)): os.makedirs(zfdir) with: try: os.makedirs(zfdir) except EnvironmentError: pass then not only will your script become a micron more robust, but assuming zfdir typically does not exist, you will have saved the call to os.path.isdir. - Anders From hwlgw at hotmail.com Wed Jan 19 06:17:10 2005 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 19 Jan 2005 03:17:10 -0800 Subject: delay and force in Python Message-ID: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> Here is a question for people who are more comfortable than I am with new Python stuff like generators. I am having fun implementing things from the Wizard book (Abelson, Sussman, "Structure and Interpretation of Computer Programs") in Python. In chapter 3.5 it is about streams as delayed lists. Streams are interesting because they are to lists like xrange is to range. Could save a lot on memory and computations. Below is my straight translation from Scheme code in the Wizard book to Python. It works, but now I want to rewrite the delay and force functions using Python's new stuff, generators or iterators or what-have-you. I have the feeling that that is possible, can you do it? The program below creates a stream with the numbers 1..995 and then filters the stream, keeping only the even numbers, and then prints the second number in the stream (implemented as the first number of the tail, just like in the 3.5 Section in the Wizard book). . # file: teststreams.py . . def delay(exp): return lambda: exp . . def force(o): return o() . . def cons_stream(a,b): return [a, delay(b)] . . def stream_hd(s): return s[0] . . # we use tl for cdr . def tl(x): . if len(x) == 2: return x[1] . else: return x[1:] . . def stream_tl(s): return force(tl(s)) . . def stream_enumerate_interval(low, high): . if low > high: . return None . else: . return cons_stream( . low, . stream_enumerate_interval(low+1, high)) . . def stream_filter(pred, s): . if s is None: . return None . elif pred(stream_hd(s)): . return cons_stream( . stream_hd(s), . stream_filter(pred, stream_tl(s))) . else: . return stream_filter(pred, stream_tl(s)) . . def isEven(n): return n % 2 == 0 . . print stream_hd(stream_tl(stream_filter( . isEven, . stream_enumerate_interval(1,995)))) . # 4 Something else: this crashes with a "maximum recursion reached" . print stream_enumerate_interval(1,998) while this does not crash . print stream_enumerate_interval(1,900) this means Python has a maximum of something like 900 recursions? From aahz at pythoncraft.com Tue Jan 25 23:23:44 2005 From: aahz at pythoncraft.com (Aahz) Date: 25 Jan 2005 23:23:44 -0500 Subject: Textual markup languages (was Re: What YAML engine do you use?) References: <35a6tpF4gmat2U1@individual.net> Message-ID: In article , Alan Kennedy wrote: > >However, I'm torn on whether to use ReST for textual content. On the one >hand, it's looks pretty comprehensive and solidly implemented. But OTOH, >I'm concerned about complexity: I don't want to commit to ReST if it's >going to become a lot of hard work or highly-inefficient when I really >need to use it "in anger". > > From what I've seen, pretty much every textual markup targetted for web >content, e.g. wiki markup, seems to have grown/evolved organically, >meaning that it is either underpowered or overpowered, full of special >cases, doesn't have a meaningful object model, etc. My perception is that reST is a lot like Python itself: it's easy to hit the ground running, particularly if you restrict yourself to a specific subset of featuers. It does give you a fair amount of power, and some things are difficult or impossible. Note that reST was/is *not* specifically aimed at web content. Several people have used it for writing books; some people are using it instead of PowerPoint. >So, I'm hoping that the learned folks here might be able to give me some >pointers to a markup language that has the following characteristics > >1. Is straightforward for non-technical users to use, i.e. can be >(mostly) explained in a two to three page document which is >comprehensible to anyone who has ever used a simple word-processor or >text-editor. > >2. Allows a wide variety of content semantics to be represented, e.g. >headings, footnotes, sub/superscript, links, etc, etc. These two criteria seem to be in opposition. I certainly wouldn't expect a three-page document to explain all these features, not for non-technical users. reST fits both these criteria, but only for a selected subset of featuers. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From cdavisNOSP at NOSPstaffmail.ed.ac.uk Wed Jan 12 05:09:03 2005 From: cdavisNOSP at NOSPstaffmail.ed.ac.uk (Cory Davis) Date: Wed, 12 Jan 2005 10:09:03 +0000 Subject: distutils linux script installation broken? Message-ID: Hi all, I have been successfully deploying my own python package with distutils for some time now, but lately, with Python 2.4, the build_scripts command has been behaving badly. In the part where it is supposed to adjust the first line of the script it now produces #!None instead of #!/whereverpythonis/python Has anyone else encountered this? Cheers, Cory. From jalil at feghhi.com Thu Jan 27 19:48:14 2005 From: jalil at feghhi.com (jalil at feghhi.com) Date: 27 Jan 2005 16:48:14 -0800 Subject: Missing _bssd in Python 2.4 In-Reply-To: <41F977C9.4020400@v.loewis.de> References: <1106864043.734366.315660@c13g2000cwb.googlegroups.com> <41F977C9.4020400@v.loewis.de> Message-ID: <1106873294.357920.7520@c13g2000cwb.googlegroups.com> I actually installed BerkeleyBD4.0 and commented out some sections of Modules/Setup that I found related to this. I got the _bsddb.o in the build environment but I still get the same error from bsddb/__init.py__ that it cannot import _bsddb. Anything I am missing? Where should this _bsddb go exactly? Is it an .so file? Thanks, -JF Martin v. L?wis wrote: > jalil at feghhi.com wrote: > > I compiled and installed python 2.4 on Redhat Linux using default > > options but don't seem to be getting _bsddb. I get an error message > > that _bssd cannot be imported. > > > > Does anybody know why this might happen? Do I need to do any special > > customization or install any other software? > > You need to install the bsddb header files and development libraries > when building Python from source. > > Regards, > Martin From tim.golden at viacom-outdoor.co.uk Fri Jan 7 11:32:37 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 7 Jan 2005 16:32:37 -0000 Subject: [Pyro] Newbie Question Regarding Pyro Message-ID: <9A28C052FF32734DACB0A288A35339910359A1@vogbs009.gb.vo.local> [John French] | I'm putting together a new project which I'm using to learn | Python and have questions about pyro. You're welcome to ask here, but you might find that posting on Pyro's own mailing list produces answers from people who don't follow c.l.py's higher traffic. | If the server needs to send an unsolicited ad hoc message to | a given client, is this possible? | (New message or a reminder, for instance) I suppose I | could poll a server side list from the client but I'm | wondering if the server can initiate the exchange. I think you want to look at the Pyro's Event server, but be careful with terms like Server and Client, because they aren't always so straightforward in the Pyro context. | Also, if a client wishes to converse with another particular | client (in a chat or IM situation, for instance). | What's a good mechanism for this? There are two things here: finding out what "client" (Pyro object) is out there; and communicating with it. To take the second one first, once you've found it, you *are* talking directly to it, so that's fine. To address the first point, though, finding it can either be through the nameserver, which is generally preferable since that's what it's there for, or -- if you know the other object's location and name -- by using the PYROLOC:// mechanism. The only thing with this second approach is that you're likely to find yourself reinventing the name server as you try to keep track of who's "on-line" etc. (assuming your typical IM situation). So I'd recommend going for the nameserver if possible. | Does pyro create a persistent client/server connection? What | happens if a pyro client goes down hard? Does it's process | continue or is there a cleanup mechanism? Hmmm. A little bit involved the answer to this one. In essence, once you've got hold of another object via Pyro it's down to the network to get the message through. If the other end goes down, you can trap the Exceptions coming back and clean up as you see fit. The Pyro plumbing does support an auto-reconnect mechanism for Pyro objects. The details escape me now -- I've never used it myself -- but I seem to remember that you restart your object and its daemon (ie server bit) telling it to reconnect as well as it can. There's no persistence involved (unless you've implemented something yourself) so you'll have to clean up whatever mess there was left over as you come back up. Hope all that helps. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From engsolnorm at peak.org Fri Jan 14 17:12:41 2005 From: engsolnorm at peak.org (engsol) Date: Fri, 14 Jan 2005 14:12:41 -0800 Subject: Com port interrupts again References: <154gu09bghnq674s2nqot9si6d50igueq7@4ax.com> <1105734343.547195.301160@f14g2000cwb.googlegroups.com> Message-ID: <3uggu0p51mosuds44f5pjkjfo3bg5irat4@4ax.com> Thanks much..:) On 14 Jan 2005 12:25:43 -0800, "wittempj at hotmail.com" wrote: >A search on google gave me this library, I haven't tested it though: >http://groups-beta.google.com/group/comp.lang.python.announce/browse_frm/thread/6d3263250ed65816/291074d7bd94be63?q=com+port+python&_done=%2Fgroups%3Fhl%3Den%26lr%3D%26safe%3Doff%26q%3Dcom+port+python%26qt_s%3DSearch+Groups%26&_doneTitle=Back+to+Search&&d#291074d7bd94be63 From FBatista at uniFON.com.ar Wed Jan 12 14:07:14 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 12 Jan 2005 16:07:14 -0300 Subject: PyAr - Python Argentina 5th Meeting, tomorrow Thursday, Decimal t alk included Message-ID: The Argentinian Python User Group, PyAr, will have its fifth meeting this Thursday, January 13th at 7:00pm. Please see http://pyar.decode.com.ar/Wiki/ProximaReunion for details (in Spanish.) Agenda ------ Despite our agenda tends to be rather open, this time we would like to cover these topics: - Planning of our first sprint: we actually have two main subjects: Messages Queues Manager with interfaces for SMTP (e-mail), SMPP (SMS) and MM7 (MMS); and Genetic Algorithms. - Website organization & content - Means of promoting the group's activities, in order to increase our member base. There will be also an introduction from me to the Decimal data type that debuted in Python 2.4 (but could be used in 2.3 as well). Where ----- We're meeting at Hip Hop Bar, Hip?lito Yirigoyen 640, Ciudad de Buenos Aires, starting at 19hs. We will be in the back room, so please ask the barman for us. About PyAr ---------- For more information on PyAr see http://pyar.decode.com.ar (in Spanish), or join our mailing list (Also in Spanish. For instructions see http://pyar.decode.com.ar/Members/ltorre/listademail) We meet on the second Thursday of every month. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From farcepest at gmail.com Thu Jan 20 14:01:44 2005 From: farcepest at gmail.com (Andy Dustman) Date: 20 Jan 2005 11:01:44 -0800 Subject: Problem in importing MySQLdb References: Message-ID: <1106247703.982996.14410@z14g2000cwz.googlegroups.com> Gurpreet Sachdeva wrote: > Is there any problem in library files?? Do I need to install anything > I have installed MySQL-shared-3.23.54a-1.i386.rpm, > MySQL-devel-5.0.2-0.i386.rpm, MySQL-client-5.0.2-0.i386.rpm, > MySQL-server-5.0.2-0.i386.rpm You should recheck those version numbers carefully. One of these things is not like the other... From gsakkis at rutgers.edu Tue Jan 25 11:07:34 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: 25 Jan 2005 08:07:34 -0800 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> Message-ID: <1106669254.838248.317170@z14g2000cwz.googlegroups.com> An iterator is perfectly ok if all you want is to iterate over the elements of a view, but as you noted, iterators are less flexible than the underlying sequence. The view should be (or at least appear) identical in functionality (i.e. public methods) with its underlying sequence. George From ewanon at gmail.com Sun Jan 2 23:25:23 2005 From: ewanon at gmail.com (EW) Date: 2 Jan 2005 20:25:23 -0800 Subject: Problem remotely shutting down a windows computer with python In-Reply-To: References: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> Message-ID: <1104726323.505127.139360@c13g2000cwb.googlegroups.com> I believe that would shutdown the computer you were physically at, but it wouldn't shutdown the computer down the hall over the LAN like this script was meant to do. From nav+posts at bandersnatch.org Thu Jan 27 08:24:16 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: Thu, 27 Jan 2005 08:24:16 -0500 Subject: Help With Python References: <87ekg8c4d0.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <1106775090.890952.40590@c13g2000cwb.googlegroups.com> Message-ID: <873bwnc8e7.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> "Matt" writes: > Not to be nit-picky, but you got some issues here ;-). Never forget > the importance of "self"! Teach me to post untested code. *hangs head* Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From apardon at forel.vub.ac.be Mon Jan 31 03:08:29 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 31 Jan 2005 08:08:29 GMT Subject: How to test that an exception is raised ? References: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> <41fa400b$0$2029$6c56d894@feed0.news.be.easynet.net> <41faa68f$0$17406$4d4efb8e@read.news.be.uu.net> Message-ID: Op 2005-01-28, StepH schreef : > Antoon Pardon a ?crit : >> Op 2005-01-28, StepH schreef : >> >>>Thanks for you answer. >>>I'm new to Python (coming from C/C++). >>> >>>Do you say that it's not possible to test (using unittest) if an exception >>>is well raised if the tested code catch it ? >>>How to solve this paradoxe ? How to automaticaly test such code ? >> >> >> IMO you want something unittest are not designed for. > > So why the assertRaises function in unittest? To see if an exception is propagated to the caller. > My goal is to test if an > exception is well raised when a bad filename is passed to the mps2xml > function. >> Unittest are supposed to test for particular results, not for particular >> behaviour within. If the expected behaviour is that calling code doesn't >> see an exception raised, then the test passed if no exception was seen. >> > > No (unless i don't well understand you), the expected behavior is to > launch an exception if a bad filename is passed. If no exception is > raised, this is not normal. What do you mean with launch an exception? Should the exception propagate to the caller or not? If it should your code was wrong to catch it. >> You equally can't test which branch of an if statement was taken or >> which parameter was given to a helper function in order to get to >> the desired result. > > I'm agree with out on this point, but not for the exception part... Why not? Exceptions are nothing special. Either you want to propagated them to the caller, in which case they can be seen as somekind of result and this can be tested for with a unittest or you don't want them to be propagted and then they are just an implementation detail of your unit. -- Antoon Pardon From alan.gauld at btinternet.com Sat Jan 1 18:18:58 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Jan 2005 23:18:58 +0000 (UTC) Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <1104511661.928284.10200@z14g2000cwz.googlegroups.com> Message-ID: On Sat, 01 Jan 2005 16:08:07 GMT, claird at lairds.us (Cameron Laird) wrote: > I argue that it's a false opposition to categorize projects in > terms of use of single languages. Many projects are MUCH better > off with a mix In practice I have *never* worked on an industrial scale project that only used one language. The nearest I came was a small protocol convertor that only used C, SQL and some shell and awk - but that's still 4 languages! And the whole project was only 40,000 lines of code in about 20 files. And most projects use many more, I'd guess around 5-8 on an "average project" of around 300-500kloc. The biggest project I worked on had about 3.5Mloc and used: Assembler (680x0 and Sparc), C C++ Lisp(Flavors) awk Bourne shell C shell - this was a mistake discovered too late to "fix" PL/SQL ???? - A UI description language for a tool called TeleUse... Pascal - No, I don't know why... ASN.1 - with a commercial compiler We also had some IDL but since it was tool generated I'll ignore it... We also had an experimental version running on a NeXt box so it used Objective C for the UI instead of ???? and C++... A total of 13 languages... with 5 geographically dispersed teams comprising a total of 200 developers (plus about 40 testers). Interesting times...in the Chinese sense! Alan G Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From petr at tpc.cz Mon Jan 10 18:44:33 2005 From: petr at tpc.cz (McBooCzech) Date: 10 Jan 2005 15:44:33 -0800 Subject: Old Paranoia Game in Python In-Reply-To: References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> <1105318366.966577.107460@c13g2000cwb.googlegroups.com> Message-ID: <1105400673.731851.87080@f14g2000cwb.googlegroups.com> Newbie in Python. I did copy the whole script form the web and save it as para1.py. I did download pyparsing module and save it to C:\\Python23\\Lib\\pyparsing122. I did run following script: import sys sys.path.append('C:\\Python23\\Lib\\pyparsing122') from pyparsing import * extraLineBreak = White(" ",exact=1) + LineEnd().suppress() text = file("Para1.py").read() newtext = extraLineBreak.transformString(text) file("para2.py","w").write(newtext) I did try to run para2.py script, but following message File "para2.py", line 169 choose(4,"You give your correct clearance",5,"You lie and claim ^ SyntaxError: EOL while scanning single-quoted string So my questions are: Why pyparser didn't correct the script? What I am doing wrong? Is it necessary to correct the script by hand anyway? Petr From steven.bethard at gmail.com Tue Jan 18 03:29:25 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 18 Jan 2005 01:29:25 -0700 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Antoon Pardon wrote: > In this case for example there are a number of people who flat out > assert that muatble dict keys in pyhthon is impossible. If you run into any of these folks, please point them to: http://www.python.org/moin/DictionaryKeys It's a pretty good summary of one of the more recent threads on this topic by Peter Maas and myself. If you feel like your point is not covered[1], feel free to add some additional material. (That is, after all, the point of a wiki.) Steve [1] I assume that you feel this way because you have repeated essentially the same point about 5 times in this thread. The wiki is a chance to make your statement once, and then simply post a pointer once per appropriate thread. It might save you some time... From jaydonnell at gmail.com Fri Jan 21 13:01:16 2005 From: jaydonnell at gmail.com (Jay donnell) Date: 21 Jan 2005 10:01:16 -0800 Subject: why am I getting a segmentation fault? Message-ID: <1106330476.419418.46920@f14g2000cwb.googlegroups.com> I have a short multi-threaded script that checks web images to make sure they are still there. I get a segmentation fault everytime I run it and I can't figure out why. Writing threaded scripts is new to me so I may be doing something wrong that should be obvious :( google messes up the python code so here is a link to it. http://kracomp.com/~jay/py.txt This is the output of the script. [jay at localhost scripts]$ ./py.py update item set goodImage = 'yes' where productId='12603' update item set goodImage = 'yes' where productId='18272' update item set goodImage = 'yes' where productId='1927' update item set goodImage = 'no' where productId='12709' update item set goodImage = 'yes' where productId='32087' update item set goodImage = 'no' where productId='25803' Segmentation fault Thanks in advance. From peter at engcorp.com Tue Jan 4 20:57:26 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 04 Jan 2005 20:57:26 -0500 Subject: python intergration bus ? In-Reply-To: <1104849906.019872.153800@z14g2000cwz.googlegroups.com> References: <1104849906.019872.153800@z14g2000cwz.googlegroups.com> Message-ID: <-LSdnY83pO1i1EbcRVn-vw@powergate.ca> Tonino wrote: > Just an interested question - I friend is testing a few JAVA > intergration bus's that will be used to intergrate his companies > services - I was wondering if there was a python intergration bus ? > other than maybe Pyro ? I'm not sure what that term means, and I don't believe it is a widely recognized term in the field of programming. I can guess, or Google for it, but I suspect most of what I find wouldn't be what you meant... Perhaps you could define what "integration bus" means to you so we could understand what your question really is? (And please do it without just referencing some Java product which none of us will know about.) Thanks, -Peter From aleaxit at yahoo.com Sun Jan 2 18:08:25 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 3 Jan 2005 00:08:25 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> Bulba! wrote: > True. I have a bit of interest in economics, so I've seen e.g. > this example - why is it that foreign branches of companies > tend to cluster themselves in one city or country (e.g. It's not just _foreign_ companies -- regional clustering of all kinds of business activities is a much more widespread phenomenon. Although I'm not sure he was the first to research the subject, Tjalling Koopmans, as part of his lifework on normative economics for which he won the Nobel Prize 30 years ago, published a crucial essay on the subject about 50 years ago (sorry, can't recall the exact date!) focusing on _indivisibilities_, leading for example to transportation costs, and to increasing returns with increasing scale. Today, Paul Krugman is probably the best-known name in this specific field (he's also a well-known popularizer and polemist, but his specifically-scientific work in economics has mostly remained in this field). > China right now)? According to standard economics it should > not happen - what's the point of getting into this overpriced > city if elsewhere in this country you can find just as good > conditions for business. Because you can't. "Standard" economics, in the sense of what you might have studied in college 25 years ago if that was your major, is quite able to account for that if you treat spatial variables as exogenous to the model; Krugman's breakthroughs (and most following work, from what I can tell -- but economics is just a hobby for me, so I hardly have time to keep up with the literature, sigh!) have to do with making them endogenous. Exogenous is fine if you're looking at the decision a single firm, the N+1 - th to set up shop in (say) a city, faces, given decisions already taken by other N firms in the same sector. The firm's production processes have inputs and outputs, coming from other firms and (generally, with the exception of the last "layer" of retailers etc) going to other firms. Say that the main potential buyers for your firm's products are firms X, Y and Z, whose locations all "happen to be" (that's the "exogenous" part) in the Q quarter of town. So, all your competitors have their locations in or near Q, too. Where are you going to set up your location? Rents are higher in Q than somewhere out in the boondocks -- but being in Q has obvious advantages: your salespeople will be very well-placed to shuttle between X, Y, Z and your offices, often with your designers along so they can impress the buyers or get their specs for competitive bidding, etc, etc. At some points, the competition for rents in quarter Q will start driving some experimenters elsewhere, but they may not necessarily thrive in those other locations. If, whatever industry you're in, you can strongly benefit from working closely with customers, then quarter Q will be where many firms making the same products end up (supply-side clustering). Now consider a new company Z set up to compete with X, Y and Z. Where will THEY set up shop? Quarter Q has the strong advantage of offering many experienced suppliers nearby -- and in many industries there are benefits in working closely with suppliers, too (even just to easily have them compete hard for your business...). So, there are easily appreciated exogenous models to explain demand-side clustering, too. That's how you end up with a Holliwood, a Silicon Valley, a Milan (for high-quality fashion and industrial design), even, say, on a lesser scale, a Valenza Po or an Arezzo for jewelry. Ancient European cities offer a zillion examples, with streets and quarters named after the trades or professions that were most clustered there -- of course, there are many other auxiliary factors related to the fact that people often _like_ to associate with others of the same trade (according to Adam Smith, generally to plot some damage to the general public;-), but supply-side and demand-side, at least for a simpler exogenous model, are plenty. Say that it's the 18th century (after the corporations' power to stop "foreign" competition from nearby towns had basically waned), you're a hat-maker from Firenze, and for whatever reason you need to move yourself and your business to Bologna. If all the best hat-makers' workshops and shops are clustered around Piazza dell'Orologio, where are YOU going to set up shop? Rents in that piazza are high, BUT - that's where people who want to buy new hats will come strolling to look at the displays, compare prices, and generally shop. That's close to where felt-makers are, since they sell to other hat-makers. Should your business soon flourish, so you'll need to hire a worker, that's where you can soon meet all the local workers, relaxing with a glass of wine at the local osteria after work, and start getting acquainted with everybody, etc, etc... Risk avoidance is quite a secondary issue here (except if you introduce in your model an aspect of imperfect-information, in which case, following on the decisions made by locals who may be presumed to have better information than you is an excellent strategy). Nor is there any "agency problem" (managers acting for their interests and against the interest of owners), not a _hint_ of it, in fact -- the hatmaker acting on his own behalf is perfectly rational and obviously has no agency problem!). So, I believe that introducing agency problems to explain clustering is quite redundant and distracting from what is an interesting sub-field of (quite-standard, by now) economics. There are quite a few other sub-fields of economics where agency problems, and specifically the ones connected with risk avoidance, have far stronger explicatory power. So, I disagree with your choice of example. Alex From thisissantanu at yahoo.com Fri Jan 28 07:28:49 2005 From: thisissantanu at yahoo.com (santanu) Date: 28 Jan 2005 04:28:49 -0800 Subject: Please suggest on the book to follow References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> Message-ID: <1106915329.743430.242080@f14g2000cwb.googlegroups.com> Thanks for the link http://gnosis.cx/TPiP/ It was wonderful. Once I get somewhat more experienced in Python, I guess this site will provide me with some good fun times. For the moment, I decided to follow Programming Python. Once done, I shall learn the newest features from some latest book like the Nutshell one. Thanks to all for replying. Regards, Santanu From stewart.midwinter at gmail.com Tue Jan 25 12:10:48 2005 From: stewart.midwinter at gmail.com (stewart.midwinter at gmail.com) Date: 25 Jan 2005 09:10:48 -0800 Subject: smtplib bug with Windows XP In-Reply-To: References: <1106614880.586616.19780@f14g2000cwb.googlegroups.com> Message-ID: <1106673048.851591.324490@f14g2000cwb.googlegroups.com> thank Peter, elbert, for the suggestions. I hadn't thought of using telnet to try to connect to the SMTP server. and when I do try, telnet can't connect either, at least on port 25. On port 110, it has no problem. So, perhaps the IT people have made some configuration changes; I'll have a chat with them. I'm relieved that it's not a Python problem, though. From pobrien at orbtech.com Wed Jan 19 15:06:34 2005 From: pobrien at orbtech.com (Pat) Date: 19 Jan 2005 12:06:34 -0800 Subject: Solutions for data storage? In-Reply-To: <1106164804.410201.100550@c13g2000cwb.googlegroups.com> References: <356c7tF4g3f64U1@individual.net> <1106164804.410201.100550@c13g2000cwb.googlegroups.com> Message-ID: <1106165194.960959.270210@f14g2000cwb.googlegroups.com> Posting using Google Groups messed up the formatting of those class definition examples. Assume that they contain the usual indentation of typical class definitions. ;-) From km at mrna.tn.nic.in Sun Jan 9 22:23:48 2005 From: km at mrna.tn.nic.in (km) Date: Mon, 10 Jan 2005 08:53:48 +0530 Subject: vi and python Message-ID: <20050110032348.GA1960@mrna.tn.nic.in> Hi all, Is there a way to display inbuilt function syntax as the user starts typing a function name with 'Vi' editor in console mode? tia, KM From bokr at oz.net Tue Jan 18 08:24:52 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 18 Jan 2005 13:24:52 GMT Subject: news feed problem -- anyone else? References: <41ec1b57.1114913110@news.oz.net> <41EC3156.80708@tundraware.com> Message-ID: <41ed0dcf.1176985375@news.oz.net> On 17 Jan 2005 16:48:24 EST, Tim Daneliuk wrote: >Bengt Richter wrote: > >> I can see postings on google, but my news service >> is having a problem since sometime during the weekend. >> Can get old stuff from other n.g., but no new. >> Wondering whether I'll see this via google. >> >> Regards, >> Bengt Richter > >Bengt - > >I've had very good luck using the following *free* newsfeed: > > http://individual.net/ > > >HTH, Thanks, I can see this via normal news now. But that looks good. Regards, Bengt Richter From ruses at users.ch Sat Jan 1 20:05:30 2005 From: ruses at users.ch (not [quite] more i squared) Date: Sun, 02 Jan 2005 02:05:30 +0100 Subject: Red Robin Jython & JDK classes In-Reply-To: References: Message-ID: <33ov84F421s0aU1@individual.net> Henri Sivonen a ?crit : > I am trying to set up the Red Robin Jython Development Tools for > Eclipse. It finds the Python libraries of Jython and my own jars. It > does not find the JDK classes. If I try to add classes.jar from the JDK > to the "Jython Class Path" of the project, the plug-in no longer finds > even my own Java classes. > > How do I make the plug-in see the JDK classes? > > I am using Eclipse 3.0.1, Mac OS X 10.3.7, Java 1.4.2_05, Jython 2.1 and > Red Robin Jython Development Tools 1.3.9. > if i may ask, did you ask the author of the eclipse plugin ? did anybody else answer you ? or could you by any chance, solve it by yourself ? From john at grulic.org.ar Tue Jan 18 08:44:11 2005 From: john at grulic.org.ar (John Lenton) Date: Tue, 18 Jan 2005 10:44:11 -0300 Subject: strange note in fcntl docs In-Reply-To: <16876.34950.976819.654894@montanaro.dyndns.org> References: <20050117053949.GA28456@grulic.org.ar> <16875.54085.712019.524951@montanaro.dyndns.org> <20050117192327.GA4723@grulic.org.ar> <16876.34950.976819.654894@montanaro.dyndns.org> Message-ID: <20050118134411.GA26210@grulic.org.ar> On Mon, Jan 17, 2005 at 09:54:46PM -0600, Skip Montanaro wrote: > > John> And, even if they were, the note is *still* wrong and misleading: > John> fcntl is available on Windows, and os.open's flags won't be. > > Does this read better? > > [snip] yes, and it takes me back to considering why file objects don't have methods suck as lock, stat and mmap where those calls are available through other mechanisms... -- John Lenton (john at grulic.org.ar) -- Random fortune: Yo mando a mi gato y mi gato manda a su rabo. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From kylotan at gmail.com Mon Jan 17 12:34:31 2005 From: kylotan at gmail.com (Ben Sizer) Date: 17 Jan 2005 09:34:31 -0800 Subject: PyChecker messages In-Reply-To: References: Message-ID: <1105983271.574296.37740@c13g2000cwb.googlegroups.com> But you could use a dict of return values, or even just assigning a different return value in each if clause. The end result is that you have a single well-defined exit point from the function, which is generally considered to be preferable. From peter at engcorp.com Mon Jan 17 19:40:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 Jan 2005 19:40:05 -0500 Subject: python execution path In-Reply-To: References: Message-ID: Dustin Lee wrote: > I'm wondering if there is a way to get python to show each line as it > is executed, sort of like sh -x does for shell programs. Seems like > this would be a nice debugging aid. The best approach, if it's really intended to be a debugging aid, might be to learn about "pdb", starting perhaps with the following line inserted shortly above where you think your bug might be: import pdb; pdb.set_trace() (run the code, wait for the prompt, type "?" for help, then read the docs ;-) ) -Peter From luisXX_lupe2XX at netvisaoXX.pt Fri Jan 21 12:55:26 2005 From: luisXX_lupe2XX at netvisaoXX.pt (Luis P. Mendes) Date: Fri, 21 Jan 2005 17:55:26 +0000 Subject: xml parsing escape characters In-Reply-To: References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efedf2$0$11622$9b622d9e@news.freenet.de> <35adg4F4jgvpnU1@individual.net> <41F01A86.2040805@v.loewis.de> Message-ID: <41F1420E.9090706@netvisaoXX.pt> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 ~From your experience, do you think that if this wrong XML code could be meant to be read only by somekind of Microsoft parser, the error will not occur? I'll try to explain: xml producer writes the code in Windows platform and 'thinks' that every client will read/parse the code with a specific Windows parser. Could that (wrong) XML code parse correctly in that kind of specific Windows client? Or in other words: Do you know any windows parser that could turn that erroneous encoding to a xml tree, with four or five inner levels of tags? I'd like to thank everyone for taking the time to answer me. Luis -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFB8UIOHn4UHCY8rB8RAgK4AKCiHjPdkCKnirX4gEIawT9hBp3HmQCdGoFK 3IEMLLXwMZKvNoqA4tISVnI= =jvOU -----END PGP SIGNATURE----- From mefjr75 at hotmail.com Sun Jan 30 13:32:55 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 30 Jan 2005 10:32:55 -0800 Subject: Disassembling strings and turning them into function parameters References: <1107107283.694377.286360@c13g2000cwb.googlegroups.com> Message-ID: <1107109975.466479.138590@f14g2000cwb.googlegroups.com> mercuryp... at gmail.com wrote: > Hi, > I'm pretty new to Python, to programming overall...so how would I make > something where the user inputs multiple words in a string - like > "connect 123.123.123.123 21 user password" or similar, and then I can > split this string up to pass these arguments to a function like > ftp_connect(ip, port, user, pw) etc...? I have no idea how to "break" > the string up so I can get these out of it.. > > > thanks for answers, > munin Ok well this is pretty basic but it sounds wrong on some level. Maybe you should post some code, you will get better responses. You could try something like: Py>stuff = "connect 123.123.123.123 21 user password" Py>parts_list = stuff.split()# can handle other seperators Py>print parts_list ['connect', '123.123.123.123', '21', 'user', 'password'] Py>def StrFtp(userinfo): ... parts = userinfo.slpit() ... funktion, ip, port, usedr, pw = parts ... funktion = funktion.lower() ... if funktion == 'connect' ... return ftp_connect(ip, port, user, pw) ... elif funktion == 'other_function_name_here': ... return 'your other action here' ... else: ... return None Py>ftpconnect = StrFtp("connect 123.123.123.123 21 user password") Also add asserts and error checking all through the code for malformed input. hth, M.E.Farmer From invalidemail at aerojockey.com Wed Jan 19 18:24:10 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 19 Jan 2005 15:24:10 -0800 Subject: Zen of Python In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> Message-ID: <1106177050.630141.33090@c13g2000cwb.googlegroups.com> Skip Montanaro wrote: > Bill> The example that occurs to me is that "import smtplib" is better > Bill> than "import stdlib.inet.services.smtp". > > Sure. There is a balance to be achieved however. "import std.smtplib" > might be better than "import smtplib", simply because making the standard > library a package reduces the possibility of namespace collisions. Yep. "Reorganize the standard library to be not as shallow" is listed right there in PEP 3000. Notice, however, that it doesn't say, "Reorganize the standard library into an intricate feudal hierarchy of packages, modules, and cross-references." :) The gist of "Flat is better than nested" is "be as nested as you have to be, no more," because being too nested is just a mess. -- CARL BANKS From cr999 at ir.hit.edu.cn Mon Jan 17 02:21:51 2005 From: cr999 at ir.hit.edu.cn (cr999) Date: Mon, 17 Jan 2005 15:21:51 +0800 Subject: pythonnt_rc_d.h is missed when building python from source ? Message-ID: <002801c4fc65$36fe04d0$1d02a8c0@cr> I download the source code of Python-2.3.4 from python.org. But I can't build python from source under Win2000. The compiler complained that there is no pythonnt_rc_d.h file which is included in Python-2.3.4\PC\python_nt.rc. Who knows the reason ? Thanks. Best Regards. Robert. -------------- next part -------------- An HTML attachment was scrubbed... URL: From samantha7395 at hotmail.com Thu Jan 20 13:46:00 2005 From: samantha7395 at hotmail.com (Samantha) Date: Thu, 20 Jan 2005 10:46:00 -0800 Subject: Print to Windows default Printer References: Message-ID: The printer is on LPT1, but I sure can't get the temp file to print for some reason. I am using Windows XP SP2. S "Tim Golden" wrote in message news:mailman.959.1106240645.22381.python-list at python.org... > [Samantha] > > [... snip my explanation of PRINT / COPY LPTx: ...] > > | Thanks Tim, > | That is exactly what I want to do. > | How do I map the printer to LPT1? > | S > > Depends on a lot of things: whether the printer is > local or networked; what version of Windows you're > running, &. > > As a very basic starting point: if it's a local printer > (ie plugged into the back of your machine) it's probably > on LPT1: already, or you could go to the Add Printer > wizard and tell it to configure it for LPT1: there. > > If it's networked, then something like: > > NET USE LPT1: \\servername\printerqueue > > should achieve the right effect. > > TJG > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ From ram at forefront-tech.No.Lunch.meat.com Wed Jan 12 16:06:57 2005 From: ram at forefront-tech.No.Lunch.meat.com (Rick Morrison) Date: Wed, 12 Jan 2005 21:06:57 GMT Subject: dict.updated Message-ID: Would there be any way to add a method to all dict objects that operated like the .update() method, but also returned a reference to the updated dict? .update() is clumsy to use inside of list comprehensions and the like. Or am I missing something? Thanks, Rick From aahz at pythoncraft.com Sat Jan 29 11:55:59 2005 From: aahz at pythoncraft.com (Aahz) Date: 29 Jan 2005 11:55:59 -0500 Subject: limited python virtual machine References: <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> Message-ID: In article <1gr5osy.7eipfq7xyz72N%aleaxit at yahoo.com>, Alex Martelli wrote: >Aahz wrote: >> Alex Martelli deleted his own attribution: >>> >>> >>> object.__subclasses__() >> >> One thing my company has done is written a ``safe_eval()`` that uses a >> regex to disable double-underscore access. > >will the regex catch getattr(object, 'subclasses'.join(['_'*2]*2)...?-) Heheh. No. Then again, security is only as strong as its weakest link, and that quick hack makes this part of our application as secure as the rest. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From aurora00 at gmail.com Thu Jan 27 16:28:54 2005 From: aurora00 at gmail.com (aurora) Date: Thu, 27 Jan 2005 13:28:54 -0800 Subject: Transparent (redirecting) proxy with BaseHTTPServer References: <35sfdaF4hka1hU1@individual.net> Message-ID: If you actually want the IP, resolve the host header would give you that. In the redirect case you should get a host header like Host: www.python.org From that you can reconstruct the original URL as http://www.python.org/ftp/python/contrib/. With that you can open it using urllib and proxy the data to the client. The second form of HTTP request without the host part is for compatability of pre-HTTP/1.1 standard. All modern web browser should send the Host header. > Hi list, > > My ultimate goal is to have a small HTTP proxy which is able to show a > message specific to clients name/ip/status then handle the original > request normally either by redirecting the client, or acting as a proxy. > > I started with a modified[1] version of TinyHTTPProxy postet by Suzuki > Hisao somewhere in 2003 to this list and tried to extend it to my needs. > It works quite well if I configure my client to use it, but using > iptables REDIRECT feature to point the clients transparently to the > proxy caused some issues. > > Precisely, the "self.path" member variable of baseHTTPRequestHandler is > missing the and the host (i.e www.python.org) part of the > request line for REDIRECTed connections: > > without iptables REDIRECT: > self.path -> GET http://www.python.org/ftp/python/contrib/ HTTP/1.1 > > with REDIRECT: > self.path -> GET /ftp/python/contrib/ HTTP/1.1 > > I asked about this on the squid mailing list and was told this is normal > and I have to reconstuct the request line from the real destination IP, > the URL-path and the Host header (if any). If the Host header is sent > it's an (unsafe) nobrainer, but I cannot for the life of me figure out > where to get the "real destination IP". Any ideas? > > thanks > Paul > > [1] HTTP Debugging Proxy > Modified by Xavier Defrang (http://defrang.com/) From stephen.thorne at gmail.com Sun Jan 2 02:08:32 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Sun, 2 Jan 2005 17:08:32 +1000 Subject: Frameworks for "Non-Content Oriented Web Apps" In-Reply-To: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <3e8ca5c80501012308353f6c6@mail.gmail.com> On 1 Jan 2005 20:51:06 -0800, mirnazim at gmail.com wrote: > But is there some sort of framework or something that is actually meant > for such web apps,application that make heavy use of forms, have very > high amount of user interaction etc. > Yeah, nevow, by those crazy twisted people, is great. The underlying concept is 'object publishing', and has some very funky technology for live-updating of a client-side web page via javascript (ala gmail). Object publishing is along the lines of, instead of having a 'form', you have an object which represents data. It knows how to handle form submissions, validate data, etc. And you 'publish' that object. The user can then interact with that object. Anyway, I haven't mucked around with nevow for months, you're better off checking out nevow.com and divmod.org yourself. Stephen. From theller at python.net Tue Jan 25 10:02:56 2005 From: theller at python.net (Thomas Heller) Date: Tue, 25 Jan 2005 16:02:56 +0100 Subject: Installer made with bdist_wininst segfaulting... References: Message-ID: Fernando Perez writes: > Hi all, > > I am seeking advice/help from those with more win32 experience than myself. I > am trying to build a proper win32 installer for IPython, after a user did most > of the hard work. For the most part, it's working very well, but I am running > into a nasty problem, which took me a few hours to finally understand. This > smells to me like a python bug, but I could be wrong. Much googling didn't > turn up anything relevant. > > Here is a brief summary: if the installer file is run from a windows drive which > is different from the one where python resides (and hence where ipython will > end up), the installer segfaults. No traceback, nothing, just a segfault > (well, one of those Windows dialogs asking me to send a binary traceback to > Redmond, but not a proper Python traceback). There are a couple of known bugs in bdist_wininst, and you just reported another one. All these bugs are related to using the post_install_script, and show up when either (thats what I currently remember): - the installer is run from a readonly location, - the installer is run from a different drive (as you reported) - the installer installs for Python 2.4 I will fix these issues in Python 2.3.5, which will probably be out as a release candidate this week, and in Python 2.4.1. I urge everyone to install this release candidate, rebuild the installer with it, and test them thoroughly. Thanks, Thomas From ngps at netmemetic.com Mon Jan 31 11:29:48 2005 From: ngps at netmemetic.com (Ng Pheng Siong) Date: Mon, 31 Jan 2005 16:29:48 +0000 (UTC) Subject: Using HTTPSConnection and verifying server's CRT References: <41fe5357@epflnews.epfl.ch> Message-ID: According to Marc Poulhi?s : > I tried to see if the M2Crypto has this possibility, but from my tests > and from what I can find on the website, it seems not :/ How did you test and where on the website does it say not? > Can someone confirm me this is not possible or point me to something > that could help me? M2Crypto does server cert verification. With M2Crypto's httpslib, you pass in an SSL.Context instance to the HTTPSConnection constructor to configure the SSL; one of the config knobs is cert verification. So, redo your test, satisfy yourself that this is doable, and send me your code to include as an example in the distribution. ;-) M2Crypto even does client certs. Since Apr 2000, according to the very last blog entry on the ZServerSSL page. -- Ng Pheng Siong http://sandbox.rulemaker.net/ngps -+- M2Crypto, ZServerSSL for Zope, Blog http://www.sqlcrypt.com -+- Database Engine with Transparent AES Encryption From ncoghlan at iinet.net.au Thu Jan 27 05:03:39 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 27 Jan 2005 20:03:39 +1000 Subject: python memory blow out In-Reply-To: <4e4a11f805012617082ebd9b80@mail.gmail.com> References: <4e4a11f805012617082ebd9b80@mail.gmail.com> Message-ID: <41F8BC7B.5060905@iinet.net.au> Simon Wittber wrote: > Does anyone have ideas on why this is occuring, or how I might > otherwise prevent memory blow out? The first thing to check is whether you might be accidentally keeping a reference to the result set alive somewhere. If that's not the case, then try to find out if the result set is created by one big allocation or lots of little ones (If the latter, other responses have pointed out how it may cause your problem). There's also a chance of a problem with the database API wrapper, so it may be worth checking with an API specific list. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From stephen.thorne at gmail.com Thu Jan 13 00:32:53 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 15:32:53 +1000 Subject: Refactoring; arbitrary expression in lists In-Reply-To: <41e5fdce.714136143@news.oz.net> References: <41e5cb07.701137402@news.oz.net> <41e5fdce.714136143@news.oz.net> Message-ID: <3e8ca5c8050112213278d6550@mail.gmail.com> On Thu, 13 Jan 2005 05:18:57 GMT, Bengt Richter wrote: > On Thu, 13 Jan 2005 12:19:06 +1000, Stephen Thorne wrote: > > >On Thu, 13 Jan 2005 01:24:29 GMT, Bengt Richter wrote: > >> extensiondict = dict( > >> php = 'application/x-php', > >> cpp = 'text/x-c-src', > >> # etcetera > >> xsl = 'test/xsl' > >> ) > >> > >> def detectMimeType(filename): > >> extension = os.path.splitext(filename)[1].replace('.', '') > extension = os.path.splitext(filename)[1].replace('.', '').lower() # better > > >> try: return extensiondict[extension] > >> except KeyError: > >> basename = os.path.basename(filename) > >> if "Makefile" in basename: return 'text/x-makefile' # XXX case sensitivity? > >> raise NoMimeError > > > >Why not use a regexp based approach. > ISTM the dict setup closely reflects the OP's if/elif tests and makes for an efficient substitute > for the functionality when later used for lookup. The regex list is O(n) and the regexes themselves > are at least that, so I don't see a benefit. If you are going to loop through extensionlist, you > might as well write (untested) *shrug*, O(n*m) actually, where n is the number of mime-types and m is the length of the extension. > >extensionlist = [ > >(re.compile(r'.*\.php') , "application/x-crap-language"), > >(re.compile(r'.*\.(cpp|c)') , 'text/x-c-src'), > >(re.compile(r'[Mm]akefile') , 'text/x-makefile'), > >] > >for regexp, mimetype in extensionlist: > > if regexp.match(filename): > > return mimetype > > > >if you were really concerned about efficiency, you could use something like: > >class SimpleMatch: > > def __init__(self, pattern): self.pattern = pattern > > def match(self, subject): return subject[-len(self.pattern):] == self.pattern > > I'm not clear on what you are doing here, but if you think you are going to compete > with the timbot's dict efficiency with a casual few lines, I suspect you are PUI ;-) > (Posting Under the Influence ;-) Sorry about that, what I was trying to say was something along the lines of: extensionlist = [ (re.compile(r'.*\.php') , "application/x-crap-language"), (re.compile(r'.*\.(cpp|c)') , 'text/x-c-src'), (re.compile(r'[Mm]akefile') , 'text/x-makefile'), ] can be made more efficient by doing something like this: extensionlist = [ SimpleMatch(".php"), "application/x-crap-language"), (re.compile(r'.*\.(cpp|c)') , 'text/x-c-src'), (re.compile(r'[Mm]akefile') , 'text/x-makefile'), ] Where SimpleMatch uses a slice and a comparison instead of a regular expression engine. SimpleMatch and re.compile both return an object that when you call .match(s) returns a value that can be interpreted as a boolean. As for the overall efficiency concerns, I feel that talking about any of this is premature optimisation. The optimisation that is really required in this situation is the same as with any large-switch-statement idiom, be it C or Python. First one must do a frequency analysis of the inputs to the switch statement in order to discover the optimal order of tests! Regards, Stephen Thorne From http Thu Jan 13 15:57:03 2005 From: http (Paul Rubin) Date: 13 Jan 2005 12:57:03 -0800 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: <7xsm559heo.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > >>> Well, it seems that Guido is wrong then. The documentation clearly > >>> states that an expression is a statement. > >> > >> no, it says that an expression statement is a statement. if you don't > >> understand the difference, please *plonk* yourself. > > > > And what else is an expression statement but an expression (list) used > > as a statement. > > Whereas an expression used within a statement is not a statement, and that > is the difference. Huh? Expressions are not statements except when they're "expression statements"? What kind of expression is not an expression statement? And logic would indicate that if we can separate statements from expressions and still have "expression statements", nothing stops us from also being able to have "statement expressions". From skip at pobox.com Sat Jan 29 15:35:36 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 29 Jan 2005 14:35:36 -0600 Subject: limited python virtual machine In-Reply-To: <1gr5th5.13asce21fjmj8tN%aleaxit@yahoo.com> References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> <16891.41849.882856.527798@montanaro.dyndns.org> <1gr5th5.13asce21fjmj8tN%aleaxit@yahoo.com> Message-ID: <16891.62360.246625.13784@montanaro.dyndns.org> Alex> I dunno, maybe I'm just being pessimistic, I guess... No, I think you are being realistic. I thought one of the basic tenets of computer security was "that which is not expressly allowed is forbidden". Any attempt at security that attempts to find and plug the security holes while leaving the basic insecure system intact is almost certainly going to miss something. Skip From craig at postnewspapers.com.au Fri Jan 28 12:09:11 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 29 Jan 2005 01:09:11 +0800 Subject: Dynamic class methods misunderstanding In-Reply-To: <797fe3d405012808171954a2b4@mail.gmail.com> References: <35v5jdF4rk3m7U1@individual.net> <797fe3d405012808171954a2b4@mail.gmail.com> Message-ID: <1106932151.4008.81.camel@albert.localnet> On Fri, 2005-01-28 at 11:17 -0500, Bill Mill wrote: > Beautiful! thank you very much. Looking into the "new" module in > python 2.4, that's equivalent to: > > self.m = type(self.__init__)(method, self, Test) > > I didn't know that you could call types to create another type. Well, a type is essentially a class (in the OOP sense, not the python- specific classobj sense). You can call a type or class to create an instance of that class or type. Here, you call the 'instancemethod' type to create an instance of type 'instancemethod'. Makes sense ... in hindsight. -- Craig Ringer From tundra at tundraware.com Fri Jan 7 17:40:34 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 07 Jan 2005 17:40:34 EST Subject: Tkinter, Alt, and Windows Message-ID: <1qf3b2-pdp.ln1@eskimo.tundraware.com> Arrrrrggg. I have a program that runs comfortably across both Unix variants and Windows ... except .... I wish to bind an Alt-ButtonRelease-3 combination to popup a menu. This works flawlessly under Unix, but with windows, the menu appears briefly and then disappears. I'm guessing that Alt under windows generates another event that I am not catching and the default internal Tk message handler is processing it and causing my menu to get destroyed. It seems that any combination involving the Alt key has this issue - for example Control-Alt-ButtonRelease-3 does the same thing. Has anyone else run into this behavior and have a fix??? TIA, ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From FBatista at uniFON.com.ar Tue Jan 11 08:29:20 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 11 Jan 2005 10:29:20 -0300 Subject: Writing huve ge Sets() to disk Message-ID: [Martin MOKREJ?] #- When importing data from a flatfile into mysql table, there's an #- option to delay indexing to the very last moment, when all keys are #- loaded (it doesn't make sense to re-create index after each new #- row into table is added). I believe it's exactly same waste of cpu/io #- in this case - when I create a dictionary and fill it with data, #- I want to create index afterward, not after every key/value pair #- is recorded. "Premature optimization is the root of all evil.". Use dict as is, profile all your code, start optimizing the slower parts, you'll never get to dicts. . Facundo Bitcora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From harold.fellermann at upf.edu Thu Jan 13 07:53:22 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 13 Jan 2005 13:53:22 +0100 Subject: Pickling a class instead of an instance In-Reply-To: References: Message-ID: <1B26AD62-6562-11D9-B3E0-003065FB7B26@upf.edu> have a look at the thread "copying classes?" some days ago. what goes for copying goes for pickling also, because the modules use the same interface. - harold - On 13.01.2005, at 13:32, Sebastien Boisgerault wrote: > Hi, > > It seems to me that it's not possible with the pickle module > to serialize a class rather than an instance, as in > >>> from pickle import * >>> >>> class C(object): >>> "... doc ..." >>> a = 1 >>> >>> pickstr = dumps(C) > > I mean, it does *something*, there is no error indeed, but > from the string pickstr, I am unable to rebuild the class > C in a brand new context (got a "you're really stupid, all > you deserve is an AttributeError because you know there is > no attribute 'C' in the 'module' object" error). > > Am I wrong ? Why would the "(new-style) classes are regular > objects too" mantra not apply in this case ? Could we imagine > a patch to the pickle module to handle this kind of situation ? > > SB > -- > http://mail.python.org/mailman/listinfo/python-list > > -- If you make people think they're thinking, they'll love you; but if you really make them think they'll hate you. From fumanchu at amor.org Thu Jan 20 03:42:21 2005 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 20 Jan 2005 00:42:21 -0800 Subject: Solutions for data storage? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398225@exchange.hqamor.amorhq.net> Leif K-Brooks wrote: > Robert Brewer wrote: > > Try svn://casadeamor.com/dejavu/trunk if you want a truly > Pythonic query > > syntax. Wait a couple of days, and I'll have version 1.3 ready and > > online at http://www.aminus.org/rbre/python -- lots of changes from > > 1.2.6 which is there now, but at least you can read old > docs online now > > without svn. > > Thanks a lot for the reply. I've skimmed the documentation (very > well-written, by the well), and I really like the looks of what I've > seen so far. I'm a bit confused about where sandboxes get created, > though; in a Web application, would I give each request a > sandbox of its > own, or create one for the entire application, or what? Correct; in a Web application, each request should get its own sandbox. Here's a sample mod_python request.py script, where "cation" is my webapp framework, and "mcontrol" is the name of the app itself, which possesses a Dejavu arena object. ------------ from cation.html.uimodpython import UserInterfaceModPython import mcontrol def handler(req): ui = UserInterfaceModPython(mcontrol.application) ui.sandbox = mcontrol.arena.new_sandbox() ui.request(req) ui.sandbox.flush_all() return ui.status_code ------------ Robert Brewer MIS Amor Ministries fumanchu at amor.org P.S. I've finally tested postgres, mysql, and sqlite on both Debian Linux and Windows 2k, and made the final updates. So the 1.3 release should be _very_ soon. From tjreedy at udel.edu Wed Jan 5 19:37:01 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 5 Jan 2005 19:37:01 -0500 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com><7x652che6z.fsf@ruckus.brouhaha.com><7xoeg4txrp.fsf@ruckus.brouhaha.com><1104895842.200010.42720@z14g2000cwz.googlegroups.com><7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> Message-ID: "John Roth" wrote in message news:10to8qulnc3vke1 at news.supernews.com... > I would like to contribute some documentation to Python. > I've got the time, I write quite a bit, etc. I've got fairly > strong opinions about some things that need to be documented, > (such as all the new style class descriptor stuff from 2.2) > and I have relatively little difficulty matching the existing style. I would love to see the written better and in the manuals. > However, I don't > know TEX, Latex, CVS or Sourceforge. (The latter two are > on my "learn sometime soon so I can put PyFIT where it belongs" > list.) Neither do I. > I have no desire to install Perl to run the documentation toolchain. > I also have no particular desire to write up a bunch of final > format stuff and drop it on someone else to put into the latex > format so it can be included. Why not? If someone is willing to do the part that is easier for him (format pre-written ascii text), why aren't you willing to do the part that is easier for you (write the text)? I am asking as someone who has done just that, at least on a micro scale of occasional sentences in response to bug reports. Terry J. Reedy From mmokrejs at ribosome.natur.cuni.cz Mon Jan 17 05:53:09 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?ISO-8859-2?Q?Martin_MOKREJ=A9?=) Date: Mon, 17 Jan 2005 11:53:09 +0100 Subject: Writing huge Sets() to disk Message-ID: <41EB9915.8080408@ribosome.natur.cuni.cz> Hi, could someone tell me what all does and what all doesn't copy references in python. I have found my script after reaching some state and taking say 600MB, pushes it's internal dictionaries to hard disk. The for loop consumes another 300MB (as gathered by vmstat) to push the data to dictionaries, then releases little bit less than 300MB and the program start to fill-up again it's internal dictionaries, when "full" will do the flush again ... The point here is, that this code takes a lot of extra memory. I believe it's the references problem, and I remeber complains of frineds facing same problem. I'm a newbie, yes, but don't have this problem with Perl. OK, I want to improve my Pyhton knowledge ... :-)) def push_to_disk(self): _dict_on_disk_tuple = (None, self._dict_on_disk1, self._dict_on_disk2, self._dict_on_disk3, self._dict_on_disk4, self._dict_on_disk5, self._dict_on_disk6, self._dict_on_disk7, self._dict_on_disk8, self._dict_on_disk9, self._dict_on_disk10, self._dict_on_disk11, self._dict_on_disk12, self._dict_on_disk13, self._dict_on_disk14, self._dict_on_disk15, self._dict_on_disk16, self._dict_on_disk17, self._dict_on_disk18, self._dict_on_disk19, self._dict_on_disk20) _size = 0 # # sizes of these tmpdicts range from 10-10000 entries for each! for _tmpdict in (self._tmpdict1, self._tmpdict2, self._tmpdict3, self._tmpdict4, self._tmpdict5, self._tmpdict6, self._tmpdict7, self._tmpdict8, self._tmpdict9, self._tmpdict10, self._tmpdict11, self._tmpdict12, self._tmpdict13, self._tmpdict14, self._tmpdict15, self._tmpdict16, self._tmpdict17, self._tmpdict18, self._tmpdict19, self._tmpdict20): _size += 1 if _tmpdict: _dict_on_disk = _dict_on_disk_tuple[_size] for _word, _value in _tmpdict.iteritems(): try: _string = _dict_on_disk[_word] # I discard _a and _b, maybe _string.find(' ') combined with slice would do better? _abs_count, _a, _b, _expected_freq = _string.split() _abs_count = int(_abs_count).__add__(_value) _t = (str(_abs_count), '0', '0', '0') except KeyError: _t = (str(_value), '0', '0', '0') # this writes a copy to the dict, right? _dict_on_disk[_word] = ' '.join(_t) # # clear the temporary dictionaries in ourself # I think this works as expected and really does release memory # for _tmpdict in (self._tmpdict1, self._tmpdict2, self._tmpdict3, self._tmpdict4, self._tmpdict5, self._tmpdict6, self._tmpdict7, self._tmpdict8, self._tmpdict9, self._tmpdict10, self._tmpdict11, self._tmpdict12, self._tmpdict13, self._tmpdict14, self._tmpdict15, self._tmpdict16, self._tmpdict17, self._tmpdict18, self._tmpdict19, self._tmpdict20): _tmpdict.clear() The above routine doesn't release of the memory back when it exits. See, the loop takes 25 minutes already, and it's prolonging as the program is in about 1/3 or 1/4 of the total input. The rest of my code is fast in contrast to this (below 1 minute). -rw------- 1 mmokrejs users 257376256 Jan 17 11:38 diskdict12.db -rw------- 1 mmokrejs users 267157504 Jan 17 11:35 diskdict11.db -rw------- 1 mmokrejs users 266534912 Jan 17 11:28 diskdict10.db -rw------- 1 mmokrejs users 253149184 Jan 17 11:21 diskdict9.db -rw------- 1 mmokrejs users 250232832 Jan 17 11:14 diskdict8.db -rw------- 1 mmokrejs users 246349824 Jan 17 11:07 diskdict7.db -rw------- 1 mmokrejs users 199999488 Jan 17 11:02 diskdict6.db -rw------- 1 mmokrejs users 66584576 Jan 17 10:59 diskdict5.db -rw------- 1 mmokrejs users 5750784 Jan 17 10:57 diskdict4.db -rw------- 1 mmokrejs users 311296 Jan 17 10:57 diskdict3.db -rw------- 1 mmokrejs users 295895040 Jan 17 10:56 diskdict20.db -rw------- 1 mmokrejs users 293634048 Jan 17 10:49 diskdict19.db -rw------- 1 mmokrejs users 299892736 Jan 17 10:43 diskdict18.db -rw------- 1 mmokrejs users 272334848 Jan 17 10:36 diskdict17.db -rw------- 1 mmokrejs users 274825216 Jan 17 10:30 diskdict16.db -rw------- 1 mmokrejs users 273104896 Jan 17 10:23 diskdict15.db -rw------- 1 mmokrejs users 272678912 Jan 17 10:18 diskdict14.db -rw------- 1 mmokrejs users 260407296 Jan 17 10:13 diskdict13.db Some spoke about mmaped files. Could I take advantage of that with bsddb module or bsddb? Is gdbm better in some ways? Recently you have said dictionary operations are fast ... Once more. I want to turn of locking support. I can make the values as strings of fixed size, if mmap() would be available. The number of keys doesn't grow much in time, mostly there are only updates. Thaks for any ideas. martin From paul at prescod.net Tue Jan 18 06:46:24 2005 From: paul at prescod.net (Paul Prescod) Date: Tue, 18 Jan 2005 03:46:24 -0800 Subject: Problem parsing namespaces with xml.dom.minidom In-Reply-To: <41eca38d@clear.net.nz> References: <41eca38d@clear.net.nz> Message-ID: <41ECF710.7000105@prescod.net> You've reversed some function parameters. Here's a program that works fine (note that you don't need to set up a SAX parser): from xml.dom import minidom text = ''' alias Thu Jan 30 15:06:06 NZDT 2003 Nothing ''' # Parse the string into a minidom mydom = minidom.parseString(text) # Look for some elements # This one shouldn't return any (I think). object_el1 = mydom.getElementsByTagName("xte:object") # This one definitely should, at least for what I want. object_el2 = mydom.getElementsByTagNameNS( 'http://www.mcs.vuw.ac.nz/renata/xte',"object", ) print '1: ' + str(object_el1) print '2: ' + str(object_el2) From t-meyer at ihug.co.nz Mon Jan 31 21:26:43 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Tue, 1 Feb 2005 15:26:43 +1300 Subject: getting data from a port in use In-Reply-To: Message-ID: > I am trying to use Python to get the data received at a > specific port (in use) on my computer. I already tried below > code which seems to hang at the statement accepting > connections. Seems to hang, or does hang? Using print statements will tell you whether that's where it's getting stuck or not. > I don't know what else I can try. Any > suggestions will be welcome. > > import socket, select, os > > PORT = 2005 > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > s.bind((socket.gethostname(), PORT)) > s.listen(1) > work_socket, addr = s.accept() > data = s.recv(1024) [...] This should be 'data = work_socket.recv(1024)'. This script works for me with that change. (i.e. I can run it with port 2005 already in use, connect to the port, and it will finish without error). =Tony.Meyer From tom at dtsam.com Wed Jan 19 12:35:16 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Wed, 19 Jan 2005 11:35:16 -0600 Subject: [OT] Good C++ book for a Python programmer References: <1106136496.719185.87850@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1106136496.719185.87850 at c13g2000cwb.googlegroups.com... > I'm picking up C++ again after years of using almost nothing but > Python. I'm frankly enjoying the experience, and it's certainly > deepening my appreciation of Python (which you can read however you > like). > Gad! After Python, how can you stand it (C++) ? Adding object oriented utility to the C language was an atrocity, albeit perhaps a necessary one given the state of the art when that particular atrocity was committed. Aren't we past this? If it is fast, fully compiled code you seek - couldn't you just C a few slow functions and use them in your Python? Thomas Bartkus From jrlen97 at gmail.com Wed Jan 26 02:07:52 2005 From: jrlen97 at gmail.com (Jan Rienyer Gadil) Date: Wed, 26 Jan 2005 15:07:52 +0800 Subject: How to assign Message-ID: Sort of a newbie question: How am i going to assign to a variable anything the user inputs on a wxTxtCtrl? From bill.mill at gmail.com Fri Jan 28 10:20:30 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 28 Jan 2005 10:20:30 -0500 Subject: Dynamic class methods misunderstanding Message-ID: <797fe3d405012807204828b8c2@mail.gmail.com> Hello all, I have a misunderstanding about dynamic class methods. I don't expect this behavior: In [2]: class test: ...: def __init__(self, method): ...: self.method = method ...: self.method() ...: In [3]: def m(self): print self ...: In [4]: test(m) --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) /cygdrive/c/Documents and Settings/Wmill/ /cygdrive/c/Documents and Settings/Wmill/ in __init__(self, method) TypeError: m() takes exactly 1 argument (0 given) ----------------------------------------------------------------------------- Why doesn't m get the implicit self parameter in the self.method() call? How would I make it a proper member of the class, so that a self.method() call would work with the above "m" function? Peace Bill Mill bill.mill at gmail.com From marklists at mceahern.com Thu Jan 27 08:18:14 2005 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 27 Jan 2005 07:18:14 -0600 Subject: exclude binary files from os.walk In-Reply-To: <1106808469.8583.14.camel@bucket.localnet> References: <41f8167b$0$8648$a1866201@visi.com> <1106808469.8583.14.camel@bucket.localnet> Message-ID: <41F8EA16.3060209@mceahern.com> The OP wrote: > Is there an easy way to exclude binary files (I'm working on Windows XP) from the file list returned by os.walk()? Sure, piece of cake: #!/usr/bin/env python import os def textfiles(path): include = ('.txt', '.csv',) for root, dirs, files in os.walk(path): for name in files: prefix, ext = os.path.splitext(name) if ext.lower() not in include: continue filename = os.path.join(root, name) yield filename path = os.getcwd() for name in textfiles(path): print name ;-) // m From marklists at mceahern.com Sun Jan 16 09:22:37 2005 From: marklists at mceahern.com (Mark McEahern) Date: Sun, 16 Jan 2005 08:22:37 -0600 Subject: accessing class variables of private classes In-Reply-To: References: Message-ID: <41EA78AD.1030001@mceahern.com> Uwe Mayer wrote: >Hi, > >I need to access class variables of a class I'd like to make private: > > Use single underscores instead of double underscores--you won't have to workaround the name mangling. Besides, nothing's really private anyway. // m From josh-tmda at yucs.org Thu Jan 20 10:46:13 2005 From: josh-tmda at yucs.org (josh) Date: Thu, 20 Jan 2005 15:46:13 +0000 (UTC) Subject: why no time() + timedelta() ? Message-ID: Why can't timedelta arithmetic be done on time objects? (e.g. datetime.time(5)-datetime.timedelta(microseconds=3) Nonzero "days" of the timedelta could either be ignored, or trigger an exception. From bokr at oz.net Fri Jan 21 23:11:32 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 22 Jan 2005 04:11:32 GMT Subject: Print a string in binary format References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> Message-ID: <41f1b14a.1480920561@news.oz.net> On Sat, 22 Jan 2005 00:45:19 +1000, Nick Coghlan wrote: >neutrino wrote: >> Greetings to the Python gurus, >> >> I have a binary file and wish to see the "raw" content of it. So I open >> it in binary mode, and read one byte at a time to a variable, which >> will be of the string type. Now the problem is how to print the binary >> format of that charater to the standard output. It seems a common task >> but I just cannot find the appropriate method from the documentation. >> Thanks a lot. >> > >FWIW, I work with serial data a lot, and I find the following list comprehension >to be a handy output tool for binary data: > > print " ".join(["%0.2X" % ord(c) for c in data]) > >The space between each byte helps keep things from degenerating into a >meaningless mass of numbers, and using 2-digit hex instead of binary works >towards the same purpose. (I actually currently use the hex() builtin, but the >above just occurred to me, and it will give nicer formatting, and avoids the >C-style "0x" prefixing each byte) > >Here's an interesting twiddle, though (there's probably already something along >these lines in the cookbook): Looks like you also played with this problem, after Alex posted a request for alternative one-liner solutions to a question on an Italian newsgroup last October? ("show_base" reminded me of "number_in_base") http://groups-beta.google.com/groups?hl=en&lr=&q=number_in_base&qt_s=Search+Groups BTW, my final version was (which can be put on one line ;-) def number_in_base(x, N=10, digits='0123456789ABCDEF'): return '-'[:x<0]+''.join([digits[r] for q in [abs(x)] for q,r in iter(lambda:divmod(q, N), (0,0))][::-1]) or digits[0] (it also takes care of sign and lets you encode with alternative digits if you like ;-) > >Py> def show_base(val, base, min_length = 1): >... chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" >... if base < 2: raise ValueError("2 is minimum meaningful base") >... if base > len(chars): raise ValueError("Not enough characters for base") >... new_val = [] >... while val: >... val, remainder = divmod(val, base) >... new_val.append(chars[remainder]) >... result = "".join(reversed(new_val)) >... return ("0" * (min_length - len(result))) + result Hm, learn something every day ;-) It didn't occur to me that a string multiplied by a negative number would default nicely to the same result as multiplying by zero. >... >Py> show_base(10, 2) >'1010' >Py> show_base(10, 2, 8) >'00001010' >Py> show_base(10, 16, 2) >'0A' >Py> show_base(254, 16, 2) >'FE' >Py> show_base(0, 16) >'0' >Py> for base in range(2, 36): >... for testval in range(1000): >... assert testval == int(show_base(testval, base), base) >... >Py> I guess that's a good idea (supplying full set of alphanumeric digits) >>> def number_in_base(x, N=10, digits='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'): ... return '-'[:x<0]+''.join([digits[r] for q in [abs(x)] ... for q,r in iter(lambda:divmod(q, N), (0,0))][::-1]) or digits[0] ... >>> for base in range(2, 36): ... for testval in range(1000): ... assert testval == int(number_in_base(testval, base), base) ... >>> For that matter, might as well go for Z base and negatives too: >>> for base in range(2, 37): ... for testval in range(-500, 500): ... assert testval == int(number_in_base(testval, base), base) ... >>> (assert did not complain) >>> for base in range(2, 37): ... for testval in (-base+2, -base+1, -base, base-2, base-1,base): ... print '%4s:%-4s'%(testval, number_in_base(testval, base)), ... print ... 0:0 -1:-1 -2:-10 0:0 1:1 2:10 -1:-1 -2:-2 -3:-10 1:1 2:2 3:10 -2:-2 -3:-3 -4:-10 2:2 3:3 4:10 -3:-3 -4:-4 -5:-10 3:3 4:4 5:10 -4:-4 -5:-5 -6:-10 4:4 5:5 6:10 -5:-5 -6:-6 -7:-10 5:5 6:6 7:10 -6:-6 -7:-7 -8:-10 6:6 7:7 8:10 -7:-7 -8:-8 -9:-10 7:7 8:8 9:10 -8:-8 -9:-9 -10:-10 8:8 9:9 10:10 -9:-9 -10:-A -11:-10 9:9 10:A 11:10 -10:-A -11:-B -12:-10 10:A 11:B 12:10 -11:-B -12:-C -13:-10 11:B 12:C 13:10 -12:-C -13:-D -14:-10 12:C 13:D 14:10 -13:-D -14:-E -15:-10 13:D 14:E 15:10 -14:-E -15:-F -16:-10 14:E 15:F 16:10 -15:-F -16:-G -17:-10 15:F 16:G 17:10 -16:-G -17:-H -18:-10 16:G 17:H 18:10 -17:-H -18:-I -19:-10 17:H 18:I 19:10 -18:-I -19:-J -20:-10 18:I 19:J 20:10 -19:-J -20:-K -21:-10 19:J 20:K 21:10 -20:-K -21:-L -22:-10 20:K 21:L 22:10 -21:-L -22:-M -23:-10 21:L 22:M 23:10 -22:-M -23:-N -24:-10 22:M 23:N 24:10 -23:-N -24:-O -25:-10 23:N 24:O 25:10 -24:-O -25:-P -26:-10 24:O 25:P 26:10 -25:-P -26:-Q -27:-10 25:P 26:Q 27:10 -26:-Q -27:-R -28:-10 26:Q 27:R 28:10 -27:-R -28:-S -29:-10 27:R 28:S 29:10 -28:-S -29:-T -30:-10 28:S 29:T 30:10 -29:-T -30:-U -31:-10 29:T 30:U 31:10 -30:-U -31:-V -32:-10 30:U 31:V 32:10 -31:-V -32:-W -33:-10 31:V 32:W 33:10 -32:-W -33:-X -34:-10 32:W 33:X 34:10 -33:-X -34:-Y -35:-10 33:X 34:Y 35:10 -34:-Y -35:-Z -36:-10 34:Y 35:Z 36:10 >>> Of course, this is the prefixed-sign and absolute value representation, which is no good if you are using base 2, 8, or 16 to get an idea of underlying bits in a negative two-s complement representation. But that's another thread ;-) Regards, Bengt Richter From rNOSPAMon at flownet.com Mon Jan 3 10:41:32 2005 From: rNOSPAMon at flownet.com (Ron Garret) Date: Mon, 03 Jan 2005 07:41:32 -0800 Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <87u0py6elt.fsf@sme.intra.citec.fi> Message-ID: In article , Just wrote: > In article <87u0py6elt.fsf at sme.intra.citec.fi>, > Simo Melenius wrote: > > > I've sometimes replaced sys.stdout (and/or sys.stderr) to > > capture/redirect debugging information in existing code that has > > unwisely just "print"ed error and warning messages, instead of using > > sys.stderr or error logging modules. > > > > py> def with_output_to_string (func): > > ... try: > > ... sys.stdout = StringIO.StringIO () > > ... func () > > ... return sys.stdout.getvalue () > > ... finally: > > ... sys.stdout = sys.__stdout__ > > Aargh, I can't believe how widespread this idiom is :-(. See my other > reply in this thread: DON'T use sys.__stdout__. Ever. It's helpful to provide an explanation when saying things like this. In this case, it's best to save the original value of sys.stdout and restore that, otherwise nested calls to with_output_to_string can fail, e.g. def f(): print 123 def g(): print 456 x = with_output_to_string(f) print 789 with_outupt_to_string(g) # Will miss the 789 rg From http Tue Jan 11 01:10:19 2005 From: http (Paul Rubin) Date: 10 Jan 2005 22:10:19 -0800 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <34h7m9F43vomsU1@individual.net> Message-ID: <7xsm58lcms.fsf@ruckus.brouhaha.com> Brion Vibber writes: > MediaWiki should run with PHP configured in CGI handler mode, but > these days mod_php has got its claws just about everywhere anyway. If > you control your own server and don't have multi-user security > worries, mod_php is simple enough to install and will probably perform > better. Thanks, yes, I could run a special apache instance with mod_php installed. I'm pretty good with apache. I have no MySQL admin experience but I suppose enough people are using MySQL that the installation procedures and docs are pretty well developed and I can follow the instructions. What I'm wondering is just how big an adventure I'd be setting off on, simply to get MediaWiki itself installed, configured, and running. Any thoughts about that? > For performance I also highly recommend using Turck MMCache or > equivalent PHP bytecode cache extension. Unlike Python, saving > compiled bytecode is not the default behavior of PHP, and for > non-trivial scripts compilation eats up a lot of runtime. Hmm, that's something I could deal with later, I guess. Is that similar to what Zend does? > > I'll say that I haven't actually looked at > > the Mediawiki code, though I guess I should do so. > > Cover your eyes...! it _is_ PHP after all. ;) Heehee. I like PHP just fine for small projects. I just cringe at the notion of something as complex as MediaWiki being written in PHP and am constantly, involuntarily thinking about how I would do it in Python. I can't help myself. Without looking at even a line of WikiMedia's code, I already want to do a total rewrite ;-). > I would generally recommend you just start with MediaWiki if you > intend to use it. To migrate a non-tiny site later you'll need to work > out a migration script to import your data in some way (some people > have asked about this in the past, I don't know if anyone's ever > completed one or made it public). You're probably right, I'll download Wikimedia and see about installing it. I have tons of server disk space, though the CPU has been getting a bit overloaded lately. > On the other hand if you _do_ write a MoinMoin-to-MediaWiki > conversion script (or vice-versa!) we'd love to include it in the > MediaWiki distribution. I think a rough approximation would be pretty easy to do. Trying to get every detail right would be very difficult. If I do something like that, I'll likely go for the rough approximation. From peter at engcorp.com Sat Jan 8 12:58:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Jan 2005 12:58:00 -0500 Subject: OT: google groups bug, or worse? In-Reply-To: <1105127965.616198.302710@z14g2000cwz.googlegroups.com> References: <1105127965.616198.302710@z14g2000cwz.googlegroups.com> Message-ID: aaronwmail-usenet at yahoo.com wrote: > I'm concerned that google groups is not correctly reflecting the > python lists. A month ago I announced the xsdbXML framework to the > python list and the python-announce list. As you can see from the > links > below the python announce submission was approved by the moderators > (thanks!) > and the python list submission also went out, but the messages cannot > be found at google groups. > > http://mail.python.org/pipermail/python-list/2004-December/254479.html > http://mail.python.org/pipermail/python-announce-list/2004-December/003583.html > > Is it a google bug? Or is it something darker, like an anti-Python > conspiracy at google? You didn't post via Google, right? Just sent to the mailing list? I believe that Google knows nothing about mailing lists, but watches a news feed, so if the list/Usenet gateway failed to deliver those messages, Google would never see them. Furthermore, news delivery is not necessarily guaranteed. (Actually, I don't recall how reliable the protocol is, but I doubt it's foolproof.) If any one of the news servers between yours and Google's happened to drop some messages, it's quite possible Google would never see them. Given the "architecture" of Usenet, I wouldn't be surprised if Google missed messages consistently, a very small percentage of the time. -Peter From deetsNOSPAM at web.de Fri Jan 28 11:27:22 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 28 Jan 2005 17:27:22 +0100 Subject: Installing Numeric with ATLAS and LAPACK References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> Message-ID: <35v7b6F4qie84U1@individual.net> > Could someone please provide instructions for install Numeric > with ATLAS and LAPACK? No idea - but telling us what os and versions of python and numeric you use might make others comment on that. -- Regards, Diez B. Roggisch From davorss at gmail.com Wed Jan 26 00:54:13 2005 From: davorss at gmail.com (Davor) Date: 25 Jan 2005 21:54:13 -0800 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <41f6f4ee$1@nntp.zianet.com> Message-ID: <1106718853.867328.55760@z14g2000cwz.googlegroups.com> thanks for the link > know what's funny: in the Lua mailing list there is currently a > discussion about adding OO to Lua. I guess most of these newer languages have no choice but to support OO if they want to attract a larger user base :-(... davor From "yardholler\" at Nospam,charter.net> Sat Jan 15 07:09:34 2005 From: "yardholler\" at Nospam,charter.net> (Misty) Date: Sat, 15 Jan 2005 06:09:34 -0600 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> <1105739748.306557.72120@z14g2000cwz.googlegroups.com> Message-ID: mr_little wrote: > Brian Eable wrote: > >>perl -e '$a="194.109.137.226"; @a = reverse split /\./, $a; for $i > > (0..3) { $sum += $a[$i]*(256**$i) } print "sum = $sum\n"' > >>226 + 35072 + 7143424 + 3254779904 = 3261958626 >> >>http://3261958626/ >> >>Which is NOT 666. > > Comrade, why perl here? :) > Are you afraid python? :) > From No_4 at dsl.pipex.com Tue Jan 11 15:50:06 2005 From: No_4 at dsl.pipex.com (Big and Blue) Date: Tue, 11 Jan 2005 20:50:06 +0000 Subject: complex numbers In-Reply-To: References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: <6-Cdnfjyqs6coXncRVnyuA@pipex.net> It's me wrote: > > I am very happy that Python included *native* complex number > support. And I have always been happy that FORTRAN supports them. > I really like Python's notion of having just one data type: the duck. So have you considered using Python for your problem? -- Just because I've written it doesn't mean that either you or I have to believe it. From jfine at pytex.org Fri Jan 7 16:19:20 2005 From: jfine at pytex.org (Jonathan Fine) Date: Fri, 07 Jan 2005 21:19:20 +0000 Subject: What could 'f(this:that=other):' mean? References: <41DC52CA.5070104@pytex.org> <10toomjdjcs5v21@corp.supernews.com> <41DCE28B.70806@pytex.org> Message-ID: <41DEFCD8.3010407@pytex.org> Jonathan Fine wrote: > I'll post some usage examples later today, I hope. Well, here are some examples. A day later, I'm afraid. ** Pipelines and other composites This is arising for me at work. I produce Postscript by running TeX on a document. And then running dvips on the output of TeX. TeX as a program has parameters (command line options). As does dvips. For various reasons I wish to wrap TeX and dvips. def tex_fn(filename, input_path=None, eps_path=None): '''Run tex on filename. Search for input files on input_path. Search for EPS files on eps_path. ''' pass def dvips_fn(filename, page_size=None, color_profile=None): '''Run dvips on filename. etc.''' pass In reality, these tex and dvips have many options. More parameters will be added later. So now I wish to produce a composite function, that runs both tex and dvips. And does other glue things. def tex_and_dvips_fn(filename, tex:input_path=xxx, dvips:color_profile=yyy): # glueing stuff tex_fn(filename, **tex) # more glueing stuff dvips_fn(filename, **dvips) To avoid a name clash, we use 'tex' for the parameter space, and 'tex_fn' for the function that takes 'tex' as parameter. The point is that parameters can be added to tex_fn and dvips_fn without our having to change tex_and_dvips_fn ** Wrapping functions This is the problem that originally motivated my suggestion. We have coded a new function. def adder(i, j): return i + j We wish to test 'adder'. But unittest is too verbose for us. We wish to define a decorator (?) test_wrap to work as follows. orig_adder = adder adder = test_wrap(adder) new_adder = adder orig_adder(i, j) and new_adder(i, j) to be effectively identical - same return, same side effects, raise same exceptions. So far, def test_wrap(fn): return fn does the job. But now we want new_adder(2, 2, returns=4) new_adder(2, '', raises=TypeError) to be same as orig_adder(2, 2) orig_adder(2, '') (which can be achieved by ignoring 'returns' and 'raises'. The idea here is that we can call adder = new(adder) early on, and not break any working code. And we also want new_adder(2, 2, 5) new_adder('', '', raises=TypeError) to raise something like an AssertionError. OK - so I have an informal specification of test_wrap. Its clear, I think, that test_wrap must be something like def test_wrap(fn): def wrapped_fn(*args, **kwargs): test_args = {} # transfer entries from one dict to another for key in ('returns', 'raises'): if kwargs.has_key(key): test_args[key] = kwargs[key] del kwargs[key] result = fn(args, kwargs) if test_args.has_key(result): assert test_args['result'] = result (I've not coded testing for 'raises'.) Now, the more parameters added by the test_wrap function, the more the chance of a name clash. So why not reduce the chances by using name spaces. One possible namespace syntax is: new_adder(2, 3, test=dict(returns=5)) Another such syntax is: new_adder(2, 3, test:returns=5) Each has its merits. The first works with Python 2.4. The second is, in my opinion, easier on the eye. Anyway, that's my suggestion. Jonathan From cartermark46 at ukmail.com Mon Jan 10 06:55:11 2005 From: cartermark46 at ukmail.com (Mark Carter) Date: Mon, 10 Jan 2005 11:55:11 +0000 Subject: Port blocking In-Reply-To: <7x3bx9sehd.fsf@ruckus.brouhaha.com> References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> Message-ID: <34f8ovF47d783U1@individual.net> Paul Rubin wrote: > Mark Carter writes: > >>Supposing I decide to write a server-side application using something >>like corba or pyro. > Usually you wouldn't run a public corba or pyro service over the > internet. You'd use something like XMLRPC over HTTP port 80 partly > for the precise purpose of not getting blocked by firewalls. Although, when you think about it, it kinda defeats the purposes of firewalls. Not that I'm criticising you personally, you understand. >>Also, is there a good tool for writing database UIs? > > > Yes, quite a few. Ah yes, but is there really? For example, I did a search of the TOC of GTK+ Reference Manual: http://developer.gnome.org/doc/API/2.0/gtk/index.html for the word "data", and there's apparently no widget which is explicitly tied to databases. So in GTKs case, for instance, it looks like one has to roll one's own solution, rather than just using one out of the box. From fumanchu at amor.org Tue Jan 4 17:31:17 2005 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 4 Jan 2005 14:31:17 -0800 Subject: Lambda as declarative idiom Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33980E3@exchange.hqamor.amorhq.net> Michael Spencer wrote: > Roman Suzi wrote: > > > Maybe this is too outlandish, but I see lambdas as a > "quote" mechanism, > > which presents a possibility to postpone (precisely > control, delegate) > > evaluation. That is, an ovehead for lambda must be much > lower but at the > > same time visible to the programmer: > > > > d = a + (lambda x, y: x+ y)(3, 4) > [...] > > I believe that this "possibility to postpone" divides into > two related but separate concepts: controlling the moment > of evaluation, and assembling the arguments required at > that moment. They are both species of 'eval', but > managing arguments is more specialized, because it includes > possibly renaming parameters, assigning default values, > processing positional and keyword arguments, and, perhaps > in the future dealing with argument types. Yes, but the "moment of evaluation" is more complex than just "postponing". In a declarative construct, you probably also want global variables to be bound early, so that the expression does not depend upon *any* free variables. Ditto for closures. A more realistic example: term = input("Enter the amount to add") e = expr(x): x + term ...MUCH code passes, maybe even a new process or thread... d = a + e(3) Robert Brewer MIS Amor Ministries fumanchu at amor.org From ncoghlan at iinet.net.au Wed Jan 26 02:17:48 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 17:17:48 +1000 Subject: python without OO In-Reply-To: <1106718853.867328.55760@z14g2000cwz.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <41f6f4ee$1@nntp.zianet.com> <1106718853.867328.55760@z14g2000cwz.googlegroups.com> Message-ID: <41F7441C.9030008@iinet.net.au> Davor wrote: > thanks for the link > > >>know what's funny: in the Lua mailing list there is currently a >>discussion about adding OO to Lua. > > > I guess most of these newer languages have no choice but to support OO > if they want to attract a larger user base :-(... Tell me, have you ever defined a C structure, and then written various functions to operate on that structure (i.e. taking a pointer to the structure as their first argument)? Have you then put both the structure definition and the function prototypes into a single header file and used that header file from other code? That's OO programming: associating several pieces of information as an 'object', and associating various methods to operate on instances of those objects. Everything else is optional. Problems with OO design generally result from violations of the KISS principle, not from OO itself (although languages like Java and C++ make it hard to avoid violating KISS, since they make you jump through so many hoops to get anything to work at all). KISS (and the XP mantra "Do the simplest thing that could possibly work") are the best means to fight off overengineering, rather than a blanket ban on OO techniques. Jeremy's "Bower's Law" page really does provide a good perspective on the benefits of judicious use of OO techniques (http://www.jerf.org/writings/bowersLaw.html). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From sjmachin at lexicon.net Tue Jan 11 20:12:27 2005 From: sjmachin at lexicon.net (John Machin) Date: 11 Jan 2005 17:12:27 -0800 Subject: Help Optimizing Word Search In-Reply-To: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Message-ID: <1105492347.701890.124830@f14g2000cwb.googlegroups.com> Case Nelson wrote: > Hi there I've just been playing around with some python code and I've > got a fun little optimization problem I could use some help with. > > Basically, the program needs to take in a random list of no more than > 10 letters, and find all possible mutations that match a word in my > dictionary (80k words). However a wildcard letter '?' is also an > acceptable character which increases the worst case time significantly. > So if the letters are ['a','b','c'] check a, b, c, ab, ac, ba, bc, ca, > cb, abc, acb, bac, bca, cab, cba where only a, ba and cab would be > added to the dict of words. If the letters are ['?','?'] check a-z, aa, > ab, ac, ad, ..., az, ba, bb, bc, bd, ..., zz This appears to be a Computer Science 101 Data Structures and Algorithms question, not a Python question, but here's an answer anyway: You appear to want to find all words that have one or more letters in common with your query or candidate string. Aside: Have you been following the long thread started by the poster who appeared to want to store all possible strings that were _not_ words in a given language but could be generated from its alphabet? Here's a possibility: use a bit mask approach. You attach a bit mask to each word; simple data structure -- a list of 2-tuples, or two parallel lists. !def mask(word): ! m = 0 ! for letter in word: ! m |= 1 << (ord(letter) - ord('a')) ! return m Searching without wildcards: !def nowc_search(candidate, mylistof2tuples): ! candmask = mask(candidate) # treating candidate as str, not list ! for word, mask in mylistof2tuples: ! if mask & candmask: ! # one or more letters in common ! yield word Note: this treats "mississippi" and "misp" the same. If "aa" is in your dictionary, what queries would retrieve it? Depending on your exact requirements, this technique may suit you, or you may want to use it as a fast(?) filter, with the matches it throws up needing further checking. You may need a "count number of bits that are set in an int" function. Ref: Fred J. Damerau, "A technique for computer detection and correction of spelling errors", CACM vol 7 number 3, March 1961. Searching with wild cards: your example of query == "??" seems to yield all two-letter words. I'd like to see what you expect for "a?", "?a", "ab?", and "aa?" before suggesting how to tackle wild cards. Reverse-engineering requirements out of other folks' code is not something I do for fun :-) An alternative for you to think about: instead of a bitmask, store the letter-sorted transformation of the words: cat->act, act->act, dog->dgo, god->dgo. Alternative data structure: key = bitmask or sorted-letters, value = list of all words that have that key. A further suggestion which should always be considered when setting up a search where the timing is worse than average O(1): have a separate dictionary for each different wordlength, or some other impossible-length-avoidance filter; that way, with minimum preliminary calculation you can avoid considering words that are so long or so short that they cannot possibly be matches. For example, with approximate matching based on edit distance, if you are searching for a 10-letter word allowing for 2 errors, you can avoid doing the complicated comparison on words shorter than 8 or longer than 12. HTH, John From Pieter.Claerhout at Creo.com Mon Jan 24 10:43:31 2005 From: Pieter.Claerhout at Creo.com (Pieter Claerhout) Date: Mon, 24 Jan 2005 16:43:31 +0100 Subject: Finding a script's home directory? Message-ID: The following should work: os.path.split( os.path.realpath( sys.argv[0] ) )[0] Cheers, pieter -----Original Message----- From: python-list-bounces+pieter.claerhout=creo.com at python.org [mailto:python-list-bounces+pieter.claerhout=creo.com at python.org] On Behalf Of Gabriel Cooper Sent: 24 January 2005 16:40 To: python-list at python.org Subject: Finding a script's home directory? In one of my python programs has a data file I need to load. My solution was to say: if os.path.exists(os.path.join(os.getcwd(), "config.xml")): self.cfgfile = os.path.join(os.getcwd(), "config.xml") Which works fine... as long as you're *in* the script's home directory when you run it (as in, run it as: ./startApp.py as opposed to ./myApp/startApp.py). If I run it from an alternate directory the program looks for the config.xml file in my current directory not the app's home directory. So how do I get the script's home directory? -- http://mail.python.org/mailman/listinfo/python-list From aleaxit at yahoo.com Sat Jan 22 06:10:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 12:10:36 +0100 Subject: list unpack trick? References: <1gqsalx.4ip95k18168r0N%aleaxit@yahoo.com> Message-ID: <1gqshen.6ugqf23hph5qN%aleaxit@yahoo.com> Fredrik Lundh wrote: > Alex Martelli wrote: > > >> or (readable): > >> > >> if len(list) < n: > >> list.extend((n - len(list)) * [item]) > > > > I find it just as readable without the redundant if guard -- just: > > > > alist.extend((n - len(alist)) * [item]) > > the guard makes it obvious what's going on, also for a reader that doesn't > know exactly how "*" behaves for negative counts. It does, but it's still redundant, like, say, if x < 0: x = abs(x) makes things obvious even for a reader not knowing exactly how abs behaves for positive arguments. Redundancy in the code to try and compensate for a reader's lack of Python knowledge is not, IMHO, a generally very productive strategy. I understand perfectly well that you and others may disagree, but I just thought it worth stating my personal opinion in the matter. > once you've seen the > "compare length to limit" and "extend", you don't have to parse the rest of > the statement. Sorry, I don't get this -- it seems to me that I _do_ still have to "parse the rest of the statement" to understand exactly what alist is being extended by. Alex From turian at gmail.com Sun Jan 23 23:52:10 2005 From: turian at gmail.com (Joseph Turian) Date: 23 Jan 2005 20:52:10 -0800 Subject: Fuzzy matching of postal addresses In-Reply-To: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <1106542330.665780.40340@f14g2000cwb.googlegroups.com> Andrew, > Basically, I have two databases containing lists of postal addresses and > need to look for matching addresses in the two databases. More > precisely, for each address in database A I want to find a single > matching address in database B. What percent of addresses in A have a unique corresponding address in B? (i.e. how many addresses will have some match in B?) This is a standard document retrieval task. Whole books could be written about the topic. (In fact, many have been). I suggest you don't waste your time trying to solve this problem from scratch, and instead capitalize on the effort of others. Hence, my proposal is pretty simple: 1. Regularize the punctuation of the text (e.g. convert it all to uppercase), since it is uninformative and---at best---a confounding variable. 2. Use a free information retrieval package to find matches. e.g. LEMUR: http://www-2.cs.cmu.edu/~lemur/ In this case, a "document" is an address in Database B. A "query" is an address in Database A. (Alternately, you could switch A and B to see if that affects accuracy.) Good luck. Joseph From vincent at visualtrans.de Tue Jan 25 14:54:30 2005 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 25 Jan 2005 20:54:30 +0100 Subject: snakespell and myspell In-Reply-To: <1106657932.301181.150050@z14g2000cwz.googlegroups.com> References: <1106657932.301181.150050@z14g2000cwz.googlegroups.com> Message-ID: <41F6A3F6.9020807@visualtrans.de> Fuzzyman wrote: > I'm looking to implement a plugin spell checker. > > I'm probably going to go with PyEnchant, as it looks to be the most > promising currently maintained spell checker. What I would like to know about PyEnchant is how to handle non-ascii input. Through trial & error I've noticed that let's say German Umlauts are stored in the dictionary as using dead accents (is that the term?) (as in 'Mu"tter'), however French accented characters appear to be stored differently (as in '\xc3\xa9levage'. Anybody know what the "system" is? > > I just wondered if anyone knew what happened to snakespell and myspell. Don't know about that. But than there also is a pyrex-driven aspell binding at http://sourceforge.net/projects/uncpythontools Regards, -- Vincent Wehren > Both seem to have dissapeared from the net. People have reported good > results from both - and it seems a shame to lose them. > Regards, > > Fuzzy > http://www.voidspace.org.uk/python/index.shtml > From petite.abeille at gmail.com Sat Jan 29 09:41:00 2005 From: petite.abeille at gmail.com (PA) Date: Sat, 29 Jan 2005 15:41:00 +0100 Subject: The next Xah-lee post contest In-Reply-To: References: Message-ID: On Jan 29, 2005, at 15:32, rbt wrote: > Unix donkey! You not elegant. You have poor design. > Sloppy Perl monkey! You be lazy! You code very very bad. > > Xah know all! Follow The True Path, follow The Xah Way To Enlightenment: "The Unix Pestilence" http://www.xahlee.org/UnixResource_dir/freebooks.html Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From honor2003 at yahoo.com Tue Jan 4 00:50:29 2005 From: honor2003 at yahoo.com (john) Date: 3 Jan 2005 21:50:29 -0800 Subject: FS: PC Doctor Message-ID: <1104817829.919110.309420@c13g2000cwb.googlegroups.com> Bought from http://www.PCbeginner.com two weeks ago. Now my computer got fixed and I do not need it any more. Asking $15 only. I will ship to you by first class mail. Email: honor2003 at yahoo.com From jhargraveiii at msn.com Sat Jan 22 22:34:55 2005 From: jhargraveiii at msn.com (Jim Hargrave) Date: Sat, 22 Jan 2005 22:34:55 -0500 Subject: embedding jython in CPython... In-Reply-To: References: Message-ID: Sorry - should have given more detail. That's what I get for posting at 1:00AM. What I want to do us write scripts in CPython that access Windows ActiveX such as Word and IE. Obviously Jython can't do this (easily at least). I also have Jython scripts that provide a high level layer on top of various Java libraries. I'd like to write as much code in Python as possible. But I have a mixture of incompatible CPython and Jython scripts - that's why I would like to embed Jython in CPython. If I can call my Jython scripts from CPython I can have the best of both world's! Would I be able to embed Jython using JPype? The PyLucene approach (compile Java source with GCJ then wrap with SWIG) looks interesting - but complicated. Here's an example of embedding Jython in a regular Java app: http://www.jython.org/docs/embedding.html Imagine doing the same in CPython, but with JPype or GCJ/SWIG. From tjreedy at udel.edu Thu Jan 6 23:53:38 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Jan 2005 23:53:38 -0500 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com><7x652che6z.fsf@ruckus.brouhaha.com><7x4qhw859p.fsf@ruckus.brouhaha.com><7xk6qrnbum.fsf@ruckus.brouhaha.com><41dcaa00.102858012@news.oz.net><7x652bnhx0.fsf@ruckus.brouhaha.com> <7xsm5et0rb.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7xsm5et0rb.fsf at ruckus.brouhaha.com... > "Terry Reedy" writes: >> Would it be possible, at least for Windows, to write a Python script >> implementing a 'virtual distribution'? IE, download Python, install it, >> download next package, install it, etc. -- prefereably table driven? > > I just don't understand why you'd want to do that, instead of putting > all the files in the distro in the first place. For myself, I can imagine writing such a script using existing installers. I have no idea how to put, say, 20 packages together in one installer. Even if I could, I would not personally buy the bandwidth for gigabyte downloads. I could, however, find somewhere to put a 1K or so script. Terry J. Reedy From della at toglimi.linux.it Sun Jan 9 16:27:09 2005 From: della at toglimi.linux.it (Matteo Dell'Amico) Date: Sun, 09 Jan 2005 21:27:09 GMT Subject: else condition in list comprehension In-Reply-To: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: Luis M. Gonzalez wrote: > Hi there, > > I'd like to know if there is a way to add and else condition into a > list comprehension. I'm sure that I read somewhere an easy way to do > it, but I forgot it and now I can't find it... > > for example: > z=[i+2 for i in range(10) if i%2==0] > what if I want i to be "i-2" if i%2 is not equal to 0? You could use [(i-2, i+2)[bool(i%2 == 0)] for i in range(10)] or, in a less general but shorter way [(i+2, i-2)[i%2] for i in range(10)] or even [i%2 and i-2 or i+2 for i in range(10)] The "if" clause in comprehensions is used as a filter condition. -- Ciao, Matteo From grante at visi.com Mon Jan 17 10:21:03 2005 From: grante at visi.com (Grant Edwards) Date: 17 Jan 2005 15:21:03 GMT Subject: List problems in C code ported to Python References: <41ead925$0$87061$a1866201@visi.com> <41eb1cd7$0$10879$a1866201@visi.com> <13PGd.1402$Rs.1375@newsread3.news.atl.earthlink.net> Message-ID: <41ebd7df$0$87049$a1866201@visi.com> On 2005-01-17, Lucas Raab wrote: > Sorry about that. I had a bad day. First there was the > migraine and then the fight with my significant other, so > yesterday was not a good day. I apologize for what I said. No worries. As somebody else said, the best way to get help solving problems is to post as small an example as possible that exhibits the problem behavior. This may take a bit of effort, since problems sometimes go away when you try to reproduce them in a small example (less than 50 lines or so). If you can post a small example that doesn't do what you want it to, I gaurantee that somebody will explain why it doesn't do what you want and how to fix it. -- Grant Edwards grante Yow! LOU GRANT froze at my ASSETS!! visi.com From kartic.krishnamurthy at gmail.com Wed Jan 5 14:25:03 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 5 Jan 2005 11:25:03 -0800 Subject: smtp question In-Reply-To: References: Message-ID: <1104953103.469153.98310@z14g2000cwz.googlegroups.com> Philippe, Looks like the problem lies where you have added the Subject header. You have terminated it with a \n\n and then your From and To headers. You may want to rewrite it as: server.sendmail(fromaddr, toaddrs, 'Subject:from python\r\n'+msg) Why dont you consider using the email module - http://python.org/doc/2.4/lib/module-email.html ? It is elegant and easy to use. Thank you, --Kartic From carribeiro at gmail.com Tue Jan 4 12:18:48 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 4 Jan 2005 15:18:48 -0200 Subject: Python evolution: Unease In-Reply-To: References: Message-ID: <864d370905010409183b621715@mail.gmail.com> On Tue, 4 Jan 2005 10:39:10 -0300, Batista, Facundo wrote: > #- need: a better standard ide, an integrated db interface with > #- a proper > #- set of db drivers (!!), a better debugger, a standard widget/windows > #- toolkit, something akin to a standard for web programming, better > #- documentation, a standard lib which is better organized, a > #- formalized > #- set of protocols and patterns for program construction. And an > #- interpreter which is fast enough to avoid using C or Pyrex in most > #- obvious cases. > > Let's take one by one: I'll take only a few ;-) > - IDE: Better than what? Than IDLE? Than Eclipse? Than SPE? Than Pythonwin? I would like to seee Eric3, with some polish & opensourced on Win (which means solving the Qt licensing problem). Perhaps someone could convince Trolltech to release a special Qt Win version just for it (Eric3). Eclipse is also an interesting approach. > - Integrated DB interface with a proper set of db drivers (what means the > "!!"?): What do you mean with an integrated db interface? An standard API to > access different DB engines? Something like the Database API specification > (http://www.python.org/topics/database/DatabaseAPI-2.0.html)? There's a SIG > on DB at http://www.python.org/sigs/db-sig/ you may want to look at. > Regarding drivers, to what DB do you miss one? At the risk of starting a huge flamewar, let's state my opinion on this. The DBAPI itself is not a problem, despite several debates about improvements and talks about a future version 3. On the other hand, I wish I could simply plug & play DBAPI modules in a totally seamlessly way. Anyone who tried know how far are we of this dream. At the risk of sounding pessimistic, I don't see plug & play interoperability between DBAPI drivers happening anytime soon. The work is simply way too fragmented. There's no real incentive for compatibility, besides the good will of individual developers, who are always busy and also, that have to keep their own code running. The only way it will work, IMHO, is: if a single entity implements a common API, be it the DBAPI2.0 or whatever, for a sufficiently large number of existing database systems. You may call it a "imposed standard". I don't mind. But it would solve the problem. > - Standard widget/windows toolkit: More standard than Tk? I may be wrong, but I think that most business developers expect more than Tk is able to offer... Canvas is great, but anyone who used more advanced toolkits (such as the ones available on Delphi, Java, or C#) surely require a lot more. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From premshree.pillai at gmail.com Wed Jan 5 08:42:49 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Wed, 5 Jan 2005 19:12:49 +0530 Subject: is python more popular than coldfusion? In-Reply-To: <41dbec00$0$23064$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dbe722$0$23057$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dbec00$0$23064$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: On Wed, 5 Jan 2005 21:30:40 +0800, worzel wrote: > Wth respect to coldfusion, is there much doubt about the fact that Python is > a more prominent and important technology? No doubt in my mind at least. > > How is colfusion percieved by the Python community? Many people belive > coldfusion is becomeing irrelavant and is on its death bed - do Python folk > generally feel this way about it? I have no much idea about Coldfusion, but as far as its *use* is concerned, it definitely isn't much. > > Thanks for your input on this by the way. > > "Premshree Pillai" wrote in message > news:mailman.192.1104931284.22381.python-list at python.org... > > On Wed, 5 Jan 2005 21:09:54 +0800, worzel wrote: > >> How seriuosly do folk take the TIOBE index? Is it a good way to ague what > >> you should be keeping up to speed with or just a 'vague' guide? > > > > I use the TIOBE index -- sometimes -- when I give presentations on > > Python (and Ruby) to people who haven't heard of the languages. > > > > The index is not something to be relied upon (take a look at the > > calculation mechanism). However, more often than not, the indices > > seems to reflect what *I* perceive the indices are in reality. So I > > kinda use them. > > > > The thing about introducing a "new" language to a bunch of folks used > > to their "favorite" language is that they wouldn't care much for a > > language it isn't popular, or if it isn't "growing in popularity". > > > > Beyond these things, I don't think anybody uses the index. I mean I > > wouldn't tell people to learn languages that hold the top position on > > TIOBE ;). > > > >> > >> "Premshree Pillai" wrote in message > >> news:mailman.189.1104927428.22381.python-list at python.org... > >> > On Wed, 5 Jan 2005 19:59:21 +0800, worzel wrote: > >> >> > >> >> > >> >> > >> >> is python more popular than coldfusion? > >> > > >> > I don't know if Coldfusion _was_ ever more "popular" than Python, but > >> > Python is definitely more "popular" _now_. > >> > > >> > This might be of some help: http://www.tiobe.com/tpci.htm > >> > > >> >> > >> >> I realsie that is a very general question as one thing does not > >> >> directly > >> >> relate to the other. My issue is that I am ditching coldfusion due to > >> >> there > >> >> being next to no work for it, and I am thinking of taking on python as > >> >> a > >> >> second language to java in the hope of improving my resume. > >> >> -- > >> >> http://mail.python.org/mailman/listinfo/python-list > >> >> > >> >> > >> > > >> > > >> > -- > >> > Premshree Pillai > >> > http://www.livejournal.com/~premshree > >> > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > >> > > > > > > -- > > Premshree Pillai > > http://www.livejournal.com/~premshree > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From bpeng at rice.edu Sat Jan 1 11:27:50 2005 From: bpeng at rice.edu (Bo Peng) Date: Sat, 01 Jan 2005 10:27:50 -0600 Subject: exposing C array to python namespace: NumPy and array module. In-Reply-To: References: Message-ID: <41D6CF86.1040902@rice.edu> Craig Ringer wrote: > On Sat, 2005-01-01 at 08:18, Bo Peng wrote: > > >>Python's array module is built-in, easy to use, but *without* a >>FromLenAndData function! Even the buffer interface provides only 'get >>buffer' but no 'set buffer' functions. Could anyone tell me how I can >>create an array object from existing data? > > > Python has no array objects in the core language, only lists. The > distinction is important when discussing numarray etc, because Python > lists and NumPy etc arrays are very different. > Thank you very much for the detailed reply! Sorry if I was not clear enough. I was talking about the differece between python array module (http://docs.python.org/lib/module-array.html, Modules/arraymodule.c in the source tree) and NumPy array. They both use C-style memory block arrangement for efficient memory access. While NumPy has both, the array module is designed to be used purely in Python so there is no header file and no function to build an array from a pointer. One of the methods you suggested (creating a new type) already implemented in arraymodule.c. I am not sure if it is appropriate to add the file into my project and add a 'CreateFromLenAndBuf' function. Bo From skullw at sina.com.cn Sat Jan 15 15:27:08 2005 From: skullw at sina.com.cn (skull) Date: Sat, 15 Jan 2005 15:27:08 -0500 Subject: How to del item of a list in loop? Message-ID: Hi everybody, it is my first post in this newsgroup. I am a newbie for python though I have several years development experience in c++. recently, I was stumped when I tried to del item of a list when iteration. here is the wrong way I did: lst = [1, 2, 3] for i in lst: print i if i == 2: lst.remove(i) the result is: 1 2 >>> as you would see, '3' is missing. this problem is caused by 'lst.remove(i)'. apparently, 'marked-and-sweep' is a solution to deal with this issue. but I think there SHOULD BE more 'wise' trick. I want to get your help. Thanks in advance. - skull From pythongnome at hotmail.com Mon Jan 17 10:28:56 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Mon, 17 Jan 2005 15:28:56 GMT Subject: List problems in C code ported to Python In-Reply-To: References: Message-ID: Lucas Raab wrote: > I'm done porting the C code, but now when running the script I > continually run into problems with lists. I tried appending and > extending the lists, but with no avail. Any help is much appreciated > Please see both the Python and C code at > http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py > > TIA OK, here's the Python code and the corresponding C code: def init_mach(): import string #setup rotor data i=1 j=0 for j in j<26, j+1: data[4],[j] = (ref_rotor[j] - 'A'+26) % 26 for i in i<4, i+1: step[i-1] = step_data[order[i-1]] for j in j<26, j+1: data[i],[j] = (rotor[order[i-1]],[j]-'A'+26)%26 data[8-i],[data[i],[j]] = j void init_mach( void ) { int i, j; int ds; int u, v; /* setup rotor data */ for (j=0;j<26;j++) data[4][j] = ((int)ref_rotor[j]-'A'+26)%26; for (i=1;i<4;i++) { step[i-1] = step_data[order[i-1]]; for (j=0;j<26;j++) { data[i][j] = ((int)(rotor[order[i-1]][j])-'A' + 26) % 26; data[8-i][data[i][j]] = j; } } Now, do I need to start boning up on lists and how to use them or am I missing the bigger picture?? Again, for the complete code see http://home.earthlink.net/~lvraab. I'm not asking you to do it for me, just some pointers on going about this. From ncoghlan at iinet.net.au Sat Jan 29 20:53:13 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 30 Jan 2005 11:53:13 +1000 Subject: Coding style article with interesting section on white space In-Reply-To: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> Message-ID: <41FC3E09.5020105@iinet.net.au> beliavsky at aol.com wrote: > The suggestions in the cited article, "How Not to Write FORTRAN in Any > Language", are reasonable but elementary and can be followed in Fortran > 90/95/2003 as well as any other language. What infuriates me is that > the author writes as if Fortran has not evolved since the 1960s. It > has. To be specific, Fortran 90 For myself, I'd be more inclined to say you can write Perl in any language, but the fact that the author used Fortan as his own hated source of unreadable code is beside the point - the entire point of the article is that readability counts, no matter what language you're writing in :) And that's why the article got published in spite of the jabs at Fortran - those jabs served to explain the source of the author's detestation of unreadable code. Anyone taking such an admittedly biased opinion and using it to form an opinion on _current_ Fortan has problems far bigger than a single article. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jjl at pobox.com Sat Jan 22 17:30:06 2005 From: jjl at pobox.com (John J. Lee) Date: 22 Jan 2005 22:30:06 +0000 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> <7xacr4ewjk.fsf@ruckus.brouhaha.com> <41ef4a7a.1323588509@news.oz.net> <7xwtu8vb17.fsf@ruckus.brouhaha.com> <41EF72DE.5030305@jessikat.fsnet.co.uk> <7xwtu8pgr4.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin <"http://phr.cx"@NOSPAM.invalid> writes: [...] > Building larger ones seems to > have complexity exponential in the number of bits, which is not too [...] Why? > It's not even known in theory whether quantum computing is > possible on a significant scale. Discuss. (I don't mean I'm requesting a discussion -- it just reads like a physics / philosophy exam essay question, which traditionally end with that word :) John From rkern at ucsd.edu Wed Jan 19 19:57:49 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 19 Jan 2005 16:57:49 -0800 Subject: Zen of Python In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> Message-ID: Timothy Fitz wrote: > On 19 Jan 2005 15:24:10 -0800, Carl Banks wrote: > >>The gist of "Flat is better than nested" is "be as nested as you have >>to be, no more," because being too nested is just a mess. > > > Which I agree with, and which makes sense. However your "gist" is a > different meaning. It's not that "Flat is better than nested" it's > that "Too flat is bad and too flat is nested so be as nested (or as > flat) as you have to be and no more." Perhaps Tim Peters is far too > concise for my feeble mind If it were scrutable, it wouldn't be Zen. :-) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From http Wed Jan 12 23:05:02 2005 From: http (Paul Rubin) Date: 12 Jan 2005 20:05:02 -0800 Subject: why are people still using classic classes? References: Message-ID: <7xacregej5.fsf@ruckus.brouhaha.com> Simon Wittber writes: > Is there a legitimate use for classic classes that I am not aware of? Yes, new-style classes don't work in older Python installations. Some Python users prefer not to be on such a frequent upgrade treadmill, so they continue to use old versions. Therefore, anyone writing Python code for wide distribution should avoid using new-style classes (and other new Python features) unless they have a good reason. From kartic.krishnamurthy at gmail.com Sat Jan 1 01:07:43 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 31 Dec 2004 22:07:43 -0800 Subject: ftplib strange behaviour In-Reply-To: <1104495025.682424.72160@c13g2000cwb.googlegroups.com> References: <1104495025.682424.72160@c13g2000cwb.googlegroups.com> Message-ID: <1104559663.334186.285970@z14g2000cwz.googlegroups.com> PiErre, I have used ftplib but never for such a huge file (assuming your problem is related to the size of the file). Have you tried downloading the file using another ftp client? Does that download succeed? The reason I ask is because I have attempted downloads from servers that terminate the connection after a certain connection time, in the middle of a download! That is the best I can help you out with the information. Have a happy New Year. Thanks, --Kartic From reinhold-birkenfeld-nospam at wolke7.net Mon Jan 3 03:07:02 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Mon, 03 Jan 2005 09:07:02 +0100 Subject: ? about file() and open() In-Reply-To: <1104706607.022890.314500@c13g2000cwb.googlegroups.com> References: <1104706607.022890.314500@c13g2000cwb.googlegroups.com> Message-ID: <33scp6F43hahrU1@individual.net> Sean wrote: > Was wondering if there was any difference between these two functions. > I have read some text that said file() wasn't introduced until 2.2 and > that it was synonymous with open(). Does this mean that I should be > using file() where I used open() before? FYI, I submitted a patch to correct the docs: http://www.python.org/sf/1094011 Reinhold From wittempj at hotmail.com Mon Jan 17 11:46:40 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 17 Jan 2005 08:46:40 -0800 Subject: pychecker - sets.Set need to be overridden In-Reply-To: References: <1105978024.706237.304360@c13g2000cwb.googlegroups.com> Message-ID: <1105980400.516211.53910@z14g2000cwz.googlegroups.com> I don't know pychecker, maybe there's something wrong with it as your code seems valid to me. From sjmachin at lexicon.net Wed Jan 26 19:09:13 2005 From: sjmachin at lexicon.net (John Machin) Date: 26 Jan 2005 16:09:13 -0800 Subject: Responding to trollish postings. In-Reply-To: References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <41F7F520.8040706@po-box.mcgill.ca> Message-ID: <1106784553.583222.218950@f14g2000cwb.googlegroups.com> Terry Reedy wrote: > > No offense taken. My personal strategy is to read only as much of trollish > threads as I find interesting or somehow instructive, almost never respond, > and then ignore the rest. I also mostly ignore discussions about such > threads. > Indeed. Let's just nominate XL to the "Full Canvas Jacket" website (http://www.ratbags.com/ranters/) and move on. From may_I_see_your_passport_please at nospamyahoo.com Fri Jan 7 15:20:31 2005 From: may_I_see_your_passport_please at nospamyahoo.com (Dwarf Electrician) Date: Fri, 07 Jan 2005 14:20:31 -0600 Subject: Recent infoworld column Message-ID: <41DEEF0F.5000300@nospamyahoo.com> from a long time listener... http://www.infoworld.com/article/04/12/30/01OPstrategic_1.html From rittersporn at gmail.com Fri Jan 7 06:09:43 2005 From: rittersporn at gmail.com (Rittersporn) Date: 7 Jan 2005 03:09:43 -0800 Subject: _Re Pre/Postconditions with decorators Message-ID: # Google-News won't let be post a follow-up right now! # Google-Beta-News destroys the formatting :-( # So I'll start a new thread. Hi Stephen I have not read anything about the "framehack lambda replacement" yet, but I do compile the pre- and postconditions. Syntax erros e.g. will be raised if the module is compiled. Although I must admit that your code snippets look more like compiled code ;-) Hi Robert thanks for the link to the Ian Bicking blog. Hi George, it would be nice to see how you have tackled the task. Maybe we will have a checker module in Python one day... ;-) Well, I have attached my latest attempt to model pre/postconditions (without "framehack lambda replacement") which does wrap the original function with a class which delegates attribute access. Now I can split my "condition" into pre- and postcondition and the "tracer" prints the original function name. I have also fixed a bug with keyword arguments. Major difference compared to other examples is probably only that I can refer to function arguments by name: class Delegate(object): def __init__(self,function): self.function=function def __getattr__(self,key): return getattr(self.function,key) def condition(pretext,posttext=""): precode=compile(pretext or "True","","eval") postcode=compile(posttext or "True","","eval") # function -> decorated(function) def decorate_condition(function): argcount=function.func_code.co_argcount var=function.func_code.co_varnames[0:argcount] class EvalCond(Delegate): def __call__(self,*args,**kargs): # FIXME: check if "var" always contains ordered list of arguments # map arguments and args_seq=[(argname,args[pos]) for pos,argname in \ enumerate(var) if (argname not in kargs)] # key-arguments to value kargs_seq=[(k,v) for k,v in kargs.iteritems()] environment=args_seq+kargs_seq # precondition assert eval(precode,{},dict(environment)),pretext tmp=function(*args,**kargs) environment2=environment+[('result',tmp)] # postcondition assert eval(postcode,{},dict(environment2)),posttext return tmp return EvalCond(function) return decorate_condition def trace(function): class Trace(Delegate): def __call__(self,*args,**kargs): print "enter function %s with " % \ self.function.func_name,args,kargs result=self.function(*args,**kargs) print "leave function %s with " % \ self.function.func_name,args,kargs return result return Trace(function) def precondition(prgtext): return condition(prgtext) def postcondition(prgtext): return condition("",prgtext) @precondition("number>0 and number<2") @postcondition("result>=0") def sqrt(number): import math return math.sqrt(number) @trace @precondition("len(seq)>0 is not None and str(more)") @postcondition("sum(seq)==result") def my_sum(seq,more): tmp=0 for element in seq: tmp+=element return tmp print sqrt(1.2) print my_sum([1,2,3],more="more") From __peter__ at web.de Thu Jan 27 03:10:08 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Jan 2005 09:10:08 +0100 Subject: building Python: up arrow broken on SuSE Linux 8.2 References: <41f6c3f7$1@nntp.zianet.com> <41f85dd8@nntp.zianet.com> Message-ID: Erik Johnson wrote: > the Apple Python distribution the OP was asking about.??I?now?notice?this > in the output of configure: > > checking for rl_pre_input_hook in -lreadline... no > checking for rl_completion_matches in -lreadline... no > > > My?system?has?/lib/libreadline.so.4.3.???I?guess?it?does?not?define > these newer functions and so that is why the readline module was not > configured in Setup to start with? That is the presumption I am working > on. Have you ensured (with yast) that readline-devel is actually installed? Peter From tzot at sil-tec.gr Mon Jan 3 16:46:05 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 03 Jan 2005 23:46:05 +0200 Subject: input record sepArator (equivalent of "$|" of perl) References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> <1103657476.495700.191020@f14g2000cwb.googlegroups.com> <1103671235.093738.198680@z14g2000cwz.googlegroups.com> Message-ID: On 21 Dec 2004 15:20:35 -0800, rumours say that "John Machin" might have written: >Subtle distinction: A metER is a measuring device. A MetRE is a unit of >distance. In this case, English (compared to American English) is closer to the original "metron" [1]. Now, if only you people wrote the plural of "parenthesis" as "parentheseis" and not "parentheses", that would ease a lot my Greek English... :) [1] through the French "m?tre" of course; great job, those revolutionaries did with the metric system. As Asimov put it, "how many inches to the mile?" -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From rogerb at rogerbinns.com Sun Jan 16 01:51:00 2005 From: rogerb at rogerbinns.com (Roger Binns) Date: Sat, 15 Jan 2005 22:51:00 -0800 Subject: there's a socket.sendall(), so why no socket.recvall()? References: <41e03ccc$0$6208$e4fe514c@news.xs4all.nl> <41e9e854$0$6212$e4fe514c@news.xs4all.nl> Message-ID: >>>> there's a socket.sendall(), so why no socket.recvall()? BTW socket.sendall() doesn't actually work for large amounts of data on Windows 2000 and probably other versions of Windows as well. Eg if you supply a 1MB buffer then you get an exception based on some internal Windows error code. I haven't experimented on Unix yet to see if it has the same issue. The workaround is to write a wrapper that really does send everything. Roger From roland.heiber at web.de Thu Jan 13 07:41:12 2005 From: roland.heiber at web.de (Roland Heiber) Date: Thu, 13 Jan 2005 13:41:12 +0100 Subject: Creating text on images In-Reply-To: <1105591796.422252.190990@f14g2000cwb.googlegroups.com> References: <1105591796.422252.190990@f14g2000cwb.googlegroups.com> Message-ID: morphex wrote: > Hi all, > > I'm trying to create a script that will superimpose text on an image. > I didn't find any great examples out there on how this can be done (I > presume using PIL is necessary), do you know of any examples? > Thanks, > > Morten > Hi, something like this? ### from PIL import Image, ImageFont, ImageDraw import sys im = Image.open(YOUR_IMAGE_HERE) idraw = ImageDraw.Draw(im) idraw.text((1,1),"Hello", fill=128) im.save(YOUR_NEW_IMAGE_HERE, IMAGE_TYPE) ### HtH, Roland From fuzzyman at gmail.com Wed Jan 5 07:49:05 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jan 2005 04:49:05 -0800 Subject: How do I make Windows Application with Python ? In-Reply-To: References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> Message-ID: <1104929345.364701.19150@z14g2000cwz.googlegroups.com> Couple of corrections - neither pypy nor starkiller are compilers. Starkiller isn't available yet and *may* be helpful in building compilers. Pyrex is an alternative language - a python/C hybrid that can be compiled. If you want to release an application then innosetup, starkit, and upx might help - but they're not python related. You will need something like py2exe, cx_freeze, or mcmillan installer. (Which are specific to python - py2exe seems to be the more mature tool). Alternatively you could consider 'Movable Python' - a frozen distribution of python that doesn't need isntalling. See http://sourceforge.net/projects/movpy Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From apardon at forel.vub.ac.be Fri Jan 14 05:46:07 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Jan 2005 10:46:07 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-01-14, Nick Coghlan schreef : > Antoon Pardon wrote: >> No I am applying set logic. Any string that is in the set of >> valid expressions is also in the set of valid statements. > > According to Python's grammar, this is not the case. It requires a NEWLINE or > ";" token on the end to turn the expression into a statement. Actually appending > either of those tokens means the string is no longer an expression. Well you are correct, but by the same logic an expression_stmt isn't a statement either. In point of fact none of the _stmt is a statement including an assignment. But changing "statements" to "simple statements" seems to make the assertion correct. -- Antoon Pardon From tchur at optushome.com.au Mon Jan 3 17:44:11 2005 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 04 Jan 2005 09:44:11 +1100 Subject: How can engineers not understand source-code control? In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> <41d8417e$0$14596$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: <41D9CABB.6050501@optushome.com.au> Cameron Laird wrote: > I've seen the infatuation for Excel (and so on) for years, but > never found it at all tempting myself. I mostly just ignore the > issue--no, actually, I guess I give them Excel, but show at the > same time that they really want the alternative views that I > also provide. See http://www.burns-stat.com/pages/Tutor/spreadsheet_addiction.html for a thoughtful essay by a statistician on this affliction. I think that Python would be an excellent addition to his Treatment Centre pharmacopoeia. Tim C From ptmcg at austin.rr._bogus_.com Sun Jan 9 03:18:31 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 09 Jan 2005 08:18:31 GMT Subject: pyparsing: how to negate a grammar References: <1105229039.136595.180640@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1105229039.136595.180640 at c13g2000cwb.googlegroups.com... > Hi, > > I want to define a rule for a line that does NOT start with a given > Literal. How do I do that? I try the following and my program just hang > there: > > BodyLine = ~Literal("HTTP/1.1") + restOfLine > > Thanks, > Khoa > Khoa - pyparsing can be run in several modes, one of which tokenizes and extracts data according to a given grammar, one of which scans for pattern matches, and one which translates matched patterns into other patterns. Its not clear from your e-mail what you are trying to do. There is nothing in your statement that would cause Python to "just hang there", what else is your program doing? -- Paul From ed at leafe.com Fri Jan 21 12:31:29 2005 From: ed at leafe.com (Ed Leafe) Date: Fri, 21 Jan 2005 12:31:29 -0500 Subject: wx.BoxSizer problem In-Reply-To: <41F11AC1.6040108@geochemsource.com> References: <41F11AC1.6040108@geochemsource.com> Message-ID: <48F31575-6BD2-11D9-9482-003065B11E84@leafe.com> On Jan 21, 2005, at 10:07 AM, Laszlo Zsolt Nagy wrote: > My problem is that only one of the buttons is visible and that one is > not expanded. (System: Windows, Python 2.3.4, wxPython 2.5.3) Works as expected on Mac OS X 10.3.7, python 2.3.4, wxPython 2.5.2.8. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From philippecmartin at sbcglobal.net Sat Jan 8 04:18:04 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Sat, 08 Jan 2005 10:18:04 +0100 Subject: "A Fundamental Turn Toward Concurrency in Software" Message-ID: <1105175884.6873.14.camel@localhost> I remember a _few_ year ago when all specialists (Intel's) included agreed that the 100MHZ barrier would never be passed - so, at least, we did get free lunch for a couple of years :-) I also must add that in my 17 years of realtime/embedded programming, the problem usually was not the CPU speed - since you know _prior_ to the design of your software whether your CPU will change context on time when the hardware IRQ comes in - but rather the fact that all the software/peripherals had to share the same bus ==> that usually was where the bottleneck was. I guess my point is to not focus the performance of a system solely on its CPU's. Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From jacobsmail at postmark.net Mon Jan 24 18:56:54 2005 From: jacobsmail at postmark.net (Jacob H) Date: 24 Jan 2005 15:56:54 -0800 Subject: Help with saving and restoring program state Message-ID: <85b54e91.0501241556.d281f90@posting.google.com> Hello list... I'm developing an adventure game in Python (which of course is lots of fun). One of the features is the ability to save games and restore the saves later. I'm using the pickle module to implement this. Capturing current program state and neatly replacing it later is proving to be trickier than I first imagined, so I'm here to ask for a little direction from wiser minds than mine! When my program initializes, each game object is stored in two places -- the defining module, and in a list in another module. The following example is not from my actual code, but what happens is the same. (code contained in "globalstate" module) all_fruit = [] (code contained in "world" module) class Apple(object): # the class hierarchy goes back to object, anyway def __init__(self): self.foo = 23 self.bar = "something" globalstate.all_fruit.append(self) apple = Apple() I enjoy the convenience of being able to refer to the same apple instance through world.apple or globalstate.all_fruit, the latter coming into play when I write for loops and so on. When I update the instance attributes in one place, the changes are reflected in the other place. But now comes the save and restore game functions, which again are simplified from my real code: (code contained in "saveload" module) import pickle import world def savegame(path_to_name): world_data = {} for attr, value in world.__dict__.items(): # actual code is selective about which attributes # from world it takes -- I'm just keeping this # example simple world_data[attr] = value fp = open(path_to_name, "w") pickle.dump(world_data, fp) fp.close() def loadgame(path_to_name): fp = open(path_to_name, "r") world_data = pickle.load(fp) for attr, value in world_data.items(): setattr(world, attr, value) fp.close() The problem is that the game objects only get overwritten in the world module. The instances in the globalstate.all_fruit list remain unchanged, which is not the behaviour I want. I started to write code to get around this. I figured that with each loadgame call, I could reset all the lists in globalstate to empty, then reappend each game object to the appropriate list. But this possibility got complicated fast, because all game objects belong to more than one list. My apple instance alone would belong to globalstate.all_things, globalstate.all_fruit, globalstate.all_items, and perhaps others. Some of the game objects contained in these lists don't need to be a part of capturing program state in the first place! But I'm stuck, because unpickling (so far as I understand it) creates a brand new instance that doesn't know it used to have references to itself in the globalstate lists. Any advice out there? I'm looking for a clean, elegant way to overwrite the same class instance in two arbitrary places at once. Perhaps the example code I've provided isn't even the best way of saving and restoring program state. Perhaps I can easily update my globalstate lists and I'm just overlooking the simple way. Or perhaps the solution lies in abandoning the concepts of referencing my game objects through module attributes and lists. I'm open to any suggestions. Thanks in advance for any help! Jacob From news at wogan.id.au.invalid Tue Jan 25 01:46:34 2005 From: news at wogan.id.au.invalid (Greg Wogan-Browne) Date: Tue, 25 Jan 2005 14:46:34 +0800 Subject: Clarification on XML parsing & namespaces (xml.dom.minidom) Message-ID: <41f5eb4b$0$10526$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Hi all, I am having some trouble figuring out what is going on here - is this a bug, or correct behaviour? Basically, when I create an XML document with a namespace using xml.dom.minidom.parse() or parseString(), the namespace exists as an xmlns attribute in the DOM (fair enough, as it's in the original source document). However, if I use the DOM implementation to create an identical document with a namespace, the xmlns attribute is not present. This mainly affects me when I go to print out the document again using Document.toxml(), as the xmlns attribute is not printed for documents I create dynamically, and therefore XSLT does not kick in (I'm using an external processor). Any thoughts on this would be appreciated. Should I file a bug on pyxml? Greg Python 2.3.3 (#1, May 7 2004, 10:31:40) [GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import xml.dom.minidom >>> raw = '' >>> doc = xml.dom.minidom.parseString(raw) >>> print doc.documentElement.namespaceURI http://example.com/namespace >>> print doc.documentElement.getAttribute('xmlns') http://example.com/namespace >>> impl = xml.dom.minidom.getDOMImplementation() >>> doc2 = impl.createDocument('http://example.com/namespace','test',None) >>> print doc2.documentElement.namespaceURI http://example.com/namespace >>> print doc2.documentElement.getAttribute('xmlns') >>> From steven.bethard at gmail.com Tue Jan 18 19:38:20 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 18 Jan 2005 17:38:20 -0700 Subject: generator expressions: performance anomaly? In-Reply-To: <41eda453.1215517842@news.oz.net> References: <377Hd.77904$Jk5.30235@lakeread01> <41ED1C0F.4030800@holdenweb.com> <41eda453.1215517842@news.oz.net> Message-ID: Bengt Richter wrote: > Which make me wonder what plans there are for providing a better > mechanism than default arguments as a way of initializing local function > variables. Nested def's to create a closure with initialized values is > pretty crufty for that, IMO. What about using a class? Associating functions with data is pretty much what they're for... > Maybe extending the default argument space > with whatever comes after e.g. a triple star delimiter in the argument list, > but which wouldn't be counted as part of the normal arguments? E.g., > > def foo(x, y=123, *args, **kw, *** i=1, deftime=time.ctime()): > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime If what you want is to have i=1 and deftime=time.ctime() available within foo, you could do something like (untested): class foo(object): def __init__(self): self.i = 1 self.deftime = time.ctime() def __call__(self, x, y=123, *args, **kwds): return x*y, (kw.get('which_time') == 'now' and time.ctime() or self.deftime) foo = foo() Or if you don't like 'foo = foo()', you could probably abuse the __new__ method (also untested): class foo(object): i = 1 deftime = time.ctime() def __new__(cls, x, y=123, *args, **kwds): return x*y, (kw.get('which_time') == 'now' and time.ctime() or self.deftime) I guess my point is that if you want attribute associated with the function, it's often easy enough to write a class instead... Steve From tjreedy at udel.edu Sun Jan 2 17:15:10 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Jan 2005 17:15:10 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com><7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com><1104620491.542938.92100@z14g2000cwz.googlegroups.com><7xsm5kfyse.fsf@ruckus.brouhaha.com> <41d7941f$1_3@127.0.0.1><7x8y7cjo57.fsf@ruckus.brouhaha.com> <87zmzsax12.fsf@hector.domek><87pt0na5zf.fsf@hector.domek> <87llbba55t.fsf@hector.domek> Message-ID: "Peter Dembinski" wrote in message news:87llbba55t.fsf at hector.domek... > Besides, shouldn't str be a reserved word or something? It is a name in the builtins module which is automatically searched after globals. Many experienced Pythoneers strongly advise against rebinding builtin names *unless* one is intentionally wrapping or overriding the builtin object. The latter are sometimes valid expert uses of masking builtins. Newbies are regularly warned on this list against making a habit of casual use of list, dict, int, str, etc. None has been reserved because there is no known good use for overriding it. True and False will be reserved someday. There have been proposals to turn on reserved status for all builtins on a per-module status. Terry J. Reedy From __peter__ at web.de Mon Jan 17 16:24:58 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Jan 2005 22:24:58 +0100 Subject: Assigning to self References: <10uo6hbn040qt24@news.supernews.com> Message-ID: Frans Englich wrote: > On Monday 17 January 2005 20:03, John Roth wrote: >> "Frans Englich" wrote in message > > > >> In other words, you're trying to create a singleton. In general, >> singletons are frowned on these days for a number of reasons, >> not least because of the difficulty of testing them. > > Then I have some vague, general questions which perhaps someone can reason > from: what is then the preferred methods for solving problems which > requires Singletons? Is it only frowned upon in Python code? Sorry, no answer here, but do you really want a singleton? Singleton: "Ensure a class only has one instance, and provide a global point of access to it" whereas Flyweight: "Use sharing to support large numbers of fine-grained objects efficiently" as per "Design Patterns" by Gamma et al. Peter From claird at lairds.us Thu Jan 6 09:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 06 Jan 2005 14:08:04 GMT Subject: navigating/changing directories References: Message-ID: In article , Nick Coghlan wrote: >The script is executed in a process separate from your command shell, and hence >has no effect on your shell's current directory. > >There are some things that batch files and shell scripts are still good for - >manipulating the shell :) . . . For more on this subject, see . From tonino.greco at gmail.com Tue Jan 4 09:45:06 2005 From: tonino.greco at gmail.com (Tonino) Date: 4 Jan 2005 06:45:06 -0800 Subject: python intergration bus ? Message-ID: <1104849906.019872.153800@z14g2000cwz.googlegroups.com> Hi, Just an interested question - I friend is testing a few JAVA intergration bus's that will be used to intergrate his companies services - I was wondering if there was a python intergration bus ? other than maybe Pyro ? Thanks Tonino From peter at somewhere.com Fri Jan 14 07:11:41 2005 From: peter at somewhere.com (Peter Maas) Date: Fri, 14 Jan 2005 13:11:41 +0100 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: Craig Ringer schrieb: > And then we have iteration .... > > (generator expressions, list comprehensions, for loops, ...?) over > (sequences, iterators, generators) Just sequences and iterators. Generators are functions which return iterators. Sequences and iterators provide two ways to build containers. My use cases: finite, can be defined by enumeration: use sequence infinite, must be defined algorithmically: use iterator generator: neat way to produce an iterator, can also be viewed as a persistent function call (better than static local variables). Once defined, sequences and iterators have nearly the same interface. To have list comprehensions but no equivalent for iterators would be strange. > I happen to be extremely fond of the flexibility this provides, but one > obvious way to do it there is not. Development of the language, backward compatibility and obviousness are diverging goals. You can't satisfy them all at the same time. And goals provide a direction but are rarely reached. :) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From daniel at bowettsolutions.com Wed Jan 5 15:18:42 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Wed, 05 Jan 2005 20:18:42 +0000 Subject: Python evolution: Unease In-Reply-To: References: Message-ID: <41DC4BA2.3090107@bowettsolutions.com> Batista, Facundo wrote: > [Daniel Bowett] > > #- Contribute to where on Sourceforge??? Which domentation are > #- we talking > #- about in general? > > Suppose you're reading Python documentation. Don't know, for example, > os.remove(). There you find that a particular parragraph is difficult > to understand. You say "Hey, this could be better written", so you > write i a more pedagogic way. > > After that you go to SF, Python project > (http://sourceforge.net/projects/python), and go to Bugs. There, if > you are logged in SF, you will see a "Submit new" link. You click on > it and you'll see a form to fill. > > Select some fields (specially bug group in "Documentation") and in > "Detailed Description:" you put something like "This particular > sentence was difficult to read. Attaching a new way to write it". Of > course, then attach the file of your text (if it's short enough you > can put it directly in that field). > > Of course, if you write any NEW documentation about something that is > not documented at all, or find some more serious issues with the docs > (for example, bad argument count in a function) you can follow the > same steps. > > . Facundo > > Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog > PyAr - Python Argentina: http://pyar.decode.com.ar/ > > > * . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . > . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . > . . . . . . . . . . . . . . . . . . . . . .* > > *_ADVERTENCIA._* > > *La informaci?n contenida en este mensaje y cualquier archivo anexo al > mismo, son para uso exclusivo del destinatario y pueden contener > informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada > por la ley.* > > *Si Ud. No es uno de los destinatarios consignados o la persona > responsable de hacer llegar este mensaje a los destinatarios > consignados, no est? autorizado a divulgar, copiar, distribuir o > retener informaci?n (o parte de ella) contenida en este mensaje. Por > favor notif?quenos respondiendo al remitente, borre el mensaje > original y borre las copias (impresas o grabadas en cualquier medio > magn?tico) que pueda haber realizado del mismo.* > > *Todas las opiniones contenidas en este mail son propias del autor del > mensaje y no necesariamente coinciden con las de Telef?nica > Comunicaciones Personales S.A. o alguna empresa asociada.* > > *Los mensajes electr?nicos pueden ser alterados, motivo por el cual > Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna > obligaci?n cualquiera sea el resultante de este mensaje.* > > *Muchas Gracias.* > Thanks, typically how long does it take for any documentation to be considered and implemented? From jerf at jerf.org Tue Jan 25 20:26:33 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 25 Jan 2005 20:26:33 -0500 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> Message-ID: On Tue, 25 Jan 2005 15:01:23 -0800, Davor wrote: > Thanks, > > I do not hate OO - I just do not need it for the project size I'm > dealing with - and the project will eventually become open-source and > have additional developers - so I would prefer that we all stick to > "simple procedural" stuff rather than having to deal with a developer > that will be convincing me that his 50 layers inheritance hierarchy is > good since it exists in some weird pattern that he saw somewhere on > some Java design patterns discussion board :-) The difference between Python OO and Java is that Python's *actually solves problems* instead of creating them. Given your experience and goals, I'd recommend going ahead with your plan, but the time will come when the Right Solution is creating a class, and I strongly recommend that you not avoid it because of the bad taste Java has legitimately left in your mouth. Odds are, that time will come sooner rather than later, too. I'd also recommend spending a bit more time with Python before trying to lead a project in it. That's general advice not Python-specific, and I understand that it is also sometimes impractical. However, you will pay for it one way or another. If nothing else, people who have learned Python and are capable of contributing valuable code are going to be very turned off when they submit perfectly reasonable classes to solve problems and get shot down for being OO. (For context on my point of view, I offer up http://www.jerf.org/writings/bowersLaw.html ; trying to create a completely class-free large project in Python will be possible, but it is probably inadvisable, as you are throwing away useful tools that you will probably end up replicating anyhow. What Java teaches about OO is actively harmful in learning Python and must be unlearned. Java is the new Basic.) From steve at holdenweb.com Thu Jan 13 09:29:49 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 13 Jan 2005 09:29:49 -0500 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com><7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: <41E685DD.30203@holdenweb.com> Fredrik Lundh wrote: > Antoon Pardon wrote: > > >>Well, it seems that Guido is wrong then. The documentation clearly >>states that an expression is a statement. > > > no, it says that an expression statement is a statement. if you don't > understand the difference, please *plonk* yourself. > OK then, "The documentation clearly states that not all statements can be expressions". Specifically Guido has justified the fact that an assignment does not return any value, and therefore cannot be used as a component of an expression. Mea culpa, but I'm not going to *plonk* myself - then *nobody* would be listening to me :-) regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From flamesrock at gmail.com Sat Jan 8 17:47:34 2005 From: flamesrock at gmail.com (flamesrock) Date: 8 Jan 2005 14:47:34 -0800 Subject: EOF for binary? In-Reply-To: <5kj0u0dodrb324oed4nl9v281b0n43s2i6@4ax.com> References: <1105147072.909665.242360@z14g2000cwz.googlegroups.com> <5kj0u0dodrb324oed4nl9v281b0n43s2i6@4ax.com> Message-ID: <1105224454.358015.216000@c13g2000cwb.googlegroups.com> ahh..that does make sense. But maybe getsize() should have a way of inferring what file is specified. I might actually submit a request.. From apardon at forel.vub.ac.be Fri Jan 14 11:51:32 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Jan 2005 16:51:32 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <1CSFd.30772$Qv5.2842746@phobos.telenet-ops.be> Message-ID: Op 2005-01-14, Roel Schroeven schreef : > Antoon Pardon wrote: >> IMO we have a: dogs are mamals kind of relationship in Python. > > I see what you mean, but I don't think it's true. > >> Every expression can be used where a statement is expected. >> (And this can be worded as: every expression is a statement.) > > Not really. An expression statement is a statement that looks like an > expression, but actually it's more than that: not only does it calculate > the value of the expression, it also prints the value. 1) Only in an interactive environment. 2) That the semantics differ according to where the expression is used doesn't make a difference. That an expression decides which branch of an if statement is executed or what object is pass as an argument in a call are also semantic difference, yet we still have an expression in both cases. > Note that it would be perfectly possible to modify the syntax into > > expression_stmt ::= "exprstmt" expression_list > > so that you would have to write > > exprstmt 6*9 > > instead of just > > 6*9 > > That makes it clearer to see the distinction: 6*9 is an expression, > > exprstmt 6*9 > > is a statement. An expression statement, more precisely. If you change the syntax, of course you will change the strings that will be accepted. I could change the syntax to: if_stmt ::= "if" "ifexpr" expression ... Have I now proved that expressions after an if are not normal expressions? > >> Not every statement can be used where an expression is expected. > > AFAIK *no* statement can be used where an expression is expected. But that was not the implication of what Guido supposedly had said. So that this is not the case doesn't counter what I said. -- Antoon Pardon From skip at pobox.com Thu Jan 13 11:10:38 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 13 Jan 2005 10:10:38 -0600 Subject: from __future__ import decorators In-Reply-To: References: Message-ID: <16870.40318.287644.824824@montanaro.dyndns.org> Jacek> Crazy idea ... would it be possible to shadow 2.3's parser with Jacek> one stolen from 2.4 ? If you're willing to go to that much trouble, why not just upgrade to 2.4? Skip From luke at tatooine.planet Tue Jan 11 14:24:06 2005 From: luke at tatooine.planet (Luke Skywalker) Date: Tue, 11 Jan 2005 20:24:06 +0100 Subject: Windows GUIs from Python References: Message-ID: On Tue, 11 Jan 2005 12:55:42 -0600, Doug Holton wrote: >You might also be interested in PyGUI although it doesn't have a native >Windows implementation yet: >http://nz.cosc.canterbury.ac.nz/~greg/python_gui/ Generally speaking, appart from MFC-style programming with Python32, what are the non-alpha alternatives to write purely Windows apps in Python today, ie. without the weight of extra bagage like wxWidgets? I'm not looking at fancy options, since the apps I write would be fine with just the core Windows widgets along with a few add-ons like a grid and the extended Win95 widgets. Thx Luke. From http Fri Jan 21 01:18:36 2005 From: http (Paul Rubin) Date: 20 Jan 2005 22:18:36 -0800 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> Message-ID: <7x651rwbib.fsf@ruckus.brouhaha.com> Steve Holden writes: > But how, in Lisp, would you transliterate the Python list [1, 2, 3, 4]? With a vector. > Clearly the Python list *is* different, and the tradeoff was to > obtain speed of random access, presumably (I wasn't taking an interest > in Python in its early days) anticipating that non-recursive > algorithms would be the norm. Python lists and Lisp vectors are generally used in about the same way. Sometimes in Lisp people use lists of conses in ways where Python would use its vector-like lists. You can still use recursive algorithms on vectors though you would normally pass extra index info to avoid copying the vectors all the time. > > beginning what the final destination is going to be. So once we can > > see where it's going, why not proceed to the finish line immediately > > instead of bothering with the intermediate steps? > > Perhaps because we don't all have your psychic powers? You snipped out the examples I gave, like [x*x for x in range(5)] leaving unnecessary residue in the name space. Was it not obvious from the beginning that that was a kludge? If it was obviously a kludge, was it not obvious that there would be reason to want to fix it someday? I'm saying that if some new feature is going to need a fix later, it's better to fix it before releasing it in the first place. From michele.simionato at gmail.com Tue Jan 4 08:43:32 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 4 Jan 2005 05:43:32 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) In-Reply-To: References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> Message-ID: <1104846212.355098.186400@c13g2000cwb.googlegroups.com> Holger: > FWIW, i added the recipe back to the online cookbook. It's not perfectly > formatted but still useful, i hope. > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361742 Uhm... on my system I get: >>> german_ae = unicode('\xc3\xa4', 'utf8') >>> print german_ae # dunno if it will appear right on Google groups ? >>> german_ae.decode('latin1') Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 0: ordinal not in range(128) ?? What's wrong? Michele Simionato From erikbethke at gmail.com Wed Jan 19 19:35:23 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 19 Jan 2005 16:35:23 -0800 Subject: ElementTree cannot parse UTF-8 Unicode? References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> Message-ID: <1106181323.553028.290370@z14g2000cwz.googlegroups.com> Hello Fredrik, 1) The exact error is in line 1160 of self._parser.Parse(data, 0 ): xml.parsers.expat.ExpatError: not well-formed (invalid token): line 3, column 16 2) You are right in that the print of the file read works just fine. 3) You are also right in that the digitally encoded unicode also works fine. However, this solution has two new problems: 1) The xml file is now not human readable 2) After ElementTree gets done parsing it, I am feeding the text to a wx.TextCtrl via .SetValue() but that is now giving me an error message of being unable to convert that style of string So it seems to me, that ElementTree is just not expecting to run into the Korean characters for it is at column 16 that these begin. Am I formatting the XML properly? Thank you, -Erik From bob_smith_17280 at hotmail.com Sat Jan 8 12:35:03 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Sat, 08 Jan 2005 12:35:03 -0500 Subject: windows mem leak Message-ID: Does the Win32 port of Python have a memory leak? I have some code that runs flawlessly on Linux, but bombs after a few hours on Windows. It's threaded and uses a lot of memory. Thanks! From http Wed Jan 5 13:26:38 2005 From: http (Paul Rubin) Date: 05 Jan 2005 10:26:38 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> Message-ID: <7x3bxfenq9.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > Okay, then start doing the work necessary to incorporate that stuff into the > core. Get Fredrik to say "okay" to including his Tkinter docs, then do what > it takes to incorporate it. The fact that Fredrik can check those docs in > himself but hasn't after several years suggests that he prefers the status > quo for one or more reasons. I thought that we had been through this already, and permission from Frederik was not forthcoming. Either he has his own plans for those docs, or he has some obligation to someone else to not release them. The Tkinter reference at http://infohost.nmt.edu/tcc/help/pubs/lang.html is actually the best doc I've seen on tkinter so far, but it's only available in ps/pdf format and again, would need permission for inclusion in Python. > There is a reference manual section for SocketServer, btw: > > http://www.python.org/doc/current/lib/module-SocketServer.html > > If that needs examples or corrections or is incomplete, feel free to submit > a patch to either SourceForge or by email to docs at python.org. It's been a while since I really had to wrestle with SocketServer, but that its docs were quite inadequate and I had to study the source code for quite a while to grok how to use it. > Look, I don't have much free time, and what free time I do have I mostly > spend moonlighting on other software (much to my wife's chagrin). I imagine > most of the other people who contribute to the Python distribution are > similarly time-afflicted. Here are a couple ideas: Thanks, but I'm not in the business of promoting Python. I like to think I contribute in some minor ways by submitting bug reports and occasional small patches. I made a conscious decision to not spend time on big patches since Python is non-GPL, and I'd rather spend my limited volunteer time on GPL projects, working on non-GPL projects only if I'm getting paid for it. I offered to make an exception once to contribute some functionality that I felt was important for Python users, but it was declined. What I see going on in clpy all the time though, is people asking whether Python is good for some type of project, and always getting told "yes" no matter what the project is. If the "yes" means that in addition to doing your own project, you find out in the middle that you also have to add features to Python that other languages already support, that makes your project finish behind schedule and whoever told you Python was good for your project really did you a disservice. I'm reacting to that phenomenon in this thread, along with possible others. > 1. Do you have more money than time? Donate a few bucks to the PSF: Nah, I'd rather donate to the FSF if I have the bucks to spare. If I want to fund the development of proprietary Microsoft products, I'm better off sending the money directly to Bill G. Of course I'm happy if PSF gets corporate donations, but that's different than someone like me operating as a free software activist. > 2. Do you have more time than money? Write a proposal to the PSF to > implement/improve/polish off some aspect of the distribution: Huh? Do you mean like a funding proposal, where PSF would use some of those donations to hire me to develop something? I guess I'd consider that in principle, but I'm probably not PSF's favorite person right now, and unlikely to get hired. And anyway, I have other commitments right now and couldn't take on anything like that. > Where did I say to go write a browser or a native-code Python compiler? If > that's your bag you can try resurrecting something Grail-like (browser) or > contribute time top PyPy or Psyco. When I said "write", I literally meant > write, as in English text. I don't experience much difference between writing text and writing code. If I say the docs are missing something and you tell me to fix them, that's not much different than telling me to go write missing code. Re browsers and compilers: I think a Python browser depends on a good GUI toolkit and right now Python only has Tkinter. (There are toolkits like wxpython but Python doesn't "have" them; they exist separately). I think the PyPy group is doing real well with compilers, or at least knows what its doing. I want to wait til PyPy is actually deployed before I pay too much attention to Python compilation, since I think supporting good compilation should actually drive the Python 3000 language design, and PyPy will make it much easier to experiment with new or changing language features. > Paul> Having to piece together info from a dozen obscure and > Paul> inconsistent PEP's and stuff in the CVS tree and source comments > Paul> is not what most people think of as "documentation". > > I was suggesting that maybe you might like to take the pieces and > make them something coherent. If it was trivial it would have > probably been done by now. I just avoid using those features. If they're not documented they probably don't work that well either. > I rather like reST (much of www.python.org is being reimplemented in reST), I don't know what that is. > Look here: > > http://www.amk.ca/diary/archives/003336.html > > As Andrew indicated, it's a "half-hour hack", but it might give someone > something to think about. That's pretty cute and python.org should link to it. From philippe at philippecmartin.com Mon Jan 31 18:38:17 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Mon, 31 Jan 2005 23:38:17 GMT Subject: serializing data structures References: <41FEBD21.5030306@v.loewis.de> Message-ID: Thanks a lot. Regards, Philippe On Tue, 01 Feb 2005 00:20:01 +0100, Martin v. L?wis wrote: > Philippe C. Martin wrote: >> I once wrote something in C to do that, but since python usually has a >> solution for me .... > > If you use arbitrary data structures, you could use pickle or xmlrpclib > to marshal the data. If you know the data is restricted to a few > well-known data types, you could use XDR (Demo/rpc/xdr.py) or CORBA > (e.g. through fnorb.sf.net) to come up with a wire format. > > Otherwise, if you want to define your own proprietary data format, > you can probably use the struct module to generate messages according > to this format. > > However, in any case, you need to define the wire format. Once you made > a choice, Python can help implement it - but Python cannot chose a wire > format for you (although pickle comes really close, as does Dopy - > http://www.mindhog.net/~mmuller/projects/dopy/) > > Regards, > Martin From http Thu Jan 6 21:46:00 2005 From: http (Paul Rubin) Date: 06 Jan 2005 18:46:00 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> Message-ID: <7xsm5et0rb.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > Would it be possible, at least for Windows, to write a Python script > implementing a 'virtual distribution'? IE, download Python, install it, > download next package, install it, etc. -- prefereably table driven? I just don't understand why you'd want to do that, instead of putting all the files in the distro in the first place. From ncoghlan at iinet.net.au Sat Jan 22 01:22:33 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 22 Jan 2005 16:22:33 +1000 Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) In-Reply-To: References: Message-ID: <41F1F129.6000308@iinet.net.au> Steven Bethard wrote: > I wrote: > > If you really want locals that don't contribute to arguments, I'd be > > much happier with something like a decorator, e.g.[1]: > > > > @with_consts(i=1, deftime=time.ctime()) > > def foo(x, y=123, *args, **kw): > > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime > > > > Then you don't have to mix parameter declarations with locals > > definitions. > > > > Steve > > > > [1] I have no idea how implementable such a decorator would be. I'd > > just like to see function constants declared separate from arguments > > since they mean such different things. > > I played around with this, and I think it's basically implementable: Raymond's constant binding decorator is probably a good model for how to do it: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ncoghlan at iinet.net.au Wed Jan 5 08:08:01 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 05 Jan 2005 23:08:01 +1000 Subject: python 3000 and removal of builtin callable In-Reply-To: References: <33v6l6F40l7hqU1@individual.net> Message-ID: <41DBE6B1.8000709@iinet.net.au> Nicolas Fleury wrote: > Mirko Zeibig wrote: > >> This is not an option for e.g. IDEs as some functions might actually >> do something when called ;-) and I like `callable` for introspection. >> >> Other ways would be to check for the `__call__` attribute or use >> several methods of the `inspect`-Module, both of which are not better >> than `callable` IMHO. > > > I totally agree with you. The callable function could be moved to a > module and be built-in, but it cannot really be removed. Calling a > callable and know if an object is a callable without calling it is > definitely not the same thing. For many of the builtins to be "removed" in Py3k, I believe the actual intent is to move them to a module (e.g. sys), with the removal being "remove from the builtins", not "remove from Python". Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jeff at ccvcorp.com Mon Jan 3 14:35:56 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 03 Jan 2005 11:35:56 -0800 Subject: Speed ain't bad In-Reply-To: <41d6a39b$0$33656$edfadb0f@dread16.news.tele.dk> References: <0189t05r3226bkp5e1vtmp0gd6odcsf2qp@4ax.com> <41d6a39b$0$33656$edfadb0f@dread16.news.tele.dk> Message-ID: <10tj7c9m9sclabd@corp.supernews.com> Anders J. Munch wrote: > Another way is the strategy of "it's easier to ask forgiveness than to > ask permission". > If you replace: > if(not os.path.isdir(zfdir)): > os.makedirs(zfdir) > with: > try: > os.makedirs(zfdir) > except EnvironmentError: > pass > > then not only will your script become a micron more robust, but > assuming zfdir typically does not exist, you will have saved the call > to os.path.isdir. ... at the cost of an exception frame setup and an incomplete call to os.makedirs(). It's an open question whether the exception setup and recovery take less time than the call to isdir(), though I'd expect probably not. The exception route definitely makes more sense if the makedirs() call is likely to succeed; if it's likely to fail, then things are murkier. Since isdir() *is* a disk i/o operation, then in this case the exception route is probably preferable anyhow. In either case, one must touch the disk; in the exception case, there will only ever be one disk access (which either succeeds or fails), while in the other case, there may be two disk accesses. However, if it wasn't for the extra disk i/o operation, then the 'if ...' might be slightly faster, even though the exception-based route is more Pythonic. Jeff Shannon Technician/Programmer Credit International From mike at lookdirect.com.au Sun Jan 30 18:12:06 2005 From: mike at lookdirect.com.au (mike) Date: 30 Jan 2005 15:12:06 -0800 Subject: Microsoft Visual C++ and pyton Message-ID: <1107126726.533325.104300@z14g2000cwz.googlegroups.com> Hi, I am new with python. Is it possible to have an MFC application and develop some module using python? what are the steps in doing this? can anybody give me a url or some documentation for this.. thanks.. mike From peter at monicol.co.uk Tue Jan 11 07:19:35 2005 From: peter at monicol.co.uk (Peter Mott) Date: Tue, 11 Jan 2005 12:19:35 -0000 Subject: Uploading files References: Message-ID: <41e3c4d1$0$23052$bed64819@news.gradwell.net> Thanks for this. Peter "Robert Brewer" wrote in message news:mailman.466.1105385969.22381.python-list at python.org... Peter Mott wrote: > If you upload a file using the cgi module is there any > way to discover the file name that the user submitted > as well as the file data? I've googled till I squint > but I can't find anything. Working example (for ASP, which uses BinaryRead to get the request stream): contentLength = int(env['CONTENT_LENGTH']) content, size = request.BinaryRead(contentLength) content = StringIO.StringIO(content) form = cgi.FieldStorage(content, None, "", env, True) content.close() for key in form: value = form[key] try: filename = value.filename except AttributeError: filename = None if filename: # Store filename, filedata as a tuple. self.requestParams[key] = (filename, value.value) else: for subValue in form.getlist(key): self.requestParams[key] = subValue Robert Brewer MIS Amor Ministries fumanchu at amor.org From esj at harvee.org Tue Jan 18 20:24:19 2005 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 18 Jan 2005 20:24:19 -0500 Subject: simultaneous multiple requests to very simple database In-Reply-To: References: Message-ID: <41EDB6C3.6090607@harvee.org> Thomas Bartkus wrote: > When you write that "super dictionary", be sure to post code! > I could use one of those myself. hmmm it looks like you have just flung down the gauntlet of "put up or quityerwhinging". I need to get the crude implementation done first but I think I can do it if I can find a good XMLRPC multithreading framework. ---eric From craig at postnewspapers.com.au Wed Jan 12 11:52:40 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Thu, 13 Jan 2005 00:52:40 +0800 Subject: Python.org, Website of Satan In-Reply-To: <20050112155821.GA12428@mylene.ghaering.de> References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> <20050112155821.GA12428@mylene.ghaering.de> Message-ID: <1105548760.26139.0.camel@bucket.localnet> On Wed, 2005-01-12 at 16:58 +0100, Gerhard Haering wrote: > On Wed, Jan 12, 2005 at 10:15:34AM -0500, Jane wrote: > > [...] Some people have too much time on their hands... > > OMG, PyPy is full of evil, too!!!1 > > print sum([ord(x) for x in "PyPy!!!!!!!!"]) > > or, if you haven't upgraded to 2.4, yet: That'll work fine in Python 2.3. I think you meant: print sum(ord(x) for x in "PyPy!!!!!!!!") which is a different matter entirely (well, regarding compatibility anyway). -- Craig Ringer From reinhold-birkenfeld-nospam at wolke7.net Thu Jan 13 13:17:34 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 13 Jan 2005 19:17:34 +0100 Subject: Free python server. In-Reply-To: <1105632112.104412.183870@f14g2000cwb.googlegroups.com> References: <1105631360.938494.286750@c13g2000cwb.googlegroups.com> <1105632112.104412.183870@f14g2000cwb.googlegroups.com> Message-ID: <34ns9uF4bpbumU1@individual.net> Kartic wrote: > And yes, they have python installed... Python 2.1! Reinhold From michael.bierenfeld at web.de Thu Jan 13 11:08:12 2005 From: michael.bierenfeld at web.de (michael) Date: 13 Jan 2005 08:08:12 -0800 Subject: dynamically inserting function into an object Message-ID: Hi, below is a snipplet that could be seen as a part of a spreadsheet with getter and setter properties and a way how to dynamically insert function to be used when setting the value of a "cell" instance import new import inspect class Cell (object): def __init__ (self, initialvalue = 0): self._func = None self.__value = initialvalue def setvalue (self, newvalue): if self._func: self.__value = self._recalculate (newvalue) else: self.__value = newvalue def getvalue (self): return self.__value def _recalculate (self, value): ret_value = self._func (value) return ret_value def delvalue (self): del self.__value value = property(getvalue, setvalue, delvalue, "I'm the 'value' property.") def curry(self, func, *args): self._func = new.function(func.func_code, func.func_globals, argdefs=args) func = property(curry, "I'm the 'func' property.") def func (value, firstcell, secondcell): return value + firstcell.value + secondcell.value cell0 = Cell (10) cell1 = Cell (20) curriedcell = Cell (100) print "uncurried initial %d " % (curriedcell.value) curriedcell.value = 60 print "uncurried set %d " % (curriedcell.value) curriedcell.curry (func, cell0, cell1) curriedcell.value = 62 print "curried set %d " % (curriedcell.value) Is there a better way to do this or am I totally on the wrong way ? Regards Michael From merman at o2online.de Fri Jan 28 18:53:42 2005 From: merman at o2online.de (T. Kaufmann) Date: Sat, 29 Jan 2005 00:53:42 +0100 Subject: Mac OS and MySQLdb In-Reply-To: <1106924449.079269.65810@z14g2000cwz.googlegroups.com> References: <41f95b17$0$3331$9b622d9e@news.freenet.de> <1106924449.079269.65810@z14g2000cwz.googlegroups.com> Message-ID: <41facd6c$0$11653$9b622d9e@news.freenet.de> Andy Dustman wrote: > The source is for all platforms. Use the Source, Luke. If 1.1.9 does > not compile on Mac OS X, file a bug. Thanks a lot;-). From dbickett at gmail.com Sat Jan 22 15:41:10 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sat, 22 Jan 2005 15:41:10 -0500 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fpq0F4mh1ffU1@individual.net> Message-ID: <1d6cdae305012212417f247f48@mail.gmail.com> Doug Holton wrote: > What do you expect? YAML is designed for humans to use, XML is not. > YAML also hasn't had the backing and huge community behind it like XML. > XML sucks for people to have to write in, but is straightforward to > parse. The consequence is hordes of invalid XML files, leading to > necessary hacks like the mark pilgrim's universal rss parser. YAML > flips the problem around, making it harder perhaps to implement a > universal parser, but better for the end-user who has to actually use > it. More people need to work on improving the YAML spec and > implementing better YAML parsers. We've got too many XML parsers as it is. However, one of the main reasons that XML is so successful is because it's roots are shared by (or, perhaps, in) a markup language that a vast majority of the Internet community knows: HTML. In it's most basic form, I don't care what anyone says, XML is VERY straight forward. Throughout the entire concept of XML (again, in its most basic form) the idea of opening and closing tags (with the exception of the standalone tags, however still very simple) is constant, for all different data types. In my (brief) experience with YAML, it seemed like there were several different ways of doing things, and I saw this as one of it's failures (since we're all comparing it to XML). However I maintain, in spite of all of that, that it can easily boil down to the fact that, for someone who knows the most minuscule amount of HTML (a very easy thing to do, not to mention most people have a tiny bit of experience to boot), the transition to XML is painless. YAML, however, is a brand new format with brand new semantics. As for the human read-and-write-ability, I don't know about you, but I have no trouble whatsoever reading and writing XML. But alas, I don't need to. Long live elementtree (once again) :-) Daniel Bickett From aleaxit at yahoo.com Thu Jan 13 13:17:18 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 13 Jan 2005 19:17:18 +0100 Subject: reference or pointer to some object? References: <10ubcp136drsu97@corp.supernews.com> Message-ID: <1gqcd8e.ehwqcw1n0y6wxN%aleaxit@yahoo.com> Jeff Shannon wrote: > Because Python uses a fundamentally different concept for variable > names than C/C++/Java (and most other static languages). In those > languages, variables can be passed by value or by reference; neither > term really applies in Python. (Or, if you prefer, Python always Java's model is quite similar to Python's, except that Java makes some exception for very low-level types such as int or float. But there is no "passing by reference" in Java, anyway: the semantics of assignment and argument passing (same thing) are VERY close in Java and Python. I hope this is enough to show that static or dynamic is quite a different issue -- Java's more or less statically typed, Python dynamically, but their model of variables is VERY similar anyway. Alex From beliavsky at aol.com Sat Jan 29 23:26:09 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 29 Jan 2005 20:26:09 -0800 Subject: Coding style article with interesting section on white space References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> Message-ID: <1107059169.510996.262480@z14g2000cwz.googlegroups.com> Michael Tobis wrote: > (unwisely taking the bait...) > > If you like your language to look like this > http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html > then more power to you. Thanks for pointing out that interesting article on Fortran 90 bugs. How long would a comparable C++ list be? Even Python has gotchas, for example the difference between deep and shallow copies. > I prefer my languages to be portable, terse and expressive. Fortran programmers are generally happy with the portability of the language. A difficulty with Python portability and maintainability is that some needed functionality is not in the core language but in C extensions. For scientific computation, consider the case of Numeric and Numarray. I don't think Numeric binaries are available for Python 2.4, and Numarray is not perfect substitute, being considerably slower for small arrays, having slightly different functionality in some areas, and as recently as Nov 2004 (c.l.py thread "numarray memory leak") leaking memory when multiplying matrices. The recent "Pystone Benchmark" message says that Python is only 75% as fast on Linux as on Windows. Fortran programs do not suffer this performance hit and are in this respect more portable. In theory, as has been mentioned, one could use a faster compiler to compile CPython on Linux, but AFAIK this has not yet been done. > There is no fundamental reason why a language with expressive power > much like Python's cannot have run-time performance comparable to > Fortran's. Unfortunately, Fortran's dominance of the relatively small > scientific computation universe has prevented such a language from > emerging. Nobody is stopping Python developers from working on projects like Psyco. > The solutions which interest me in the short run are 1) > writing a code generation layer from Python to a compiled language > (possibly F77 though I will try to get away with C) and 2) wrapping > legacy Fortran in Python. The latter is quite regularly subverted by > non-standard binary data structures across compilers and a pretty > profound disinterest in interoperability by the people designing the > Fortran standard that makes their interest look more like turf > protection and less like an interest in the progress of science. So uninterested in interoperability is the Fortran standards committee that they added interoperability with C in Fortran 2003 standard. > Python fundamentally respects the programmer. What does that mean? > Fortran started from a point of respecting only the machine, (which is > why Fortrans up to F77, having a well-defined objective, were > reasonable) I have found that Fortran 90/95 is better at the objective of FORmula TRANslation for array expressions (mostly what I need) than previous versions. > but now it is a motley collection of half-baked and > confusing compromises between runtime performance, backward > compatibility, and awkward efforts at keeping up with trends in > computer languages. This is true to some extent of any language "of a certain age", including C++. > For more see http://www.fortranstatement.com And the rebuttal at http://www.fortranstatement.com/Site/responses.html . From bokr at oz.net Wed Jan 5 14:29:38 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 05 Jan 2005 19:29:38 GMT Subject: type declarations, interfaces, etc as program information composition Message-ID: <41dc2b84.70478372@news.oz.net> I just read Guido's http://www.artima.com/weblogs/viewpost.jsp?thread=86641 "Adding Optional Static Typing to Python -- Part II" and I it struck me that if you step back to a more distant perspective, you can see specific source syntax proposals as a special case of composing program information, and I wondered if the coupling inherent in editing a particular source to add information is always best. Certainly it makes for a handy single-file package of info, unlike C source and header files for example. Not to mention make files and the plethora of information they can direct the composition of. But, e.g., what is the best way to tell python that I intend to use its "sum" builtin to add a list of integers, so that it can figure out that it will be safe to generate machine code using 32-bit integers? Should I have to code a new version with static type declarations? What about stuff I've alrady written, that I'm pretty sure would work fine with floating point, but which has no type information? Should I have to edit that code, that may be in CVS, in order to tell python to generate more specialized code? Or would it be useful to have a specialization tool that I can tell what to do with what existing sources. IOW a pythonic make of some sort. What if specialization info for mylib/myutil.py were in currproj/myutil.pyspec and a pymake or pycc tool knew how to do the right thing? A .pyc file would contain the combined information and specialized code, and a smart inspection tool could show the combined source information in context by going to the relevant sources of myutil.py and myutil.pyspec etc. So the argument that all needs to be in the same file for easy reading is not absolute. Of course, it would be good if the combined presentation format were also a legal input format, for those who want a single specialization in a single file. A specialization tool could well raise exceptions saying a particular source module def foo... can't be specialized as you want, because e.g., it returns both strings and ints, and your interface info says foo(int, int) -> int. Anyway, I consider the Lego-like composability of python programming elements to be one of python's greatest attractions. I hope Guido can figure some way to let us snap in type info without filing existing knobs into new shapes. Regards, Bengt Richter From ptmcg at austin.rr._bogus_.com Mon Jan 31 13:40:34 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 31 Jan 2005 18:40:34 GMT Subject: ANNOUNCE: KirbyBase 1.7 References: <7xy8ea1qgt.fsf@ruckus.brouhaha.com> Message-ID: "Jamey Cribbs" wrote in message news:dMdLd.67932$re1.17016 at fe2.columbus.rr.com... > Paul Rubin wrote: > > That's cute, especially the part about using Python expressions > > instead of SQL to express queries. I don't see anything in the info > > page about what happens when you have multiple clients updating the db > > concurrently. Do you make any attempt to handle that? > > Yep. There are two server scripts included with the distribution. One > (kbsimpleserver.py) does serial, blocking requests, so there are no > concurrent-access issues. The second server script > (kbthreadedserver.py) is threaded and non-blocking. I have code in the > script that manages read and write locks for each table. I'm no rocket > scientist, but I have been using kbthreadedserver.py at work for several > months with no issues so far, so I am beginning to trust the code. :) > > Jamey Before you get too confident, you might try your code on a multiprocessor machine, under some heavy stress test (or ask one of your collaborators if you don't have access to such a thing). Threaded code that runs on uniprocessors can do very different/unexpected/unwanted things on multiprocessors. -- Paul From bokr at oz.net Fri Jan 7 17:29:44 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 07 Jan 2005 22:29:44 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> Message-ID: <41df0cae.259192429@news.oz.net> On Fri, 07 Jan 2005 16:34:48 -0000, mike at hobbshouse.org (Michael Hobbs) wrote: >David Brown wrote: >> Hello. I recently came across a free operating system called Unununium (or >> something like that) and it was developed in Python and Assembly. >> >> Now, I have been looking for a way to make an operating system for a long >> long time and the only possibilities I could find were C++ and assembly. > >The problem when using Python instead of C for OS development is that >C was *specifically designed* to create an OS, while Python was designed >for completely different purposes. If you want to write an OS, it would >be wise to use a language that is suited for that purpose. If you >dislike C so much and prefer Python so much more, your first step should >be to design a Python dialect that is more appropriate for writing OS's. > >(I know that you mentioned C++, not C, but I decided to setup C as a >straw-man to make my argument.) I'd say look at Ada for HLL inspiration, if you want to deal with OS level stuff in Python. Regards, Bengt Richter From ialbert at mailblocks.com Thu Jan 20 12:34:33 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 20 Jan 2005 12:34:33 -0500 Subject: What YAML engine do you use? In-Reply-To: <35a6tpF4gmat2U1@individual.net> References: <35a6tpF4gmat2U1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > You will be amazed, and never think of XML again. XML with elementtree is what makes me never have think about XML again. Istvan. From stephen.thorne at gmail.com Wed Jan 19 02:04:45 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Wed, 19 Jan 2005 17:04:45 +1000 Subject: generator expressions: performance anomaly? In-Reply-To: <_NCdnVV_I9UrZHDcRVn-og@comcast.com> References: <377Hd.77904$Jk5.30235@lakeread01> <41ED1C0F.4030800@holdenweb.com> <41eda453.1215517842@news.oz.net> <41edcc68.1225778626@news.oz.net> <_NCdnVV_I9UrZHDcRVn-og@comcast.com> Message-ID: <3e8ca5c8050118230461949030@mail.gmail.com> On Tue, 18 Jan 2005 23:09:57 -0700, Steven Bethard wrote: > @with_consts(i=1, deftime=time.ctime()) > def foo(x, y=123, *args, **kw): > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime > > Then you don't have to mix parameter declarations with locals definitions. > > [1] I have no idea how implementable such a decorator would be. I'd > just like to see function constants declared separate from arguments > since they mean such different things. (untested) def with_constant(**constants_kwargs): def decorator(f) def closure(*arg, **kwargs): kwargs.update(constants_kwargs) return f(*arg, **kwargs) return closure return decorator Regards, Stephen Thorne From jfouhy at paradise.net.nz Tue Jan 4 22:33:34 2005 From: jfouhy at paradise.net.nz (John Fouhy) Date: 4 Jan 2005 19:33:34 -0800 Subject: Tkinter, iconbitmap and Windows XP Message-ID: Hi all, I have been attempting to change the title bar icon of my Tkinter applications in Windows XP. Chasing round in google, I discovered: - This is a common difficulty. - There aren't any good answers. Eventually, I stumbled across a link to this: http://www.tcl.tk/man/tcl8.4/TkCmd/wm.htm#M18 Here is the significant information: "On the Windows operating system, an additional flag is supported: wm iconbitmap window ?-default? ?image?. If the -default flag is given, the icon is applied to all toplevel windows (existing and future) to which no other specific icon has yet been applied. In addition to bitmap image types, a full path specification to any file which contains a valid Windows icon is also accepted (usually .ico or .icr files), or any file for which the shell has assigned an icon. Tcl will first test if the file contains an icon, then if it has an assigned icon, and finally, if that fails, test for a bitmap." The Tkinter source (Python 2.3.4) includes this: def wm_iconbitmap(self, bitmap=None): """Set bitmap for the iconified widget to BITMAP. Return the bitmap if None is given.""" return self.tk.call('wm', 'iconbitmap', self._w, bitmap) I modified this, to look like: def wm_iconbitmap(self, bitmap=None, default=None): """Set bitmap for the iconified widget to BITMAP. Return the bitmap if None is given.""" if default: return self.tk.call('wm', 'iconbitmap', self._w, '-default', default) else: return self.tk.call('wm', 'iconbitmap', self._w, bitmap) The following code now does exactly what you would like it to: ##### from Tkinter import * tk = Tk() tk.iconbitmap(default='foo.ico') Label(tk, text='This window now has a custom icon.').pack() t = Toplevel(tk) Label(t, text='This one has the same custom icon.').pack() tk.mainloop() ##### I hope this is helpful to people... (now to see if I can figure out how to submit a patch in Sourceforge) -- John. From pedro.werneck at terra.com.br Fri Jan 21 09:31:02 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Fri, 21 Jan 2005 12:31:02 -0200 Subject: TypeError error on tkinter.createfilehandler dummy example In-Reply-To: <41F0CAF8.3080806@corp.ya.com> References: <41F0CAF8.3080806@corp.ya.com> Message-ID: <20050121123102.6e7dd249.pedro.werneck@terra.com.br> Hi, The createfilehandler is not supported on Windows since Tcl/TK 8.0. tkinter.createfilehandler is None, so you get the NoneType is not callable error. I wrote a simple module with a mix-in class to solve this problem. I had a lote of code using it on linux and needed to run it on Windows. I can send it to you in pvt, if you want. Pedro Werneck On Fri, 21 Jan 2005 10:27:20 +0100 David wrote: > Hi, > > I'm getting the following error: > > > Traceback (most recent call last): > File "..\kk.py", line 37, in ? > tkinter.createfilehandler(filex, tkinter.READABLE, _dispatch) > TypeError: 'NoneType' object is not callable > > > when executing this code on my Windows box: > > > from Tkinter import * > > def _dispatch(self, *args): > print "voila" > > filex = open('d:\\zz.txt', 'r') > tkinter.createfilehandler(filex, tkinter.READABLE, _dispatch) > > > Any ideas? What am I missing? I've been searching for something like > this with no luck. I cannot imagine a simpler code for testing > tkinter.createfilehandler functionality but it does not work :( > > > TIA > > -- > David Santiago > > From fredrik at pythonware.com Sat Jan 22 02:37:41 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 08:37:41 +0100 Subject: default value in a list References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: Paul McGuire wrote: > I asked a very similar question a few weeks ago, and from the various > suggestions, I came up with this: > > expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen] I wouldn't trust whoever suggested that. if you want a function, use a function: def expand(seq, default, minlen): return (seq + [default]*minlen)[:minlen] From tadmc at augustmail.com Sun Jan 30 08:09:30 2005 From: tadmc at augustmail.com (Tad McClellan) Date: Sun, 30 Jan 2005 07:09:30 -0600 Subject: [perl-python] sending email References: <1107041765.890014.112530@c13g2000cwb.googlegroups.com> Message-ID: J?rgen Exner wrote: > Xah Lee wrote: > [...] >> Here's how the situation stands as of 2001 March: > ^^^^^^^^^^ > > Well, at least now we know why Mr. Lee is a little bit behind .... Mr. Lee is a *big* behind! -- Tad McClellan SGML consulting tadmc at augustmail.com Perl programming Fort Worth, Texas From cdieterich at geosci.uchicago.edu Wed Jan 26 17:33:48 2005 From: cdieterich at geosci.uchicago.edu (Christian Dieterich) Date: Wed, 26 Jan 2005 16:33:48 -0600 Subject: inherit without calling parent class constructor? In-Reply-To: <8IadnVLUPfL7bmrcRVn-tg@comcast.com> Message-ID: <58D77AEA-6FEA-11D9-8B47-000A9582377C@geosci.uchicago.edu> On D? C?adaoin, Ean 26, 2005, at 13:45 America/Chicago, Steven Bethard wrote: > Note that: > @deco > def func(...): > ... > is basically just syntactic sugar for: > def func(...): > ... > func = deco(func) Oh, I learned something new today :-) Nice thing to know, these descriptors. > Note that b.size and d.size are only calculated once each, and if > d.size is never accessed, you'll never incur the costs of calculating > it. That's exactly what I need. It works fine for Python 2.2 and 2.3. So, I'll try to implement that into my package. Thanks a bunch for your help, Christian From bokr at oz.net Tue Jan 18 19:55:24 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 19 Jan 2005 00:55:24 GMT Subject: generator expressions: performance anomaly? References: <354esdF4fouh0U1@individual.net> <354kntF4g4crnU1@individual.net> Message-ID: <41eda8bf.1216649950@news.oz.net> On Tue, 18 Jan 2005 15:29:06 +0100, "Diez B. Roggisch" wrote: >> I don't see how generating byte code for a = 9; when seeing the >> expression a = 3 + 6, would be a problem for non-functional >> languages. > >Most probably. But I don't see much code of that type that it would be worth >optimizing for, either. The cost for re-evaluation such an expression >doesn't really account for any performance problems you hit - in python, of >course. >See this: > >deets at kumquat:/usr/lib/python2.3$ python timeit.py -c "[4*5 for i in >xrange(10000)]" >100 loops, best of 3: 5.5e+03 usec per loop >deets at kumquat:/usr/lib/python2.3$ python timeit.py -c "[20 for i in >xrange(10000)]" >100 loops, best of 3: 4.3e+03 usec per loop > > >Now of course the longer the expressions get, the more time it costs - but >how many long arithmetical expression of constant evaluation value do you >have? > >> >> I agree that things like [time.time() for i in xrange(10)] shouldn't >> be pregenerated and that the problem is more complicated as I thought. >> >> But during compilation the compilor could do an anlysis of the code >> do determine whether there are side effects or not. If the compilor >> then would store a code in the byte code for functions that are >> guaranteed side-effect free and only pregenerated objects generated >> by expressions with no side-effect, some common subexpression >> elimination could be done even in a non-functional language. > >This analysis would only be possible for the most primitive of examples, >the reason beeing that due to the dynamic features syntactically equivalent >expressions can have totally different semantics. So its not really worth >the effort. IOM that doesn't mean there might not be an alternative interesting angle. E.g., what if we had a yield_constant (instant bf here ;-) as well as a yield. IOW an explicit promise that the generator would always yield the same thing for the same input args. This could potentially allow tuple(x for x in foo(1234)) to be pre-calculated, or marked for sticky internal caching or such, if repeat use benefit could not be determined. I guess we can write memoizing decorators now, so how would you e.g., spell memoizing a generator expression? No end to probably impractical ideas ;-) IMO it's more a matter of RO[D]I (return on [development] investment) and restraints on bloat than whether optimizations and other ideas are feasible. I think practicality vs purity drives actual implementation, but purity issues drive a lot of interesting, if not too practical, discussions. Of course, if someone has the energy to become champions of their ideas, and actually implement them for testing and evaluation, more power to them. I don't think we should beat up on Antoon for his interest in exploring theoretical possibilities. Sometimes a spark may fly off and provide some useful illumination. OTOH, interesting is in the eye of the beholder ;-) Regards, Bengt Richter From zathras at thwackety.com Fri Jan 7 00:50:33 2005 From: zathras at thwackety.com (Michael Sparks) Date: Fri, 07 Jan 2005 05:50:33 +0000 Subject: Embedding a restricted python interpreter References: Message-ID: <41ddd257$0$29355$ed2e19e4@ptn-nntp-reader04.plus.net> Rolf Magnus wrote: > I would like to embed a python interpreter within a program, but since > that program would be able to automatically download scripts from the > internet, I'd like to run those in a restricted environment, which > basically means that I want to allow only a specific set of modules to be > used by the scripts, so that it wouldn't be possible for them to remove > files from the hard drive, kill processes or do other nasty stuff. > Is there any way to do that with the standard python interpreter? Current advice seems to be essentially "no". I've been pondering adding limited scripting to some personal apps I've written and due to this toyed around with the idea of simple but parser that only used ":" and whitespaces for indicating blocks with the aim of being a generic/"universal"(*) language parser that could be used for many little "languages". (ie no keywords, just "pure" structure) (*) By "universal" I mean something that allows a variety of different styles of syntax to be used, whilst technically still sharing the same underlying syntax. (Since that's a rather bogus statement, that's why it has quotes :) In the end I sat down and wrote such a beast largely as a fun exercise. (It uses PLY and is an SLR grammar) It *doesn't* have any backend so you get to decided how restricted it can be, but, for example, the following code would parse happily: (It's not quite python, but it's close syntactically) class Grammar(object): from Lexer import Tokens as tokens precedence = ( ( "left", "DOT")) def p_error(self,p): print "Syntax error at", p end end This parses as follows: A class function is provided with 3 arguments: * Grammar(object) * A code block * A lexical token "end" (Which could be anything) The code block then contains 3 statements * The first is a function call, to a function called "from" * The second is an assignment statement * The third is a function call to the function "def" (which in turn takes 3 arguments - a signature, a codeblock and a trailing token (the trailing token allows "else" clauses and try/except style blocks) etc However it will also parse happily: EXPORT PROC compare(field::PTR TO person,type=>NIL) OF person: DEF result=FALSE IF type: SELECT type: CASE NAME: result:=compare_name(self.name,field) CASE PHONE: result:=compare_telephone(self.telephone,field) CASE ADDRESS: result:=compare_address(self.address,field) ENDCASES ENDSELECT ELSE: result:=compare_name(self.name,field,ORDER) # if type = NIL, ordering ENDIF ENDPROC result And also programs of the form: shape square: pen down repeat 4: forward 10 rotate 90 end pen up end repeat (360/5): square() rotate 5 end and so on. If you're prepared to write backends to traverse an AST then you might find it useful. (I also wrote the parser as an exercise in trying to generate a parser in a test first manner) If you're curious as to the sorts of languages it could parse the test cases are here: * http://thwackety.com/viewcvs/viewcvs.cgi/Scratch/SWP/progs/ Some rather random examples are: 29, A copy of the parser file at that point in time, but rewritten in a python-esque language parsable by the parser 33, A simple program in a logo type language 34, A simple program based on declarative l-systems for modelling biological growth systems. 35, A simple SML-like language file implementing a stack 37, An implementation of a "Person" object module in an Amiga-E like language. (NB, here "language" means whatever AST a given backend might understand, since they're all technically the same language) http://thwackety.com/viewcvs/viewcvs.cgi/Scratch/SWP/README?rev=1.1 Describes the grammar, etc. (31 explicit rules, or alternatively 13 aggregate rules) If you think it might be useful to you, feel free to do an anonymous checkout: cvs -d :pserver:anonymous at cerenity.org:2401/home/cvs/cvsroot login cvs -d :pserver:anonymous at cerenity.org:2401/home/cvs/cvsroot co Scratch/SWP/ Since there is *no* backend at all at present this would be a bit of work. (I've been tempted to investigate putting a lisp backend on the back, but not found the time to do so. If I did though this would be a brackets free lisp :) You can fine PLY here: http://systems.cs.uchicago.edu/ply/ . Best Regards, Michael. From jfj at freemail.gr Mon Jan 3 15:54:48 2005 From: jfj at freemail.gr (jfj) Date: Mon, 03 Jan 2005 12:54:48 -0800 Subject: Python! Is! Truly! Amazing! In-Reply-To: References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: <41D9B118.3050902@freemail.gr> Ron Garret wrote: > In article <1104657461.868175.252380 at c13g2000cwb.googlegroups.com>, > "Erik Bethke" wrote: > > >>I have NEVER experienced this kind of programming joy. > > > Just wait until you discover Lisp! > > ;-) I've had it with all those lisp posts lately ;-) There were functional and non-functional programming languages (the first being *much* simpler to implement). There is a *reason* people chose C over lisp. It's not that we were all blind and didn't see the amazingness of lisp. Procedural languages are simply better, and I'm not replying to this flamewar. Thank you:) G. From bokr at oz.net Tue Jan 25 07:52:39 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 25 Jan 2005 12:52:39 GMT Subject: is there better 32 clock() timing? References: <41f61372.1768192005@news.oz.net> Message-ID: <41f63d79.1778950866@news.oz.net> On Tue, 25 Jan 2005 11:42:35 +0000, Stephen Kellett wrote: >>>that time.clock() is inaccurate. The problem is that the "time.clock()" >>>statement takes several hundred microseconds to execute. > >The statement is incorrect. clock() itself isn't slow, but it is >accessing a resource, the accuracy of which is no better than 1ms. I believe that is quite wrong as a general statement. It may be right on some benighted system, but not on win32/NT python 2.4. How do you account for getting deltas of 6-7 microseconds in abs(clock()-clock()) ? If the "resource" only had ~1ms granularity, the minimum would be zero, as it is if you call time.time() in a tight loop, since it doesn't tick over often enough. time.clock does tick over fast enough that you can't snag the same reading on two successive clock() calls on a 300mhz P2. > >There are various timers available, documented and undocumented, all of >which end up at 1ms or 1.1ms, give or take. For anything shorter you >need QueryPerformanceCounter() (but that *is* a slow call), or use the Have you timed it, to make that claim? What do you mean by "slow"? >RDTSC instruction which is fast but gives a count of instruction cycles >executed and is thus not totally accurate (multiple execution pipelines, >plus multithreading considerations). Accurate for what. A single clock AFAIK drives RDTSC > >You have to choose the system that works best for you. In many cases >RDTSC works OK. I wrote an extension to access it directly, and was agble to get down to 23 cycles IIRC for a C call pair like above on a 300 mhz P2. 23/300 us I guess, less than 100 ns between the clock reads of two calls. The main problem with a CPU clock based reading is that it's very stable unless there's variable clock rate due to power management. Why am I doing this? ;-) Regards, Bengt Richter From steven.bethard at gmail.com Tue Jan 11 02:35:26 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 11 Jan 2005 00:35:26 -0700 Subject: Handing a number of methods to the same child class In-Reply-To: <6cWdnTY8IPa5hH7cRVn-sg@rcn.net> References: <6cWdnTY8IPa5hH7cRVn-sg@rcn.net> Message-ID: Dave Merrill wrote: > Somewhat silly example: I know you've hedged this by calling it a "silly" example, but I would like to point out that your set_X methods are unnecessary -- since Python allows you to overload attribute access, getters and setters are generally unnecessary. > class Address: > def __init__(): > self.displayed_name = '' > self.adr = '' > self.city = '' > self.state = '' > def set_name(name): > self.displayed_name = name > def set_adr(adr): > self.adr = adr > def set_city(city): > self.city = city > def set_state(state): > self.state = state > > class Phone: > def __init__(): > self.displayed_name = '' > self.number = '' > def set_name(name): > self.displayed_name = name > def set_number(number): > self.number = number > > class Customer: > def __init__(): > self.last_name = '' > self.first_name = '' > self.adr = Adr() > self.phone = Phone() > def set_adr_name(name): > self.adr.set_name(name) > def set_adr_adr(adr): > self.adr.set_adr(adr) > def set_adr_city(city): > self.adr.set_city(city) > def set_adr_state(state): > self.adr.set_state(state) > def set_phone_name(name): > self.phone.set_name(name) > def set_phone_number(number): > self.phone.set_number(number) > > IOW, all the adr methods go to the corresponding method in self.adr, all the > phone methods go to self.phone, theorectically etc for other rich > attributes. > > What I'd really like is to say, "the following list of methods pass all > their arguments through to a method of the same name in self.adr, and the > following methods do the same but to self.phone." Is there some sane way to > express that in python? py> class Address(object): ... def __init__(self, city, state): ... self.city = city ... self.state = state ... py> class Customer(object): ... def __init__(self, name, addr): ... self.name = name ... self.addr = addr ... def __getattr__(self, attr): ... if attr.startswith('adr_'): ... return getattr(self.addr, attr[4:]) ... raise AttributeError(attr) ... py> c = Customer("Steve", Address("Tucson", "AZ")) py> c.adr_city 'Tucson' py> c.adr_state 'AZ' I've used a slightly different example from yours, but hopefully you can see how to apply it in your case. The __getattr__ method is called when an attribute of an object cannot be found in the normal locations (e.g. self.__dict__). For all attributes that begin with "adr_", I delegate the attribute lookup to the self.addr object instead. Steve From pekka.niiranen at wlanmail.com Mon Jan 3 14:41:41 2005 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Mon, 03 Jan 2005 21:41:41 +0200 Subject: HELP: Tkinter idiom needed: SOLUTION In-Reply-To: <41d6b0c9$0$16584$39db0f71@news.song.fi> References: <41d6b0c9$0$16584$39db0f71@news.song.fi> Message-ID: <41d99fae$0$20423$39db0f71@news.song.fi> Hi there, got it. Note the root.distroy()-command. -pekka- ----- CODE STARTS ---- from Tkinter import * from ScrolledText import ScrolledText import tkFont class Message_box: # Graphical message box for printing unicode texts def __init__(self, myParent): self.myContainer1 = Frame(myParent) self.myContainer1.pack(side=TOP, expand=1, fill=BOTH) self.button1 = Button(self.myContainer1) self.button1["text"]= "Close" self.button1.pack(side=BOTTOM) self.button1.bind("", self.button1Click) self.font = tkFont.Font(family="Arial Unicode MS", size=8) self.text = ScrolledText(self.myContainer1, font=self.font,\ state=NORMAL, height=40, width=120, wrap=NONE) self.text.pack(side=TOP, expand=1, fill=BOTH) def button1Click(self, event): self.myContainer1.quit() def write(self,s): self.text.insert(END, s) def enable_write(self): self.text.config(state=NORMAL) def disable_write(self): self.text.config(state=DISABLED) if __name__ == '__main__': # first window root = Tk() print "blah1" root.title(' Message window') root.protocol("WM_DELETE_WINDOW", NONE) widget = Message_box(root) m = "blah2" widget.write("%s\n" % m) widget.disable_write() root.mainloop() root.destroy() print "blah3" # second window root = Tk() root.title(' Message window') root.protocol("WM_DELETE_WINDOW", NONE) widget = Message_box(root) m = "blah4" widget.write("%s\n" % m) widget.disable_write() root.mainloop() root.destroy() print "blah5" ----- CODE ENDS ---- Pekka Niiranen wrote: > Hi there, > > after reading TkInter/thread -recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 > I wondered if it was possible to avoid using threads > for the following problem: > > I have script started from W2K console that normally > prints ascii messages to the screen. However, I have > command line "debug" -flag that might cause printing > of UTF-8 data to the screen. This fails occassionally > due to Console encoding, of course. > > What I need is Tkinter window where some printouts > are directed when script is run in Debug -mode > (Redirection of stdout is out of question). > > While testing, I have got this far already: > > ---script starts---- > > from Tkinter import * > from ScrolledText import ScrolledText > import os, sys, tkFont, codecs > > class Pyg_message_box: > def __init__(self, parent): > self.myParent = parent > self.myContainer1 = Frame(parent) > self.myContainer1.option_add("*font",\ > tkFont.Font(family="Arial Unicode MS", size=8)) > self.myContainer1.pack() > self.text = ScrolledText() > self.text.pack() > self.button1 = Button(self.myContainer1, text="Quit",\ > command=self.button1Click) > self.button1.pack(side=LEFT) > self.button1.bind("", self.button1Click) > > def button1Click(self, event): > self.myContainer1.quit() > > def write(self, s): > self.text.insert(END, s) > > root = Tk() > widget = Pyg_message_box(root) > sys.stdout = widget > a = codecs.open("d:\\test.txt", "r", "utf_16").readlines() > for x in a: > print x > root.mainloop() > > ---script ends---- > > My questions are: > - Can I open Tk -window without enclosing the whole script > between "root=Tk()" and "root.mainloop()"? > - What is the idiom of opening Tk -window only when Debug -flag > is encountered (the script stops running until window is closed)? > > Something like: > > if not my_debug == "ON": > print "message" # prints to console > else: > # 1) open temporary ScrolledText() Tk -window > # 2) Print stuff to window > # 3) Ask user to close window > > I would no like to always open Tkwindows just in case user runs script > with debug -flag on. > > -pekka- From mirnazim at gmail.com Thu Jan 6 08:05:03 2005 From: mirnazim at gmail.com (mirnazim at gmail.com) Date: 6 Jan 2005 05:05:03 -0800 Subject: Nevow Tutorial and sample app Message-ID: <1105016703.493588.308570@z14g2000cwz.googlegroups.com> Hi, Can any one redirect me to a good nevow tutorial and/or a an appliction that is niether too big nor too small and can be help in learning nevow. Nevow tutorial with the distrubution is too simple and it doesnot even skim the surface. Another one http://www.nevow.com/Nevow2004Tutorial.html is good but the does not conform to the current nevow relaese(0.3). e.g. its says from nevow.rend import htmlfile while as htmlfile is actually in loaders module. thanks ---- Mir Nazim From b at b.b Sat Jan 8 03:28:12 2005 From: b at b.b (Roose) Date: Sat, 08 Jan 2005 08:28:12 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> Message-ID: > But I thought Python was an all-purpose language. After all, OS's > have been written in Lisp before too. It is a general purpose APPLICATION language. I am surprised that this hasn't been mentioned on this thread. An OS is NOT an application. It is a completely different kind of program. Do you guys understand the difference between user and kernel mode? Do you know what address spaces and hardware interrupts are? Python is not equipped to handle these things. You would end up doing so much in C extensions that it could barely be called Python. I am not trying to be insulting... but unless someone would like to educate me otherwise, the idea of an OS written in Python is almost ludicrous. As I said, I think you might mean an OS SHELL, which would be a reasonable (although maybe unconventional) thing to write in python. Also I am no threading expert, but I would imagine it would be very hard to write a task scheduler in Python given that it has the whole GIL thing. (As I said that isn't my domain of expertise but I'm sure someone here could expound on that.) From pdemb at illx.org Sun Jan 2 16:39:51 2005 From: pdemb at illx.org (Peter Dembinski) Date: Sun, 02 Jan 2005 22:39:51 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <87hdlza4t4.fsf@hector.domek> Bulba! writes: [...] > The point is obviously "cover your ass" attitude of managers: Managers get paid for taking risk :) From apardon at forel.vub.ac.be Thu Jan 20 03:12:40 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Jan 2005 08:12:40 GMT Subject: Zen of Python References: Message-ID: Op 2005-01-19, Steve Holden schreef : > Peter Hansen wrote: > >> Timothy Fitz wrote: >> >>> While I agree that the Zen of Python is an amazingly concise list of >>> truisms, I do not see any meaning in: >>> >>> Flat is better than nested. >>> > [incrdeibly secret PSU facts blurted out] >> >> And with that out of the way, one is left with "there's a balance >> along the flat/nested dimension which is appropriate to any >> given situation, so nest with moderation and only when necessary". >> > They'd probably been talking to Antoon Pardon :-) Just what I thought: They'll be accusing me of this :-) -- Antoon Pardon From P.Schnizer at nospam.gsi.de Mon Jan 24 03:07:46 2005 From: P.Schnizer at nospam.gsi.de (Pierre Schnizer) Date: 24 Jan 2005 09:07:46 +0100 Subject: pygsl-0.3.1 released Message-ID: <87k6q35jxp.fsf@smtp.gsi.de> pyGSL is a wrapper for the GNU Scientific Library. Get it from http://sourceforge.net/projects/pygsl. Up to now it provides the following modules: Blas, Chebyshev, Combination, Const Diff, Deriv, Eigen, Fit, FFT, Ieee, Integrate Interpolation, Linalg, Math Minimize, Multifit, Multifit_nlin, Multimin, Multiroots, Odeiv, Permutation Poly, Qrng, Rng, Roots, Siman (Simulated Annealing) Special Functions, Spline GSL >= 1.3 and numerical python are required. It requires either Numeric or numarray. Please send all bug reports, requests, patches to pygsl-discuss at lists.sf.net Yours sincerely Pierre Schnizer -- Please remove the nospam for direct reply From rmemmons at member.fsf.org Sat Jan 1 14:28:16 2005 From: rmemmons at member.fsf.org (Rob Emmons) Date: Sat, 01 Jan 2005 13:28:16 -0600 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: > For managers of companies it's worse: the company makes > VERY substantial investments into any technology it "marries", > and that means big losses if it goes. Long-term stability > of this technology in terms of "we're not going to be left out > in cold alone with this technology to feed it" means a lot > to them. Even a poor technology with external backing > of big, stable vendor is better than the excellent technology > without ...... There is the stability issue you mention... but also probably the fear issue. If you choose a solution from a major company -- then it fails for some reason or they drop the product -- it's their fault -- you've got an automatic fall guy. On the other hand, an open source solution or otherwise less accepted solution ... it will probably be consider your fault by the organization. It's a rational decision to avoid personal risk when you don't get much reward for choosing something different. Rob From grante at visi.com Sat Jan 1 21:31:07 2005 From: grante at visi.com (Grant Edwards) Date: 02 Jan 2005 02:31:07 GMT Subject: Approximating scattered data References: <41d72377$0$31717$a1866201@visi.com> <1104624125.552423.63000@z14g2000cwz.googlegroups.com> Message-ID: <41d75ceb$0$31682$a1866201@visi.com> On 2005-01-02, beliavsky at aol.com wrote: >>However, I can't find anything usable from Python, and my >>Fortram skills are pretty rusty. I tried SciPy, but it's spline >>fitting module doesn't work at all for my data. I've found >>mentions of a Python port NURBS toolbox, but all the links I >>can find are broken. > > NURBS is available in Matlab and Scilab at > http://www.aria.uklinux.net/nurbs.php3 , and translating to > Python with Numeric/Numarray should not be too hard. Right. It says there's a Python module for the NURBS toolkit, but there's nothing about NURBS on the page to which the link points. Googling for Python and NURBS toolkit doesn't find anything else. > If you are trying to fit z = f(x,y) without having a particular > functional form in mind, you can apply a nonparametric regression > technique. One of the easiest approaches to code is Nadaraya-Watson > kernel regression -- see for example > http://www.quantlet.com/mdstat/scripts/spm/html/spmhtmlnode24.html , > equation 4.68, Well, I can see it, but that's about it... :) > where a Gaussian kernel can be used for K. PyML at > http://pyml.sourceforge.net/doc/tutorial/tutorial.html may > implement this (I have not tried it). Thanks, I'll take a look. > LIBSVM at http://www.csie.ntu.edu.tw/~cjlin/libsvm/ has a > Python interface for Support Vector Machines, a fairly popular > and recent flexible regression method. I'll give that a look also. One of the important considerations is the efficiency of evaluating the approximating function (calculating z given x and y). That code is going to be running on a rather slow processor w/o floating point HW, and if the evaluation takes more than about 40ms, I'm going to have problems. The evaluating the spline surface produced by scipy's FITPACK wrapper was fast enough, but I had to force the scattered data onto a grid (which introduced errors), and then the spline surfaces generated were wildly unstable between the grid points. -- Grant Edwards grante Yow! The Korean War must at have been fun. visi.com From ahaas at airmail.net Wed Jan 12 12:50:07 2005 From: ahaas at airmail.net (Art Haas) Date: Wed, 12 Jan 2005 11:50:07 -0600 Subject: [ANNOUNCE] Twenty-first release of PythonCAD now available Message-ID: <20050112175007.GC22649@artsapartment.org> I'm pleased to announce the twenty-first development release of PythonCAD, a CAD package for open-source software users. As the name implies, PythonCAD is written entirely in Python. The goal of this project is to create a fully scriptable drafting program that will match and eventually exceed features found in commercial CAD software. PythonCAD is released under the GNU Public License (GPL). PythonCAD requires Python 2.2 or newer. The interface is GTK 2.0 based, and uses the PyGTK module for interfacing to GTK. The design of PythonCAD is built around the idea of separating the interface from the back end as much as possible. By doing this, it is hoped that both GNOME and KDE interfaces can be added to PythonCAD through usage of the appropriate Python module. Addition of other PythonCAD interfaces will depend on the availability of a Python module for that particular interface and developer interest and action. The twenty-first release of PythonCAD adds the ability to save the visibility and locked status of entities when saving a drawing. This release also includes improved code for handling the undo/redo operations by simplifying various routines as well as making similiar routines in various modules consistent. Like all previous releases, numerous bug fixes and code improvements have been applied. A mailing list for the development and use of PythonCAD is available. Visit the following page for information about subscribing and viewing the mailing list archive: http://mail.python.org/mailman/listinfo/pythoncad Visit the PythonCAD web site for more information about what PythonCAD does and aims to be: http://www.pythoncad.org/ Come and join me in developing PythonCAD into a world class drafting program! Art Haas -- Man once surrendering his reason, has no remaining guard against absurdities the most monstrous, and like a ship without rudder, is the sport of every wind. -Thomas Jefferson to James Smith, 1822 From jtr at ofb.net Thu Jan 20 19:19:03 2005 From: jtr at ofb.net (John Reese) Date: Fri, 21 Jan 2005 00:19:03 +0000 (UTC) Subject: Is there a library to parse Mozilla "mork" documents? Message-ID: Mozilla, Firefox, Thunderbird, and so forth use this awful format called MORK to store all kinds of things: which messages you've read in a newsgroup, headers and indexes into the mbox file of messages in a mail folder, and address books. It's documented to some extent here: http://www.mozilla.org/mailnews/arch/mork/primer.txt Does anyone know of a Python library for parsing these files? A single file basically just stores the equivalent of a nested dictionary with text that can be declared separately and interpolated. jwz has an over-specific perl version at http://www.jwz.org/hacks/marginal.html, which I might have to try to translate if there's nothing already available in Python. From noway at sorry.com Mon Jan 31 20:58:15 2005 From: noway at sorry.com (Giovanni Bajo) Date: Tue, 01 Feb 2005 01:58:15 GMT Subject: set, dict and other structures References: <1107214762.198058.55680@f14g2000cwb.googlegroups.com> Message-ID: Raymond Hettinger wrote: > If set-ifying a dictionary turns out to be an essential and > time-critical operation, it is possible to add some special case code > for this. The question is whether it is worth it. If you find the > need is pressing, file a feature request explaining why it is > essential. Then, I'll implement it for you. On the other hand, if > this is a theoretical nice-to-have, then why clutter up the code > (with pre-sizing and forcing all values to True). Just today I was writing some code where I wanted to use sets for the abstraction (intersection, etc.), but also carry some values with them to process. So, yes, I believe that having set-like abstraction for dictionaries would be great. In fact, for a moment I wondered if dict.keys() was already of type set in 2.4, because it could have made sense. My concrete situation was a routine that was updating a current snapshot of data (stored in a dictionary) with a new snapshot of data (another dictionary). With 'updating' I mean some kind of algorithm where you have to do different things for: - items that were present in the current snapshot but not in the new snapshot anymore (obsolete items) - items that were not present in the current snapshot but are presente in the new snapshot (new items) - items that were present in both the current and the new snapshot (possibly modified items) So, this was a perfect suit for sets. Given my dictionaries d1 and d2, I would have liked to be able to do: for k,v in (d1 - d2).iteritems(): ... for k,v in (d2 - d1).iteritems(): ... for k,v in (d1 & d2).iteritems(): # uhm, not fully correct ... Of course, there are some nitpicks. For instance, in the last case the dictionary at the intersection should probably hold a tuple of two values, one coming from each dictionary (since the intersection finds the items whose key is present in both dictionaries, but the value can obviously be different). So you'd probably need something: for k,(v1,v2) in (d1 & d2).iteritems(): ... Another solution would be to say that set-like operations, like (d1 & d2), return an iterator to a sequence of keys *only*, in this case the sequence of keys available in both dictionaries. I also tried a different approach, that is putting my data in some structure that was suitable for a set (with __hash__ and __key__ methods that were caring of the key part only): class FakeForSet: def __init__(self, k, v): self.key = key self.value = value def __hash__(self): return hash(self.key) def __cmp__(self, other): return cmp(self.key, other.key) but this looked immediatly weird because I was lying to Python somehow. It then became clear that it's not going to work, because when you go through (s1 & s2) you do not know if the items you get are coming from s1 or s2, and that is important because the value member is going to be different (even if you're lying to Python saying that those items are equal anyway). I know of course there are other ways of doing the same thing, like: # intersection for k in d1: if k not in d2: continue v1, v2 = d1[k], d2[k] ... But I don't think there is anything wrong in providing an abstraction for this, especially since we already decided that set-like abstractions are useful. So, FWIW, I would find set-like operations on dictionaries an useful addition to Python. Besides, I guess they can be easily experimented and studied by subclassing dict. -- Giovanni Bajo From dalke at dalkescientific.com Thu Jan 6 14:24:52 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Thu, 06 Jan 2005 19:24:52 GMT Subject: Other notes References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> <41DD40F1.5030301@holdenweb.com> Message-ID: Me >>>> (BTW, it needs to be 1 .. 12 not 1..12 because 1. will be interpreted >>>> as the floating point value "1.0".)< Steve Holden: > Indeed, but if ".." is defined as an acceptable token then there's > nothing to stop a strict LL(1) parser from disambiguating the cases in > question. "Token" is not the same thing as "character". Python's tokenizer is greedy and doesn't take part in the lookahead. When it sees 1..12 the longest match is for "1." which is a float. What remains is ".2". That also gets tokenized as a float. is not allowed in Python so the parser raises an compile time SyntaxError exception >>> 1..12 File "", line 1 1..12 ^ SyntaxError: invalid syntax >>> Consider the alternative of "1..a". Again "1." is tokenized as a float. What remains is ".a". The longest match is "." with "a" remaining. Then the next token is "a". The token stream looks like which gets converted to the same thing as getattr(1.0, "a") That is legal syntax but floats don't have the "a" property so Python raises an AttributeError at run-time. >>> 1..a Traceback (most recent call last): File "", line 1, in ? AttributeError: 'float' object has no attribute 'a' >>> Here's a property that does exist >>> 1..__abs__ >>> Because of the greedy lexing it isn't possible to do "1.__abs__" to get the __abs__ method of an integer. That's because the token stream is which is a syntax error. >>> 1.__abs__ File "", line 1 1.__abs__ ^ SyntaxError: invalid syntax >>> One way to avoid that is to use "1 .__abs__". See the space after the "1"? The tokenizer for this case creates which create code equivalent to getattr(1, "__abs__") and is valid syntax >>> 1 .__abs__ >>> Another option is to use parentheses: (1).__abs__ I prefer this latter option because the () is easier to see than a space. But I prefer using getattr even more. Andrew dalke at dalkescientific.com From chrisdewinN0SPAM at yahoo.com.au Sat Jan 29 13:05:53 2005 From: chrisdewinN0SPAM at yahoo.com.au (Dfenestr8) Date: Sun, 30 Jan 2005 04:05:53 +1000 Subject: An mysql-python tutorial? References: Message-ID: On Sat, 29 Jan 2005 06:41:37 +0000, Kartic wrote: [snip] > And here is one more site, good stuff here too:- > http://www.kitebird.com/articles/pydbapi.html > Hi. I followed the instructions there, tried out the test script they recommend. Can you tell me why this command, in the python interpreter: >>>conn = MySQLdb.connect (host = "localhost", user = "flipper", passwd = "[hidden]", db = "mydb") produces this error: Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/site-packages/MySQLdb/__init__.py", line 63, in Connect return apply(Connection, args, kwargs) File "/usr/lib/python2.3/site-packages/MySQLdb/connections.py", line 115, in __init__ self._make_connection(args, kwargs2) File "/usr/lib/python2.3/site-packages/MySQLdb/connections.py", line 41, in _make_connection apply(super(ConnectionBase, self).__init__, args, kwargs) _mysql_exceptions.OperationalError: (1045, "Access denied for user: 'flipper at localhost' (Using password: YES)") I also have MySQL installed, and tried setting up the user flipper with the mysql client, as per the instructions here: http://vsbabu.org/mt/archives/2003/04/17/mysql_in_mandrake_91.html From gandalf at geochemsource.com Mon Jan 31 09:44:38 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Mon, 31 Jan 2005 15:44:38 +0100 Subject: re module - cannot make expression Message-ID: <41FE4456.5050504@geochemsource.com> Hi All! I would like to match strings not beginning with '/webalizer'. How can I do this? The only one negation command is ^ inside [] but it cannot be used here. I looked over "re" examples on the net but I could not find an example about how to match "not beginning with" type expressions. Thanks, Laci 2.0 From flupke at nonexistingdomain.com Thu Jan 6 09:27:10 2005 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 06 Jan 2005 14:27:10 GMT Subject: logging from severl classes In-Reply-To: <1104193858.640852.120730@z14g2000cwz.googlegroups.com> References: <1104193858.640852.120730@z14g2000cwz.googlegroups.com> Message-ID: <2VbDd.21742$Nv5.1294471@phobos.telenet-ops.be> Vinay Sajip wrote: > It works for me: > > #file3.py > import file1 > import file2 > > a = file1.A() > b = file2.B() > b.otherfunction() > > gives > > 2004-12-28 00:18:34,805 DEBUG file2 6 creating class B > 2004-12-28 00:18:34,805 DEBUG file2 9 in otherfunction > yeah, the classes where a simplification of the classes i'm using and used these to just show what i wanted to do without testing them. they indeed work. strange. Thanks for your answer benedict From luv2luv_u at comcast.net Tue Jan 18 02:55:44 2005 From: luv2luv_u at comcast.net (collegebabe2004) Date: 17 Jan 2005 23:55:44 -0800 Subject: Advice to a Junior in High School? In-Reply-To: References: Message-ID: <1106034944.793262.19950@z14g2000cwz.googlegroups.com> wow! Aren't we getting ahead of ourselves? Well, I'm glad you are beefing up your college knowledge but let's just sit back for a minute and breathe..........there, feel better? Now, listen. When I was a freshman and sophomore in high school I was so sure I wanted to be an artist and attend one of the most highly recognized and expensive art schools in the country. I wanted to go to college back east away from my parents. Now I'm a psychology major in community college and I want to attend UCLA! First of all, NEVER SETTLE FOR LESS when it comes to your major. Do what it is true to your heart and never let people say you can't! You can double major if you want to be on the safe side. Compsci isn't an easy thing to do as you know and it's a highly regarded profffession! By the time you graduate college, the world could be a completely different place. But let's just worry about here and now. If you think too much about the future IT WILL DRIVE YOU CRAZY! Trust me, you are doing everything right so far. I applaud your effort but relax and everything will fall into place eventually! I would suggest taking Japanese because you will have to work with them eventually if you do decide to choose compsci as your proffesion. Margaux From fortepianissimo at gmail.com Fri Jan 21 00:55:28 2005 From: fortepianissimo at gmail.com (fortepianissimo at gmail.com) Date: 20 Jan 2005 21:55:28 -0800 Subject: Example of resolving an alias using Carbon.File module? Message-ID: <1106286928.806519.67720@c13g2000cwb.googlegroups.com> This is a question only relevant to Mac OS X. Could someone offer a simple example how to use Carbon.File module (perhaps Alias.FSResolveAlias()?) to resolve an alias? Basically I'd like to load in an alias file and find out which file/directory the alias points to. Thanks a lot! From tjreedy at udel.edu Thu Jan 27 00:44:49 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Jan 2005 00:44:49 -0500 Subject: Which is faster? References: <1106793602.782397.61260@z14g2000cwz.googlegroups.com> Message-ID: "Aggelos I. Orfanakos" wrote in message news:1106793602.782397.61260 at z14g2000cwz.googlegroups.com... > Any idea which of the following is faster? > > 'a/b/c/'[:-1] > 'a/b/c/'.rstrip('/') I find the first easier to read and mentally process. Others may have a different answer. But perhaps you meant with the CPython 2.x implementation ;-) > P.S. I could time it but I thought of trying my luck here first, in > case someone knows already, and of course the reason. For more on the CPython (2.2) reason, consider >>> def f1(s): return s[:-1] ... >>> def f2(s): return s.rstrip('/') ... >>> import dis >>> dis.dis(f1) 0 SET_LINENO 1 3 SET_LINENO 1 6 LOAD_FAST 0 (s) 9 LOAD_CONST 1 (-1) 12 SLICE+2 13 RETURN_VALUE 14 LOAD_CONST 0 (None) 17 RETURN_VALUE >>> dis.dis(f2) 0 SET_LINENO 1 3 SET_LINENO 1 6 LOAD_FAST 0 (s) 9 LOAD_ATTR 1 (rstrip) 12 LOAD_CONST 1 ('/') 15 CALL_FUNCTION 1 18 RETURN_VALUE 19 LOAD_CONST 0 (None) The second has a load attribute (via dict lookup) that the first does not. More important, the second has a generic function call versus a specific byte-coded slice call. The rstrip will also do a slice after it determines the endpoint of the slice. Terry J. Reedy From richardjones at optushome.com.au Sat Jan 29 16:34:39 2005 From: richardjones at optushome.com.au (richard) Date: Sun, 30 Jan 2005 08:34:39 +1100 Subject: Marketing reST (was Re: What YAML engine do you use?) References: <35a6tpF4gmat2U1@individual.net> Message-ID: <41fc016f$0$29490$afc38c87@news.optusnet.com.au> Aahz wrote: > While I can see how you'd get that impression of reST, it's not true: > like Python, reST is intended to be simpl*er* and readable, but not > simple.??The?joy?of?reST?is?that?I?can?concentrate?on?writing?instead?of > formatting, just as I do when writing Usenet posts.??;-)??Even?after > using reST for a long time, I'm still constantly looking up features that > I use rarely (such as correct formatting of URLs). > But reST is great because it's relatively unobtrusive. Those of us > who've used reST to document code for a long time have gotten into the > habit of using some reST-isms even when not writing reST: have you > noticed the number of Pythonistas who use constructs like ``foo()``? > Even if you didn't know it was from reST, the meaning is obvious. And this is the core of it for me too (if you want simple, use Word). Roundup's documentation__ (in particular the `Customisation Doc`__ which is now huge) is entirely written in reST. It uses a fraction of the total pool of reST constructs, but I believe the end result is perfectly legible. I also tend to write in reST style when composing emails (a biggie for me is starting examples with "::"). Anyway, some sample Roundup docs: __ http://roundup.sourceforge.net/doc-0.8/index.html __ http://roundup.sourceforge.net/doc-0.8/customizing.html > As you say, reST can/does get messy when you're doing complicated things, > but it stays more readable than XML/DocBook. Indeed - I chose to use reST for Roundup's documentation for two very important reasons: 1. lower the barrier for me to write the docs - and I am *really* happy with how current the Roundup docs stay, because I don't feel like actually writing them is a pain, as opposed to any sort of Markup Language format, and 2. the first contributor of docs suggested it, and I've had several contributors since. It's easier for contributors to write for Roundup's documentation - even if they don't get the reST markup correct, it's trivial to fix. This is less the case with a Markup Language. Richard From kartic.krishnamurthy at gmail.com Mon Jan 10 14:30:51 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 10 Jan 2005 11:30:51 -0800 Subject: Importing Problem on Windows In-Reply-To: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> References: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> Message-ID: <1105385451.560381.57650@c13g2000cwb.googlegroups.com> It is quite possible that in linux, you launched the python interpreter shell from the same directory you stored your parser.py and parse.py files. On windows, you probably saved the parser*.py files to some place like "my documents" and launched the python interpreter or IDLE. So, you could probably try this: 1. Launch command shell. 2. CD to the directory where you saved the parser*.py files. 3. Start python.exe from the command prompt (not from the Program Files shortcut) 4. Try importing. Easier...copy the parser*.py files into the Libs folder of your python installation in your windows machine. Thanks, --Kartic From ruses at users.ch Wed Jan 12 11:42:28 2005 From: ruses at users.ch (more i squawed) Date: Wed, 12 Jan 2005 17:42:28 +0100 Subject: java 5 could like python? In-Reply-To: References: Message-ID: <34l1saF4c17ifU1@individual.net> vegetax wrote : > I was a java developer one year ago ,before i moved to python i realy liked > it at the beggining, but i got very disapointed lately since my > previus two python proyects where relatively big,and python didnt feel > well suited for the task. > > The reasons are mainly due to the standard library,the language > performance was aceptable, but the library, in my opinion has several grave > issues: > > -No naming convention. The speech of "it fits in my head" is no longer valid > when i use a lot of functionality,modules,classes in a large proyect. > > For example if i remember a function i want ie:get attribute, i dont > remember if the module implementer coded it as > getAttribute,GetAttribute,get_attribute, then i have to go and check the > doc, every time,which is a waste of time. I believe this is a rather ill-suited example. People will react. > > -library Organization,we have modules that can have 20 classes(I imagine > that is because of the commodity of having all in one file) I challenge you to comparative statistics with Java. > which makes > reading the doc horribly painfull and is very hard to find the stuff > coupled with the "pool" of modules that is the python installation > directory,all throwed away at the installation directory without a > categorization. Well, for the soothing it can provide, I often feel nostalgic of the python documentation when I use javadoc. > > -Is python library half object oriented? half functional oriented? I can > understand that python allows some functional programing components when > they are necesary,but there are libraries that totaly ignore object > orientation which makes them problematic to use.for example,Whats with the > os.path module and files? why do i have to say os.path.getfilesize(f.name) > all the time? why cant i say f.size? Why does urlparse returns a tuple of 7 > items instead of an URL object? why there isnt an URL object? and so on.. > > I havent figured out a way to overcome those factors,the delaying and lost > of focus that is having to check the docs all the time,every 5 seconds and > having to make object oriented wrapers for several libraries or having to > go and read the source code to know what the heck a function returns or > what are its arguments makes coding unpleasant an very slow , i often have > 15 pydocs windows open at the same time. What should i do? First, you should believe the newsgroup when you get told that reading the source code "to know what the heck a function returns" is a not a need the python documentation leaves most pythoneers with. > -Realying on ides is imposible due to python dinamic nature,very litle(next > to nothing) assistance can be espected from them. > > -Memorazing all the function names,parameters,return values,conventions of > the modules i use doesnt look like a good solution. > > Join it with poor and outdated documention and we have a very unpleasant > standard library. You would be much closer to the mark, imho, by admitting that the main issue with "knowing a programming language" is knowing its standard library while feeling at home with the documentation thereof; *and* then admitting that changing languages generally implies the unpleasant experience of loosing touch with the content and style of one's beloved standard library and docs. > > In the other hand, with the recent changes in java 5 i can pythonize > java,And take advantage of a well designed library that coupled with the > "apache commons" libraries has no match,not even .Net. > > for example with the static import feature i can say: > > import static mylib.Toolbox.print; > import static mylib.Console.run; > // or import static mylib.Toolbox.*; > > class C{ > public void func(){ > print("hello world"); // instead of System.out.println("hello world"); > print(run("ls /tmp")); > } > } Well you should provide the complete python equivalent, and I anticipate that you will be hard pressed to find someone on clp who will share your feeling that this java version is evidently better. Regards. From ncoghlan at iinet.net.au Thu Jan 6 05:38:15 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 06 Jan 2005 20:38:15 +1000 Subject: [Python-Dev] Let's get rid of unbound methods In-Reply-To: <001d01c4f34c$a02f8770$6402a8c0@arkdesktop> References: <001d01c4f34c$a02f8770$6402a8c0@arkdesktop> Message-ID: <41DD1517.8080903@iinet.net.au> Andrew Koenig wrote: >>duck typing? > > > That's the Australian pronunciation of "duct taping". More Kiwi, I'm thinking ;) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From rnd at onego.ru Tue Jan 4 16:44:33 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 5 Jan 2005 00:44:33 +0300 (MSK) Subject: Python evolution: Unease In-Reply-To: <41DAFF93.7030502@pythonapocrypha.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> Message-ID: On Tue, 4 Jan 2005, Dave Brueck wrote: >Roman Suzi wrote: >>>>It may be optional in the sense that the language will >>>>accept missing declarations but as soon as the feature >>>>is available it will become "mandatory" to use it >>>>(peer pressure, workplace practices). >> >> >> What about generic programming coming into fashion anytime soon? > >Roman, I think I've read every single thread in the past year or three wherein >you've brought up generic programming, and I think you'd do well to choose a new >term for the idea you're trying to convey. IIRC, I did it only once: at fall 2004. >The term "generic programming" is too... er... generic. :) Nope. It is not generic. It has it's definition made by the co-author of STL - A.Stepanov. And the Boost C++ library (many of us know it as Boost Python) standardise on the approach, AFAIK. >As you know, Python >already includes a _lot_ of support for generic programming (a function that >iterates over a sequence can easily process a list, or a string, or a tuple as >input; a function that takes a file-like object can often work just as will with >a true file object or a cStringIO object; etc.). So when you bring up "generic >programming", it's too easy to dismiss the comment because (1) it's too vague >and (2) Python already does a lot of it. > >So, what is your term for the type of generic programming that Python doesn't >yet support? Interfaces? Protocols? Adapters? Metatype hierarchies? Python could have honest support of concepts. Everything else will be available with them. That is the whole point that Python supports GP. It is only one step to do concepts right (and GvR it seems want type-checking into Python 3.0 anyway), so support for concepts/concept checking is very logical, isn't it? Right now concepts in Python are things which experienced Python programmers know from practise. Sometimes, they feel them unconsciously. Concepts could be veryfied and this, for example, could prevent errors like DB-API-complient module doesn't have some small, but necessary to comply, attributes. Standard concepts could be part of standard concept "metalibrary", along with verification mechanisms (this could be done even on C++, why not in a candy like Python?). So every programmer could verify that his/her class, created to satisfy concept XYZ is (formally) such. Your example - cStringIO - does it really satisfy concept of STRING? It does. Partially. Those "partially" here and there could lead to madness. Unit testing will be simplified too, because structural tests will be built into concept-checking mechanism. And BTW, are we really disputing? What do you propose instead? Old-fashioned Pascal-like type definitions? Java-like interface/implementaion ...? IMHO it could be a big mistake to play catch-up. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From steve at holdenweb.com Fri Jan 7 06:36:31 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 07 Jan 2005 06:36:31 -0500 Subject: Other notes In-Reply-To: References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> <41DD40F1.5030301@holdenweb.com> <41dda7c5.167823026@news.oz.net> Message-ID: Andrew Dalke wrote: > Bengt Richter: > >>But it does look ahead to recognize += (i.e., it doesn't generate two >>successive also-legal tokens of '+' and '=') >>so it seems it should be a simple fix. > > > But that works precisely because of the greedy nature of tokenization. > Given "a+=2" the longest token it finds first is "a" because "a+" > is not a valid token. The next token is "+=". It isn't just "+" > because "+=" is valid. And the last token is "2". > [...] You're absolutely right, of course, Andrew, and personally I don't think that this is worth trying to fix. But the original post I responded to was suggesting that an LL(1) grammar couldn't disambiguate "1." and "1..3", which assertion relied on a slight fuzzing of the lines between lexical and syntactical analysis that I didn't want to leave unsharpened. The fact that Python's existing tokenizer doesn't allow multi-character tokens beginning with a dot after a digit (roughly speaking) is what makes the whole syntax proposal infeasibly hard to adapt to. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From ncoghlan at iinet.net.au Tue Jan 18 03:46:03 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 18 Jan 2005 18:46:03 +1000 Subject: [Python-Dev] Getting rid of unbound methods: patch available In-Reply-To: References: Message-ID: <41ECCCCB.6070606@iinet.net.au> Guido van Rossum wrote: > What do people think? (My main motivation for this, as stated before, > is that it adds complexity without much benefit.) Something important that came up in my response to Marc-Andre: What about C method implementations which are relying on this typecheck and assuming that 'self' is (nearly) guaranteed to be of the correct type? The string object implementation is where I noticed this assumption being made, but I suspect it would be fairly widespread. Obviously, use of im_func can break such code already, but that's a far cry from having C.f skip the type check. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From markfanty at yahoo.com Sun Jan 23 11:05:26 2005 From: markfanty at yahoo.com (Mark Fanty) Date: Sun, 23 Jan 2005 16:05:26 GMT Subject: best way to do a series of regexp checks with groups Message-ID: In perl, I might do (made up example just to illustrate the point): if(/add (\d+) (\d+)/) { do_add($1, $2); } elsif (/mult (\d+) (\d+)/) { do_mult($1,$2); } elsif(/help (\w+)/) { show_help($1); } or even do_add($1,$2) if /add (\d+) (\d+)/; do_mult($1,$2) if /mult (\d+) (\d+)/; show_help($1) if /help (\w+)/; How can I best do this in pyhon? Attempt 1: m = re.search(r'add (\d+) (\d+)', $line) if m: do_add(m.group(1), m.group(2)) else: m = re.search(r'mult (\d+) (\d+)', $line) if m: do_mult(m.group(1), m.group(2)) else: m = re.search(r'help (\w+)', $line) show_help(m.group(1)) The increasing nesting is a problem. I could put them in a while loop just so I can use break while 1: m = re.search(r'add (\d+) (\d+)', $line) if m: do_add(m.group(1), m.group(2)) break m = re.search(r'mult (\d+) (\d+)', $line) if m: do_mult(m.group(1), m.group(2)) break m = re.search(r'help (\w+)', $line) if m: show_help(m.group(1)) break No nesting, but the while is misleading since I'm not looping and this is a bit awkward. I don't mind a few more key strokes, but I'd like clarity. I wish I could do if m = re.search(r'add (\d+) (\d+)', $line): do_add(m.group(1), m.group(2)) elif m = re.search(r'mult (\d+) (\d+)', $line): do_mult(m.group(1), m.group(2)) else m = re.search(r'help (\w+)', $line): show_help(m.group(1)) Now that's what I'm looking for, but I can't put the assignment in an expression. Any recommendations? Less "tricky" is better. Not having to import some personal module with a def to help would be better (e.g. for sharing).. Thanks From xun.ling at gmx.de Fri Jan 7 13:22:45 2005 From: xun.ling at gmx.de (xunling) Date: 7 Jan 2005 10:22:45 -0800 Subject: "Re: Probleme mit der Installation der openSource Bittorrent.... python vs JAVA" Message-ID: OK, no win english ;D I want to build my own bittorrent client to add some usefull features as "special download directory" and "save as rar-file passwordprotected" Does anyone know if the azureus project has an opensource version? I want to write it in JAVA because java is what i like ;) If no "open-source-bittorrent-client" could be find in java, i would write it in python. Anyone who could tell me what the best developmentkit is to write network app in python?, and maybe a good book that i could eat while im sleeping? thanks for your time - xunling --------------------------------------------------------------------- ] God is the father of my doughter ;]] O_o Hu?! [ From knguyen at megisto.com Sat Jan 8 19:03:59 2005 From: knguyen at megisto.com (knguyen at megisto.com) Date: 8 Jan 2005 16:03:59 -0800 Subject: pyparsing: how to negate a grammar Message-ID: <1105229039.136595.180640@c13g2000cwb.googlegroups.com> Hi, I want to define a rule for a line that does NOT start with a given Literal. How do I do that? I try the following and my program just hang there: BodyLine = ~Literal("HTTP/1.1") + restOfLine Thanks, Khoa From jdhunter at ace.bsd.uchicago.edu Wed Jan 26 10:32:31 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 26 Jan 2005 09:32:31 -0600 Subject: detect tk mainloop Message-ID: In matplotlib using the tkagg backend, the tk mainloop is started at the end of a python script by issuing a call to a "show" function, which realizes all the created figure windows and the calls Tkinter.mainloop(). This can cause problems if the mainloop was started by another module (eg idle). Is there a way to query tkinter to detect whether the mainloop has already been called? Thanks, JDH From bob_smith_17280 at hotmail.com Sat Jan 8 18:26:16 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Sat, 08 Jan 2005 18:26:16 -0500 Subject: windows mem leak In-Reply-To: <41XDd.70234$Jk5.40626@lakeread01> References: <41XDd.70234$Jk5.40626@lakeread01> Message-ID: <41E06C18.6050407@hotmail.com> Steve Holden wrote: > Bob Smith wrote: > >> Does the Win32 port of Python have a memory leak? I have some code >> that runs flawlessly on Linux, but bombs after a few hours on Windows. >> It's threaded and uses a lot of memory. >> >> Thanks! > > > Yes, that's a well-known problem. Code that runs with a few errors will > port without any trouble at all to Windows, but once it runs flawlessly > on Linux it starts to leak memory on Windows. The PSU suspects a plot in > Redmond, the basic details of which ar Oh, the humor of it all ;) Attached is the code. Run it yourself and see. You too Peter. Be gentle with me, this was my first attempt with threads. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: web_scan.py URL: From ialbert at mailblocks.com Mon Jan 24 09:49:43 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 24 Jan 2005 09:49:43 -0500 Subject: What YAML engine do you use? In-Reply-To: <35i2qpF4nd7g0U1@individual.net> References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <35i2qpF4nd7g0U1@individual.net> Message-ID: rm wrote: > http://www.theinquirer.net/?article=20868 :-) There's a lot of nonsense out there propagated by people who do not understand XML. You can't possibly blame that on XML... For me XSLT transformations are the main reason for using XML. If I have an XML document I can turn it into other formats with a few lines of code. Most importantly these are much safer to run than a program. I think of an XML document as a "mini-database" where one can easily and efficiently access content via XPath. So there is a lot more to XML than just markup and that's why YAML vs XML comparisons make very little sense. Istvan. From tjv at hotmail.com Mon Jan 31 01:41:00 2005 From: tjv at hotmail.com (tjv at hotmail.com) Date: 30 Jan 2005 22:41:00 -0800 Subject: Image stats - going from Matlab to Python Message-ID: <1107153660.431217.145160@f14g2000cwb.googlegroups.com> Hi all, I am working with images in python using PIL. I come from a MATLAB background so I am finding it to be sometimes frustrating to do things correctly and quickly. All I need to do is load an image and store a list of pixel coordinates at which the alpha channel is set to 1. In Matlab this would be easy...Lets say we have a 2x2x4 array that represents the image. I would just type something like: indices = find(im(:,:,3)==1); then work with indices to get xy coords. Is there a similar way to accomplish the same thing in python and PIL without having a nested for loop and checking every pixel? I would appreciate advice. Thanks very much for your attention! -Tim From vincent at visualtrans.de Sat Jan 29 14:42:39 2005 From: vincent at visualtrans.de (vincent wehren) Date: Sat, 29 Jan 2005 20:42:39 +0100 Subject: tk global bindings In-Reply-To: References: Message-ID: vincent wehren wrote: > Gabriel B. wrote: > >> I'm starting to write a POS application UI's module. > In Tk here are three levels of binding: instance binding, class binding, > and application binding represented by the bind, bind_class, and > bind_all methods. You're probably looking for the the bind_all method, > as in self.bind_all("", self.onSomeKey) > > HTH, > -- > Vincent Wehren Oh and you of course __must__ look at the (recently updated!) New Mexico Tech tkinter document at: http://infohost.nmt.edu/tcc/help/pubs/tkinter.pdf See page 75 and follwing for more info on keyboard bindings... -- Vincent Wehren >> Thanks, >> Gabriel From python-url at phaseit.net Sun Jan 23 12:08:15 2005 From: python-url at phaseit.net (Josiah Carlson) Date: Sun, 23 Jan 2005 17:08:15 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 23) Message-ID: QOTW: "XML with elementtree is what makes me never have [to] think about XML again." -- Istvan Albert "'Plays well with others' was a strong motivator for Python's design, and that often means playing by others' rules." -- Tim Peters Type mutability, and why some types are immutable. This has been discussed before, and should be a FAQ topic (if it isn't already): http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/f05c9cbb7e58db9b http://www.python.org/tim_one/000195.html Caching instances of classes for reuse: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9178beed046956d2 Storing data in a persistant fashion. One link discussing concurrency, the other discussing data storage mechanisms. A link to PyTables as a way of storing and indexing large amounts of data, and the announcement for Dejavu 1.3, which also stores persistant data: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/072e6da39a4e8760 http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/7f2849d3099abfdc http://pytables.sourceforge.net/html/WelcomePage.html http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/01a77dc70a55fc94 So, you want to use SFTP in Python? Paramiko is the answer (or so I read): http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e95e8482c023fe25 http://www.lag.net/paramiko/ Circular iteration, or any strange iteration tasks? Try itertools! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/42bd800632199d2a What do PyChecker and Pylint have to do with each other? Are they configurable? And do *you* know a half-dozen distinct formats for printing a multi-line text? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2ff633d4474e52e7/ Jeremy Bowers and Dan Stromberg know that some applications should do the right thing, whether they happen to have a bit-mapped user interface at run time or not: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9ff27f0e5fea2045/ The Bangalore Python Meetup first convened on 22 January 2005: http://python.meetup.com/158/events/?eventId=3974233&action=pastdetail Why generator expressions sometimes don't beat list comprehensions, and fitting Python to requirements. Let not the anti-functional fashion obscure that filter() still sometimes makes for better coding than the comparable list comprehension: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/0155347dab27026d http://groups-beta.google.com/group/comp.lang.python/msg/b15bab678ad9b2dc Security is hard. Even the narrow aspect of cryptography is hard, if only for the complication state politics makes of the mathematics and engineering involved. Paul Rubin, Nick Craig- Wood, and others present a few details: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/fcf8b0764d369cfa No, really--Python does *that*, too. Although many people regard hardware interfacing, and its associated bit-twiddling, as outside Python's purview, they're ... wrong. See for yourself how Python makes for *clearer* codings than C or Java or Assembler or ...: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ea293235bef39473/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. deli.cio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From bokr at oz.net Tue Jan 18 22:00:05 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 19 Jan 2005 03:00:05 GMT Subject: generator expressions: performance anomaly? References: <377Hd.77904$Jk5.30235@lakeread01> <41ED1C0F.4030800@holdenweb.com> <41eda453.1215517842@news.oz.net> Message-ID: <41edcc68.1225778626@news.oz.net> On Tue, 18 Jan 2005 17:38:20 -0700, Steven Bethard wrote: >Bengt Richter wrote: >> Which make me wonder what plans there are for providing a better >> mechanism than default arguments as a way of initializing local function >> variables. Nested def's to create a closure with initialized values is >> pretty crufty for that, IMO. > >What about using a class? Associating functions with data is pretty >much what they're for... > >> Maybe extending the default argument space >> with whatever comes after e.g. a triple star delimiter in the argument list, >> but which wouldn't be counted as part of the normal arguments? E.g., >> >> def foo(x, y=123, *args, **kw, *** i=1, deftime=time.ctime()): >> return x*y, kw.get('which_time')=='now' and time.ctime() or deftime > >If what you want is to have i=1 and deftime=time.ctime() available >within foo, you could do something like (untested): > >class foo(object): > def __init__(self): > self.i = 1 > self.deftime = time.ctime() > def __call__(self, x, y=123, *args, **kwds): > return x*y, (kw.get('which_time') == 'now' > and time.ctime() or self.deftime) >foo = foo() Total: 8 lines, much irrelevant cruft. > >Or if you don't like 'foo = foo()', you could probably abuse the __new__ >method (also untested): > >class foo(object): > i = 1 > deftime = time.ctime() > def __new__(cls, x, y=123, *args, **kwds): > return x*y, (kw.get('which_time') == 'now' > and time.ctime() or self.deftime) Total: 6 lines, newbie-unfriendly abuse of __new__ ;-) > >I guess my point is that if you want attribute associated with the >function, it's often easy enough to write a class instead... vs. 2 easy lines with minimal irrelevant cruft ;-) Regards, Bengt Richter From ncoghlan at iinet.net.au Sun Jan 2 00:43:30 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 02 Jan 2005 15:43:30 +1000 Subject: Frameworks for "Non-Content Oriented Web Apps" In-Reply-To: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <41D78A02.10804@iinet.net.au> mirnazim at gmail.com wrote: > But is there some sort of framework or something that is actually meant > for such web apps,application that make heavy use of forms, have very > high amount of user interaction etc. Hmm, PJE's PEAK might be worth having a look at: http://peak.telecommunity.com/ However, I'm not sure if that will provide enough of the 'web' side of things. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jeff at ccvcorp.com Wed Jan 12 12:30:00 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 12 Jan 2005 09:30:00 -0800 Subject: a new Perl/Python a day In-Reply-To: <34k2q9F4bitrcU1@individual.net> References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> <87r7ku3pwq.fsf@mithril.chromatico.net> <34ism6F4athpcU1@individual.net> <34k2q9F4bitrcU1@individual.net> Message-ID: <10uanam1c9f7i36@corp.supernews.com> Jon Perez wrote: > ... or why 'Perl monkey' is an oft-heard term whereas 'Python > monkey' just doesn't seem to be appropriate? That's just because pythons are more likely to *eat* a monkey than to be one.... :) Jeff Shannon Technician/Programmer Credit International From sjmachin at lexicon.net Mon Jan 24 19:37:39 2005 From: sjmachin at lexicon.net (John Machin) Date: 24 Jan 2005 16:37:39 -0800 Subject: Looking for Form Feeds In-Reply-To: References: Message-ID: <1106613459.770572.44200@z14g2000cwz.googlegroups.com> Greg Lindstrom wrote: > Hello- > I have a file generated by an HP-9000 running Unix containing form feeds > signified by ^M^L. I am trying to scan for the linefeed to signal > certain processing to be performed but can not get the regex to "see" > it. Suppose I read my input line into a variable named "input" > > The following does not seem to work... > input = input_file.readline() You are shadowing a builtin. > if re.match('\f', input): print 'Found a formfeed!' > else: print 'No linefeed!' formfeed == not not linefeed???? > > I also tried to create a ^M^L (typed in as Q M L) but that > gives me a syntax error when I try to run the program (re does not like > the control characters, I guess). Is it possible for me to pull out the > formfeeds in a straightforward manner? > For a start, resolve your confusion between formfeed and linefeed. Formfeed makes your printer skip to the top of a new page (form), without changing the column position. FF, '\f', ctrl-L, 0x0C. Linefeed makes the printer skip to a new line, without changing the column position. LF, '\n', ctrl-J, 0x0D. There is also carriage return, which makes your typewriter return to column 1, without moving to the next line. CR, '\r', ctrl-M, 0x0A. Now you can probably guess why the writer of your report file is emitting "\r\f". What we can't guess for you is where in your file these "\r\f" occurrences are in relation to the newlines (i.e. '\n') which Python is interpreting as line breaks. As others have pointed out, (1) re.match works on the start of the string and (2) you probably don't need to use re anyway. The solution may be as simple as: if input_line[:2] == "\r\f": BTW, have you checked that there are no other control characters embedded in the file, e.g. ESC (introducing an escape sequence), SI/SO (change character set), BEL * 100 (Hey, Fred, the printout's finished), HT, VT, BS (yeah, probably lots of that, but I mean BackSpace)? HTH, John From claird at lairds.us Sat Jan 1 11:08:07 2005 From: claird at lairds.us (Cameron Laird) Date: Sat, 01 Jan 2005 16:08:07 GMT Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <1104511661.928284.10200@z14g2000cwz.googlegroups.com> Message-ID: In article <1104511661.928284.10200 at z14g2000cwz.googlegroups.com>, wrote: >Bulba wrote: >>OK, so what projects and why would you consider >>Python: >>1. "clearly unsuitable" > >Large-scale scientific computing projects, such as numerical weather >prediction, where performance is critical. Python could be used as the >"glue" but not the "guts", where Fortran 95 and C++ are more >appropriate. In my tests, some posted here, there has been a . . . I feel like growling that it's clearly a mistake for large-scale scientific computing projects not to leverage dynamic languages, at least in part. Yes, I've seen projects that would have been disasters if done entirely in Python. I've also seen many, many large-scale scientific projects that soaked up far more resources than they should have because they limited themselves to C++ or Fortran. I argue that it's a false opposition to categorize projects in terms of use of single languages. Many projects are MUCH better off with a mix of Python and Fortran, say (and probably SQL and JavaScript and ...), and it's pernicious to accomodate the managerial conceit that One Language will suffice. From http Sat Jan 29 23:02:42 2005 From: http (Paul Rubin) Date: 29 Jan 2005 20:02:42 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41f1a70b$0$25959$9b622d9e@news.freenet.de> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <7xzmysqmxk.fsf@ruckus.brouhaha.com> Message-ID: <7xy8ebzhr1.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > >> * Quixote > > Paul> Don't know what this is. > > Web app framework. I think Python should add a web app framework to its core, again since it otherwise can't seriously begin to compete with PHP. However, there are lots of approaches so this is an example of where your suggested process of letting a bunch of different implementations circulate before choosing something is a good idea. > >> * PyInline > > Paul> Not sure what this is. > > A module for inlining C code within a Python module. Also see Weave from > the scipy.org folks. It was inspired by the Perl Inline::C module. Hmm, sounds like it has the same issues as Pyrex. I'm also not sure why you'd want both PyInline and Pyrex. > >> * PyGTK > > Paul> wxPython might be a better choice. > > Doesn't matter. At work they decreed GTK as the GUI platform long before I > came along (they also use gtkmm for C++ apps). Can't wxPython use GTK? > It's still an example of a broadly useful package available outside > the core distribution. I'd say if access to GTK is widely important functionality, then the core should provide it in some way (e.g. through wxPython) and that's enough. If your company wants some different (i.e. nonstandard, if wxPython becomes the standard) form of access, then it can deal with the consequences of not following standards. > Paul> 2. Isn't xmlrpclib written in Python? > Yes. The implementation language is just a detail. I think it's more than a detail. If an external module is written in Python, I can download it from wherever and include it with my own app that I send to an end user. I do the work so the end user doesn't have to. If it's written in C, then the end user has to deal with it. > Paul> See, as Python improved, those things went into the core. > > Sure, than that's what Martin has been trying to tell you about your AES > proposal. Put it out there, refine it, and get it into the core when it's > mature. What kind of refinements are you envisioning? This isn't a web application framework we're talking about. It's more like the sha module. > Paul> Could you use sigalarm instead? > > I suppose. That's not the point though. I'm not married to the concept as > you seem to be that something has to be in the core distribution to be of > use to me. I'm perfectly happy incorporating solutions other people > provide. So aren't you happier when the other person provides you with a solution that installs with one command, instead of a solution that requires you to download N different modules from who knows where, and install them separately, all while hoping that they haven't been tampered with? If I'm trying to provide someone else with a solution, I'd rather use sigalarm than make the end-user download an extra module, because I think they'll be happier that way. > Paul> What happens if you send your Python program to a > Paul> nonprogrammer friend who has just a vanilla Python installation? > > I figure out some other packaging solution. In my world most of the > software I write is for my employer, so this is not a problem I face very > often. People use freeze, py2exe, py2app or other packaging solutions to > solve most/all of these problems. Only those people who think that a cross-platform application is one that works on both XP Home and XP Pro. That does simplify some things. Life in a cult is often indeed simpler than life in the real world . > Actually, there were at least two fairly mature implementations of > CSV modules out there before the PEP was a twinkle in anyone's eye. > The authors of those modules got together and wrote the current PEP > and module from scratch based upon their collective experience. Yes, CSV is complicated and benefits from that process just like web app frameworks do. Let's pick another example, the hmac module that appeared in Python 2.2. It implements the RFC 2104 HMAC algorithm. Where are the two mature implementations that circulated before the hmac module was added? Where were the authors pooling their collective wisdom? Where was the year of user feedback? The answer is, nothing like that was needed. HMAC is simple enough for a module author to read RFC 2104 and implement what it says, run some tests, and declare the module good to go. > I think the effort of having a couple versions out in the field > followed by joint effort to produce something worthy of inclusion in > the core is an excellent demonstration of what Martin has been > saying all along. Martin is saying the opposite: that he doesn't understand the point of writing a new module that synthesizes from experiences with old modules, instead of just using one of the old modules. I don't think there's a one-size-fits-all answer to any of these questions. You have to have your hands in the details of a specific problem, to arrive at the best way to deal with that problem. From python-url at phaseit.net Sun Jan 23 11:28:30 2005 From: python-url at phaseit.net (Josiah Carlson) Date: Sun, 23 Jan 2005 16:28:30 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 23) Message-ID: QOTW: "XML with elementtree is what makes me never have [to] think about XML again." -- Istvan Albert "'Plays well with others' was a strong motivator for Python's design, and that often means playing by others' rules." -- Tim Peters Type mutability, and why some types are immutable. This has been discussed before, and should be a FAQ topic (if it isn't already): http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/f05c9cbb7e58db9b http://www.python.org/tim_one/000195.html Caching instances of classes for reuse: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9178beed046956d2 Storing data in a persistant fashion. One link discussing concurrency, the other discussing data storage mechanisms. A link to PyTables as a way of storing and indexing large amounts of data, and the announcement for Dejavu 1.3, which also stores persistant data: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/072e6da39a4e8760 http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/7f2849d3099abfdc http://pytables.sourceforge.net/html/WelcomePage.html http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/01a77dc70a55fc94 So, you want to use SFTP in Python? Paramiko is the answer (or so I read): http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e95e8482c023fe25 http://www.lag.net/paramiko/ Circular iteration, or any strange iteration tasks? Try itertools! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/42bd800632199d2a What do PyChecker and Pylint have to do with each other? Are they configurable? And do *you* know a half-dozen distinct formats for printing a multi-line text? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2ff633d4474e52e7/ Jeremy Bowers and Dan Stromberg know that some applications should do the right thing, whether they happen to have a bit-mapped user interface at run time or not: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/9ff27f0e5fea2045/ The Bangalore Python Meetup first convened on 22 January 2005: http://python.meetup.com/158/events/?eventId=3974233&action=pastdetail Why generator expressions sometimes don't beat list comprehensions, and fitting Python to requirements. Let not the anti-functional fashion obscure that filter() still sometimes makes for better coding than the comparable list comprehension: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/0155347dab27026d http://groups-beta.google.com/group/comp.lang.python/msg/b15bab678ad9b2dc Security is hard. Even the narrow aspect of cryptography is hard, if only for the complication state politics makes of the mathematics and engineering involved. Paul Rubin, Nick Craig- Wood, and others present a few details: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/fcf8b0764d369cfa No, really--Python does *that*, too. Although many people regard hardware interfacing, and its associated bit-twiddling, as outside Python's purview, they're ... wrong. See for yourself how Python makes for *clearer* codings than C or Java or Assembler or ...: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ea293235bef39473/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. deli.cio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From steven.bethard at gmail.com Wed Jan 26 11:30:23 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 09:30:23 -0700 Subject: Help With Python In-Reply-To: References: Message-ID: <7dWdnbKpQs8_WGrcRVn-pw@comcast.com> Thomas Guettler wrote: > Am Wed, 26 Jan 2005 15:55:28 +0000 schrieb Judi Keplar: > > >>I am currently taking a course to learn Python and was looking for >>some help. I need to write a Python statement to print a comma- >>separated repetition of the word, "Spam", written 511 times ("Spam, >>Spam, ? Spam"). >> >>Can anybody help me get started? I am completely new to programming! > > > Hi, > > # This way, there is a comma after the last: > import sys > for i in range(511): > sys.stdout.write("Spam, ") > > # No comma at the end: > mylist=[] > for i in range(511): > mylist.append("Spam") > print ", ".join(mylist) # also no comma at the end, using a list comprehension print ", ".join(["Spam" for _ in xrange(511)]) # also no comma at the end, using a generator expresssion (Python 2.4) print ", ".join("Spam" for _ in xrange(511)) Steve From phil at freehackers.org Mon Jan 31 23:18:12 2005 From: phil at freehackers.org (Philippe Fremy) Date: Tue, 01 Feb 2005 05:18:12 +0100 Subject: Next step after pychecker Message-ID: <41ff0308$0$6503$636a15ce@news.free.fr> Hi, I would like to develop a tool that goes one step further than pychecker to ensure python program validity. The idea would be to get close to what people get on ocaml: a static verification of all types of the program, without any kind of variable declaration. This would definitely brings a lot of power to python. The idea is to analyse the whole program, identify constraints on function arguments and check that these constraints are verified by other parts of the program. What is in your opinion the best tool to achieve this ? I had an extensive look at pychecker, and it could certainly be extended to do the job. Things that still concern me are that it works on the bytecode, which prevents it from working with jython and the new .NET python. I am currently reading the documentation on AST and visitor, but I am not sure that this will be the best tool either. The AST seems quite deep and I am afraid that it will make the analysis quite slow and complicated. For a simple pattern of what I want to do: def f1( a ): return a+1 def f2(): f1( [] ) Obviously, this won't work, but neither pychecker nor the python interpreter will catch it. But a program analysis can catch it in this simple example. regards, Philippe From aahz at pythoncraft.com Sun Jan 2 12:03:50 2005 From: aahz at pythoncraft.com (Aahz) Date: 2 Jan 2005 12:03:50 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <41d6ee45$1_2@127.0.0.1> Message-ID: In article <41d6ee45$1_2 at 127.0.0.1>, Donn Cave wrote: > >I can only believe that if you think the benefit of static typing is >psychological, either something is very different between the way you >and I write programs, or you're not doing it right. > >For me, the effect is striking. I pound out a little program, couple >hundred lines maybe, and think "hm, guess that's it" and save it to >disk. Run the compiler, it says "no, that's not it - look at line 49, >where this expression has type string but context requires list string." >OK, fix that, iterate. Most of this goes about as fast as I can edit, >sometimes longer, but it's always about structural flaws in my program, >that got there usually because I changed my mind about something in >midstream, or maybe I just mistyped something or forgot what I was doing. >Then, when the compiler is happy -- the program works. Not always, but >so much more often than when I write them in Python. That's just not true for me. Take my recent Java experience (please!). I spent much effort trying to resolve stupid type dependencies that made no sense. Python's duck-typing just works -- if it looks like you should be able to use an object for a particular operation, you probably can. Python programs that I write mostly just work; instead of pounding out two hundred lines of code straight, I keep adding stubs and filling them in, testing operation as I go. This isn't even unit-testing -- I haven't drunk that Kool-Aid yet. This is easy because running a Python program is faster than invoking the Java compiler -- and you still haven't tested the actual operation of your Java program. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From simon.brunning at gmail.com Fri Jan 7 11:21:02 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 7 Jan 2005 16:21:02 +0000 Subject: Getting rid of "self." In-Reply-To: <1105114214.359029.152240@f14g2000cwb.googlegroups.com> References: <740c3aec05010705393048a374@mail.gmail.com> <1105114214.359029.152240@f14g2000cwb.googlegroups.com> Message-ID: <8c7f10c6050107082174ef1f7f@mail.gmail.com> On 7 Jan 2005 08:10:14 -0800, Luis M. Gonzalez wrote: > The word "self" is not mandatory. You can type anything you want > instead of self, as long as you supply a keyword in its place (it can > be "self", "s" or whatever you want). You *can*, yes, but please don't, not if there's any chance that anyone other than you are going to have to look at your code. 'self.whatever' is clearly an instance attribute. 's.whatever' isn't clearly anything - the reader will have to go off and work out what the 's' object is. The self prefix is a perfectly good convention. Let's stick to it. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From claird at lairds.us Tue Jan 25 11:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 25 Jan 2005 16:08:04 GMT Subject: Another scripting language implemented into Python itself? References: <10vb8cve125v0b0@corp.supernews.com> Message-ID: In article , Orlando Vazquez wrote: >Jeff Shannon wrote: > >snip > >> Because you cannot make Python secure against a malicious (or ignorant) >> user -- there's too much flexibility to be able to guard against every >> possible way in which user-code could harm the system. Parsing your own >> (limited) scripting language allows much better control over what >> user-code is capable of doing, and therefore allows (at least some >> measure of) security against malicious code. > >I don't see how that would equate to something that the original >programmer should be concerned about. You could include a bit in your >licensing scheme that voids all support on code that has been modified >in any way. You shouldn't be obligated and no one expects you to support >something the end-user has mucked with. > >You could trivially enforce this by keeping checksums of all the system >files. > >In any case, there's nothing you can really do to "secure" your code. >This is true of any language, C, C++, and especially scripting languages >like Python. Anyone who has the determination get at and modify the code >probably will. > >The only time where I can see someone using another language in place of >Python for a scripting language is just domain-specific factors, e.g. if >you need the extension language to be easily used non-programmers. . . . I think there's a bit of "talking past" each other. There's a serious issue here that I suspect Mr. Vazquez misunderstood. I'll try to illustrate: The original poster wants to work in Python. That's fine. Several of us have suggested he further expose Python itself to his end-users as an extension language. That certainly is feasible. He needn't explain all of Python to those end-users--probably only a bit about "assignments", control structures, and maybe lists. That approach creates a sort of fragility, though. Python includes, along with much else, os.unlink(). Suppose our original poster doesn't want end-users to be able to delete files (or directories ...). That particular design decision is NOT particularly apt for a licensing specification, much as I generally favor trust in the latter; don't-delete-filesystem- entries is simply too low-level to admit good expression in legal language. More broadly, the model of "end-users mucking around" captures the range of concerns only poorly. This is a serious issue. It's also one that brings Tcl, mentioned several times in this thread, back into focus. Tcl presents the notion of "safe interpreter", that is, a sub- ordinate virtual machine which can interpret only specific commands. It's a thrillingly powerful and correct solution to the main problem Jeff and others have described. From caseyhHAMMER_TIME at istar.ca Sun Jan 2 03:19:40 2005 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Sun, 02 Jan 2005 08:19:40 GMT Subject: What can I do with Python ?? References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> Message-ID: Aren't games using full screen mode to address only 320 by 240 resolution for faster screen painting? If one used only 320 by 240 in a window, then that would be 1/4 of the screen or less! -- Regards, Casey From tchur at optushome.com.au Tue Jan 11 23:18:51 2005 From: tchur at optushome.com.au (Tim Churches) Date: Wed, 12 Jan 2005 15:18:51 +1100 Subject: Python.org, Website of Satan Message-ID: <200501120418.j0C4IpkA021269@mail08.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From tim.peters at gmail.com Fri Jan 7 20:09:27 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 7 Jan 2005 20:09:27 -0500 Subject: Returning same type as self for arithmetic in subclasses In-Reply-To: <41df0d7b$0$190$edfadb0f@dread12.news.tele.dk> References: <41df0d7b$0$190$edfadb0f@dread12.news.tele.dk> Message-ID: <1f7befae05010717095902528a@mail.gmail.com> [Max M] > """ > I subclass datetime and timedelta > > >>> dt = myDatetime(1970,1,1) > >>> type(dt) > > > >>> td = myTimedelta(hours=1) > >>> type(td) > > > But when I do arithmetic with these classes, they return datetime and > timedelta, ... > >>> new_time = dt + td > >>> new_time > datetime.datetime(1970, 1, 1, 1, 0) > > >>> type(new_time) > Yes, and all builtin Python types work that way. For example, int.__add__ or float.__add__ applied to a subclass of int or float will return an int or float; similarly for a subclass of str. This was Guido's decision, based on that an implementation of any method in a base class has no idea what requirements may exist for invoking a subclass's constructor. For example, a subclass may restrict the values of constructor arguments, or require more arguments than a base class constructor; it may permute the order of positional arguments in the base class constructor; it may even be "a feature" that a subclass constructor gives a different meaning to an argument it shares with the base class constructor. Since there isn't a way to guess, Python does a safe thing instead. > where I want them to return myDatetime and myTimedelta > > So I wondered if there was a simlpler way to coerce the result into my > desired types rather than overwriting the __add__, __sub__ etc. methods? Generally speaking, no. But I'm sure someone will torture you with a framework that purports to make it easy . From tadmc at augustmail.com Wed Jan 26 21:13:36 2005 From: tadmc at augustmail.com (Tad McClellan) Date: Wed, 26 Jan 2005 20:13:36 -0600 Subject: 20050126 find replace strings in file References: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> <1106776836.679242.167880@c13g2000cwb.googlegroups.com> Message-ID: [ Followup set ] Dan Perl wrote: > I can't imagine why or how, but there are > actually 26 members in the perl-python Yahoo! group who have registered to > get these bogus lessons sent to them daily! There is one born every minute. -- Tad McClellan SGML consulting tadmc at augustmail.com Perl programming Fort Worth, Texas From harold.fellermann at upf.edu Thu Jan 13 07:45:36 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Thu, 13 Jan 2005 13:45:36 +0100 Subject: Unclear On Class Variables In-Reply-To: References: Message-ID: <0574006A-6561-11D9-B3E0-003065FB7B26@upf.edu> Hi Tim, If you have class Foo(object) : x = 0 y = 1 foo = Foo() foo.x # reads either instance or class attribute (class in this case) foo.x = val # sets an instance attribute (because foo is instance not class) Foo.x = val # sets a class attribute foo.__class.__x = val # does the same this might be sometimes confusing. IMHO, the following is especially nasty: >>> foo = Foo() >>> foo.x += 1 >>> >>> print foo.x 1 >>> print Foo.x 0 although the += operator looks like an inplace add it isn't. it is just syntactic sugar for foo.x = foo.x + 1. - harold - On 13.01.2005, at 07:18, Tim Daneliuk wrote: > I am a bit confused. I was under the impression that: > > class foo(object): > x = 0 > y = 1 > > means that x and y are variables shared by all instances of a class. > But when I run this against two instances of foo, and set the values > of x and y, they are indeed unique to the *instance* rather than the > class. > > It is late and I am probably missing the obvious. Enlightenment > appreciated ... > -- > ----------------------------------------------------------------------- > ----- > Tim Daneliuk tundra at tundraware.com > PGP Key: http://www.tundraware.com/PGP/ > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Everyone is a genius. It's just that some people are too stupid to realize it. From webmaster at smallco.com Wed Jan 19 11:40:43 2005 From: webmaster at smallco.com (Webmaster) Date: Wed, 19 Jan 2005 11:40:43 -0500 (EST) Subject: Automatic response to your mail (Error) Message-ID: The automatic reply to this e-mail which you should have received in response to your e-mail to webmaster at smallco.com has not been defined. Please contact postmaster at smallco.com for assistance. From jacek.generowicz at cern.ch Fri Jan 7 08:38:01 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 07 Jan 2005 14:38:01 +0100 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> Message-ID: "Anna" writes: > Having taken some calculus (derivatives, limits, some integrals) but > never even heard of lambda calculus, to me, lambda means absolutely > NOTHING. Less than nothing. And before you took calculus, the chances are that derivatives, limits and integrals meant less than nothing to you. But now, I am quite sure, you know that in Python lambda is a keyword which creates anonymous functions. Now that you know what lambda does, what's the problem with it? (It certainly doesn't mean "Less than nothing" to you now.) > So, I guess I don't like the word itself Fair enough. I guess there are people out there who might have a distaste for the word "class" or "def" or any of the other words which are keywords in Python. > Every other word in Python has an obvious meaning. lambda doesn't. Obvious to whom? The meaning of every word is obvious, once you have been taught it; and a complete mystery if you have not. What do you make of "seq[2:-2]"? It means "less than nothing" to the uninitiated. Just like lambda. Getting students in my Python courses to understand "seq[2:-2]" takes about as much (maybe even a bit more) effort as getting them to understand lambda[*]. But once they have been taught these features, they can handle them just fine. [*] Funnily enough, getting them to understand that "lambda x: fn(x)" is just a very silly way of writing "fn", can be quite a struggle at times ... but that's probably a consequence of the context in which lambda is introduced. From ajsiegel at optonline.net Mon Jan 31 12:11:09 2005 From: ajsiegel at optonline.net (ajsiegel at optonline.net) Date: Mon, 31 Jan 2005 12:11:09 -0500 Subject: variable declaration Message-ID: <180af5f180c303.180c303180af5f@optonline.net> MT writes - >In summary, again with all due respect and gratitude for the >spectacularly excellent product that Python is today, I wonder *why* >this strong aversion to declarative statements, and *whether* decorator >syntax constitutes a violation of it. I'd appreciate any responses or >links First be warned that I fit fairly well the profile Robert paints in the previous post on this thread - my life and livelihood do not depend on being a Python programmer. Though I would claim that my efforts to wrap my mind around it have enhanced both. Personal growth kind of thing. And I clutter this news group from time to time with observations which I admit are light on technical savy. I *can* tell you that some very bright, respected and technical members of the community argued *for* decorators on the exact grounds that Python needed to break away from its aversion to declarative statements. Someone like myself without a full grasp of the technical terminology and little grasp of the underlying structures, cannot tell you whether decorators are or are not declarative. I can observe that folks tend to get to where they want to get in these kinds of discussions by playing with the ambiguities in these kinds of words. >From an outside observer point of view, I seem to notice that in the world of programming, there seems to be more ambiguity in technical words than one would expect (or ideally like to see) in words that purport to be technical words. In short, I suspect there is a lot of semantics to be played with in answering your question. My own sense is that decorators do break a dam in Python, for better or for worse, and that it is OK to let folks provoke you into concluding for yourself what words best describe the specifics. But don't let the old hands convince you they represent business as usual. Though the authorative tone of your post indicates, I suspect, that this post was quite unnecessary. Art From c00lways at gmail.com Thu Jan 27 18:21:35 2005 From: c00lways at gmail.com (James) Date: Fri, 28 Jan 2005 07:21:35 +0800 Subject: threading and internet explorer com Message-ID: <41f9777f_2@news.tm.net.my> hi, i'm using python 2.4 with pywin32... I've tried to use internet explorer control with a class. it was fine until i decided to inherit thread for the class... class domain01(threading.Thread): def __init__(self): #blabla threading.Thread.__init__(self) def run(self): self.ie = win32com.client.Dispatch('InternetExplorer.Application.1') #this line gives error if i use .start(), but if i use .run.. no error... self.ie.Visibble = 1 print "running" xyz = domain() xyz.start() =========== this is what i get: Exception in thread Thread-23: Traceback (most recent call last): File "C:\Python24\lib\threading.py", line 442, in __bootstrap self.run() File "C:\python2exe\domain01.py", line 41, in run self.dologin() File "C:\python2exe\domain01.py", line 56, in dologin self.ie=win32com.client.Dispatch('InternetExplorer.Application.1') File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 79, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147221008, 'CoInitialize has not been called.', None, None) ===== but if i run: xyz = domain() xyz.run() ##no error! it's weird.... anyone know how to solve this problem? thank you :) best regards, James From harold.fellermann at upf.edu Mon Jan 10 12:05:46 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Mon, 10 Jan 2005 18:05:46 +0100 Subject: syntax error in eval() In-Reply-To: References: Message-ID: Thank you, Duncan and Steven. I completely forgot about setattr. Of course that's the way ... as its name might suggest *g* > What you are doing wrong is attempting to use eval before exhausting > all > the simpler techniques. Why not just call 'setattr'? > >>>> setattr(X, 'attr', 5) > > BTW, the syntax error is because eval evaluates an expression and > an assignment statement is a statement not an expression. -- Abandon the search for Truth -- settle for a good fantasy. -- From steven.bethard at gmail.com Sun Jan 16 17:48:00 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 16 Jan 2005 15:48:00 -0700 Subject: Why would I get a TypeEror? In-Reply-To: References: <34ql1vF4dqd9pU1@individual.net> Message-ID: Stian Soiland wrote: > P? 14. jan 2005 kl. 22:58 skrev Steven Bethard: > > (Any mac users? How do I fix this to appear in Norwegian? =) > >> Note that if you're not comfortable with short-circuiting behavior, >> you can also code this using lazy evaluation: >> >> (lambda: 1/x, lambda: 1.0e99)[x==0]() > > > .. and people wonder why so many Python people want to get rid of Lambda =) > Heh heh. No I don't. ;) In fact, I don't ever use lambdas in any of my own "real" code. But I don't mind being a little dirty when I post to c.l.py. ;) I guess I could have written this as: def inverse(): return 1/x def largenum(): return 1.0e99 b = (inverse, largenum)[x==0]() but I'm usually too lazy, and it's an ugly solution anyway, compared to the simple one which the OP was apparently trying to avoid: if x != 0: b = 1/x else: b = 1.0e99 =) Steve From eeykay at gmail.com Mon Jan 3 06:00:17 2005 From: eeykay at gmail.com (eeykay at gmail.com) Date: 3 Jan 2005 03:00:17 -0800 Subject: Developing Commercial Applications in Python Message-ID: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Hello All, I am trying to convince my client to use Python in his new product. He is worried about the license issues. Can somebody there to point me any good commercial applications developed using python ?. The licence clearly says Python can be used for commercial applications. Is there any other implications like that of GPL to make the source open ? Thanks for any help. eeykay From craig at postnewspapers.com.au Sat Jan 8 02:10:11 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 08 Jan 2005 15:10:11 +0800 Subject: _tkinter problem In-Reply-To: <002f01c4f54b$933fc9c0$8301a8c0@sanjay> References: <002f01c4f54b$933fc9c0$8301a8c0@sanjay> Message-ID: <1105168211.29489.1.camel@bucket.localnet> On Sat, 2005-01-08 at 14:30, Jatinder Singh wrote: > Hi > I am running a script which is importing tkinter from "/usr/local/lib/python2.3/lib-tk/Tkinter.py" and generating an error > " import _tkinter > ImportError: No module named _tkinter " > > can anybody tell me what is it? and how to get away with it? I think your question is the same problem as another recent poster - that is, you didn't have the Tcl and Tk headers installed when you installed Python. Please see my answer to "Help uninstalling/installing Python 2.4" (Yes, I know yours isn't Python 2.4 - it doesn't matter). -- Craig Ringer From sp1d3rx at gmail.com Tue Jan 11 18:18:29 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 11 Jan 2005 15:18:29 -0800 Subject: Time script help sought! In-Reply-To: References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> <1105477084.525279.312970@f14g2000cwb.googlegroups.com> <1105479292.689762.155510@f14g2000cwb.googlegroups.com> <1105480151.431987.327080@c13g2000cwb.googlegroups.com> Message-ID: <1105485509.346577.292130@f14g2000cwb.googlegroups.com> man, now that is beautifully done. Paul, I wish I knew about pyparsing a while ago. I could have used it in a few projects. :) From danperl at rogers.com Mon Jan 24 15:36:17 2005 From: danperl at rogers.com (Dan Perl) Date: Mon, 24 Jan 2005 15:36:17 -0500 Subject: Python 2.1 - 2.4 differences References: Message-ID: I'm not sure whether it's worth learning python from a book on 2.1 because of the changes that were made especially in 2.2 (see http://www.python.org/doc/2.2.1/whatsnew/, http://www.python.org/2.2.1/descrintro.html). I don't know of a specific e-book on Python although there are several good on-line tutorials. But if getting published books is difficult in your country, then I would heartily recommend Safari Books Online (http://www.safaribooksonline.com/). I have been using it for a few months and I find it to be very useful. Dan "BOOGIEMAN" wrote in message news:tcedpqix23lw$.v3p06vutw05p$.dlg at 40tude.net... >I found some e-book about Python 2.1, I want to print it but just to check > first if sintax of Python 2.1 is same as 2.4 ? Also does anybody know > where > can I download any newer Python related e-book, because there isn't any > published yet in my country. From peter at engcorp.com Sun Jan 16 21:13:12 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 16 Jan 2005 21:13:12 -0500 Subject: [perl-python] 20050115, for statement In-Reply-To: References: <1105783084.748174.307680@f14g2000cwb.googlegroups.com> Message-ID: <41EB1F38.70008@engcorp.com> Jeremy Bowers wrote: > (Hell, five days into Python and some people are already producing working > Backgammon games (I think that was the post last week), and Xah Lee here > is still on for loops! Woo! Go Xah!) Mah Jongg, actually (if we're thinking of the same post), which name is often applied in the world of computer games to a what amounts to the old game of "Concentration" (rather than the real Mah Jongg which bears no more resemblance to the computerized version than Bridge bears to Go Fish). The player merely turns over cards/tiles two at a time and any identical pairs are removed. A backgammon game, with the computer actually playing against a human and all the logic that entails, would be much more sophisticated, and rather more work. ...not to diminish the impressiveness of someone new to Python building a visually attractive GUI application in only a few days and delivering it to the web which in several ways is far more than I've contributed in over five years. ;-) (Doffs hat to the former newbie who achieved this.) -Peter From claird at lairds.us Sat Jan 15 10:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Sat, 15 Jan 2005 15:08:04 GMT Subject: reusing Tkinter Canvases References: Message-ID: In article , Sean McIlroy wrote: >I'd like to save one Tkinter Canvas in order to use it on another >Canvas later. The problem is that it gets saved as EPS but it needs to >be GIF to be reuseable. How can I convert that format? . . . There's probably a snappy answer to this, but I don't know it. There certainly are EPS -> GIF converters, if you truly want to go that way. In the Tk tradition, there are two main approaches to this need: 1. Use the Img extension, which knows how to render Canvases as .gif (and much else); 2. "Serialize" the canvas, and re-render it. Img is a venerable Tk extension, with a long, distinguished, history. It's not in the core only because of administrative issues not of interest here. It ought to work fine with Tkinter--but I know of no one who's succeeded in the attempt. From mike at hobbshouse.org Tue Jan 4 11:02:07 2005 From: mike at hobbshouse.org (Michael Hobbs) Date: Tue, 04 Jan 2005 16:02:07 -0000 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> Message-ID: <10tlffven8m3jdf@corp.supernews.com> Ville Vainio wrote: > What form of extreme dynamic behaviour have you been using lately? One real-world example: in my new coverage analysis tool (to be released any month now), I need to trace threads without changing any code. To do so, I redefine the thread.start_new_thread() function from outside the thread module, like so: orig_start_new_thread = thread.start_new_thread def traced_start_new_thread(func, args, kwargs={}): return orig_start_new_thread(traced_func_call, (func, args, kwargs)) def traced_func_call(func, args, kwargs): sys.settrace(my_trace_func) func(*args, **kwargs) thread.start_new_thread = traced_start_new_thread Granted, doing something like this on a regular basis is really bad coding style, but the ability to do something like this when I really need it is what I love about Python. From aaronwmail-usenet at yahoo.com Thu Jan 27 13:34:50 2005 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 27 Jan 2005 10:34:50 -0800 Subject: On benchmarks, heaps, priority queues In-Reply-To: References: <1106835562.598569.211370@c13g2000cwb.googlegroups.com> <1106842754.010427.74630@c13g2000cwb.googlegroups.com> <1106843673.755688.244160@f14g2000cwb.googlegroups.com> Message-ID: <1106850890.521046.11090@c13g2000cwb.googlegroups.com> re http://xsdb.sourceforge.net/bench/pq3.py Tim Peters: > If you repair that, and > instrument mixBench() to keep track of queue size statistics, you'll > find that even at 1000000, the queue at the top of the loop never > exceeds 30 entries, and has a mean size less than 3. Aha. Now that is embarrassing :(. If I fix it then I do see greater differences at sizes of 100000+. Below that, PQ0 still looks better on my machine, which I still consider weird. Thanks! -- Aaron Watters ==== War dims hope for peace -- a "real life headline" From jerf at jerf.org Sun Jan 30 22:58:36 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 30 Jan 2005 22:58:36 -0500 Subject: next line, new line References: <1107142942.626773.131980@c13g2000cwb.googlegroups.com> Message-ID: On Sun, 30 Jan 2005 19:42:22 -0800, rasdj wrote: > I have a lot of SQL to convert to postgres from oracle. I have most of the > problems worked out except for this last bit. Many of my tables need the > last comma replaced with a close parenthesis - they look like this: > > create table schema.table ( > FLD000 NUMERIC(10,0) NOT NULL, > FLD001 CHAR(3) NOT NULL, > FLD002 DATE NOT NULL, > ; > > when the syntax requires: > > FLD002 DATE NOT NULL) > ; > > I output the text in reverse thinking I could find the semicolon, go to > the next line and replace the 'comma newline' with 'closeparen newline' > and then go on to find the next semicolon. You don't give a heck of a lot of details here, but the first thing that leaps to mind is, * Suck it all into a string, let's call it "s". * s = s.replace(",\n;", ")\n;") * Dump out s. Failing that, regex can be used to allow for any whitespace, but worry about that if this isn't enough. We can also discuss trying to stream this operation if your SQL won't fit into memory all at once, but on modern machines that would be a breathtaking number of table definitions that would make me think you have other, larger problems :-) From matternc at comcast.net Thu Jan 27 15:01:12 2005 From: matternc at comcast.net (Chris Mattern) Date: Thu, 27 Jan 2005 15:01:12 -0500 Subject: [perl-python] 20050127 traverse a dir References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> Message-ID: Xah Lee wrote: > > # the above showcases a quick hack. > # File::Find is one of the worst module > # there is in Perl. One cannot use it > # with a recursive (so-called) "filter" > # function. And because the way it is > # written, one cannot make the filter > # function purely functional. (it relies > # on the $_) And the filter function > # must come in certain order. (for > # example, the above program won't work > # if g is moved to the bottom.) ... > > # the quality of modules in Perl are > # all like that. Is it just me, or is the disappointing lack of flamewars slowly ratcheting up the level of vitriol in his posts? -- Christopher Mattern "Which one you figure tracked us?" "The ugly one, sir." "...Could you be more specific?" From nelson at monkey.org Tue Jan 11 19:09:58 2005 From: nelson at monkey.org (Nelson Minar) Date: Wed, 12 Jan 2005 00:09:58 GMT Subject: XPath and XQuery in Python? Message-ID: Could someone help me get started using XPath or XQuery in Python? I'm overwhelmed by all the various options and am lacking guidance on what the simplest way to go is. What library do I need to enable three line Python programs to extract data with XPath expressions? I have this problem a lot with Python and XML. Even with Uche's excellent yearly roundups I have a hard time finding how to do fancy things with XML in Python. I think it's a bit like web server frameworks in Python - too many choices. http://www.xml.com/pub/a/2004/10/13/py-xml.html From hans at zephyrfalcon.org Sat Jan 1 16:48:20 2005 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sat, 01 Jan 2005 16:48:20 -0500 Subject: UserDict deprecated In-Reply-To: References: Message-ID: Uwe Mayer wrote: > Why is the UserDict module is deprecated after Python 2.2. The application > of it I have in mind is, i.e. multiple inheritance from "file" and "dic" - > which is not possible. I am curious, what would you do with a class that derives from both file and dict? -- Hans Nowak http://zephyrfalcon.org/ From luisXX_lupe2XX at netvisaoXX.pt Wed Jan 19 15:02:18 2005 From: luisXX_lupe2XX at netvisaoXX.pt (Luis P. Mendes) Date: Wed, 19 Jan 2005 20:02:18 +0000 Subject: xml parsing escape characters Message-ID: <357s61F4iossjU1@individual.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, I only know a little bit of xml and I'm trying to parse a xml document in order to save its elements in a file (dictionaries inside a list). When I access a url from python 2.3.3 running in Linux with the following lines: resposta = urllib.urlopen(url) xmldoc = minidom.parse(resposta) resposta.close() I get the following result: <DataSet> ~ <Order> ~ <Customer>439</Customer> (... others ...) ~ </Order> </DataSet> _____________________________________________________________ In the lines below, I try to get all the child nodes from string, first by counting them, and then ignoring the /n ones: stringNode = xmldoc.childNodes[0] print stringNode.toxml() dataSetNode = stringNode.childNodes[0] numNos = len(dataSetNode.childNodes) todosNos={} for no in range(numNos): todosNos[no] = dataSetNode.childNodes[no].toxml() posicaoXml = [no for no in todosNos.keys() if len(todosNos[no])>4] print posicaoXml (I'm almost sure there's a simpler way to do this...) _____________________________________________________________ I don't get any elements. But, if I access the same url via a browser, the result in the browser window is something like: ~ ~ ~ 439 (... others ...) ~ ~ and the lines I posted work as intended. I already browsed the web, I know it's about the escape characters, but I didn't find a simple solution for this. I tried to use LL2XML.py and unescape function with a simple replace text = text.replace("<", "<") but I had to convert the xml document to string and then I could not (or don't know) how to convert it back to xml object. How can I solve this? Please, explain it having in mind that I'm just beggining with Xml and I'm not very experienced in Python, too. Luis -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFB7rzKHn4UHCY8rB8RAhnlAKCYA6t0gd8rRDhIvZ5sdmNJlEPSeQCgteB3 XUtZ0JoHeTavBOCYi6YYnNo= =VORM -----END PGP SIGNATURE----- From asda at sdarta.com Sat Jan 8 08:00:27 2005 From: asda at sdarta.com (worzel) Date: Sat, 8 Jan 2005 21:00:27 +0800 Subject: tuples vs lists Message-ID: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> I get what the difference is between a tuple and a list, but why would I ever care about the tuple's immuutability? Also, do you say 'too-ple' or 'chu-ple' - if you get my drift. (tomato or tomato kind of thing) TIA From tzot at sil-tec.gr Fri Jan 14 08:57:48 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 14 Jan 2005 15:57:48 +0200 Subject: newbie q References: <34mgq0F4dq4buU1@individual.net> <34mku4F4c8bdkU1@individual.net> <41e7098e.782680124@news.oz.net> Message-ID: On Fri, 14 Jan 2005 00:08:09 GMT, rumours say that bokr at oz.net (Bengt Richter) might have written: >As I'm sure you know, with 2.4's generator expressions you >don't have to build the temporary list. >Which could be important if 'something' >is (or generates) a huge sequence. > > for i in (x[0] for x in something): and for some functional fun: from itertools import imap from operator import itemgetter for i in imap(itemgetter(0), something): -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From BOOGIEMANPN at YAHOO.COM Tue Jan 4 10:02:24 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Tue, 4 Jan 2005 16:02:24 +0100 Subject: How do I make Windows Application with Python ? References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> Message-ID: <1r9ydq5jsele7.1c45eb2jskpli.dlg@40tude.net> On Mon, 03 Jan 2005 19:56:10 -0600, Rob Emmons wrote: > I believe also if you want to use MS Visual Studio -- Active State sells > python programming tools that plug into MS Visual Studio if you want to do > that. I've not tried these so I don't know how they work or if they are > any good. Thanks all for very detailed answers. BTW I tried this one but it seems that it doesn't use VS'es visual designer. Also it doesn't have "build" option so it is basicly only usefull to higlight Python syntax. Active Sate Komodo looks like much better choice From gdamjan at gmail.com Mon Jan 24 09:43:05 2005 From: gdamjan at gmail.com (Damjan) Date: Mon, 24 Jan 2005 15:43:05 +0100 Subject: Python curses wizard Message-ID: <35kfrpF4n2odiU1@individual.net> Is there some tool that can help me design a simple curses wizards, preferably one that uses Python, but if there's some other sollution I'd be happy to hear. The important requirement is that its curses based (or similar text based UI). -- damjan From FBatista at uniFON.com.ar Tue Jan 18 10:20:59 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 18 Jan 2005 12:20:59 -0300 Subject: bind error!!!!! Message-ID: [Perrin Aybara] #- my code was working pretty well until yesterday.suddenly it started #- giving me bind error: address already in use. #- but i have logged out and again logged in, but still the #- problem is not solved #- can somebody give me solution for this Do you really think that somebody could help you with the information that you're giving? You should read this: http://www.catb.org/~esr/faqs/smart-questions.html Regards, . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From phr at localhost.localdomain Mon Jan 24 16:27:51 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Mon, 24 Jan 2005 21:27:51 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> Message-ID: [Note: this is a 2nd attempt at posting reply to Martin's message, since the first one didn't reach the server. It's a rewrite from memory but says about the same thing as the other attempt. --Paul] "Martin v. L?wis" writes: > Paul Rubin wrote: > > If he understood how Python is actually used, he'd understand that any > > C module is a lot more useful in the core than out of it. > > This is non-sense. I have been distributing C modules outside the > core for quite some time now, and I found that the modules are quite > useful. distutils makes it really easy for anybody to use them. Maybe we're not thinking about the same problems. Say I'm an app writer and I want to use one of your modules. My development environment is GNU/Linux, and I want to ship a self-contained app that anyone can run without having to download additional components. That includes people wanting to run my app on Windows, Macintosh, Amiga, and various other Python target platforms that I don't have compilers for. How do I do it? I'm sure your modules are excellent but as an app writer, I feel I must try to avoid needing them, in favor of modules that are already in the core, even if it means more work for me or worse functionality in my app, just for the sake of reducing installation headaches for my target audience. So, if your modules are generally useful, I hope you will try to get them into the core. > > There are already tons of 3rd party crypto modules outside the > > core, and the module I was writing wouldn't add anything useful to those. > > Why do you think these are not part of the core? It's not because > they contain crypto code, or because they had been rejected. They > are primarily not included in Python because they have not been > contributed to Python, yet. I can't speak for the authors but I'd personally say that none of those old modules are really suitable for the core on technical grounds. They're too fancy and specialized, or they depend on external libraries like OpenSSL, or they're written mostly to support some specific application and don't present a simple, general-purpose interface like a core module should have. Maybe the authors felt the same way and chose not to submit them. Or maybe the authors had other reasons, such as licensing priorities that conflict with the Python license. The module I'm discussing would simply implement the FIPS standard block ciphers (AES and DES) and the FIPS operating modes. These are the basic building blocks that I feel are missing from the core. They should be enough to fill the crypto needs of most applications. > If they were contributed, a number of things still would need to > be considered, e.g. what is the size of the code, including libraries, > is the contributor really the author, is the code likely going > to be maintained, and so on. However, it never got that far. The module we're talking about wouldn't have had any of those problems. > I know that *I* am very opposed to any contribution of a larger > module that has not seen any real users, yet. We're not talking about a "larger module", we're talking about a module that implements the basic AES and DES block ciphers (similar to how the sha module implements the basic SHA-1 hash algorithm) and wraps them with some well-defined FIPS operating modes (similar to how the hmac module wraps the sha module to compute RFC 2104 hmac authentication codes). This stuff isn't rocket science. It's just straightforward implementation of modes and algorithms that go back to the 1970's, are the subject of national and international standards, and are already in use in thousands of non-Python applications all over the world. Also, I've already released a pure-Python implementation of the interface, suitable for application testing but too slow for real use. I tried rather hard to design a convenient and general interface that I feel was an improvement over PEP 272. I don't know if anyone except me is using it, but several people including Andrew (author of PEP 272) have written favorably about it based on reading the specification. The spec was designed from the beginning to fill the needs of the core. If I were writing it as a non-core module I would have included more stuff. > So if the module was primarily written to be included in the core, I > would initially reject it for that very reason. After one year or so > in its life, and a recognizable user base, inclusion can be > considered. That makes no sense; improving the core is a perfectly valid reason to write something. If someone wrote a straightforward patch that made the Python interpreter 3x faster, would you still want to wait a year before thinking about including it? I certainly believe that every contribution needs code review and user testing before entering wide release, but that doesn't seem to be what you're getting at. > I fail to see the problem you seem to have with C modules. They are > very easy to use if written properly. Well again, maybe we're not talking about the same thing, or perhaps I just need more explanation of what you mean. Suppose I want to write an "application" that tells people the SHA-1 checksum of their name. I write 3 lines of Python using the built-in sha module: import sha name = raw_input('Enter your name: ') print 'Your hash is', sha.new(name).hexdigest() I release this "app" and presto, every Python user on every OS platform can run it with no fuss. That includes CGI authors who aren't allowed to install C modules at all, without getting their hosting service to do it. How do I do the same thing if there's no built-in sha module and all I have is sha.c? To me, the whole Python notion of "batteries included" expresses precisely the idea that I'm trying to describe. Commonly-used functions belong in the core, because making people download or install them separately is a pain in the neck. From amk at amk.ca Fri Jan 21 13:04:10 2005 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 21 Jan 2005 12:04:10 -0600 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> Message-ID: On Fri, 21 Jan 2005 18:30:47 +0100, rm wrote: > Nowadays, people are trying to create binary XML, XML databases, > graphics in XML (btw, I'm quite impressed by SVG), you have XSLT, you > have XSL-FO, ... . Which is an argument in favor of XML -- it's where the activity is, so it's quite likely you'll encounter the need to know XML. Few projects use YAML, so the chance of having to know its syntactic details is small. --amk From brent.hughes at comcast.net Thu Jan 13 15:45:36 2005 From: brent.hughes at comcast.net (Brent W. Hughes) Date: Thu, 13 Jan 2005 13:45:36 -0700 Subject: Newbie: Pythonwin References: Message-ID: Thanks guys! That helps a lot. Brent From roy at panix.com Fri Jan 7 23:08:08 2005 From: roy at panix.com (Roy Smith) Date: Fri, 07 Jan 2005 23:08:08 -0500 Subject: Securing a future for anonymous functions in Python References: <7xvfa90w6g.fsf@ruckus.brouhaha.com> Message-ID: In article , James Stroud wrote: > On Friday 07 January 2005 01:24 pm, Paul Rubin wrote: > > Nick Coghlan writes: > > > Add in the fact that there are many, many Python programmers with > > > non-CS backgrounds, and the term 'lambda' sticks out like a sore thumb > > > from amongst Python's other English-based keywords. > > > > Richard Feynman told a story about being on a review committee for > > some grade-school science textbooks. One of these book said something > > about "counting numbers" and it took him a while to figure out that > > this was a new term for what he'd been used to calling "integers". > > > I think we should not try too hard to make everything "English" like. Its a > crappy language anyway (though its the only one I speak good). Matt Neuberg, > in _AppleScript: The Definitive Guide_, refers to "the English-likeness > monster". His example is that instead of > > x = 4 > > you have to say > > copy 4 to x The syntax was taken directly from HyperCard. From fuzzyman at gmail.com Thu Jan 6 19:16:34 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 6 Jan 2005 16:16:34 -0800 Subject: Python Operating System??? In-Reply-To: <10trb0mgiflcj4f@corp.supernews.com> References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: <1105056994.107116.216480@f14g2000cwb.googlegroups.com> The bootloader would have to be a 'python-core'. Ideally a fast implementation of just the python syntax and language features. Now *that* would be an excellent basis for a restricted mode python interpreter - which could make 'python applets' closer to a reality. It would also make python for embedded systems and embedding python in larger programs easier as well. A purely 'core language' implementation with no libraries..... Obviously you'd need file systems, drivers, and something to create the functionality of the os and sys libraries. Basing it on the existing Linux kernel would seem like a much more sensible idea.... There is/was a project (Peter Hansen ?) to produce a pure python file system. that could be an interesting component. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml David Brown wrote: > Hello. I recently came across a free operating system called Unununium (or > something like that) and it was developed in Python and Assembly. > > Now, I have been looking for a way to make an operating system for a long > long time and the only possibilities I could find were C++ and assembly. I > don't mind assembly so much if I don't have to use it very often. But C++ is > so complicated and errors are pretty much impossible to find in the code for > me. > > So, I was wondering if it would be possible to find a bootloader that loads > a python file at startup or something... > > Is there an example somewhere of a Python OS? > > Thanks! From mfinder at digipen.edu Fri Jan 21 11:44:37 2005 From: mfinder at digipen.edu (M Jared Finder) Date: Fri, 21 Jan 2005 08:44:37 -0800 Subject: how to write a tutorial In-Reply-To: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> Message-ID: <35cprlF4hhav6U1@individual.net> Xah Lee wrote: > i've started to read python tutorial recently. > http://python.org/doc/2.3.4/tut/tut.html What does this have to do with Perl, Lisp, Scheme, or C? -- MJF From belred at gmail.com Mon Jan 31 01:53:40 2005 From: belred at gmail.com (Bryan) Date: Sun, 30 Jan 2005 22:53:40 -0800 Subject: Regarding exception handling In-Reply-To: References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> Message-ID: <41FDD5F4.8030507@gmail.com> Dan Perl wrote: > "Bryan" wrote in message > news:mailman.1614.1107137827.22381.python-list at python.org... > >>IMO, that is not the reason for the try/finally statement and it is not >>redundant. the try/finally statement guarantees the resource is closed >>and the try/finally statement only gets executed if and only if the >>opening of the resource doesn't raise an exception. it has nothing to do >>with exception handling. > > > But IMO, try-finally is meant to be used only if the block in the try clause > may raise exceptions. Here is an example that shows what I meant: > s = ... # socket opens > try: > a = 1 > finally: > s.close() > > works perfectly the same as: > s = ... # socket opens > a = 1 > s.close() > the above is not the same. make the a = ... raise an exception and you'll see the difference. s = ... # a = 1/0 s.close() as you can see, s.close() will never be called. also, in this example, i intentionally didn't put the extra try/except around the try/finally statement. usually i let an exception caused by s = ... to bubble up to some level that knows how to handle that error. we are talking about a resource here and in my experience, these low level functions (below the UI or management layer) don't know how to or shouldn't handle resources that can't be opened. bryan > The try-finally statement does not "handle" the exception, but it makes > sense only if exceptions are possible. There is no point in enclosing "a = > 1" in any kind of try statement. > > According to a following posting from Angelos he did expect some other > exceptions than socket.error and hence the nested try's. To my defence > though, I put in a disclaimer for that case in my initial posting. > > >>in the previous 2 examples s = ... was placed inside the try/finally, but >>if an exception occures and s doesn't get bound to an object, then >>s.close() in both examples will raise a NameError on s. > > > That is a very good point. I missed it. > > Dan > > From davorss at gmail.com Wed Jan 26 21:55:49 2005 From: davorss at gmail.com (Davor) Date: Wed, 26 Jan 2005 21:55:49 -0500 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> Message-ID: Timo Virkkala wrote: > This guy has got to be a troll. No other way to understand. not really - it was not my intention at all - but it seems people get upset whenever this OO stuff is mentioned - and what I did not expect at all at this forum as I believed Python people should not be so OO hardcore (seems not all as quite a few have indicated in their replies)... Nevertheless, I think the discussion has several quite good points! From sbryce at scottbryce.com Mon Jan 10 00:11:58 2005 From: sbryce at scottbryce.com (Scott Bryce) Date: Sun, 09 Jan 2005 22:11:58 -0700 Subject: a new Perl/Python a day In-Reply-To: References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: Bob Smith wrote: > Scott Bryce wrote: > >> Xah Lee wrote: >> >>> frustrated constantly by its inanities and incompetences.) >> >> >> I don't see what this has to do with Perl. > > > You're joking, right? No. Perl may have some interesting idiosyncrasies, especially for a programmer with little or no Unix experience, but I find it neither frustrating, inane nor incompetent. The more I use it, the more I like it. From steve at holdenweb.com Sun Jan 9 10:59:59 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 09 Jan 2005 10:59:59 -0500 Subject: Python3: on removing map, reduce, filter In-Reply-To: <34csn1F4a46hqU1@individual.net> References: <34csn1F4a46hqU1@individual.net> Message-ID: <5CcEd.70344$Jk5.19962@lakeread01> Andrey Tatarinov wrote: > Hi. > > How does GvR suggestions on removing map(), reduce(), filter() correlate > with the following that he wrote himself (afaik): > > http://www.python.org/doc/essays/list2str.html > > ? It promotes the sensible realization that when optimization is the goal code may well tend to get ugly, sometimes uglier than necessary. Note that the first version is completely straightforward and comprehensible. And note that the summary in the conclusiogn BEGINS with "Rule number one: only optimize when there is a proven speed bottleneck", which seems to adequately imply that straightforward code is to be preferred unless speed requirements override that. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From fredrik at pythonware.com Mon Jan 31 11:05:54 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 31 Jan 2005 17:05:54 +0100 Subject: import doesn't work as i want References: <41fe5438$0$18865$8fcfb975@news.wanadoo.fr> Message-ID: Olivier Noblanc wrote: > In the botom of this post you will see my source code. > > The problem is when i launch main.py that doesn't make anything why ? the "if __name__" statement checks the name of the module. if you run Python file as a script, by passing a filename to the python interpreter, the __name__ variable is set to "__main__". if you import a file as a module, the __name__ is the name of the module, not "__main__". if you want main.py to do something, move that code to main.py (or move it into a function, and call it from main.py) From ncoghlan at iinet.net.au Mon Jan 10 05:16:43 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 10 Jan 2005 20:16:43 +1000 Subject: static compiled python modules In-Reply-To: <87u0pqn5pz.fsf@dev.null.daemon.de> References: <87u0pqn5pz.fsf@dev.null.daemon.de> Message-ID: <41E2560B.2040908@iinet.net.au> Thomas Linden wrote: > How can I tell python to use the compiled in modules and not try to > load them from outside? http://www.python.org/dev/doc/devel/api/importing.html Take a look at the last three entries about registering builtin modules. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jbperez808 at wahoo.com Sat Jan 15 04:21:29 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Sat, 15 Jan 2005 17:21:29 +0800 Subject: Integration with java (Jpype vs. JPE) In-Reply-To: References: Message-ID: <34s5krF4c85d5U1@individual.net> Can someone summarize in a nutshell what is the difference between JPype and JPE? From jonasgalvez at gmail.com Thu Jan 20 12:24:32 2005 From: jonasgalvez at gmail.com (Jonas Galvez) Date: Thu, 20 Jan 2005 15:24:32 -0200 Subject: What YAML engine do you use? In-Reply-To: <35a7grF4jjrcsU1@individual.net> References: <35a6tpF4gmat2U1@individual.net> <35a7grF4jjrcsU1@individual.net> Message-ID: <7c60b60505012009243f72944@mail.gmail.com> Diez B. Roggisch wrote: > I first used yaml, tried to migrate to syck. What I like about > syck is that it is faster and doesn't try to create objects but > only dicts - but it crashed if the number of yaml objects grew > larger. So I still use yaml. Hmm.. I've never had any problems with syck. In fact, I'm using it in a small project now where I store a helluva of data in yaml files... Strange. From cepl at surfbest.net Sat Jan 1 14:58:09 2005 From: cepl at surfbest.net (cepl at surfbest.net) Date: 1 Jan 2005 11:58:09 -0800 Subject: Python equivalent of script(1) In-Reply-To: <87d5wprla1.fsf@thomas.local> References: <1104607982.132310.181560@c13g2000cwb.googlegroups.com> <87d5wprla1.fsf@thomas.local> Message-ID: <1104609489.059828.296610@c13g2000cwb.googlegroups.com> Thanks a lot. From invalidemail at aerojockey.com Tue Jan 4 19:52:41 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 4 Jan 2005 16:52:41 -0800 Subject: Optional Static Typing: Part II In-Reply-To: <10tluavnqqufg07@news.supernews.com> References: <10tluavnqqufg07@news.supernews.com> Message-ID: <1104886361.160069.315210@z14g2000cwz.googlegroups.com> John Roth wrote: > http://www.artima.com/weblogs/viewpost.jsp?thread=86641 Nitpicking: I don't think he's necessarily in good company w.r.t. types vs classes. Take Ada, for example. In Ada, a class is a set of types (in particular, the type and all its subtypes), which is kind of the opposite way Guido claims to see it. Not the Ada is relevant, and not that there is ever any agreement on terminology in computer science, but still. Based on their English language meanings, I would tend to agree with Ada's terminology. But, based on how the terminology developed for computer languages (especially under the influence of C++), it seems that most people would regard class as more of an implementation. Another question: can anyone think of something an interface statement could syntactically that an interface metaclass couldn't? I couldn't think of anything, based on the description, and it's not like th BDFL to throw out keywords for things that current syntax can handle. It leads me to suspect that maybe he has something up his sleeve. Hmm. -- CARL BANKS From dmerrillq at usaq.netq Sat Jan 8 15:23:52 2005 From: dmerrillq at usaq.netq (Dave Merrill) Date: Sat, 8 Jan 2005 15:23:52 -0500 Subject: Installing IPython on win2k References: <1105213017.820231.67050@c13g2000cwb.googlegroups.com> Message-ID: "Tim G" wrote in message news:1105213017.820231.67050 at c13g2000cwb.googlegroups.com... > Dave Merrill wrote: > > Hi, I'm new to python, and ipython, but not to programming, having > trouble > > getting ipython installed on windows 2000, python 233. Any help would > be > > much appreciated; I'm sure I'm being some basic flavor of dense... > > First of all, rest assured that it does work (and quite > easily) so welcome to Python and iPython and I hope > the going's a bit smoother as you go along. I'm having fun with python itself, but feeling a little constrained in the IDE and debugger departments. (Not to mention the clues I haven't got...). > > Then downloaded ipython-0.6.6.zip and unzipped it. When I > double-click > > setup.py, I get only a brief wait cursor; nothing else happens, and > > importing ipython as a test fails. > > First of all, ipython isn't really an import into python; you run > it and it runs python (if you understand me). So when you've > installed it, I think it puts an item on your start menu. On > linux, it puts an executable ipython onto your path. > > I've just downloaded and run the setup.py, and it does > create a Start Menu item which will start iPython. Look > out for that and see if it does the business. Removed the files I'd unzipped and started over, putting a fresh unzip in Program Files. Ran setup.py while watching the windows task list, and pythonw ran for just a second, then disappeared. I saw no other signs of anything running, and there's no shortcut for ipython in my start menu. > > Both files in the scripts dir, ipython and pycolor, have no filename > > extension, which seems odd to my newbie eye. I tried renaming them to > .py, > > still no difference. > > This is a unixism. Some unix types decry the use of file extensions > because the information the extension gives -- which executable > program to use -- is already embedded in the first line of a file. So what do I do to try ipython directly, bypassing the shortcut (since I can make my own later)? I tried right-click on scripts/ipython, Open With, and chose python, but got only a quick DOS window. Now what? Thanks, Dave Merrill From rasdj at frontiernet.net Sun Jan 30 22:42:22 2005 From: rasdj at frontiernet.net (rasdj at frontiernet.net) Date: 30 Jan 2005 19:42:22 -0800 Subject: next line, new line Message-ID: <1107142942.626773.131980@c13g2000cwb.googlegroups.com> I have a lot of SQL to convert to postgres from oracle. I have most of the problems worked out except for this last bit. Many of my tables need the last comma replaced with a close parenthesis - they look like this: create table schema.table ( FLD000 NUMERIC(10,0) NOT NULL, FLD001 CHAR(3) NOT NULL, FLD002 DATE NOT NULL, ; when the syntax requires: FLD002 DATE NOT NULL) ; I output the text in reverse thinking I could find the semicolon, go to the next line and replace the 'comma newline' with 'closeparen newline' and then go on to find the next semicolon. ; FLD002 DATE NOT NULL, FLD001 CHAR(3) NOT NULL, FLD000 NUMERIC(10,0) NOT NULL, create table schema.table ( ; FLD002 DATE NOT NULL, FLD001 CHAR(3) NOT NULL, FLD000 NUMERIC(10,0) NOT NULL, create table schema.table2 ( I don't seem to be making any progress altho I have had some interesting output. Throw me a bone? Thank you, RasDJ From newsgroups at jhrothjr.com Tue Jan 4 15:15:06 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 4 Jan 2005 14:15:06 -0600 Subject: Optional Static Typing: Part II Message-ID: <10tluavnqqufg07@news.supernews.com> Guido has posted a second blog entry on the optional static typing initiative. I like this a lot better than the first. http://www.artima.com/weblogs/viewpost.jsp?thread=86641 Now, the base objective seems to be to incorporate PyChecker functionality into the root. This in turn requires type inference, which in turn strongly suggests type annotations to help the inferencer out over rough spots. I like this approach a lot. There's also an explicit recognition that there are a lot of use cases for being able to access type information at run time. I also like this. I'm kind of neutral to the idea of using it for actual type checking: I don't think that it catches that many errors if the developer is doing a decent job of testing. However, since it's going to be supplemental to type inference, it will be a lot less intrusive. There's a new approach to interfaces that looks intriguing. One nice part is the ability to include Design By Contract type preconditions with the interface. It will be even better if they can be checked at compile time, or by the PyChecker functionality. I have to say this turned my attitude around on the subject: I'm quite in favor of the direction Guido seems to be going. John Roth From http Wed Jan 5 06:53:29 2005 From: http (Paul Rubin) Date: 05 Jan 2005 03:53:29 -0800 Subject: Python evolution: Unease References: Message-ID: <7xvfac6qiu.fsf@ruckus.brouhaha.com> "EP" writes: > Python: it tastes so good it makes you hungrier. QOTW From philippe at philippecmartin.com Tue Jan 18 16:19:52 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 18 Jan 2005 21:19:52 GMT Subject: Tkinter in thread hangs on windows but not on Linux References: <1106080941.235008.296640@c13g2000cwb.googlegroups.com> Message-ID: Well this is what is on the top of my script: from Tkinter import * import threading from ScrolledText import * I still hang under XP .... wish I had 2K to test. I almost sounds like tkinter does not get refresh events anymore. I'll keep at it On Tue, 18 Jan 2005 12:42:21 -0800, Kamilche wrote: > This example worked for me on Windows 2000, after inserting > > import threading > from Tkinter import * > import ScrolledText > > > at the top. From tadmc at augustmail.com Mon Jan 17 23:53:14 2005 From: tadmc at augustmail.com (Tad McClellan) Date: Mon, 17 Jan 2005 22:53:14 -0600 Subject: [perl-python] 20050117, filter, map References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> Message-ID: Erik Max Francis wrote: > Steven Bethard wrote: > >> Is there any chance you could post these all as part of the same thread? >> That would be really nice for those of us who aren't interested -- >> then we could just ignore the thread... > > Or, better yet, not posting it at all. He's got his mailing list, what > does he need to post it here for? There isn't much point in trolling if you don't have an audience. -- Tad McClellan SGML consulting tadmc at augustmail.com Perl programming Fort Worth, Texas From martin at v.loewis.de Thu Jan 20 15:57:52 2005 From: martin at v.loewis.de (=?ISO-8859-2?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 20 Jan 2005 21:57:52 +0100 Subject: ElementTree cannot parse UTF-8 Unicode? In-Reply-To: References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> <1106230846.455765.7310@c13g2000cwb.googlegroups.com> <1106233137.588111.216480@z14g2000cwz.googlegroups.com> Message-ID: <41F01B50.8030107@v.loewis.de> Jarek Zgoda wrote: >> So why are there non-UNICODE versions of wxPython??? To save memory or >> something??? > > > Win95, Win98, WinME have problems with unicode. This problem can be solved - on W9x, wxPython would have to pass all Unicode strings to WideCharToMultiByte, using CP_ACP, and then pass the result to the API function. Regards, Martin From tzot at sil-tec.gr Tue Jan 25 17:14:08 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 26 Jan 2005 00:14:08 +0200 Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: On Sun, 23 Jan 2005 12:28:12 -0500, rumours say that Hans Nowak might have written: >Xah Lee wrote: >> the first paragraph of 9.1 "A Word About Terminology" is epitome of >> masturbation. The entire 9.1 is not necessary. >> >> Large part of 9.2 "Python Scopes and Name Spaces" is again >> masturbatory. > >So I can just take a copy of the tutorial to the bathroom next time. >Thanks for the tip, man! The first day I (got) laid my eyes on the Python tutorial, I knew the days of "Pyboy", "Pythouse" and "Python 10" were over. I'm glad that finally others, too, really grok the "joy of Python programming". PS I just *love* the Classes chapter centerfold. All-time classic. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From claird at lairds.us Tue Jan 25 18:08:06 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 25 Jan 2005 23:08:06 GMT Subject: Another scripting language implemented into Python itself? References: Message-ID: <0juic2-68k.ln1@lairds.us> In article , Terry Reedy wrote: . . . >worrying about Python security seems superfluous. Why worry, for instance, >about os.unlink when the user can just do the same much easier in a text or >gui shell? . . . It's an apt question--and one with several answers. I'll hint at the range by observing that part of security has to do with prevention not of malicious acts, but of common mistakes. I entirely agree with you that it's crucial to think of wider context, and whether a particular choice's costs are worth its benefits. From http Thu Jan 6 17:21:28 2005 From: http (Paul Rubin) Date: 06 Jan 2005 14:21:28 -0800 Subject: Embedding a restricted python interpreter References: <345mkrF46jc4cU1@individual.net> Message-ID: <7xvfaaurkn.fsf@ruckus.brouhaha.com> Peter Maas writes: > I think PHP has a safe mode which solves the probem of isolating > scripts of different users on application level. This is not optimal > but better than nothing. Best solution would probably be to create > a thread for each request that can operate only with the id of an > authenticated user. But this seems to be a problem with Apache or > with Linux? Threads wouldn't do it--you'd need separate processes. For example, multiple threads in the same process can access each other's file descriptors. From http Tue Jan 11 21:18:53 2005 From: http (Paul Rubin) Date: 11 Jan 2005 18:18:53 -0800 Subject: Help Optimizing Word Search References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Message-ID: <7xacrfl78y.fsf@ruckus.brouhaha.com> "Case Nelson" writes: > Basically, the program needs to take in a random list of no more than > 10 letters, and find all possible mutations that match a word in my > dictionary (80k words). However a wildcard letter '?' is also an > acceptable character which increases the worst case time significantly. For that size pattern and dictionary, simply compiling the pattern to a regexp, joining the dictionary together into one big string ("abc def ghijk..."), and matching the regexp against the big string, may well be faster than using some fancy algorithm coded completely in python. From jeff at ccvcorp.com Thu Jan 27 14:34:31 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 27 Jan 2005 11:34:31 -0800 Subject: String Fomat Conversion In-Reply-To: References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> Message-ID: <10vig6ss9gigc60@corp.supernews.com> Stephen Thorne wrote: > On Thu, 27 Jan 2005 00:02:45 -0700, Steven Bethard > wrote: > >>By using the iterator instead of readlines, I read only one line from >>the file into memory at once, instead of all of them. This may or may >>not matter depending on the size of your files, but using iterators is >>generally more scalable, though of course it's not always possible. > > I just did a teensy test. All three options used exactly the same > amount of total memory. I would presume that, for a small file, the entire contents of the file will be sucked into the read buffer implemented by the underlying C file library. An iterator will only really save memory consumption when the file size is greater than that buffer's size. Actually, now that I think of it, there's probably another copy of the data at Python level. For readlines(), that copy is the list object itself. For iter and iter.next(), it's in the iterator's read-ahead buffer. So perhaps memory savings will occur when *that* buffer size is exceeded. It's also quite possible that both buffers are the same size... Anyhow, I'm sure that the fact that they use the same size for your test is a reflection of buffering. The next question is, which provides the most *conceptual* simplicity? (The answer to that one, I think, depends on how your brain happens to see things...) Jeff Shannon Technician/Programmer Credit International From ncoghlan at iinet.net.au Mon Jan 31 05:15:42 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 31 Jan 2005 20:15:42 +1000 Subject: Nested scopes and class variables In-Reply-To: References: Message-ID: <41FE054E.5000907@iinet.net.au> Dave Benjamin wrote: > I ran into an odd little edge case while experimenting with functions that > create classes on the fly (don't ask me why): It gets even kookier: Py> x = 5 Py> def f(y): ... class C(object): ... x = x ... print C.x ... Py> f(5) # OK with x bound at global 5 Py> def f(x): ... class C(object): ... x = x ... print C.x ... Py> f(6) # Oops, ignores the argument! 5 Py> def f(y): ... class C(object): ... x = y ... print C.x ... Py> f(6) # OK with a different name 6 Py> y = 5 Py> def f(y): ... class C(object): ... x = y ... print C.x ... Py> f(6) # Correctly use the nearest scope 6 That second case is the disturbing one - the class definition has silently picked up the *global* binding of x, whereas the programmer presumably meant the function argument. With a nested function definition (instead of a class definition), notice that *both* of the first two cases will generate an UnboundLocalError. Anyway, the Python builtin disassembler is very handy when looking at behaviour like this (I've truncated the dis output below after the interesting section): Py> import dis Py> def f1(x): ... class C(object): ... x = x ... print C.x ... Py> def f2(y): ... class C(object): ... x = y ... print C.x ... Py> dis.dis(f1) 2 0 LOAD_CONST 1 ('C') 3 LOAD_GLOBAL 0 (object) 6 BUILD_TUPLE 1 9 LOAD_CONST 2 (", line 2>) [...] Py> dis.dis(f2) 2 0 LOAD_CONST 1 ('C') 3 LOAD_GLOBAL 0 (object) 6 BUILD_TUPLE 1 9 LOAD_CLOSURE 0 (y) 12 LOAD_CONST 2 (", line 2>) [...] Notice the extra LOAD_CLOSURE call in the second version of the code. What if we define a function instead of a class?: Py> def f3(x): ... def f(): ... x = x ... print x ... f() ... Py> def f4(y): ... def f(): ... x = y ... print x ... f() ... Py> dis.dis(f3) 2 0 LOAD_CONST 1 (", line 2>) [...] Py> dis.dis(f4) 2 0 LOAD_CLOSURE 0 (y) 3 LOAD_CONST 1 (", line 2>) [...] Again, we have the extra load closure call. So why does the function version give us an unbound local error, while the class version doesn't?. Again, we look at the bytecode - this time of the corresponding internal code objects: Py> dis.dis(f1.func_code.co_consts[2]) 2 0 LOAD_GLOBAL 0 (__name__) 3 STORE_NAME 1 (__module__) 3 6 LOAD_NAME 2 (x) 9 STORE_NAME 2 (x) 12 LOAD_LOCALS 13 RETURN_VALUE Py> dis.dis(f3.func_code.co_consts[1]) 3 0 LOAD_FAST 0 (x) 3 STORE_FAST 0 (x) 4 6 LOAD_FAST 0 (x) 9 PRINT_ITEM 10 PRINT_NEWLINE 11 LOAD_CONST 0 (None) 14 RETURN_VALUE In this case, it's the LOAD_FAST opcode that blows up, while the LOAD_NAME falls back on the globals and then the builtins. Looking at the class based version that works also lets us see why: Py> dis.dis(f2.func_code.co_consts[2]) 2 0 LOAD_GLOBAL 0 (__name__) 3 STORE_NAME 1 (__module__) 3 6 LOAD_DEREF 0 (y) 9 STORE_NAME 3 (x) 12 LOAD_LOCALS 13 RETURN_VALUE Here we can see the "LOAD_DEREF" instead of the "LOAD_NAME" that was present in the version where the same name is reused. The dereference presumably picks up the closure noted earlier. I vote bug. If the assignment is going to be allowed, it should respect the nested scopes. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From bill.mill at gmail.com Wed Jan 19 16:16:40 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 19 Jan 2005 16:16:40 -0500 Subject: a question In-Reply-To: References: <797fe3d405011912511a609c1c@mail.gmail.com> Message-ID: <797fe3d405011913161812785@mail.gmail.com> You are correct, sir. Didn't know you could do that. Neato. Peace Bill Mill bill.mill at gmail.com On Wed, 19 Jan 2005 22:10:05 +0100, Fredrik Lundh wrote: > Bill Mill wrote: > > > You've got a couple problems. First, you need to end the string before > > putting a continuation in. > > >>> "no\ > ... pe" > 'nope' > > >>> "however\ > File "", line 1 > "however\ > ^ > SyntaxError: EOL while scanning single-quoted string > > (in the second case, the ^ is trying to point out that I added > some whitespace after the backslash) > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From aleaxit at yahoo.com Thu Jan 27 08:39:57 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 27 Jan 2005 14:39:57 +0100 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <10vdt2bpr0m84db@corp.supernews.com> <200501262039.23260.francis.girard@free.fr> <1993411a01509c62cae1715b62fe16f5@gmail.com> <200501262135.30872.francis.girard@free.fr> Message-ID: <1gr1xu0.nco4on13ibk3dN%aleaxit@yahoo.com> PA wrote: > Yes. But even with the "best" tool and the "best" intents, projects > still fail. In fact, most IT projects are considered failures: > > http://www.economist.com/business/PrinterFriendly.cfm?Story_ID=3423238 The main thesis of the article you quote (although it acknowledges that other think differently) is that better tools (including iterative, NOT waterfall, development; and, agile programming approaches, more generally) are the way to mitigate that horrid track record. Alex From bokr at oz.net Thu Jan 13 19:55:08 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 14 Jan 2005 00:55:08 GMT Subject: finding/replacing a long binary pattern in a .bin file References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> <41e6293f.725257715@news.oz.net> <10udjc3fmnhro9d@corp.supernews.com> Message-ID: <41e70dbd.783751855@news.oz.net> On Thu, 13 Jan 2005 11:40:52 -0800, Jeff Shannon wrote: >Bengt Richter wrote: > >> BTW, I'm sure you could write a generator that would take a file name >> and oldbinstring and newbinstring as arguments, and read and yield nice >> os-file-system-friendly disk-sector-multiple chunks, so you could write >> >> fout = open('mynewbinfile', 'wb') >> for buf in updated_file_stream('myoldbinfile','rb', oldbinstring, newbinstring): >> fout.write(buf) >> fout.close() > >What happens when the bytes to be replaced are broken across a block >boundary? ISTM that neither half would be recognized.... That was part of the exercise ;-) (Hint: use str.find to find unbroken oldbinstrings in current inputbuffer and buffer out safe changes, then when find fails, delete the safely used front of the input buffer, and append another chunk from the input file. Repeat until last chunk has been appended and find finds no more. Then buffer out the tail of the input buffer (if any) that then won't have an oldbinstring to change). > >I believe that this requires either reading the entire file into >memory, to scan all at once, or else conditionally matching an >arbitrary fragment of the end of a block against the beginning of the >oldbinstring... Given that the file in question is only a few tens of >kbytes, I'd think that doing it in one gulp is simpler. (For a large >file, chunking it might be necessary, though...) It's certainly simpler to do it in one gulp, but it's not really hard to do it in chunks. You just have to make sure your input buffer/chunksize is/are larger than oldbinstring ;-) Regards, Bengt Richter From dave at pythonapocrypha.com Tue Jan 4 15:41:55 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 04 Jan 2005 13:41:55 -0700 Subject: Python evolution: Unease In-Reply-To: References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> Message-ID: <41DAFF93.7030502@pythonapocrypha.com> Roman Suzi wrote: > On Tue, 4 Jan 2005, Dave Brueck wrote: > > >>>It may be optional in the sense that the language will >>>accept missing declarations but as soon as the feature >>>is available it will become "mandatory" to use it >>>(peer pressure, workplace practices). > > > What about generic programming coming into fashion anytime soon? Roman, I think I've read every single thread in the past year or three wherein you've brought up generic programming, and I think you'd do well to choose a new term for the idea you're trying to convey. The term "generic programming" is too... er... generic. :) As you know, Python already includes a _lot_ of support for generic programming (a function that iterates over a sequence can easily process a list, or a string, or a tuple as input; a function that takes a file-like object can often work just as will with a true file object or a cStringIO object; etc.). So when you bring up "generic programming", it's too easy to dismiss the comment because (1) it's too vague and (2) Python already does a lot of it. So, what is your term for the type of generic programming that Python doesn't yet support? Interfaces? Protocols? Adapters? Metatype hierarchies? -Dave From rkern at ucsd.edu Thu Jan 13 15:43:36 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 13 Jan 2005 12:43:36 -0800 Subject: News Reader In-Reply-To: References: Message-ID: Robert Kern wrote: > Daniel Bowett wrote: > >> Is anyone reading this list through thunderbird as news? If so - how >> did you set it up? > > > I subscribed to comp.lang.python under my USENET news server account. I guess I should add that that's all I did. There's nothing special to set up. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From shoot at the.moon Sat Jan 8 09:36:09 2005 From: shoot at the.moon (Steve Horsley) Date: Sat, 08 Jan 2005 14:36:09 +0000 Subject: tuples vs lists In-Reply-To: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: worzel wrote: > I get what the difference is between a tuple and a list, but why would I > ever care about the tuple's immuutability? Mainly for security and speed. Many library functions return info by returning a reference to an internally held tuple, and could be damaged / compromised / corrupted if that internal data was modified by malicious code. If tuples were mutable (lists) then it would be necessary to return a copy instead. > Also, do you say 'too-ple' or 'chu-ple' - if you get my drift. (tomato or > tomato kind of thing) Try 'Two-pull'. Steve From exarkun at divmod.com Sat Jan 1 22:36:22 2005 From: exarkun at divmod.com (Jp Calderone) Date: Sun, 02 Jan 2005 03:36:22 GMT Subject: PEP 288 ponderings In-Reply-To: Message-ID: <20050102033622.26823.987540620.divmod.quotient.806@ohm> On Sun, 02 Jan 2005 01:04:06 GMT, Steven Bethard wrote: >PEP 288 was mentioned in one of the lambda threads and so I ended up > reading it for the first time recently. I definitely don't like the > idea of a magical __self__ variable that isn't declared anywhere. It > also seemed to me like generator attributes don't really solve the > problem very cleanly. An example from the PEP[1]: > > [snip] You may be interested in greenlets. They solve this problem in a way which is conceptually much simpler and cleaner. They are available as a third party extension, and unfortunately are not terribly well documented yet (but luckily they are quite simple). http://codespeak.net/svn/user/arigo/greenlet/ Jp From rbt at athop1.ath.vt.edu Mon Jan 10 15:49:54 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 10 Jan 2005 15:49:54 -0500 Subject: exceptions and items in a list Message-ID: If I have a Python list that I'm iterating over and one of the objects in the list raises an exception and I have code like this: try: do something to object in list except Exception: pass Does the code just skip the bad object and continue with the other objects in the list, or does it stop? Thanks From dbickett at gmail.com Sun Jan 2 23:19:57 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 2 Jan 2005 23:19:57 -0500 Subject: Problem remotely shutting down a windows computer with python In-Reply-To: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> References: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> Message-ID: <1d6cdae305010220191567dc84@mail.gmail.com> While I have no solution for the recipe you cited, it seems like alot of trouble could be avoided by simply importing the os module and running the following command using os.system: shutdown -s Daniel Bickett On 2 Jan 2005 20:13:35 -0800, EW wrote: > I have a problem when using the python script found here: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/360649 > > It is a script to remotely shutdown a windows computer. When I use it, > the computer shuts down, but doesn't power off like with a regular > shutdown. It stays on the "Safe to power off" screen and I have to push > the power button to actually power off. Anyone know why this happens > with this script? Thanks for any help. > > Eric > > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at holdenweb.com Mon Jan 10 05:35:27 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Jan 2005 05:35:27 -0500 Subject: 20050119: quoting strings In-Reply-To: <1105346247.031739.36550@c13g2000cwb.googlegroups.com> References: <1105346247.031739.36550@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > #strings are enclosed in double quotes quotes. e.g. > a="this and that" > print a > > #multiple lines must have an escape backslash at the end: > b="this\n\ > and that" > print b > > #One can use r"" for raw string. > c=r"this\n\ > and that" > print c > > #To avoid the backslash escape, one can use triple double quotes to > print as it is: > d="""this > and > that""" > print d > > --------------- > # in Perl, strings in double quotes acts as Python's triple """. > # String is single quote is like Python's raw r"". > # Alternatively, they can be done as qq() or q() respectively, > #and the bracket can be just about any character, > # matching or not. (so that escapes can be easy avoided) > > $a=q(here, everthing is literal, $what or \n or what not.); > $b=qq[this is > what ever including variables $a that will be > evaluated, and "quotes" needn't be quoted.]; > print "$a\n$b"; > > #to see more about perl strings, do on shell prompt > #perldoc -tf qq > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html > Well, that gets that sorted out, then. Tomorrow: using single quotes. Using single quotes. The larch. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From http Fri Jan 28 23:16:35 2005 From: http (Paul Rubin) Date: 28 Jan 2005 20:16:35 -0800 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> Message-ID: <7xu0p0yin0.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > After my original flippant reply, I've been thinking some more about > this, and whether CPython can really benefit from initial notification > of a security flaw going privately to the developers first. > > And, due to CPython's release model, I really don't think it can. > > Upgrading your Python interpreter (even to a new maintenance branch > release) in a production environment is usually a fairly involved > exercise requiring a significant amount of testing, and the fact of That's true of any production environment, and yet if there's a serious flaw, you absolutely have to do it. > So, for CPython, the window of vulnerability is driven mainly by the > time to when application developers, system administrators and end > users get around to upgrading, not by the time to when a patched > version is released. No. If you're running a production system you have to stay on top of security patches and install them ASAP. If a vulnerability is bad enough, you have to close down your service until you're done installing the fix. If it takes 72 hours for the developers to make a patch, and 8 hours for you to install the patch once it's announced, then your exposure to attackers who learn of the bug from the announcement is 10 times smaller if the bug and patch are announced simultaneously than if the bug is announced immediately and the patch is released 72 hours later. > More significantly, any security problem is likely to be with a > specific function or object that has been implemented in C. False; the Cookie module example we talked about was caused by an unforeseen interaction between pure Python modules (Cookie and pickle). > So the most appropriate response to security issues in the CPython > interpreter and standard library is to notify application developers > as to what the issue is, and exactly which features it affects. It helps a lot if when the application developers are notified, a patch is already available, since once there's a lot of notification, the bug is public. > Sending a private notification to the *interpreter* developers does > nothing to assist in this. Um, it lets them get a patch ready before they notify the app developers. > If the problem is significant, then it should also be brought directly > to the attention of python-dev. It's a sure bet that attackers are monitoring python-dev and one should generally assume that they're monitoring the email of any developer for projects with serious security footprints. Notifying python-dev isn't much different than broadcasting the info on "Attack TV". Security bug reports should be made through SSL-encrypted web pages, not unencrypted email. Bugzilla already has this feature. I think it should also be added to Sourceforge, if it's not already there. If it's available in Sourceforge, then Python's Sourceforge project should enable it. Meanwhile, the OP can always open a CERT notification (www.cert.org), though it usually takes a very long time for anything to happen with those. From jtr at ofb.net Sun Jan 2 20:19:17 2005 From: jtr at ofb.net (John Reese) Date: Mon, 3 Jan 2005 01:19:17 +0000 (UTC) Subject: using HTTP Digest auth with arbitrary HTTP methods? Message-ID: Hello there. I've run into some missing functionality with HTTP Digest authentication in the 2.3 library and I was wondering if I'm just missing something. Missing functionality the first: urllib2 1a. You can add "handlers" to your opener indicating that you want to use HTTP Digest auth. This is nice way to handle it, but I don't see any way to use a custom verb in your URLOpener -- it always uses either GET or POST depending on whether you provided data. Is there any way to specify an arbitrary method? This would allow urllib2 to be used to write WebDAV clients. 1b. HTTPDigestAuthHandler is initialized with an HTTPPasswordMgr object, which unfortunately deals in cleartext passwords. Digest authentication can be computed using only a hash of username, password, and realm; it would be nice if there was an alternate version of HTTPPasswordMgr that let you deal in hashes instead of or in addition to plaintext passwords. Missing functionality the second: httplib. 2a. httplib.HTTPConnection lets you execute arbitrary HTTP methods with arbitrary headers and data; this is the missing functionality in 1a above. However, you have to deal with following redirects and authentication and so forth yourself. Is there any way to use the flexibility of HTTPConnection.request(method, url[, body[, headers]]) with the convenience of the chains of urllib2 handlers? The upshot is what I'm trying to do is write a WebDAV-using DAV client library, and I almost have everything I need to do it; the problem is I can't find an easy way to do digest authentication for arbitrary HTTP methods. WebDAV (RFC 2518), for those not familiar, is an extension to HTTP that defines some new methods and settles the semantics of some existing but rarely implemented HTTP methods (PUT and DELETE, for example) to define something similar to a file system. It's intended for things like letting a group of people author a web site. From danb_83 at yahoo.com Sun Jan 9 17:04:40 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 9 Jan 2005 14:04:40 -0800 Subject: else condition in list comprehension References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: <1105305000.052714.188980@c13g2000cwb.googlegroups.com> Luis M. Gonzalez wrote: > Hi there, > > I'd like to know if there is a way to add and else condition into a > list comprehension. I'm sure that I read somewhere an easy way to do > it, but I forgot it and now I can't find it... > > for example: > z=[i+2 for i in range(10) if i%2==0] > what if I want i [sic] to be "i-2" if i%2 is not equal to 0? z = [i + (2, -2)[i % 2] for i in range(10)] In general, the expression "T if C is true, or F if C is false" can be written as (F, T)[bool(C)]. (If you know that C will always be either 0 or 1, as is the case here, the "bool" is redundant.) Unless, of course, either F or T has side effects. For a side-effect free expression, you can use (C and [T] or [F])[0] or one of the many other ternary operator substitutes. (Search for PEP 308.) From jeff at ccvcorp.com Tue Jan 11 20:50:09 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 11 Jan 2005 17:50:09 -0800 Subject: python guy ide In-Reply-To: <1105491287.384930.167400@z14g2000cwz.googlegroups.com> References: <41e46d24@usenet01.boi.hp.com> <1105491287.384930.167400@z14g2000cwz.googlegroups.com> Message-ID: <10u908d5llrj528@corp.supernews.com> Kartic wrote: > SPE is great, > but it stops responding when I try to run my wxPython apps (probably > something I am doing!). I don't know about SPE specifically, but this is a common issue with a lot of lower-end IDEs. The IDE is a GUI application, which operates using an event loop. If the IDE runs user code in the same process that it runs in itself, and if that user code also contains some sort of event loop, then the two loops will interfere with each other (or rather, the first loop won't run until the inner loop quits, which tends to make Windows unhappy...) Most commercial IDEs, I believe, run user code in a separate process and thus avoid this problem. I *think* that IDLE now runs user code out-of-process as well, but I'm not sure about that. I can't afford to pay for an IDE for hobby purposes, so when I'm writing GUI apps, I also keep a command shell open. Edit, save, alt-tab to command shell, uparrow-enter to run program... not as convenient as a toolbar button or hotkey, but it works. Jeff Shannon Technician/Programmer Credit International From Scott.Daniels at Acm.Org Fri Jan 14 17:18:54 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 14 Jan 2005 14:18:54 -0800 Subject: query python env In-Reply-To: References: Message-ID: <41e841bb$1@nntp0.pdx.net> David Bear wrote: > How does one query the python environment, ie pythonhome, pythonpath, > etc. > > also, are there any HOWTO's on keeping multiple versions of python > happy? In general, (and in this case) the answer is system-specific. You need to explain (A) what operating system, and (B) what you mean by multiple Python versions. For example, for Windows 2K/XP, As long as you try for only distinct major versions (2.2.x, 2.3.x, 2.4.x). There should not be a problem. The primary issues are where (and how) does your system get to the python files. --Scott David Daniels Scott.Daniels at Acm.Org From bokr at oz.net Wed Jan 12 20:24:29 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 01:24:29 GMT Subject: Refactoring; arbitrary expression in lists References: Message-ID: <41e5cb07.701137402@news.oz.net> On Wed, 12 Jan 2005 18:16:23 +0000, Frans Englich wrote: > >As continuation to a previous thread, "PyChecker messages", I have a question >regarding code refactoring which the following snippet leads to: > >> > runner.py:200: Function (detectMimeType) has too many returns (11) >> > >> > The function is simply a long "else-if" clause, branching out to >> > different return statements. What's wrong? It's simply a "probably ugly >> > code" advice? >> >> That is also advice. Generally you use a dict of functions, or some other >> structure to lookup what you want to do. > >More specifically, my function looks like this: > >#-------------------------------------------------------------- >def detectMimeType( filename ): > > extension = filename[-3:] > basename = os.path.basename(filename) > > if extension == "php": > return "application/x-php" > > elif extension == "cpp" or extension.endswith("cc"): > return "text/x-c++-src" ># etcetera > elif extension == "xsl": > return "text/xsl" > > elif basename.find( "Makefile" ) != -1: > return "text/x-makefile" > else: > raise NoMimeError >#-------------------------------------------------------------- >(don't bother if the MIME detection looks like stone age, it's temporary until >PyXDG gets support for the XDG mime type spec..) > >I'm now wondering if it's possible to write this in a more compact way, such >that the if-clause isn't necessary? Of course, the current code works, but >perhaps it could be prettier. > >I'm thinking along the lines of nested lists, but what is the obstacle for me >is that both the test and return statement are simple expressions; not >functions or a particular data type. Any ideas? > I think I would refactor along these lines: (untested) extensiondict = dict( php = 'application/x-php', cpp = 'text/x-c-src', # etcetera xsl = 'test/xsl' ) def detectMimeType(filename): extension = os.path.splitext(filename)[1].replace('.', '') try: return extensiondict[extension] except KeyError: basename = os.path.basename(filename) if "Makefile" in basename: return 'text/x-makefile' # XXX case sensitivity? raise NoMimeError Regards, Bengt Richter From harold.fellermann at upf.edu Tue Jan 11 13:36:53 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 11 Jan 2005 19:36:53 +0100 Subject: exporting from Tkinter Canvas object in PNG In-Reply-To: <41E4178F.4050804@free.fr> References: <41E4178F.4050804@free.fr> Message-ID: On 11.01.2005, at 19:14, Nicolas Pourcelot wrote: > Hello, > I'm new to this mailing list and quite to Pyhon too. > I would like to know how to export the contain of the Canvas object > (Tkinter) in a PNG file ? > Thanks :) > Nicolas Pourcelot > -- > http://mail.python.org/mailman/listinfo/python-list you can make a postscript dump using >>> canvas = Tkinter.Canvas(master) >>> canvas.postscript(file="your_file_name.ps") If you have ImageMagick, you can later use % convert your_file_name.ps your_file_name.png on the comand line, if you want to have png. - harold - -- Science is to see what everybody else has seen, and think what nobody else has thought. -- From fredrik at pythonware.com Mon Jan 31 02:02:11 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 31 Jan 2005 08:02:11 +0100 Subject: a Python bug in processing __del__ method ?? References: <1107154011.859866.23480@z14g2000cwz.googlegroups.com> Message-ID: Baoqiu Cui wrote: > The error returned is this: > > $ python bug.py > Exception exceptions.AttributeError: "'NoneType' object has no > attribute 'population'" in <__main__.Person instance at 0xa0c9fec>> ignored > > However, if I rename variable name 'peter' to something like 'peter1' > or 'david', the error is gone. Looks to me the > error only happens to variable name 'peter'. > > Does anyone know what is wrong? Is this a bug only on Cygwin? it is not a bug, and the documentation has the answer: language reference -> index -> __del__ http://docs.python.org/ref/customization.html#l2h-175 Warning: Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead. Also, when __del__() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the __del__() method may already have been deleted. For this reason, __del__() methods should do the absolute minimum needed to maintain external invariants. if you absolutely need to have reliable access to globals, you need to make sure they're available as instance variables, or are bound in some other way. From kumar.rakesh at gmail.com Sat Jan 29 08:40:26 2005 From: kumar.rakesh at gmail.com (Rakesh Kumar) Date: 29 Jan 2005 05:40:26 -0800 Subject: Coding style article with interesting section on white space References: Message-ID: <1107006026.348724.80080@z14g2000cwz.googlegroups.com> Thanx Nick From fredrik at pythonware.com Mon Jan 17 04:54:38 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Jan 2005 10:54:38 +0100 Subject: [perl-python] 20050116 defining a function References: <1105886753.149519.194980@z14g2000cwz.googlegroups.com> Message-ID: Ala Qumsieh wrote: > > ? my $n= @_[0]; > > Do you ever test your code before making fun of yourself in front of millions? this perl usability study is getting more and more interesting. who needs television? From duncan.booth at invalid.invalid Mon Jan 10 11:50:16 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Jan 2005 16:50:16 GMT Subject: syntax error in eval() References: Message-ID: harold fellermann wrote: > Python 2.4 (#1, Dec 30 2004, 08:00:10) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> class X : pass > ... > >>> attrname = "attr" > >>> eval("X.%s = val" % attrname , {"X":X, "val":5}) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1 > X.attr = val > ^ > SyntaxError: invalid syntax > > > Does anyone have a clue what might be wrong? Thanks in advance. What you are doing wrong is attempting to use eval before exhausting all the simpler techniques. Why not just call 'setattr'? >>> setattr(X, 'attr', 5) BTW, the syntax error is because eval evaluates an expression and an assignment statement is a statement not an expression. From marklists at mceahern.com Thu Jan 20 20:07:24 2005 From: marklists at mceahern.com (Mark McEahern) Date: Thu, 20 Jan 2005 19:07:24 -0600 Subject: Print a string in binary format In-Reply-To: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> Message-ID: <41F055CC.90800@mceahern.com> neutrino wrote: >Greetings to the Python gurus, > >I have a binary file and wish to see the "raw" content of it. So I open >it in binary mode, and read one byte at a time to a variable, which >will be of the string type. Now the problem is how to print the binary >format of that charater to the standard output. It seems a common task >but I just cannot find the appropriate method from the documentation. >Thanks a lot. > How is this *not* what you want: import sys f = open(filename, 'rb') data = f.read(1) while data: sys.stdout.write(data) data = f.read(1) Of course, that's the long version of: print open(filename, 'rb').read() // m From stian at soiland.no Sun Jan 23 16:36:56 2005 From: stian at soiland.no (Stian Soiland) Date: Sun, 23 Jan 2005 22:36:56 +0100 Subject: Keyboard problems with Python shell over SSH In-Reply-To: <8h38v0h322qokr7cgmen17805kbldhi87o@4ax.com> References: <8h38v0h322qokr7cgmen17805kbldhi87o@4ax.com> Message-ID: P? 23. jan 2005 kl. 21:55 skrev Nils Emil P.Larsen: > > I connect to my server using SSH and then run 'python' to enter the > shell. I can't use the arrow buttons (up, down, left and right). > Instead I get this ^[[A , ^[[B, ^[[C or ^[[D. Your Python installation is probably compiled without readline support. It is the readline library that enables arrow keys and Ctrl-R and stuff to work. Try "import readline" - you will probably get an error. I won't go into detail on how to install readline on your OS. In Linuxes, it might be apt-get install readline-dev. In other OSes, different licensing and packaging issues might have prevented readline's precense. -- -- Stian S?iland You can't say civilization don't Trondheim, Norway advance, however, for in every war http://www.soiland.no/ they kill you in a new way. [Rogers] =/\= From bob_smith_17280 at hotmail.com Sun Jan 16 20:57:27 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Sun, 16 Jan 2005 20:57:27 -0500 Subject: python mode indentation problem In-Reply-To: <1105842678.044409.270450@z14g2000cwz.googlegroups.com> References: <1105802644.939051.229990@f14g2000cwb.googlegroups.com> <1105842678.044409.270450@z14g2000cwz.googlegroups.com> Message-ID: Xah Lee wrote: > ? ok, here's the ordeal. > ? > ? for i in range(5): > ? print i > ? for i in range(2): > ? print i, 'tt' > ? for i in [3]: > ? print i > ? for i in [32]: > ? print i > ? > ? # 1 level, 4 space > ? # 2 level, 1 tab > ? # 3 level, 1 tab, 4 spaces > ? # 4 level, 2 tabs. > ? > ? who the fuck coded the python mode in emacs? fuckhead please peruse: > ? http://xahlee.org/UnixResource_dir/writ/responsible_license.html I hope you never need a favor or interview for a job with someone who reads news groups. You're committing eSuicide by posting insulting rants such as this. All you accomplish is to isolate yourself. Try to be friendly. Ideas are only half the battle... presentation is the other half. You have some good and valid ideas, but your presentation is offensive and condescending. Your ideas are like golden coins wrapped in horse shit. Personally, I've had enough of your horse shit... perhaps I speak for others as well. From ptmcg at austin.rr._bogus_.com Wed Jan 12 13:10:14 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 12 Jan 2005 18:10:14 GMT Subject: counting items References: Message-ID: "It's me" wrote in message news:ukdFd.10645$5R.2000 at newssvr21.news.prodigy.com... > Okay, I give up. > > What's the best way to count number of items in a list? > > For instance, > > a=[[1,2,4],4,5,[2,3]] > > I want to know how many items are there in a (answer should be 7 - I don't > want it to be 4) > I've sure seen a lot of questions about the flattening of lists. I found this version of flatten somewhere, I thought I got it from the Python Cookbook but I can't find it now. Perhaps it was posted here on c.l.py. I *don't* claim authorship, I'm merely an admirer of such a clean-looking solution. def flatten(a): if not isinstance(a, (tuple,list)): return [a] if len(a)==0: return [] return flatten(a[0])+flatten(a[1:]) a = [[1, 2, 4], 4, 5, [2, 3], 6, [6], [], 'askjdf'] print len(flatten(a)) gives the value 10. Considering how often this comes up, might there be a place for some sort of flatten() routine in the std dist, perhaps itertools? -- Paul From steven.bethard at gmail.com Sun Jan 30 17:52:43 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 30 Jan 2005 15:52:43 -0700 Subject: how do i create such a thing? In-Reply-To: References: Message-ID: <7vGdnTsopcKl-GDcRVn-rw@comcast.com> Pedro Werneck wrote: > If you need direct access to some atribute, use object.__getattribute__. > >>>>class DefaultAttr(object): > > ... def __init__(self, default): > ... self.default = default > ... def __getattribute__(self, name): > ... try: > ... value = object.__getattribute__(self, name) > ... except AttributeError: > ... value = self.default > ... return value > ... > >>>>x = DefaultAttr(99) >>>>print x.a > 99 > >>>>x.a = 10 >>>>print x.a > 10 Of if you only want to deal with the case where the attribute doesn't exist, you can use getattr, which gets called when the attribute can't be found anywhere else: py> class DefaultAttr(object): ... def __init__(self, default): ... self.default = default ... def __getattr__(self, name): ... return self.default ... py> x = DefaultAttr(99) py> x.a 99 py> x.a = 10 py> x.a 10 Steve From as006d4848 at blueyonder.co.uk Fri Jan 28 10:30:19 2005 From: as006d4848 at blueyonder.co.uk (Philip Smith) Date: Fri, 28 Jan 2005 15:30:19 GMT Subject: Elliptic Code References: Message-ID: thanks for the suggestion I understand the algorithm quite well but how to code the multiplication stage most efficiently in python eludes me. William Stein's code is obviously not high performance because in the region where ecm should do well (30-40 dec digits) my python implementation of the rho algorithm blows it away. In terms of factoring implementations generally (in python) I think nzmath's mpqs is brilliant - and it has such a small footprint I can run it in 10 threads at once. anyway - I'll have a look at MIRACL (I have the library but have never used it yet. Phil wrote in message news:m3acqtu6r1.fsf at localhost.localdomain... > "Philip Smith" writes: >> Does anyone have/know of a python implementation of the elliptic curve >> factoring algorithm (lenstra) which is both: >> >> simply and cleanly coded >> functional > > It's not in Python but take a look at Mike Scott's C++ implementation > in MIRACL, > > http://indigo.ie/~mscott/ > > It's the simplest and most direct implementation I know of, just the > bare essentials. It could probably be translated into Python pretty > straightforwardly. > >> I'm aware of William Stein's code (from elementary number theory >> book) but I don't understand his coding style and the algorithm >> doesn't seem to work efficiently. > > A high performance implementation means complicated code, e.g. Peter > Montgomery has done a few of those. If it's for instructional > purposes I think the MIRACL version is far more understandable even if > it's slower. > > If you mean you don't understand the algorithm, try Neal Koblitz's > book "A Course in Number Theory and Cryptography". It has no code but > it explains the algorithm in a pretty accessible way. From phr at localhost.localdomain Tue Jan 25 20:40:39 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Wed, 26 Jan 2005 01:40:39 GMT Subject: Help! Host is reluctant to install Python References: Message-ID: Daniel Bickett writes: > I've been trying to convince my host to install python/mod_python on > his server for a while now, however there are a number of reasons he > is reluctant to do so, which I will outline here: I'm surprised that you're getting such detailed answers from him. Usually, low-cost web hosts want to offer a one-size-fits-all package that requires minimal interaction with customers. If you're paying $10 a month for hosting and a host admin has to spend 1 hour sending you email, that probably wipes out at least 6 months of profits from you as a customer. If you want custom service you usually have to pay a lo tmore. > 1. His major reason is optimization. He uses Zend's optimization of > PHP as an example, and he has stated that python is rather resource > consuming. Maybe that's true, though if there's enough customer demand for Python anyway, the answer is to buy more equipment and pass the costs on. The real problem is there's not enough demand. > 2. Another one of his points is that he is unexperienced in installing > python, and he would not know how to do it securely. By 'securely', > I'm assuming he means disallowing a malicious (or ignorant) user from > harming the server That's a serious issue too, and "securely" means not just securing against the service's own customers, but also against outside attacks. I have no idea how carefully mod_python has been audited. I don't use it myself, though I do run some Python cgi's. > I have no experience with this sort of thing, so I'm asking a little > assistance in the direction of any documents or websites (or what have > you) I could show him in order to answer some of these questions, or > perhaps even some unspoken ones -- anything worth noting. (all I'm > really going to do is link him to this thread once it has accumulated > any answers) I think you should look into some type of virtual hosting that gives you more ability to install your own software. Typing "uml hosting" (UML is user-mode Linux) into Google finds a lot of such services. If you find one that you like, post it here, I'm interested in this myself. From wittempj at hotmail.com Sun Jan 23 11:29:16 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 23 Jan 2005 08:29:16 -0800 Subject: best way to do a series of regexp checks with groups In-Reply-To: References: Message-ID: <1106497756.578620.152920@z14g2000cwz.googlegroups.com> what about something like this? >>> import re >>> m = re.match(r"""(?Padd|mult) (?P\d+) (?P\d+)""", 'add 3 5') >>> from operator import add, mul >>> op = {'add': add, 'mult: mul} >>> op[m.groupdict()['operator']](int(m.groupdict()['int_1']), int(m.groupdict()['int_2'])) 8 From philippecmartin at sbcglobal.net Fri Jan 7 10:18:05 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Fri, 07 Jan 2005 16:18:05 +0100 Subject: Tkinter: passing parameters to menu commands (looping through a list) Message-ID: <1105111085.9221.28.camel@localhost> >>l_dec.add_command(label=i, command=lambda x=i: self.__Dec(x)) Woof! I'd better do my homework on lambda ! Thanks, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From andybak at gmail.com Fri Jan 14 12:53:39 2005 From: andybak at gmail.com (andybak at gmail.com) Date: 14 Jan 2005 09:53:39 -0800 Subject: Integration with java In-Reply-To: <1105723092.315634.181590@z14g2000cwz.googlegroups.com> References: <1105723092.315634.181590@z14g2000cwz.googlegroups.com> Message-ID: <1105725219.247286.312590@f14g2000cwb.googlegroups.com> How about this? http://jpype.sourceforge.net/ (I haven't used it myself) From kenneth.m.mcdonald at sbcglobal.net Mon Jan 31 16:04:36 2005 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Mon, 31 Jan 2005 21:04:36 GMT Subject: Request for Feedback; a module making it easier to use regular expressions. Message-ID: <310120051504352505%kenneth.m.mcdonald@sbcglobal.net> I'm working on the 0.8 release of my 'rex' module, and would appreciate feedback, suggestions, and criticism as I work towards finalizing the API and feature sets. rex is a module intended to make regular expressions easier to create and use (and in my experience as a regular expression user, it makes them MUCH easier to create and use.) I'm still working on formal documentation, and in any case, such documentation isn't necessarily the easiest way to learn rex. So, I've appended below a rex interactive session which was then annotated with explanations of the features being used. I believe it presents a reasonably good view of what rex can do. If you have time, please read it, and then send your feedback via email. Unfortunately, I do not currently have time to keep track of everything on comp.lang.python. Thanks, Ken McDonald ============================================= What follows is an illustration by example of how the 'rex' module works, for those already knowledgable of regular expressions as used in Python's 're' (or similar) regular expressions package. It consists of a quick explanation of a rex feature, followed by an interactive demo of that feature. You need to understand a couple of quick points to understand rex and the demo. 1) To distinguish between standard regular expressions as constructed by hand and used with the 're' package, and regular expressions constructed by and used in 'rex', I'll call the former 'regexps', and the latter 'rexps'. 2) The Rexp class, of which every rexp is an instance, is simply a subclass of Python's regular string class, with some modified functionality (for example, the __add__ method has been changed to modify the action of the '+' operation), and many more operators and methods. I'm not sure this was the wisest thing to do, but it sure helps when trying to relate rexps to regexps; just construct a rexp interactively or in a program and print it, and in either case you'll see the underlying string that is passed to the 're' module functions and methods. On to the tutorial. 'rex' is designed have few public names, so the easiest way to use it is to import all the names: >>> from rex import * The most basic rex function is PATTERN, which simply takes a string or strings, and produces a rexp which will match exactly the argument strings when used to match or search text. As mentioned above, what you see printed as the result of executing PATTERN is the string that will be (invisibly) passed to 're' as a regexp string. >>> PATTERN("abc") 'abc' If given more than one argument, PATTERN will concatenate them into a single rexp. >>> PATTERN("abc", "d") 'abcd' The other rex function which converts standard strings to rexps is CHARSET, which produces patterns which match a single character in searched text if that character is in a set of characters defined by the CHARSET operation. This is the equivalent of the regexp [...] notation. Every character in a string passed to CHARSET will end up in the resulting set of characters. >>> CHARSET("ab") '[ab]' If CHARSET is passed more than one string, all characters in all arguments are included in the result rexp. >>> CHARSET("ab", "cd") '[abcd]' If an argument to CHARSET is a two-tuple of characters, it is taken as indicating the range of characters between and including those two characters. This is the same as the regexp [a-z] type notation. For example, this defines a rexp matching any single consonant. >>> CHARSET('bcd', 'fgh', ('j', 'n'), ('p', 't'), 'vwxz') '[bcdfghj-np-tvwxz]' When using CHARSET (or any other rexp operation), you do _not_ need to worry about escaping any characters which have special meanings in regexps; that is handled automatically. For example, in the follwing character set containing square brackets, a - sign, and a backslash, we have to escape the backslash only because it has a special meaning in normal Python strings. This could be avoided by using raw strings. The other three characters, which have special meaning in regexps, would have to be escaped if building this character set by hand. >>> CHARSET('[]-\\') '[\\[\\]\\-\\\\]' The result above is what you'd need to type using re and regexps to directly define this character set. Think you can get it right the first time? CHARSET provides a number of useful attributes defining commonly used character sets. Some of these are defined using special sequences defined in regexp syntax, others are defined as standard character sets. In all cases, the common factor is that CHARSET attributes all define patterns matching a _single_ character. Here are a few examples: >>> CHARSET.digit '\\d' >>> CHARSET.alphanum '\\w' >>> CHARSET.uspunctuation '[~`!@#$%\\^&*()_\\-+={\\[}\\]|\\\\:;"\'<,>.?/]' Character sets can be negated using the '~' operator. Here is a rexp which matches anything _except_ a digit. >>> ~CHARSET(('0','9')) '[^0-9]' Remember from above that PATTERN constructs rexps out of literals, and also concatenates multiple arguments to form a rexp which matches if all of those arguments match in sequence. However, the arguments to PATTERN don't have to be just strings; they can be other rexps, which are concatenated correctly to produce a new rexp. The following expression produces a rexp which matches the string 'abc' followed by any of 'd', 'e', or 'f'. >>> PATTERN("abc", CHARSET("def")) 'abc[def]' Instead of passing multiple arguments to PATTERN to obtain concatenation, you can simple use the '+' operator, which has exactly the same effect, but in many circumstances may produce easier-to-read code. However, if '+' is used in this way, its left operand _must_ be a rexp; a plain string won't work. >>> PATTERN("abc") + CHARSET("def") 'abc[def]' To obtain an alternation rexp--one which matches if any one of several other rexps match--we use the ANYONEOF function. This is equivalent to the "|" character in regexp notation. >>> ANYONEOF("a", "b", "c") 'a|b|c' As with PATTERN and '+', the '|' operator may be used in place of ANYONEOF to obtain alternation. As usual, the left-hand operand must be a rexp: >>> PATTERN("a") | "b" | "c" 'a|b|c' Note in the above that only the _first_ operand needs to be a rexp; this is because the first and second operands combine to form a rexp, and that rexp then becomes the left operand for the second '|' operator. Now we come to a very significant difference between regexps and rexps; the ability to combine smaller expressions into larger expressions. Below are two regexps, the first matching any one of 'a' or 'b' or 'c', the second matching 'd', 'e', or 'f'. It would be nice if there were an easy way to combine them to match strings of the form ('a' or 'b' or 'c') followed by ('d' or 'e' or 'f') using simple string addition: >>> "a|b|c" + "d|e|f" 'a|b|cd|e|f' Unfortunately, this produces a regexp which matches any one of 'a', 'b', 'cd', 'e', or 'f'. The simplest way I know of to achieve the desired result in this case is something like "("+"a|b|c"+")("+"d|e|f"+")". This is not exactly pretty, or easy to type. Something like this isn't necessary when dealing with all string literals as above, but what if the two operands were other regexps? Then you would have to type something like "("+X+")("+Y+")". This is much clearer useing rexps: >>> PATTERN(ANYONEOF("a","b", "c"), ANYONEOF("d", "e", "f")) '(?:a|b|c)(?:d|e|f)' or, shortening the expression using the '+' operator: >>> ANYONEOF("a", "b", "c") + ANYONEOF("d", "e", "f") '(?:a|b|c)(?:d|e|f)' Note that when rexps are put together like this, the parentheses used for grouping are 'numberless' parentheses--they will not be considered when extracting match subresults using numbered groups. Since the insertion of these parentheses in the produced regexp are invisible to the rex user, this is exactly what is desired. Precedence works as you might expect, with '+' having higher precedence than '|' (though the example below is rather simple as an illustration of this.) >>> PATTERN("a") + "b" | "e" + "f" 'ab|ef' To match a pattern 0 or more times, use the ZEROORMORE function. This is analogous to the regexp '*' character. Note that parentheses are inserted to ensure the function applies to all of what you pass in. >>> ZEROORMORE("a") '(?:a)*' >>> ZEROORMORE("abc") '(?:abc)*' ONEORMORE matches a sequence of one or more rexps, and is like the "+" regexp operator. >>> ONEORMORE("abc") '(?:abc)+' The short way of obtaining repetition, and of matching more limited repetitions of a pattern, is to use the "*" operator. This expression is the same as ZEROORMORE("abc"): >>> PATTERN("abc")*0 '(?:abc)*' ...and this is the same as ONEORMORE("abc"): >>> PATTERN("abc")*1 '(?:abc)+' If a negative sign precedes the match number, it indicates the resulting rexp should match _no more_ than that many repetitions of the (positive) number. This matches anywhere from 0 to 3 repetitions of "abc": >>> PATTERN("abc")*-3 '(?:abc){0,3}' Use a two-tuple to specify both an upper and lower bound. Match anywhere from 2 to five repetitions of "abc". >>> PATTERN("abc")*(2,5) '(?:abc){2,5}' The OPTIONAL function indicates that the argument rexp is optional (the containing pattern will match whether or not the rexp produced by OPTIONAL matches.) >>> OPTIONAL("-") '(?:\\-)?' There is no shorthand form for OPTIONAL. However, the following is semantically identical, though it produces a different regexp: >>> PATTERN("-")*(0,1) '(?:\\-){0,1}' Let's look a bit more at how easy it is to combine rexps into more complex rexps. PATTERN provides an attribute defining a rexp which matches floating-point numbers (without exponent): >>> PATTERN.float '(?:\\+|\\-)?\\d+(?:\\.\\d*)?' Using this to build a complex number matcher (assuming no whitespace) is trivial: >>> PATTERN.float + ANYONEOF("+", "-") + PATTERN.float + "i" '(?:\\+|\\-)?\\d+(?:\\.\\d*)?(?:\\+|\\-)(?:\\+|\\-)?\\d+(?:\\.\\d*)?i' I think the rexp construct is a little easier to understand and modify than the produced regexp :-) What if we want to extract the real and imaginary parts of any complex number we happen to match? To do this, we name the rexp subpatterns which match the numeric portions of the complex number, by indexing them with the desired name. This corresponds to re's named groups facility for regexps, using the (?P...) notation. >>> complexrexp = PATTERN.float['re'] + ANYONEOF("+", "-") + PATTERN.float['im'] + "i" >>> complexresult = complexrexp.match("-3.14+2.17i") By the way, here's the regexp resulting from the above rexp. >>> complexrexp '(?P(?:\\+|\\-)?\\d+(?:\\.\\d*)?)(?:\\+|\\-)(?P(?:\\+|\\-)?\\d+(?:\\.\\d*)?)i' Would you really like to write it out by hand? To extract the what matched the named group, we simply index the match result: >>> complexresult['re'] '-3.14' I highly recommend using named groups when constructing rexps; it makes code more readable and less error-prone. However, if you do want to use a numbered group for some reason, use the group() method on an existing rexp: >>> PATTERN.float.group() + ANYONEOF("+", "-") + PATTERN.float.group() + "i" '((?:\\+|\\-)?\\d+(?:\\.\\d*)?)(?:\\+|\\-)((?:\\+|\\-)?\\d+(?:\\.\\d*)?)i' If a match fails, we get a MatchResult which evaluates to False when used as a boolean: >>> complexresult = complexrexp.match("-3.14*2.17i") >>> complexresult >>> bool(complexresult) False Attempting to extract a subgroup from a failed match raises a KeyError and prints an appropriate error message. >>> complexresult['re'] Traceback (most recent call last): File "", line 1, in ? File "/local/python/packages/rex/__init__.py", line 508, in __getitem__ return self.get(key) File "/local/python/packages/rex/__init__.py", line 518, in get else: raise KeyError, "Invalid group index: "+ `key` + " (a failed match result only has one group, indexed by 0)." KeyError: "Invalid group index: 're' (a failed match result only has one group, indexed by 0)." However, extracting group 0 (which in a successful match always represents the entirety of the matched text) of a failed MatchResult still results in the entire string against which the match was attempted. This may seem pointless now, but will be very useful when we get into iterative searches using rexps. >>> complexresult[0] '-3.14*2.17i' We can do some nice things with named groups which cannot be accomplished with standard regexps. The keys() method returns the names of all named subgroups which participated in a match (but does not return the names of subgroups which did _not_ participate in the match, such as a subgroup contained in a failed OPTIONAL rexp): >>> complexresult.keys() ['re', 'im'] In addition, if a named group matches the _entire_ matched string, then the name of that group can be obtained with the 'getname' method. This is useful for determining which of a number top-level alternative rexps matched. >>> altrexp = PATTERN.float['number'] | PATTERN.word['symbol'] >>> altrexp.match("3.14").getname() 'number' >>> altrexp.match("abc").getname() 'symbol' Note that if more than one named group matches the entire matched substring, then getname() will return one of the appropriate names, but which one is not predictable. Lesser-used pattern matching facilities have not been neglected. Non-greedy reptition can be expressed in the same way as standard (greedy) repetition, by using the ** operator in place of *: >>> PATTERN("a")**0 '(?:a)*?' >>> PATTERN("a")**1 '(?:a)+?' In this next example, the big number in the resulting regexp is sys.MAXINT. This is the closest I know how to express "three to infinity" in a regexp pattern. >>> PATTERN("a")**3 '(?:a){3,2147483647}?' Lookahead and lookback assertions are supported with the '+' and '-' unary operators: >>> +PATTERN("a") '(?=a)' >>> -PATTERN("a") '(?<=a)' Both types of assertions can be negated by prepending with a tilde, as can be done with CHARSET rexps: >>> ~-PATTERN("a") '(?>> ~+PATTERN("a") '(?!a)' Any regular expression can be considered as denoting the set of all strings which it matches. (Or, for those who've taken a formal class on RE's and finite automate, the set of strings which it "generates".) So, matching a piece of text against a regular expression is really the same thing as asking if that text is in the set of strings "generated" by the regular expression. Rexps provide a nice way of doing this using Python's "in" operator. The examples below ask if a couple of strings are in the set of strings consisting of a sequence of one or more 'a' characters: >>> "aa" in PATTERN("a")*1 True >>> "ab" in PATTERN("a")*1 False Searching text is done using a rexp's search() method. Let's find the string "cd" in the text "abcdef": >>> searchresult = PATTERN("cd").search("abcdef") We know the search succeeded by evaluating the MatchResult as a boolean... >>> bool(searchresult) True ...and can easily extract the start and end positions of the matched string, and the string itself (which might be useful if the search rexp was not a literal): >>> searchresult.start(0) 2 >>> searchresult.end(0) 4 >>> searchresult[0] 'cd' Iterative searching--that is, searching for _all_ instances in a piece of text matched by a regular expression--can be a bit awkward when using regexps. It is very easy when using rexps. The example below uses the fact that __str__ in a MatchResult object is defined so that str(matchresult) returns the entire substring matched by the MatchResult; str() is mapped over the sequence of MatchResult instances generated by itersearch() to get a list of the matched substrings. >>> map(str, CHARSET.digit.itersearch("ab0c9de7")) ['0', '9', '7'] 'itersearch' is a generator function, which means that it only computes and returns MatchResult instances as they are requested by the enclosing loop. So, itersearch() can be used in a memory-efficient manner even on very large pieces of text. 'itersearch' can also be used more flexibly. If defines an optional paramater named 'matched' which defaults to True and indicates that only successful MatchResults should be returned. If we perform a search with this parameter set to False, then only _failing_ MatchResults will be returned... >>> map(str, CHARSET.digit.itersearch("ab0c9de7", matched=False)) ['ab', 'c', 'de'] ...and if None is passed as the value of 'matched', then both successful and failed MatchResults will be returned: >>> map(str, CHARSET.digit.itersearch("ab0c9de7", matched=None)) ['ab', '0', 'c', '9', 'de', '7'] We can still determine which of these results are failures and which are successes by using the MatchResults as a boolean: >>> map(bool, CHARSET.digit.itersearch("ab0c9de7", matched=None)) [False, True, False, True, False, True] This leads to a great little idiom for going through _all_ the text of a string, and processing each part as appropriate (the bit of Python code below is not part of the interactive session): for result in myRexp.itersearch(myText, matched=None): if result: ...process the successful match... else: ...process the failed match... Rexps also have a 'replace' method, to replace found text with other text. Let's replace all digits in a string with the word "DIGIT": >>> CHARSET.digit.replace("DIGIT", "ab0c9de7") 'abDIGITcDIGITdeDIGIT' More specific replacements can be achieved by passing in a dictionary as the replace argument. Any matched substring must have a key defined in the dictionary (else a KeyError will be thrown), and is replaced with the value associated with that key: >>> CHARSET.digit.replace({"9":"NINE", "0":"ZERO", "7":"SEVEN"}, "ab0c9de7") 'abZEROcNINEdeSEVEN' For the ultimate in flexibility, we can pass in a function as the replace argument. Whenever a match is found, its MatchResult will be passed as an argument to the function, and the result of the function will be used as the replacement value. Here's an example which increments the integer interpretation of each digit in some text by 1. >>> def incr(matchresult): ... return str(1+int(matchresult[0])) ... >>> CHARSET.digit.replace(incr, "ab0c9de7") 'ab1c10de8' From fuzzyman at gmail.com Mon Jan 24 06:06:39 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Jan 2005 03:06:39 -0800 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> Message-ID: <1106564799.011057.181280@c13g2000cwb.googlegroups.com> I also feel the lack of a standard cryptography module in the core... even a *basic* one. At least rotor provided that, before it was deprecated. I (along with many other python users) write CGIs where the only extension modules that I can use are either pure python, or ones my web hoster is willing to install. Luckily my hoster will install modules without too much fuss - others aren't so lucky. Cryptography is a pretty 'standard' requirement these days.. and IMHO ought to be in the 'standard library'. Without commenting (or reading properly) on this exchange... it does seem that many of ''s contributions have been very bad tempered recently. Hmmm..... Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From reinhold-birkenfeld-nospam at wolke7.net Fri Jan 14 14:13:48 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 14 Jan 2005 20:13:48 +0100 Subject: Octal notation: severe deprecation In-Reply-To: <41e6f606.777680996@news.oz.net> References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> <39ednWfqlrgB6HvcRVn-iA@powergate.ca> <41e6f606.777680996@news.oz.net> Message-ID: <34qjvcF4dkctuU2@individual.net> Bengt Richter wrote: > On Thu, 13 Jan 2005 08:18:25 -0500, Peter Hansen wrote: > >>and-google at doxdesk.com wrote: >>> In Mythical Future Python I would like to be able to use any base in >>> integer literals, which would be better. Example random syntax: >>> >>> flags= 2x00011010101001 >>> umask= 8x664 >>> answer= 10x42 >>> addr= 16x0E800004 # 16x == 0x >>> gunk= 36x8H6Z9A0X >> >>I think I kinda like this idea. Allowing arbitrary values, >>however, would probably be pointless, as there are very >>few bases in common enough use that a language should make >>it easy to write literals in any of them. So I think "36x" >>is silly, and would suggest limiting this to 2, 8, 10, and >>16. At the very least, a range of 2-16 should be used. >>(It would be cute but pointless to allow 1x000000000. :-) >> > My concern is negative numbers when you are interested in the > bits of a typical twos-complement number. (BTW, please don't tell me > that's platform-specific hardware oriented stuff: Two's complement is > a fine abstraction for interpreting a bit vector, which is another > fine abstraction ;-) > > One way to do it consistently is to have a sign digit as the first > digit after the x, which is either 0 or base-1 -- e.g., +3 and -3 would be > > 2x011 2x101 > 8x03 8x75 > 16x03 16xfd > 10x03 10x97 Why not just -2x11? IMHO, Py2.4 does not produce negative values out of hex or oct literals any longer, so your proposal would be inconsistent. Reinhold From rbt at athop1.ath.vt.edu Sat Jan 29 12:53:37 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Sat, 29 Jan 2005 12:53:37 -0500 Subject: Description Field in WinXP Services Message-ID: How does one associate a "Description" with a Windows service written in Python? I've just started experimenting with Python services. Here's my code... copied straight from Mr. Hammond's "Python Programming on Win32": import win32serviceutil import win32service import win32event class test_py_service(win32serviceutil.ServiceFramework): _svc_name_ = "test_py_service" ## Tried the following to no avail. _svc_description_ = "Test written by Brad" _svc_display_name_ = "Test Python Service" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) if __name__ == '__main__': win32serviceutil.HandleCommandLine(test_py_service) From richie at entrian.com Fri Jan 21 09:41:01 2005 From: richie at entrian.com (Richie Hindle) Date: Fri, 21 Jan 2005 14:41:01 +0000 Subject: ElementTree.findtext() Message-ID: Hi, I can't get ElementTree.findtext() to work with anything other than a single-level path: >>> from elementtree import ElementTree >>> tree = ElementTree.fromstring("""\ ... ... ... ... The title ... ... ... """) >>> print tree.findtext("*/title") The title >>> print tree.findtext("html/head/title") None >>> What am I missing? I'm using elementtree-1.2.4-20041228 on Windows with Python 2.3. -- Richie Hindle From aleaxit at yahoo.com Sat Jan 29 17:23:10 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 29 Jan 2005 23:23:10 +0100 Subject: limited python virtual machine References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> <16891.41849.882856.527798@montanaro.dyndns.org> <1gr5th5.13asce21fjmj8tN%aleaxit@yahoo.com> Message-ID: <1gr6ber.i8gzs6l2o8yiN%aleaxit@yahoo.com> Skip Montanaro wrote: > Alex> I dunno, maybe I'm just being pessimistic, I guess... > > No, I think you are being realistic. I thought one of the basic tenets of > computer security was "that which is not expressly allowed is forbidden". > Any attempt at security that attempts to find and plug the security holes > while leaving the basic insecure system intact is almost certainly going to > miss something. I guess security is drastically different from all other programming spheres because you DO have an adversary, who you should presume to be at least as clever as you are. In most tasks, good enough is good enough and paranoia doesn't pay; when an adversary IS there, only the paranoid survive...;-) Alex From apardon at forel.vub.ac.be Tue Jan 11 10:04:44 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 11 Jan 2005 15:04:44 GMT Subject: Python 2.4 and os.open question? References: <41e3e670$0$20038$39db0f71@news.song.fi> Message-ID: Op 2005-01-11, Eino M?kitalo schreef : > I just test in Windows XP with Python 2.4 > > I'd like to create a file with exclusive flag. Why? What is it about the exclusive flag that makes you like to use it? > If file exist I try to use it, if not I'd like to create it. If you want that, you cant use the exclusive flag. > Python (and underlying library) works differently with/without O_EXCL > flag. Well if the absence and presence of this flag wouldn't make a difference, it would hardly be usefull to have such a flag, wouldn't it? > Is this okay. How I should use this. > > Has somebody manual :-) ? > > Eino M?kitalo > > see scenarios (1 without flag ) (2 with flag) > > Scenario 1: > > To create file if it's not available this works ok > > >>> aa=os.open("c:\\temp\\a.txt",os.O_RDWR|os.O_CREAT) > >>> os.close(aa) > >>> aa=os.open("c:\\temp\\a.txt",os.O_RDWR|os.O_CREAT) > >>> os.close(aa) > > > Scenario 2: > But if you try to do same with O_EXCL then it does not use same logic??? That is what flags are for: to change the logic. O_EXCL, makes sure you are the one that creats the file. If the file exists it fails. This is to make sure that if two programs can create the same file but shouldn't work on it the same time, the file isn't opened multiple times. > >>> aa=os.open("c:\\temp\\a.txt",os.O_RDWR|os.O_EXCL|os.O_CREAT) > >>> os.close(aa) > >>> aa=os.open("c:\\temp\\a.txt",os.O_RDWR|os.O_CREAT) I suppose this should again be the instrcution two lines above; this actually works. (At least on my linux box, if it didn't on your XP box, that is a bug) > Traceback (most recent call last): > File "", line 1, in > OSError: [Errno 17] File exists: 'c:\\temp\\a.txt' Which is exactly as it should, provided you actually used the os.O_EXCL flag twice. -- Antoon Pardon From claird at lairds.us Tue Jan 25 12:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 25 Jan 2005 17:08:03 GMT Subject: Another scripting language implemented into Python itself? References: <1106624803.825442.73870@f14g2000cwb.googlegroups.com> Message-ID: In article <1106624803.825442.73870 at f14g2000cwb.googlegroups.com>, Carl Banks wrote: . . . >> Python, or Perl, or TCL, or Ruby, or PHP, > >Not PHP. PHP is one of the better (meaning less terrible) examples of >what happens when you do this sort of thing, which is not saying a lot. >PHP was originally not much more than a template engine with some >crude operations and decision-making ability. Only its restricted >problem domain has saved it from the junkheap where it belongs. > >TCL isn't that great in this regard, either, as it makes a lot of >common operations that ought to be very simple terribly unweildy. . . . I've lost track of the antecedent by the time of our arrival at "this regard". I want to make it clear that, while Tcl certainly is different from C and its imitators, and, in particular, insists that arithmetic be expressed more verbosely than in most languages, the cause is quite distinct from the imperfections perceived in PHP. PHP is certainly an instance of "scope creep" in its semantics. Tcl was designed from the beginning, though, and has budged little in over a decade in its fundamentals; Tcl simply doesn't bother to "make a lot of common operations ..." concise. From danperl at rogers.com Mon Jan 31 00:06:23 2005 From: danperl at rogers.com (Dan Perl) Date: Mon, 31 Jan 2005 00:06:23 -0500 Subject: Regarding exception handling References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> Message-ID: "Bryan" wrote in message news:mailman.1614.1107137827.22381.python-list at python.org... > IMO, that is not the reason for the try/finally statement and it is not > redundant. the try/finally statement guarantees the resource is closed > and the try/finally statement only gets executed if and only if the > opening of the resource doesn't raise an exception. it has nothing to do > with exception handling. But IMO, try-finally is meant to be used only if the block in the try clause may raise exceptions. Here is an example that shows what I meant: s = ... # socket opens try: a = 1 finally: s.close() works perfectly the same as: s = ... # socket opens a = 1 s.close() The try-finally statement does not "handle" the exception, but it makes sense only if exceptions are possible. There is no point in enclosing "a = 1" in any kind of try statement. According to a following posting from Angelos he did expect some other exceptions than socket.error and hence the nested try's. To my defence though, I put in a disclaimer for that case in my initial posting. > in the previous 2 examples s = ... was placed inside the try/finally, but > if an exception occures and s doesn't get bound to an object, then > s.close() in both examples will raise a NameError on s. That is a very good point. I missed it. Dan From fredrik at pythonware.com Tue Jan 18 05:53:57 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Jan 2005 11:53:57 +0100 Subject: Problem parsing namespaces with xml.dom.minidom References: <41eca38d@clear.net.nz> <41ece45f@clear.net.nz> Message-ID: Mike McGavin wrote: >> is the DOM API an absolute requirement? > > It wouldn't need to conform to the official specifications of the DOM API, but I guess I'm after > some comparable functionality. > > In particular, I need to be able to parse a namespace-using XML document into some kind of node > tree, and then being able to query the tree to select elements based on their namespace and local > tag names, and so on. I don't mind if the methods provided don't conform exactly to DOM > specifications. sounds like this might be exactly what you need: http://effbot.org/zone/element-index.htm (it's also the fastest and most memory-efficient Python-only parser you can get, but I suppose that's not a problem ;-) From xah at xahlee.org Wed Jan 19 00:12:26 2005 From: xah at xahlee.org (Xah Lee) Date: 18 Jan 2005 21:12:26 -0800 Subject: [perl-python] 20050119 writing modules Message-ID: <1106111546.794861.148010@c13g2000cwb.googlegroups.com> ? # -*- coding: utf-8 -*- ? # Python ? ? # one can write functions, ? # save it in a file ? # and later on load the file ? # and use these functions. ? ? # For example, save the following line in ? # a file and name it module1.py ? # def f1(n): returns range(n) ? ? # to load the file, use import ? import mymodule ? ? # to use the function, use ? # fileName.functionName. ? print mymodule.f1(5) ? ? # the file name without the .py suffix ? # is the module's name, and is available ? # as the variable fileName.__name__ ? print mymodule.__name__ ? ? # for more on modules, see ? # http://python.org/doc/2.3.4/tut/node8.html ? ? -------------------- ? # the perl analogue is like this: ? # save the following 3 lines in a file ? # and name it mymodule.pm ? ? # package mymodule; ? # sub f1($){(1..$_[0])} ? # 1 ? ? # then, call it like the following way ? use mymodule; ? use Data::Dumper; ? print Dumper [&mymodule::f1(7)]; ? ? # this is about the simplest way ? # to write a modlue in perl and ? # calling its function. ? # for an inscrutable treatment, ? # see "perldoc perlmod" ? ? Xah ? xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html From generate at gmail.com Tue Jan 4 15:55:54 2005 From: generate at gmail.com (generate at gmail.com) Date: 4 Jan 2005 12:55:54 -0800 Subject: Working with flat files [LDIF]. In-Reply-To: <33A3E2B3.7F5CF6F0@whoi.edu> References: <33A3E2B3.7F5CF6F0@whoi.edu> Message-ID: <1104872154.907906.213620@z14g2000cwz.googlegroups.com> Scott A. McIntyre wrote: > > I looked around but didn't see any LDIF tools for perl or python... > > Any assistance or advice is appreciated!! > > Scott Hello Scott, Did you ever get this issue resolved? I have a similar need to merge two LDIF files. I did find a program called mmldif, but I believe it is proprietary to Sun. Cheers, Charles From a at b.c Sun Jan 23 12:49:09 2005 From: a at b.c (Doug Holton) Date: Sun, 23 Jan 2005 11:49:09 -0600 Subject: compile python to binary In-Reply-To: References: <1d6cdae3050123080242bf8994@mail.gmail.com> Message-ID: <_YCdnROs58UKfm7cRVn-vA@comcast.com> Fredrik Lundh wrote: > Daniel Bickett wrote: > > >>I believe Sam was talking about "frozen" python scripts using tools >>such as py2exe: > > > oh, you mean that "python compiler" didn't mean "the python compiler". > I wouldn't assume a novice uses terms the same way you would. It was quite clear from his message that py2exe and the like were what he was referring to, if you had read his first sentence: "I have seen some software written in python and delivered as binary form." From ewanon at gmail.com Sun Jan 2 23:13:35 2005 From: ewanon at gmail.com (EW) Date: 2 Jan 2005 20:13:35 -0800 Subject: Problem remotely shutting down a windows computer with python Message-ID: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> I have a problem when using the python script found here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/360649 It is a script to remotely shutdown a windows computer. When I use it, the computer shuts down, but doesn't power off like with a regular shutdown. It stays on the "Safe to power off" screen and I have to push the power button to actually power off. Anyone know why this happens with this script? Thanks for any help. Eric From usenet_spam at janc.invalid Wed Jan 5 17:57:33 2005 From: usenet_spam at janc.invalid (JanC) Date: Wed, 05 Jan 2005 22:57:33 GMT Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> Message-ID: Peter Hansen schreef: >> You mean to say that your editor does not have rectangle operations ? >> :-) > > I wouldn't know.** I try quite hard to limit the features > that I have to learn and remember to a very, very small > list. Why the heck would I ever have to do "rectangle > operations" on a regular basis? ;-) > ** I'm using Scite; it probably has it. It has quite a few > features -- far more than I'll ever use. Remarkable how > simple an editor could be and still be effective... for > some people. Rectangular selection only works with the mouse in SciTE/Scintilla: alt-click-drag. Most of SciTE's (editor-)features are also available in other Scintilla based editors. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From b_b at net.hr Fri Jan 14 12:26:04 2005 From: b_b at net.hr (Brane) Date: Fri, 14 Jan 2005 18:26:04 +0100 Subject: python to mssql Message-ID: <1lmwxbtst8x8x$.10hwcoinem3cs.dlg@40tude.net> can someone please give me some info regarding subject please advice regards brane From cjbottaro at alumni.cs.utexas.edu Sat Jan 8 02:17:06 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Sat, 08 Jan 2005 01:17:06 -0600 Subject: How to read/write blobs with mysqldb? Message-ID: First off, writing the blob. From what I gather on the internet, I'm suppose to read the entire file into memory (a Python string), then create a dbiRaw object with that string and use the dbiRaw object in an insert statement? That doesn't sound very efficient to me. What if my computer only has 64 MB of memory and the data I want to insert is 128 MB? It seems like there should be a way to read part of the data, insert that part into the DB, then get the next part, append, etc. Also, what if you are inserting a huge piece of data, like a GB, and you want to have a progress bar in your UI? How would you do that if you couldn't split up the insert statements? Thanks for the help. From douardda at free.fr Sat Jan 29 13:44:26 2005 From: douardda at free.fr (David Douard) Date: Sat, 29 Jan 2005 19:44:26 +0100 Subject: Redirecting stdout/err under win32 platform Message-ID: <41fbd6b5$0$6098$626a14ce@news.free.fr> Hi everybody, let me explain by problem: I am working on an application which consists in a C++ dll (numeric computations) and a Python IHM (Python/Tk), which must run under Linux and win32. My problem is the C++ lib does write stuffs on its stdout, and I would like to print those messages in a Tk frame. When I run the computation, it has it's own thread. So my question is : how van I redirect the dll's stdout to something I can retrieve in Python (pipe, socket,...)? I can do it easily under Linux. I made tests with a socket which just works fine. In the threaded function (that will do the heavy computation), I write: import os, sys from socket import * s=socket(AF_UNIX, SOCK_STREAM) s.connect(...) os.dup2(sys.__stdout__.fileno(), s.fileno()) very_intensive_function(many_parameters) s.close() That's OK under Linux, but does not work under win32 (even if I use an INET localhost socket), cause I cannot do the os.dup2 trick (Windows does not want to consider a socket as a file! What a shity system!). So my question is : is there a simple solution ? I have tested different solutions. I am trying hacks with pipes created with the win32api. But I have not yet managed this simple operation. Note that I have no access to the dll source code, so I cannot modify it so it uses a named pipe (for example) as message output pipe instead os stdout... Thanks, David From SSchukat at dspace.de Fri Jan 28 07:45:06 2005 From: SSchukat at dspace.de (Stefan Schukat) Date: Fri, 28 Jan 2005 13:45:06 +0100 Subject: threading and internet explorer com Message-ID: ... and pythoncom.CoUninitialize() My preferred way is: def run(): pythoncom.CoInitialize() try: ie = win32com.client.Dispatch('InternetExplorer.Application.1') finally: # Trigger the release of the object since after CoUninitialize # it could not be reached ie = None pythoncom.CoUninitialize() Stefan > -----Original Message----- > From: python-list-bounces+sschukat=dspace.de at python.org > [mailto:python-list-bounces+sschukat=dspace.de at python.org]On Behalf Of > Roger Upole > Sent: Friday, January 28, 2005 7:29 AM > To: python-list at python.org > Subject: Re: threading and internet explorer com > > > You'll need to call pythoncom.CoInitialize() in each thread. > > Roger > > "James" wrote in message > news:41f9777f_2 at news.tm.net.my... > > hi, > > > > i'm using python 2.4 with pywin32... > > I've tried to use internet explorer control with a class. > > it was fine until i decided to inherit thread for the class... > > > > class domain01(threading.Thread): > > def __init__(self): > > #blabla > > threading.Thread.__init__(self) > > > > def run(self): > > self.ie = > win32com.client.Dispatch('InternetExplorer.Application.1') #this > > line gives error if i use .start(), but if i use .run.. no error... > > self.ie.Visibble = 1 > > print "running" > > > > > > > > xyz = domain() > > xyz.start() > > > > =========== > > this is what i get: > > Exception in thread Thread-23: > > Traceback (most recent call last): > > File "C:\Python24\lib\threading.py", line 442, in __bootstrap > > self.run() > > File "C:\python2exe\domain01.py", line 41, in run > > self.dologin() > > File "C:\python2exe\domain01.py", line 56, in dologin > > > self.ie=win32com.client.Dispatch('InternetExplorer.Application.1') > > File > "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line > > 95, in Dispatch > > dispatch, userName = > > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) > > File > "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line > > 91, in _GetGoodDispatchAndUserName > > return (_GetGoodDispatch(IDispatch, clsctx), userName) > > File > "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line > > 79, in _GetGoodDispatch > > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, > > pythoncom.IID_IDispatch) > > com_error: (-2147221008, 'CoInitialize has not been > called.', None, None) > > > > > > > > ===== > > but if i run: > > xyz = domain() > > xyz.run() > > > > ##no error! it's weird.... > > > > anyone know how to solve this problem? > > > > thank you :) > > > > best regards, > > > > James > > > > > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure > Usenet News==---- > http://www.newsfeeds.com The #1 Newsgroup Service in the > World! >100,000 Newsgroups > ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- > -- > http://mail.python.org/mailman/listinfo/python-list > From tim.peters at gmail.com Tue Jan 4 19:46:17 2005 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 4 Jan 2005 19:46:17 -0500 Subject: Restore a unified diff In-Reply-To: References: Message-ID: <1f7befae050104164661991e58@mail.gmail.com> [Nick Allen] > After using ndiff from difflib, the function restore > would return the sequence that generated the delta. It can actually reproduce either sequence from which the delta was generated. But this is really trivial: ndiff was intended to produce diff output for humans to read, and includes the full text of both input sequences in "the diff" it generates. > Unfortunately, restore does not do the same for unified_diff. I do > not see any similar function that is intended for unified_diff. Does > anyone know how to "restore" from a unified diff generated delta? That's in general impossible, since unified diffs generally omit most lines that compared equal to begin with. Unified and context diffs are, in part, compression gimmicks, showing only what changed plus a bit of context. ndiff shows everything, so can restore everything too. From jeremy+plusnews at jeremysanders.net Wed Jan 26 04:50:19 2005 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Wed, 26 Jan 2005 09:50:19 +0000 Subject: Python with no significant whitespace References: <35oh4gF4nvvfoU1@individual.net> Message-ID: On Wed, 26 Jan 2005 11:31:18 +0800, mep wrote: > Hi,all > Is there anybody trying to release a modification version to current > python source code with no significant whitespace, say replacing whitespace > by {} > like C or java. I do *NOT* mean whitespace is good or bad, just > want to know. It probably would be easy to convert source in the form using brackets to indented form on the fly, and use exec to interpret the converted form. You need to do something like convert XXXX { to XXXX: foo Of course this isn't a good idea. Jeremy From aahz at pythoncraft.com Thu Jan 27 20:48:13 2005 From: aahz at pythoncraft.com (Aahz) Date: 27 Jan 2005 20:48:13 -0500 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> Message-ID: In article <1106863164.745581.11920 at f14g2000cwb.googlegroups.com>, wrote: > >Who are the appropriate people to report security problems to in >respect of a module included with the Python distribution? I don't >feel it appropriate to be reporting it on general mailing lists. There is no generally appropriate non-public mechanism for reporting security issues. If you really think this needs to be handled privately, do some research to find out which core developer is most likely to be familiar with it. Even before you do that, check SourceForge to find out whether anyone else has reported it as a bug. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From roccomoretti at hotpop.com Mon Jan 24 20:20:40 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Mon, 24 Jan 2005 19:20:40 -0600 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: Message-ID: Roy Smith wrote: > In article , > Quest Master wrote: > >>So, my question is simply this: is there an implementation of another >>scripting language into Python? > > Python *is* a scripting language. Why not just let your users write > Python modules which you them import and execute via some defined API? I can think of a couple of reasons off the top of my head: The OP doesn't mention his application, but there is something to be said about domain specific scripting languages. A well designed domain-specific scripting language(*) with the appropriate high level constructs can make script writing simpler. There's also an audience factor. Python is easy to learn, but it's still a programming language. A well designed domain-specific scripting language(*) can make it very easy to get work done in a particular case without having to learn the Python mind frame. (How assignments work, mutable/immutable, Python's call passing system, etc.) Python's also dangerous. Every time you do an "import module", you put your system at risk of crashing, having the hard-drive wiped, sending incorrect signal codes to peripherals, etc. A well-designed specialty language(*) minimizes those risks - don't need disk access? Don't allow it in your language. There's also the valuable learning experience of designing and implementing a scripting language. (*) Note that I keep saying "well-designed". A poorly designed scripting language is very bad - you can feel shackled by the restrictions it imposes, and find yourself unable to do what you want without laborious contortions, if at all. I also say "domain specific" because, at this time, there are enough general purpose scripting languages that you are likely to find what you need already existing, unless you are experimeting with a completely new programing paradigm. To answer the OP's question: Yes - sort of. Currently work is underway to implement the Python scripting language in Python. Cleverly called "PyPy", the website is "http://www.codespeak.net/pypy". From tonino.greco at gmail.com Fri Jan 21 09:54:30 2005 From: tonino.greco at gmail.com (Tonino) Date: 21 Jan 2005 06:54:30 -0800 Subject: tkinter socket client ? In-Reply-To: <1106318469.311179.126140@c13g2000cwb.googlegroups.com> References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> <1106311130.446259.30710@f14g2000cwb.googlegroups.com> <1106318469.311179.126140@c13g2000cwb.googlegroups.com> Message-ID: <1106319270.932204.180590@c13g2000cwb.googlegroups.com> hi there , yeah - had a look at createfilehandler() - was a bit confusing - but your example helps ;) Thanks Tonino From fuzzyman at voidspace.org.uk Wed Jan 12 05:25:29 2005 From: fuzzyman at voidspace.org.uk (Fuzzyman) Date: Wed, 12 Jan 2005 10:25:29 +0000 Subject: [Ann] PyName and downman Message-ID: <41E4FB19.8010707@voidspace.org.uk> A couple of new 'modules' available from Voidspace Pythonutils. PyName http://www.voidspace.org.uk/python/modules.shtml#pyname Slightly tongue in cheek, this isn't really a python module. It's three lists of English words containing 'py' - intended to be helpful to those choosing names for python projects. The word lists were produced from an initial file of about 8mb. Words selected all contain 'py', single words or hyphenated words, but no compound words. * pywordlist.txt All words contain 'py' 23kb - 1946 words * pywordlist2.txt All words starting or ending in 'py' 16kb - 1406 words * pywordlist3.txt All words as pywordlist2, but only words less than 10 chars long 5kb - 658 words. downman.py Version 0.2.1 14th December 2004 Simple Download Manager http://www.voidspace.org.uk/python/cgi.shtml#downman This is a simple download manager tool. It may be egotistical, but I like to know which of my projects are being downloaded (and which aren't). Simply make your files available in a single directory and have the links point to downman (see the download link for downman itself for an example) and downman will track the downloads. At the moment it only presents simple data - but all the raw data is collected to do per week/last month (or whatever) analysis. It will also manage links as well. See the example output at http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py Regards, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From aahz at pythoncraft.com Sat Jan 8 11:07:43 2005 From: aahz at pythoncraft.com (Aahz) Date: 8 Jan 2005 11:07:43 -0500 Subject: "A Fundamental Turn Toward Concurrency in Software" References: <1105171949.823433.72860@f14g2000cwb.googlegroups.com> Message-ID: In article <1105171949.823433.72860 at f14g2000cwb.googlegroups.com>, wrote: >Michele deleted an attribution: >> >> So I've always had it in >> the back of my mind that languages that can easily support massive >> (especially automatic) parallelization will have their day in the sun, >> at least someday. > >and the language of the future will be called ... FORTRAN! > >:-) > >(joking, but it is the only language I know supporting massive >parallelization ...) Less of a joke than you think, perhaps. Back in the early 1980s, a family friend said something like, "In the year 2000, there will be a programming language. I don't know what it will look like, and I don't know what it will do. But I do know one thing: it will be called FORTRAN." After all, FORTRAN 2003 contains OOP support.... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From info at frengky.no Fri Jan 7 09:58:06 2005 From: info at frengky.no (Øystein Western) Date: Fri, 7 Jan 2005 15:58:06 +0100 Subject: countint words from an input string Message-ID: Hello! Try to write som code that will get an input string from the user. Futher more, I'd like to have the program to count all the word the user has written. Startet out like this: /------------- s = raw_input("Write a text line") print s.split() /---------------- How can I count the words in the split function. Do I have to use the split function to count the words in the S variable? Regards Frengky -- Organisation nr: 983063349 Frengky, Olsokveien 65,1727 Sarpsborg, Norway Tel: +47 92611725 Fax: +47 69152017 Email: oystein.western at frengky.no Web: www.frengky.no From steve at holdenweb.com Thu Jan 6 10:40:59 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Jan 2005 10:40:59 -0500 Subject: Embedding a restricted python interpreter In-Reply-To: References: Message-ID: <41DD5C0B.3030007@holdenweb.com> Jp Calderone wrote: [...] > > > A Python sandbox would be useful, but the hosting provider's excuse > for not allowing you to use mod_python is completely bogus. All the > necessary security tools for that situation are provided by the > platform in the form of process and user separation. Not sure this is strictly true: mod_python gets loaded into the server's address space and gives the ability to add any type of handler. While Apache might well be able to respawn failed subprocesses, it's not something that most hosting providers would like to have to do all the time for many hosted sites. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From jeff at ccvcorp.com Thu Jan 6 17:27:55 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 06 Jan 2005 14:27:55 -0800 Subject: The Industry choice In-Reply-To: References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: <10trej2fl8dip65@corp.supernews.com> Bulba! wrote: > On Thu, 06 Jan 2005 08:39:11 GMT, Roel Schroeven > wrote: > >>That's generally the goal of the Free Software Foundation: they think >>all users should have the freedom to modify and/or distribute your code. > > You have the freedom of having to wash my car then. ;-) A more accurate analogy would be, "You're free to borrow my car, but if you do, you must wash it and refill the gas tank before you return it." Note that the so-called 'viral' nature of GPL code only applies to *modifications you make* to the GPL software. The *only* way in which your code can be 'infected' by the GPL is if you copy GPL source. Given the standard usage of closed-source software, you never even have access to the source. If you use GPL software in the same way that you use closed-source software, then the GPL cannot 'infect' anything you do. The 'infective' nature of the GPL *only* comes when you make use of the *extra* privelidges that open source grants. So yes, those extra privelidges come with a price (which is that you share what you've done); but if you don't want to pay that price, you have the choice of not using those privelidges. This does not, in any way, prevent you from using GPL'ed software as a user. (Problems may come if someone licenses a library under the GPL; that's what the LGPL was invented for. But the issue here is not that the GPL is bad, it's that the author used the wrong form of it.) Personally, I'm not a big fan of the GPL. I'm much more likely to use BSD-ish licenses than [L]GPL. But it still bugs me to see the GPL misrepresented as some plot to steal the effort of hardworking programmers -- it is, instead, an attempt to *encourage* hardworking programmers to share in a public commons, by ensuring that what's donated to the commons remains in the commons. Jeff Shannon Technician/Programmer Credit International From davorss at gmail.com Tue Jan 25 16:49:48 2005 From: davorss at gmail.com (Davor) Date: 25 Jan 2005 13:49:48 -0800 Subject: python without OO Message-ID: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Is it possible to write purely procedural code in Python, or the OO constructs in both language and supporting libraries have got so embedded that it's impossible to avoid them? Also, is anyone aware of any scripting language that could be considered as "Python minus OO stuff"? (As you can see I'm completely new to Python and initially believed it's a nice&simple scripting language before seeing all this OO stuff that was added in over time) Thanks, Davor From lbolognini at gmail.com Thu Jan 6 06:26:10 2005 From: lbolognini at gmail.com (lbolognini at gmail.com) Date: 6 Jan 2005 03:26:10 -0800 Subject: wxPython clipboard Message-ID: <1105010770.911397.278520@c13g2000cwb.googlegroups.com> Hi all, I'm thinking about coding a free version of this software: http://www.pitrinec.com/pkindex.htm I would use wxPython and wx.Clipboard class (hoping to be able to make it cross-platform) The software above detects macros you code in any Windows active window and replaces them with a text: something like you write "/ff" and he pastes "Feel free to call us back for whatever questions you might have". This kind of softwares are very usefull in a call-centre environment (where I'm currently working). The thing is I'm thinking about the best approach (in terms of CPU resources) to detect the macro. Not sure how keyloggers work but I suspect I could run a service that compares everything beign written in the active window with the macros I saved in the software configuration. Could you please give me some advice on the best approach to solve this problem? Thanks a lot, Lorenzo -- http://www.bolognini.net/ From aleaxit at yahoo.com Wed Jan 5 13:05:37 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 5 Jan 2005 19:05:37 +0100 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> <1gpx56v.yb9ubn188tj2yN%aleaxit@yahoo.com> Message-ID: <1gpxj3q.1uqc3s6sy7m08N%aleaxit@yahoo.com> Roman Suzi wrote: > Alex, I think you are +10 for adding interfaces into Python. "Concept" > is more compact word and I am sure it is not used as a name in existing > projects, unlike other words. Actually, I want protocols -- semantics (and pragmatics), too, not just syntax (method names and signatures). Eby's PyProtocols comes closest to my desiderata (though it possibly exceeds them). But if you start coding a PyConcepts alternative to PyProtocols I'll be delighted to try it out, contribute, &c -- I won't be a stickler for the name. Indeed, "protocol" is no doubt more overloaded, since it's an established name in networking, and if you google for "protocol adaptation" you get a mix mostly related to networking with a few examples of the way PEP 246 uses the phrase thrown in;-). Alex From peter at engcorp.com Fri Jan 14 23:32:50 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 14 Jan 2005 23:32:50 -0500 Subject: porting C code In-Reply-To: References: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> <0NidnetRONZTgHrcRVn-oQ@powergate.ca> Message-ID: Lucas Raab wrote: > Sorry, the third "byte" is what I meant. Fair enough. Note, however, that as someone pointed out, it's actually the *fourth* of something, and it would not necessarily be a byte. In fact, in your case, it's not: > typedef unsigned long int word32 ; > void mu(word32 *a) > { > int i ; > word32 b[3] ; This defines an array of *3* long (32-bit) integers. > b[0] = b[1] = b[2] = 0 ; Each of these is just indexing into that array, starting as Python does with an index origin of zero. > The "a[#]" and "b[#]" are the parts that are giving me trouble. Between the clarifications you've got and Duncan's post, you shouldn't have much more trouble now. :-) -Peter From peter at engcorp.com Sun Jan 9 09:45:33 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jan 2005 09:45:33 -0500 Subject: Python Installation In-Reply-To: <1105232505.142279.85810@c13g2000cwb.googlegroups.com> References: <1105220812.579690.292260@c13g2000cwb.googlegroups.com> <1105232505.142279.85810@c13g2000cwb.googlegroups.com> Message-ID: Simon John wrote: > I would say install on one machine, then just copy the C:\Python24 > directory, but then you'd have to deal with the missing Registry > entries.... That part is pretty trivial to automate as well. Fredrik Lundh has a useful utility on his web site that will do much of what is required. Google for his name and "python registry" to find out more. -Peter From ncoghlan at iinet.net.au Mon Jan 17 06:18:15 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 17 Jan 2005 21:18:15 +1000 Subject: getting a class attribute using a keyword argument In-Reply-To: References: Message-ID: <41EB9EF7.60203@iinet.net.au> Guy Robinson wrote: > Hello, > > I have a list of class instances. I wish to get the appropriate class > attribute in each class instance depending on a SINGLE keyword in the > calling class. Py> help(getattr) Help on built-in function getattr in module __builtin__: getattr(...) getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From theller at python.net Thu Jan 6 07:39:35 2005 From: theller at python.net (Thomas Heller) Date: Thu, 06 Jan 2005 13:39:35 +0100 Subject: Is there any way/where to subscribe for automated PEP status emails? References: <41dc24f8.68802652@news.oz.net> Message-ID: Nick Coghlan writes: > Thomas Heller wrote: >> You could probably subscribe to python-checkins, and filter it. >> Or read it via gmane. > > Hmm - can SF be used to setup a mailing list just for checkins to a > single directory in the source tree? Yes. You should suggest this on python-dev. > If so, that would seem to be an easy way to provide a > python-pep-updates mailing list. > > Cheers, > Nick. Thomas From skullw at sina.com.cn Sat Jan 15 21:07:27 2005 From: skullw at sina.com.cn (skull) Date: Sat, 15 Jan 2005 21:07:27 -0500 Subject: How to del item of a list in loop? References: <34rvjqF4f6l70U1@individual.net> <34s7omF4emdsaU1@individual.net> Message-ID: Reinhold Birkenfeld writes: >> Quick solution: >> >> for i in lst[:] >> >> iterates over a copy. > > Addition: In Py2.4, I can't find a problem with > > for i in reversed(lst) > > Any objections? > > Reinhold I just downloaded py2.4, and made a test using reversed. it sure be no problem, I thought maybe the reversed holded a copy of list, and eventually iterated through the copy. but the truth is not as I thought so: import sys class Test: pass lst = [Test(),Test(),Test()] E1: for i in lst[:]: E2: for i in reversed(lst): print sys.getrefcount(i) ################### E1 outputs: 4 4 4 E2 outputs: 3 3 3 It looks that the reversed does not make a copy of list in contrast with lst[:]. so should we regard: reversed is faster than lst[:]? I do not have any idea about why it is. - skull From fccoelho at gmail.com Tue Jan 11 10:51:35 2005 From: fccoelho at gmail.com (Flavio codeco coelho) Date: 11 Jan 2005 07:51:35 -0800 Subject: Python serial data aquisition References: <41e384d0.552090624@news.oz.net> Message-ID: bokr at oz.net (Bengt Richter) wrote in message news:<41e384d0.552090624 at news.oz.net>... > On 9 Jan 2005 14:13:28 -0800, fccoelho at gmail.com (Flavio codeco coelho) wrote: > > >Hi, > > > >I am using pyserial to acquire data from an A/D converter plugged to > >my serial port. > > > >my hardware represents analog voltages as 12bit numbers. So, according > >to the manufacturer, this number will be stored in two bytes like > >this; > > |-------------bits(1-8)-----------| > >Byte1: x x x n1 n2 n3 n4 n5 > >Byte2: x n6 n7 n8 n9 n10 n11 n12 > > > >where x is some other information, and nx are the digits of my number. > > > >My problem is to how to recover my reading from these bytes, since > >pyserial gives me a character (string) from each byte... I dont know > >how to throw away the unneeded bits and concatenate the remaining > >bits to form a number... > > > The others have shown how to recover a 12 bit positive value 0 through 4095, > but if the number is signed, and you want the signed value, you'll have to > find out how signed numbers are represented. An offset is common, in which > case you would subtract 2048 (2**11). If it's two's complement by some chance, > you'll want (I think -- untested ;-) to do num -= 2*(num&2048) instead of always num -= 2048 > If you need speed in converting large strings of byte pairs, you could > convert pairs of bytes with the array module ('H' for unsigned 2-byte numbers) > and use the resulting 16-bit numbers as indices into another array of final values > prepared beforehand with redundant information that will accomplish the effect > of masking and shifting and adjusting sign. > If you need this speed, volunteers will magically appear. Maybe even if you don't ;-) > Regards, > Bengt Richter Hi Bengt, The Idea of using Array is realy cool Though I have to think about it since I would to plot the values as they are sampled... Anyway, how would you set up this array to do the shifting and masking? BTW, since this thread is generating quite a bit of attention let me post a complete description of my problem so that it may serve as reference to others: Hardware: DI-151RS from Dataq (2 analog channels, 2 digital input, single ended/differential recording, max sampling rate 240Hz) connects to the serial pro through a standard db9 plug. Encryption table: B7 B6 B5 B4 B3 B2 B1 B0 Byte1 A4 A3 A2 A1 A0 1 Din 0 Byte2 A11 A10 A9 A8 A7 A6 A5 1 Byte3 B4 B3 B2 B1 B0 1 Din 1 Byte4 B11 B10 B9 B8 B7 B6 B5 1 first two bytes are for analog ch 1 and remaining two are for ch 2. Din stands for digital in. AXX and BXX are the nth bits of each reading. A0 and B0 are the least significant bits. The latest and preferred solution on how to convert these bytes is, according to the suggestion of Chris Liechti (author of pyserial) is: (this is for the first channel only, repeat for the second) import struct l, h = struct.unpack(">BB", ser.read(2)) n = (l >> 3) + ((h >> 1)<<5) struct.unpack returns a tuple of values represented by a string(the output of the read command) packed according to the format specified by ">BB" In this forma string, ">" stands for big Endian representation and "B" stands for unsigned char. If anyone has a better suggestion, speack up! oof! I started this thread knowing next to nothing about this stuff, It seem that I am finally getting the idea! :)) cheers, Fl?vio From steve at holdenweb.com Sun Jan 2 09:17:47 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 02 Jan 2005 09:17:47 -0500 Subject: The Industry choice In-Reply-To: <7xekh423b6.fsf@ruckus.brouhaha.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xfz1lal5d.fsf@ruckus.brouhaha.com> <7xekh423b6.fsf@ruckus.brouhaha.com> Message-ID: <_rTBd.66275$Jk5.46@lakeread01> Paul Rubin wrote: > Steve Holden writes: > >>>It seems to me >>>that IDLE and a lot of the rest of Python are examples of someone >>>having a cool idea and writing a demo, then releasing it with a lot of >>>missing components and rough edges, without realizing that it can't >>>reasonably be called complete without a lot more work. >> >>^Python^open source^ > > > I wouldn't say so. I'd say the Linux kernel, GCC, Emacs, Apache, > Mozilla, etc. are all developed with a much more serious attitude than > Python is. Of course there are lots of other FOSS programs that > someone wrote for their own use and released, that are less polished > than Python, but that are also the subject of less advocacy than Python. Well clearly there's a spectrum. However, I have previously written that the number of open source projects that appear to get stuck somewhere between release 0.1 and release 0.9 is amazingly large, and does imply some dissipation of effort. Give that there's no overall coordination this is of course inevitable, but some open source projects are doomed from the start to be incomplete because the original authors have never been involved in producing software with a reasonably large user base, and so their production goals and quite often their original specifications (where there are any) are unrealistic. These projects meander towards a half-assed initial implementation and then become moribund. This is not to tar respectable projects like Linux, many (but not all) of the Gnu projects, and Python with that same brush, and personally I think the Python *core* is pretty solid and quite well-documented, but I don;t regard IDLE as part of the core myself. Since I'm not an active developer, this may not be in line with python-dev's opinions on the matter. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From sbryce at scottbryce.com Sun Jan 9 20:31:44 2005 From: sbryce at scottbryce.com (Scott Bryce) Date: Sun, 09 Jan 2005 18:31:44 -0700 Subject: a new Perl/Python a day In-Reply-To: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > frustrated constantly by its inanities and incompetences.) I don't see what this has to do with Perl. From bj_666 at gmx.net Wed Jan 12 15:24:42 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 12 Jan 2005 21:24:42 +0100 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <41e41633$1@nntp0.pdx.net> <41e458a9$0$7090$8fcfb975@news.wanadoo.fr> Message-ID: In <41e458a9$0$7090$8fcfb975 at news.wanadoo.fr>, Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle. wrote: > I understand, but I have a feeling of attempt at hegemony. Is english > language really least-common-denominator for a russian who writes into > cyrillic, or not anglophone chinese? > > And, did you think of klingons? Klingons don't do Python, they hack ('n slash) in var'aq: http://www.geocities.com/connorbd/varaq/ SCNR, Marc 'BlackJack' Rintsch From flamesrock at gmail.com Thu Jan 27 19:58:24 2005 From: flamesrock at gmail.com (flamesrock) Date: 27 Jan 2005 16:58:24 -0800 Subject: Question about 'None' In-Reply-To: <2fCdnYr1l-CZwmTcRVn-ig@comcast.com> References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> <2fCdnYr1l-CZwmTcRVn-ig@comcast.com> Message-ID: <1106873904.761513.153710@z14g2000cwz.googlegroups.com> Wow! Thanks for all the replies. I'll have to reread everything to absorb it. The test code is pretty simple: if 2 > None: print 'true' else: print 'false' It prints false every time. I should also mention that I'm using version 2.0.1 (schools retro solaris machines :( ) At home (version 2.3.4) it prints out 'True' for the above code block. From ptmcg at austin.rr._bogus_.com Mon Jan 17 14:13:34 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 17 Jan 2005 19:13:34 GMT Subject: Assigning to self References: <200501171845.46766.frans.englich@telia.com> <1105988333.379592.327600@z14g2000cwz.googlegroups.com> Message-ID: wrote in message news:1105988333.379592.327600 at z14g2000cwz.googlegroups.com... > An implementation of what you want can be found here: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52558 > I think this recipe pre-dates the introduction of __new__ in Python. How about something like this (requires the name to be the first constructor argument): ------------------------------------------- class RegisteredObject(object): registry = {} def __new__(cls,name,*args,**kwargs): if name not in cls.registry: cls.registry[name] = object.__new__(cls) return cls.registry[name] class foo (RegisteredObject): def __init__(self,name): self.myName = name def yo(self): return self.myName def main(): a = foo( "test" ) print "ATTR:", a.yo() print id(a) b = foo( "test" ) print "ATTR:", b.yo() print id(b) c = foo( "test2" ) print "ATTR:", c.yo() print id(c) if __name__ == "__main__": main() ---------------------------------------------- gives: ATTR: test 7886256 ATTR: test 7886256 ATTR: test2 7887984 -- Paul From stephen.thorne at gmail.com Sun Jan 30 20:14:21 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Mon, 31 Jan 2005 11:14:21 +1000 Subject: Problem with loading textfiles into dictionaries. In-Reply-To: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> References: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> Message-ID: <3e8ca5c805013017145017e17f@mail.gmail.com> On 30 Jan 2005 16:43:26 -0800, mercuryprey at gmail.com wrote: > Hello, > I want to do the following: > > def do_load(self, arg): > sitefile = file('sitelist', 'r+', 1) > while True: > siteline = sitefile.readline() > site_rawlist = siteline.split() > sitelist[site_rawlist[0]] = site_rawlist[1:] > if len(siteline) == 0: > break maybe you would be better off doing something slightly simpler, and in such a way that you see the input which is causing problems. sitelist = {} for line in file('sitelist'): elems = line.split() if len(elems) == 1: raise ValueError, "Invalid line in file %r" % line sitelist[elem[0]] = elem[1:] :) Stephen From engsolnorm at peak.org Wed Jan 12 21:02:49 2005 From: engsolnorm at peak.org (engsol) Date: Wed, 12 Jan 2005 18:02:49 -0800 Subject: pyserial and com port interrupts References: Message-ID: <24lbu0htudrc9ir4b0na3r1m6g09qlbck4@4ax.com> On Wed, 12 Jan 2005 17:45:48 -0500, Peter Hansen wrote: >engsol wrote: >> Has anyone done a script that will rspond to the serial com port(s) >> receive buffer interrupt, as opposed to polling and timeouts? >> Win2000 is the main interest right now. > >What problem do you hope to avoid by not using "polling >and timeouts"? (Note that if you specify a sizable >read timeout, you're closer to being interrupt-driven >than you are to what is traditionally called "polling".) > >-Peter Peter, Thanks for the reply. I'm working on a s/w test program using python code. Com1 and com2 play a part. The problem is that the python code has a lot of work to do...and the results from the hardware under test can come from either com1 or com2...at any time. It may be a few milliseconds, or several seconds, sometimes minutes, before a response is expected. I'm not sure what timeout value I'd use. Using threads, and re-loading the timeout values on the fly may be a solution, but I'm not experienced with threads....and was hoping to avoid them. Norm B From aleaxit at yahoo.com Mon Jan 10 04:51:01 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 10 Jan 2005 10:51:01 +0100 Subject: Getting rid of "self." References: <1gq4ery.1v79c2t9lsfinN%aleaxit@yahoo.com> <10u2dlj4p45psf0@news.supernews.com> Message-ID: <1gq64d2.1iwvg0313tohejN%aleaxit@yahoo.com> BJ?rn Lindqvist wrote: ... > > http://starship.python.net/crew/mwh/hacks/selfless.py > > That's excellent! There is one small problem with the code though: It shows the fundamentals of how to rewrite the bytecode, yes. > .class Hi(Selfless): > . __attrs__ = ["x"] > . def __init__(x): > . self.x = x > > In this case, I think the Python interpreter should realise that the > parameter x shadows the attribute x. But the selfless code has > problems with that. I want it to work exactly like how the situation > is handled in Java and C++. I believe you're referring to the test in rewrite_method: if op.arg < code.co_argcount: raise ValueError, "parameter also instance member!" If you think that parameters that are also instance members should "shadow" instance members, just skip the op.arg cases which are less than code.co_argcount -- those are the parameters. > > Alex Martelli: > > A decorator can entirely rewrite the bytecode (and more) of the method > > it's munging, so it can do essentially anything that is doable on the > > basis of information available at the time the decorator executes. > > Which I believe means that the instance variables have to be declared > in the class? I am content with declaring them like the selfless > approach does: It means the information about which names are names of instance attributes must be available somewhere, be that "declared", "inferred", or whatever. For example, many C++ shops have an ironclad rule that instance attributes, and ONLY instance attributes, are always and invariably named m_. If that's the rule you want to enforce, then you don't necessarily need other declarations or inferences, but rather can choose to infer the status of a name from looking at the name itself, if you wish. "Declarations" or other complications yet such as: > alternative would be not to declare the variables in an __attr__ list, > and instead let them be "declared" by having them initialised in the > __init__. I.e: > > .def __init__(hi, foo): > . self.hi = hi > . self.foo = foo > > When the metaclass then does it magic, it would go through the code of > the __init__ method, see the assignments to "self.hi" and "self.foo", > decide that "hi" and "foo" are attributes of the object and replace > "hi" and "foo" in all other methods with "self.hi" and "self.foo". The OK, but this approach is not compatible with your stated desire, which I re-quote...: > I want it to work exactly like how the situation > is handled in Java and C++. ...because for example it does not deal with any attributes which may be initialized in a *superclass*'s __init__. However, I guess it could be extended at the cost of some further lack of transparency, to obtain just as horrid a mess as you require, where it's impossible for any human reader to guess whether, say, hi = 33 is setting a local variable, or an instance variable, without chasing down and studying the sources of an unbounded number of superclasses. I do not think there is any _good_ solution (which is why many C++ shops have that rule about spelling this m_hi if it's an instance variable, keeping the spelling 'hi' for non-instance variables -- an attempt to get SOME human readability back; a smaller but non-null number of such shops even achieve the same purpose by mandating the use of 'this->hi' -- just the Python rule you want to work around, essentially). The least bad might be to rely on __attrs__, enriching whatever is in the current class's __attr__ with any __attrs__ that may be found in base classes PLUS any member variables specifically set in __init__ -- if you focus on convenience in writing the code, to the detriment of ability to read and understand it; or else, for more readability, demand that __attrs__ list everything (including explicitly attributes coming from subclasses and ones set in any method by explicit "self.whatever = ...") and diagnose the problem, with at least a warning, if it doesn't. Yes, there's redundancy in the second choice, but that's what declarations are all about: if you want to introduce the equivalent of declarations, don't be surprised if redundancy comes with them. > downside is that it probably could never be foolproof against code > like this: > > .def __init__(hi, foo): > . if hi: > . self.hi = hi > . else: > . self.foo = foo > > But AFAIK, that example is a corner case and you shouldn't write such > code anyway. :) I don't see any problem with this code. A static analysis will show that both hi and foo are local variables. Either may be not initialized, of course, but having to deal with variables which are not initialized IS a common problem of C++: you said you want to do things like in C++, so you should be happy to have this problem, too. > > Alex Martelli: > > You do, however, need to nail down the specs. What your 'magic' does > > is roughly the equivalent of a "from ... import *" (except it > > ... > > Then, you must decide whether this applies to all names the method > > accesses (which aren't already local). For example, if the method > > has a statement such as: > > x = len(y) > > All names should be checked like this: > 1. Is the name in the parameter list? If so, do not rebind it. > 2. Is the name in the objects attribute list? If so, prepend "self." > 3. Do stuff like normal. That's basically what the already-mentioned "selfless" does, then, with the small change to consider name conflicts (parameter vs instance attribute) to be OK rather than errors, as above mentioned; and possibly larger changes to determine the attribute names, depending on what strategy you want to pursue for that. > > Alex Martelli: > > If you can give totally complete specifications, I can tell you > > whether your specs are doable (by a decorator, or other means), how, > > and at what cost. Without knowing your specs, I can't tell; I can > > _guess_ that the answer is "probably doable" (as long as you're not > > demanding the code in the decorator to be an oracle for the future, > > This is promising, I'm content with whatever slowdowns necessary as > long as I can prove those who say "you can't do it" wrong. :) It seems Nobody (that I saw) said you can't do it, as long as you're willing to pay the price in terms of some mixture of extra stuff to write (__attrs__ or whatever), more difficulty in human reading (not being able to tell locally what's a local variable and what isn't), new and interesting kinds of errors such as "uninitialized member variables", and time to execute the class statement or its methods, depending on the exact mix and strategies you choose. > to me that it should be doable by having the metaclass that modifies > the class go through the class and bytecode-rewrite all its methods. > So there has to be a big slowdown when the class is created, but after > that, it should execute at pure Python speed? That doesn't seem to > hard, and pretty robust too since bytecode doesn't change so often. Starting with "selfless" and the few extra pointers I've given, I agree it should not be too hard. Not sure what you mean by bytecode not changing often: the bytecode rewrite will happen every time you execute the 'class' statement, and only then. > And THEN I'll rewrite python-mode so that it syntax highlights member > attributes! It will be cool. This part might well be pretty hard, given the possibility of inheritance from classes that might be anywhere at all -- sys.path can change dynamically, so to know exactly what classes from other modules your class is inheriting from (and that is crucial to determine which names are those of instance attributes) basically requires executing all the program up to the 'class' statement. If you're keen on this part I suggest you use one of the approaches that also facilitate human reading: for exactly the same reasons they'll facilitate the highlighting. Either use something like m_ as the name for instance attributes, or have all instance attributes listed in __attrs__, considering it an error (worth at least a warning... and a lack of highlighting!) to use other instance attributes (from superclasses or whatever) that _aren't_ listed in __attrs__. Alex From aleaxit at yahoo.com Sat Jan 22 08:10:35 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 14:10:35 +0100 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> <1gqsayh.th49i518ixczeN%aleaxit@yahoo.com> <7xpszxljra.fsf@ruckus.brouhaha.com> Message-ID: <1gqsmuk.n2y4senmpr3fN%aleaxit@yahoo.com> Paul Rubin wrote: > aleaxit at yahoo.com (Alex Martelli) writes: > > If it changed the semantics of for-loops in general, that would be quite > > inconvenient to me -- once in a while I do rely on Python's semantics > > (maintaining the loop control variable after a break; I don't recall if > > I ever used the fact that the variable is also maintained upon normal > > termination). > > Some languages let you say things like: > for (var x = 0; x < 10; x++) > do_something(x); > and that limits the scope of x to the for loop. That seems like a > reasonable way to offer for-loops that don't leak. Yes, that's how C++ introduced it, for example. But note that, after waffling quite a bit in various betas of VC++, Microsoft ended up having this form *not* limit the scope, for years, in two major releases; I'm not privy to their reasons for accepting the syntax but rejecting its key semantic point, and I think they've finally broken with that in the current VC++ (don't know for sure, haven't used MS products for a while). But it sure made for quite a long transition period. It's far from clear to me that it's worth complicating Python by introducing a third form of loop, next to normal while and for ones, to mean "a for loop whose control variables are hyperlocalized" (plural, in general, of course -- ``for n, v in d.iteritems():'' etc). > > (musing...): I think the reason there's no real use case for using a > > listcomp's control variable afterwards is connected to this distinction: > > listcomps have no `break'... > > Of course you can still break out of listcomps: You can abort them by having an exception raised -- that's quite a different issue. > class oops: pass > def f(x): > if x*x % 11 == 3: raise oops > return x*x > try: > lcomp = [f(x) for x in range(10)] > except oops: pass > print x > > prints "5" This way, you don't get anything assigned to lcomp. break is quite different from raise, which aborts the whole caboodle up to the handler. Alex From merkosh at hadiko.de Sat Jan 1 17:15:55 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Sat, 01 Jan 2005 23:15:55 +0100 Subject: UserDict deprecated References: Message-ID: Saturday 01 January 2005 22:48 pm Hans Nowak wrote: > Uwe Mayer wrote: > >> Why is the UserDict module is deprecated after Python 2.2. The >> application of it I have in mind is, i.e. multiple inheritance from >> "file" and "dic" - which is not possible. > I am curious, what would you do with a class that derives from both file > and dict? I was writing a class that read /writes some binary file format. I implemented the functions from the file interface such that they are refering to records. However, the file format has some header fields and I'd wanted to grant access to those via the dict-interface. Another example: working with PyQt I have an instance of a QListView and wanted to use the list-interface to get and set individual records. Ciao Uwe From kartic.krishnamurthy at gmail.com Sun Jan 9 11:16:58 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 9 Jan 2005 08:16:58 -0800 Subject: use a file as a database, access rights In-Reply-To: References: Message-ID: <1105287418.765236.250270@c13g2000cwb.googlegroups.com> Steve Holden wrote: > Sounds to me like you need to add a rights layer to gadfly. Aha...I did not consider that possibility. I have not gone indepth into Gadfly...is that a straigtforward thing to implement? From jeff at ccvcorp.com Thu Jan 6 15:43:18 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 06 Jan 2005 12:43:18 -0800 Subject: What could 'f(this:that=other):' mean? In-Reply-To: <41DCE28B.70806@pytex.org> References: <41DC52CA.5070104@pytex.org> <10toomjdjcs5v21@corp.supernews.com> <41DCE28B.70806@pytex.org> Message-ID: <10tr8eo5skqo2a3@corp.supernews.com> Jonathan Fine wrote: > Jeff Shannon wrote: > >> Jonathan Fine wrote: >> >>> Giudo has suggested adding optional static typing to Python. >>> (I hope suggested is the correct word.) >>> http://www.artima.com/weblogs/viewpost.jsp?thread=85551 >>> >>> An example of the syntax he proposes is: >>> > def f(this:that=other): >>> > print this > > > > >>> I'm going to suggest a different use for a similar syntax. >>> >>> In XML the syntax >>> > >>> is used for name spaces. >>> >>> Name spaces allow independent attributes to be applied to an >>> element. For example, 'fo' attributes for fonts and layout. >>> XSLT is of course a big user of namespaces in XML. >>> >>> Namespaces seems to be a key idea in allow independent >>> applications to apply attributes to the same element. >>> [...] >>> Here's an example of how it might work. With f as above: >>> > f(this:that='value') >>> {'that': 'value'} >> >> >> >> I fail to see how this is a significant advantage over simply using >> **kwargs. It allows you to have multiple dictionaries instead of just >> one, that's all. And as you point out, it's trivial to construct your >> own nested dicts. > > > This argument could be applied to **kwargs (and to *args). In other > words, **kwargs can be avoided using a trivial construction. The use of *args and **kwargs allows functions to take a variable number of arguments. The addition of ***nsargs does not add significantly. Note that *args and **kwargs should always be used together, because to do otherwise would require the function caller to know details of the function's implementation (i.e. which arguments are expected to be positional and which must be keywords). Since we *want* the caller to not need to know this, then ***nsargs would always need to be used together with *args and **kwargs. (A function defined 'def f(***nsargs): ...' could not be called with 'f(1)'. This means that all you're gaining is an extra bag to put variable numbers of arguments in. The value here is that it maintains a parallel with *args and **kwargs when one allows 'namespaced' arguments -- if one allows that, then ***nsargs is required for consistency's sake, but it does not simplify anything by itself. So really, we need to look at what gains we'd get from having 'namespaced' arguments. What's the real advantage here? When using 'namespace' arguments, instead of standard keyword arguments, the function body would be given a dictionary instead of a set of local variables, right? 'def f1(arg1, arg2, arg3, arg4)' creates four names in locals(), where 'def f2(ns1:arg1, ns1:arg2, ns1:arg3, ns1:arg4) creates a single dict named ns1 in locals(), which contains four items (keyed on 'arg1', 'arg2', etc.), and 'def f3(ns1:arg1, ns1:arg2, ns2:arg3, ns2:arg4)' creates two dicts (ns1 and ns2) with two entries each. Okay, now, let's take a look at how these functions will be used. f1(1, 2, 3, 4) f1(arg1=1, arg2=2, arg3=3, arg4=4) Note that f1 doesn't care which of these methods of calling is employed -- both result in the same situation inside of f1(). So what's the intended way of calling f2()? I'd presume that it shouldn't care whether keywords or namespaces are specified, so that the following should all be equivalent: f2(1, 2, 3, 4) f2(1, 2, arg3=3, arg4=4) f2(1, 2, arg3=3, ns1:arg4=4) Note that this doesn't *add* any utility. The function caller hasn't gained anything. Since arg4 is unambiguous regardless of whether it's referred to as arg4 or ns1:arg4, the only time that the caller has any reason to specify the namespace is if argnames within different namespaces clash -- that is, if we allow something like 'def f4(ns1:arg1, ns1:arg2, ns2:arg1, ns2:arg2)'. Now, though, we've lost the ability to specify *only* the argname and not the namespace as well -- that is, you *cannot* call f4 with keywords but not namespaces. From the caller's vantage point, this means that they need to know the full namespace spec of the function, which makes it no different than simply using longer (but unique) keyword names. So, we can see that allowing namespaces and ***nsargs doesn't add any utility from the caller's perspective. How much does the callee gain from it? Well, the following functions would be equivalent: def g1(arg1, arg2, arg3, arg4): ns1 = {'arg1':arg1, 'arg2':arg2, 'arg3':arg3, 'arg4':arg4} return ns1 def g2(ns1:arg1, ns1:arg2, ns1:arg3, ns1:arg4): return ns1 You might say "Wow, look at all that repetetive typing I'm saving!" But that *only* applies if you need to stuff all of your arguments into dictionaries. I suspect that this is a rather small subset of functions. In most cases, it will be more convenient to use your arguments as local variables than as dictionary entries. def gcd1(a, b): while a: a, b = b%a, a return b def gcd2(ns1:a, ns1:b): while ns1['a']: ns1['a'], ns1['b'] = ns1['b']%ns1['a'], ns1['a'] return ns1['b'] Speaking of repetetive typing.... :P Besides, another function equivalent to the above two would be: def g3(arg1, arg2, arg3, arg4): ns1 = locals() return ns1 ...which is quite a bit less repetetive typing than the 'namespace' version. So, you're looking at making the function-calling protocol significantly more complex, both for caller and callee, for the rather marginal gain of being able to get arguments prepackaged in a dictionary or two, when there already exist easy ways of packaging function arguments into a dict. Given the deliberate bias against adding lots of new features to Python, one needs a *much* better cost/benefit ratio for a feature to be considered worthwhile. >> Besides, Python already uses the concept of namespaces by mapping them >> to object attributes. [...] > > Here, I don't understand. Could you give an example of two obvious ways > of doing the same thing, should my suggestion be adopted? My main point here is that 'namespace' is a term/concept that is already in use in Python, in different circumstances and using a completely different mechanism. Functions already *have* namespaces, whose contents can be inspected with locals() and modules have namespaces that can be accessed through globals(). I'd note also that the usage you're drawing from, in XML/XSLT, isn't really comparable to function parameters. It's a much closer parallel to object attributes. Python *does* have this concept, but it's spelled differently, using a '.' instead of a ':'. In other words, the XML fragment you give, ... would be more appropriate to render in Python as e = Element() e.this.that = 'other' It's quite reasonable to suppose that some object of type Element may have a set of font attributes and a set of image attributes, and that some of these may have the same name. Python would use font objects and image objects instead of 'namespaces' -- e.font.size = '14pt' e.image.size = (640, 480) So while these namespaces are probably a great thing for XML, XSLT, they're not very useful in Python. Which, given the rather different goals and design philosophies behind the languages, shouldn't really be much of a surprise. Jeff Shannon Technician/Programmer Credit International From fuzzyman at gmail.com Fri Jan 28 10:09:44 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 28 Jan 2005 07:09:44 -0800 Subject: Help with web dashboard In-Reply-To: References: Message-ID: <1106924984.507889.265070@c13g2000cwb.googlegroups.com> Ifd you want to use standard CGI I've written a CGI user authentication/management module called logintools. See http://www.voidspace.org.uk/python/logintools.html Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From http Fri Jan 7 16:28:33 2005 From: http (Paul Rubin) Date: 07 Jan 2005 13:28:33 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> Message-ID: <7xmzvl0vzy.fsf@ruckus.brouhaha.com> Donn Cave writes: > I don't by any means agree that this notation is worth adopting, and > in general I think this kind of readability issue is more or less a lost > cause for a language with Python's scoping rules, but the motive makes > sense to me. But we're talking about the mythical/hypothetical Python 3, so maybe there's a chance of fixing the scoping rules, which it seems to me are currently pretty badly broken. From rogerb at rogerbinns.com Tue Jan 11 02:28:42 2005 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 10 Jan 2005 23:28:42 -0800 Subject: PyChecker messages References: Message-ID: > runner.py:878: Function (main) has too many lines (201) > > What does this mean? Cannot functions be large? Or is it simply an advice that > functions should be small and simple? It is advice. > runner.py:200: Function (detectMimeType) has too many returns (11) > > The function is simply a long "else-if" clause, branching out to different > return statements. What's wrong? It's simply a "probably ugly code" advice? That is also advice. Generally you use a dict of functions, or some other structure to lookup what you want to do. > _must_ take two arguments; is there any way that I can make 'frame' go away? Yes, you can name it just _ (underscore). There are a few other names like that that are ignored. (Check the doc). > Also, another newbie question: How does one make a string stretch over several > lines in the source code? Is this the proper way? > > print "asda asda asda asda asda asda " \ > "asda asda asda asda asda asda " \ > "asda asda asda asda asda asda" Depends what you are trying to achieve. Look at triple quoting as well. Roger From Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org Sun Jan 30 23:40:38 2005 From: Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org (Alexander) Date: Mon, 31 Jan 2005 07:40:38 +0300 Subject: variable declaration Message-ID: Hello All! I'am novice in python, and I find one very bad thing (from my point of view) in language. There is no keyword or syntax to declare variable, like 'var' in Pascal, or special syntax in C. It can cause very ugly errors,like this: epsilon=0 S=0 while epsilon<10: S=S+epsilon epselon=epsilon+1 print S It will print zero, and it is not easy to find such a bug! Even Visual Basic have 'Option Explicit' keyword! May be, python also have such a feature, I just don't know about it? Alexander, zatv at bk.ru From fredrik at pythonware.com Sun Jan 16 05:41:51 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 16 Jan 2005 11:41:51 +0100 Subject: How to del item of a list in loop? References: <1105835640.771989.163400@f14g2000cwb.googlegroups.com> Message-ID: John Machin wrote: >> (if you have 2.4, try replacing [] with () and see what happens) > > The result is a generator with a name ("lst") that's rather misleading > in the context. according to my dictionary, the word "list" means "A series of names, words, or other items written, printed, or imagined one after the other". I'd say that matches both list objects and iterators pretty well. but alright, you can change the name to "seq" if you want. > Achieving the same result as the list comprehension, by doing lst = list(i for ... etc etc), appears to be slower. the original post didn't contain a complete use case; a generator is a perfect replacement for a list in many cases. I'm sure most comp.lang.python readers are smart enough to understand when and why. From fumanchu at amor.org Fri Jan 14 12:36:05 2005 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 14 Jan 2005 09:36:05 -0800 Subject: python to mssql Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33981C0@exchange.hqamor.amorhq.net> Brane wrote: > can someone please give me some info regarding subject http://sourceforge.net/projects/mysql-python Ask a broad question... Robert Brewer MIS Amor Ministries fumanchu at amor.org From brion at pobox.com Tue Jan 11 00:49:24 2005 From: brion at pobox.com (Brion Vibber) Date: Mon, 10 Jan 2005 21:49:24 -0800 Subject: OT: MoinMoin and Mediawiki? In-Reply-To: <7x6524d6pv.fsf@ruckus.brouhaha.com> References: <7x6524d6pv.fsf@ruckus.brouhaha.com> Message-ID: <34h7m9F43vomsU1@individual.net> Paul Rubin wrote: > Mediawiki is written in PHP and > is far more complex than MoinMoin, plus it's database backed, meaning > you have to run an SQL server as well as the wiki software itself > (MoinMoin just uses the file system). Plus, I'll guess that it really > needs mod_php, while MoinMoin runs tolerably as a set of cgi's, at > least when traffic is low. MediaWiki should run with PHP configured in CGI handler mode, but these days mod_php has got its claws just about everywhere anyway. If you control your own server and don't have multi-user security worries, mod_php is simple enough to install and will probably perform better. For performance I also highly recommend using Turck MMCache or equivalent PHP bytecode cache extension. Unlike Python, saving compiled bytecode is not the default behavior of PHP, and for non-trivial scripts compilation eats up a lot of runtime. > I'll say that I haven't actually looked at > the Mediawiki code, though I guess I should do so. Cover your eyes...! it _is_ PHP after all. ;) > What I'm getting at is I might like to install MoinMoin now and > migrate to Mediawiki sometime later. Anyone have any thoughts about > whether that's a crazy plan? Should I just bite the bullet and run > Mediawiki from the beginning? Is anyone here actually running > Mediawiki who can say just how big a hassle it is? I would generally recommend you just start with MediaWiki if you intend to use it. To migrate a non-tiny site later you'll need to work out a migration script to import your data in some way (some people have asked about this in the past, I don't know if anyone's ever completed one or made it public). On the other hand if you _do_ write a MoinMoin-to-MediaWiki conversion script (or vice-versa!) we'd love to include it in the MediaWiki distribution. -- brion vibber (brion @ pobox.com) From http Fri Jan 14 15:30:57 2005 From: http (Paul Rubin) Date: 14 Jan 2005 12:30:57 -0800 Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <1105734450.961150.32980@z14g2000cwz.googlegroups.com> Message-ID: <7xfz13zrb2.fsf@ruckus.brouhaha.com> "Chris Lasher" writes: > Forgive my ignorance, but what does using mmap do for the script? My > guess is that it improves performance, but I'm not sure how. I read the > module documentation and the module appears to be a way to read out > information from memory (RAM maybe?). Mmap lets you treat a disk file as an array, so you can randomly access the bytes in the file without having to do seek operations. Just say a[234]='x' and you've changed byte 234 of the file to the letter x. It works through the OS's virtual memory system and the computer's MMU hardware, and so it has lower overhead than doing system calls for every access. From deetsNOSPAM at web.de Wed Jan 26 09:33:01 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 26 Jan 2005 15:33:01 +0100 Subject: 4suite XSLT thread safe ? References: <6lkkc2-fbd.ln1@pluto.i.infosense.no> Message-ID: <35pntaF4os76kU1@individual.net> Ola Natvig wrote: > Anybody out there who knows if the 4suite implementation of XSLT are a > threadsafe one? What do you mean by that? You can of course transform xml using xslt in as many threads as you like - but what do you want with two or more threads in _one_ transformation? You start it, and some time later the result is there. -- Regards, Diez B. Roggisch From roy at panix.com Tue Jan 4 20:06:56 2005 From: roy at panix.com (Roy Smith) Date: Tue, 04 Jan 2005 20:06:56 -0500 Subject: coding conventions, PEP vs. practice References: Message-ID: Roman Roelofsen wrote: > These frameworks are using "mixedCase" but PEP8 suggests > "lower_case_with_underscores" except "in contexts where that's already the > prevailing style" which is not the case here IMHO. > > So, are there any specific reasons for breaking the rules here? I think > consistent conventions are very important. Being a Java developer in the last > couple of years, i learned how practical it can be to have only one naming > style. My personal preference is camelCase over words_with_underscores, but fundamentally, this is a bit of a religious issue. Pick a style, and go with it. If you're working on existing code, go with the prevailing style. If you're working in a group, pick a common style and go with the group decision. Of all the software engineering issues to worry about, this is pretty low on the list. From martin at v.loewis.de Mon Jan 17 17:24:51 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 17 Jan 2005 23:24:51 +0100 Subject: Static executable with shared modules In-Reply-To: References: <41e80078$0$1518$9b622d9e@news.freenet.de> Message-ID: <41ec3b31$0$3328$9b622d9e@news.freenet.de> Rickard Lind wrote: > I'll be more specific: when I build python 2.3.4 on FreeBSD 4.9, > the interpreter binary is linked against three shared libraries: > libutil.so.3, libm.so.2 and libc_r.so.4. Now, these libraries are > not present on the TARGET system (which is distinct from the build > system, but based on the same version of FreeBSD) so I add "-static" > to LDFLAGS. This produces an interpreter that runs on the target > system (no dependency on shared libc etc) but it also cannot load > modules compiled as shared libraries. Man page for dlopen(3) says > it is located in libc (and consquently there seems to be no libdl), > and anyway I'd expect to get a link error if the dl* functions were > not present. What I DO get is an ImportError exception. Most likely, the static libc.a does not provide dlopen (contrary to what the man page says). Python's configure detects that you don't have dlopen (when linking with -static), and concludes that dynamic loading of modules is not supported on your system. Then, during import, it checks built-in modules, module.py, module.pyc, and finds neither - it then reports an import error. To confirm this theory, have a look at pyconfig.h, and check whether HAVE_DLOPEN and/or HAVE_DYNAMIC_LOADING are defined; I expect that neither is defined. > At present I see no other option than to link the modules into the > interpreter which is very inconvenient since I'll have to rebuild > the every time a module changes :-( The other option, clearly, is to move the shared libraries to the target system along with the interpreter binary (assuming the target system supports shared libraries). If the target system does not have a dlopen, and the static libc.a does not have dlopen, either, there is nothing you can do except to use a different operating system. Regards, Martin From steve at holdenweb.com Thu Jan 13 09:56:15 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 13 Jan 2005 09:56:15 -0500 Subject: Octal notation: severe deprecation In-Reply-To: <1105587098.932273.315230@c13g2000cwb.googlegroups.com> References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> Message-ID: <41E68C0F.4040205@holdenweb.com> and-google at doxdesk.com wrote: > John Machin wrote: > > >>I regard continued usage of octal as a pox and a pestilence. > > > Quite agree. I was disappointed that it ever made it into Python. > > Octal's only use is: > > a) umasks > b) confusing the hell out of normal non-programmers for whom a > leading zero is in no way magic > > (a) does not outweigh (b). > > In Mythical Future Python I would like to be able to use any base in > integer literals, which would be better. Example random syntax: > > flags= 2x00011010101001 > umask= 8x664 > answer= 10x42 > addr= 16x0E800004 # 16x == 0x > gunk= 36x8H6Z9A0X > > But either way, I want rid of 0->octal. > > >>Is it not regretted? > > > Maybe the problem just doesn't occur to people who have used C too > long. > :-) > OT: Also, if Google doesn't stop lstrip()ing my posts I may have to get > a proper news feed. What use is that on a Python newsgroup? Grr. I remember using a langauge (Icon?) in which arbitrary bases up to 36 could be used with numeric literals. IIRC, the literals had to begin with the base in decimnal, folowed by a "b" followed by the digits of the value using a through z for digits from ten to thirty-five. So gunk = 36b8H6Z9A0X would have been valid. nothing-new-under-the-sun-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From bill.mill at gmail.com Fri Jan 28 11:28:54 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 28 Jan 2005 11:28:54 -0500 Subject: Dynamic class methods misunderstanding In-Reply-To: <1106928492.114459.191320@c13g2000cwb.googlegroups.com> References: <1106928492.114459.191320@c13g2000cwb.googlegroups.com> Message-ID: <797fe3d405012808284aed5cf1@mail.gmail.com> Kamilche, On Fri, 28 Jan 2005 08:10:07 -0800 (PST), Kamilche wrote: > I see what you're attempting to do. However, your code, if it DID run, > would result in a method being added to the object, not the object's > class! Modify the class itself, not the object, as follows: > > |class Test: > | def __init__(self): > | self.method() > | > |def m(self): > | print self > | > |setattr(Test, 'method', m) > |Test() > beautiful; so this appears to be equivalent to the __class__ method that Hans suggested. Thanks a lot. Peace Bill Mill bill.mill at gmail.com > -- > http://mail.python.org/mailman/listinfo/python-list > From spam at nospam.org Tue Jan 25 17:19:56 2005 From: spam at nospam.org (Erik Johnson) Date: Tue, 25 Jan 2005 15:19:56 -0700 Subject: building Python: up arrow broken on SuSE Linux 8.2 Message-ID: <41f6c3f7$1@nntp.zianet.com> I am trying to upgrade my Python installation. After downloading sources and building Python 2.3.4, I am unable to use the command history editing feature in the interactive interpreter (where the up-arrow would previously give you the last command line to edit, it now just prints "^[[A".) This is a feature I use often, and it kinda nullifies that warm fuzzy feeling you get when things are otherwise working as expected. Python 2.2.2 was installed via YaST (standard SuSE distribution) and works fine. Unfortunately, several modules I need are not part of that installation and there doesn't seem to be a newer installation via that route (that I know of). I downloaded source and built Python 2.3.4 in my local directory. There were a lot of warnings like this: Objects/intobject.c:1125: warning: comparison between signed and unsigned Objects/intobject.c:1135: warning: comparison between signed and unsigned I don't know exactly what "normal" output is, but things seem to have gone pretty well, as this is the output after 'make test': ... test_zlib 226 tests OK. 29 tests skipped: test_aepack test_al test_bsddb test_bsddb185 test_bsddb3 test_cd test_cl test_curses test_dbm test_email_codecs test_gdbm test_gl test_imgfile test_linuxaudiodev test_macfs test_macostools test_nis test_normalization test_ossaudiodev test_pep277 test_plistlib test_scriptpackages test_socket_ssl test_socketserver test_sunaudiodev test_timeout test_urllibnet test_winreg test_winsound 3 skips unexpected on linux2: test_dbm test_gdbm test_bsddb (I'm not doing anything with DBM stuff, so I don't think I care about the three skipped tests.) I thought the problem may have had something to do with the curses module, which is apparently not enabled by default. In the Modules/Setup file, I changed this: # First, look at Setup.config; configure may have set this for you. #_curses _cursesmodule.c -lcurses -ltermcap # Wrapper for the panel library that's part of ncurses and SYSV curses. #_curses_panel _curses_panel.c -lpanel -lncurses to this (my system has /usr/lib/libncurses.so.5.3): # First, look at Setup.config; configure may have set this for you. #_curses _cursesmodule.c -lcurses -ltermcap _curses _cursesmodule.c -lncurses # Wrapper for the panel library that's part of ncurses and SYSV curses. #_curses_panel _curses_panel.c -lpanel -lncurses I got a clean compile and the test_curses.py file executes silently: sand:~/Python-2.3.4/Lib/test> ../../python ./test_curses.py sand:~/Python-2.3.4/Lib/test> Unfortunately, that didn't solve the problem. Has anyone else seen this problem? Or, more importantly, can someone tell me how to fix this? Thanks for taking the time to read my post. -ej From elephantum at dezcom.mephi.ru Tue Jan 11 08:50:38 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Tue, 11 Jan 2005 16:50:38 +0300 Subject: embedded scripts debugging In-Reply-To: References: <347dpqF45nskbU1@individual.net> Message-ID: <34i3teF4auq8gU1@individual.net> Miki Tebeka wrote: >>So the question is: Is there suitable library for simple python gui >>debugger, or may be there are some other techniques for debugging >>embedded scripts? > > What I usually do is add > from pdb import set_trace > in the embedded module somewhere and then add a call to set_trace > (breakpoint) whenever I with. > When the code reaches the call to set_trace, you'll have pdb prompt and you > can debug as you like. > > Note that you can't add breakpoint dynamically this way. Thanks, I gathered pros and cons of embedding and decided to use python extending (i.e. creating python modules) instead of embedding. Happily I have an option to choose From maxm at mxm.dk Sat Jan 8 11:30:19 2005 From: maxm at mxm.dk (Max M) Date: Sat, 08 Jan 2005 17:30:19 +0100 Subject: Returning same type as self for arithmetic in subclasses In-Reply-To: References: <41df0d7b$0$190$edfadb0f@dread12.news.tele.dk> Message-ID: <41e00a3b$0$265$edfadb0f@dread12.news.tele.dk> Tim Peters wrote: > Yes, and all builtin Python types work that way. For example, > int.__add__ or float.__add__ applied to a subclass of int or float > will return an int or float; similarly for a subclass of str. This > was Guido's decision... I will not discuss it with him. He is usually right :-s > Generally speaking, no. But I'm sure someone will torture you with a > framework that purports to make it easy . Apparently not... But here is my solution. If anybody is interrested. It should also be obvious what I am working on. Btw. I really love doctests ... Unittests are a nice idea. But doctest is a really practical solution. ############################### class vDatetime(datetime): """ A subclass of datetime, that renders itself in the iCalendar datetime format. >>> dt = vDatetime(1970, 1,1, 12, 30, 0) >>> str(dt) '19700101T123000' >>> dt2 = vDatetime(1970, 1,1, 0, 0, 0) >>> str(dt - dt2) 'PT12H30M' Adding is not allowed >>> dt + dt2 Traceback (most recent call last): ... AttributeError: 'NotImplementedType' object has no attribute 'days' """ def __init__(self, *args, **kwargs): datetime.__init__(self, *args, **kwargs) self.params = Params() def __add__(self, other): return self._to_vdatetime(datetime.__add__(self, other)) def __sub__(self, other): return self._to_vdatetime(datetime.__sub__(self, other)) def _to_vdatetime(self, result): if hasattr(result, 'timetuple'): return vDatetime(*result.timetuple()[:6]) return vDuration(result.days, result.seconds) def fromstring(st): "Class method that parses" try: timetuple = map(int, (( st[:4], # year st[4:6], # month st[6:8], # day st[9:11], # hour st[11:13], # minute st[13:15], # second ))) except: raise ValueError, 'Wrong format' return vDatetime(*timetuple) fromstring = staticmethod(fromstring) def __str__(self): return self.strftime("%Y%m%dT%H%M%S") -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From baza at localhost.localdomain Wed Jan 12 17:50:34 2005 From: baza at localhost.localdomain (baza) Date: Wed, 12 Jan 2005 22:50:34 +0000 Subject: Game programming in Python References: Message-ID: On Wed, 12 Jan 2005 09:49:50 +0800, Simon Wittber wrote: >> I'm looking for any books or on-line resources on game programming >> using Python. Does anyone have any advice? > > Hi Baza, > > If I you are as I assume, a programmer just starting out with game > programming, the best suggestion I can give is head over to > pygame.org, and after downloading and installing the library (also > install PyOpenGL if you can), go through the tutorials listed at > http://www.pygame.org/docs/ . > > You will also find the pygame mailing list very helpfu, and, if you > are so inclined, the IRC #pygame channel on freenode.net > > Sw. Thanks for these. I'm sorted now. pygame looks very interesting. Baz From __peter__ at web.de Thu Jan 27 03:35:21 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Jan 2005 09:35:21 +0100 Subject: string.atoi and string.atol broken? [OT] References: <1106700417.482871.45140@z14g2000cwz.googlegroups.com> Message-ID: Christos TZOTZIOY Georgiou wrote: >>> In current Greek hexadecimal is "????????????" ("dekaexadikon"). I borrowed Guido's time machine to fix the above (hopefully) :-) >>The Latin part escaped me. > > By Latin I suppose you jokingly mean the Greek parts... :) I thought it was a well-known fact that speakers of the awful German language have absolutely no humour. My first assumption was that hexadecimal is Greek and then I modified that to a Greek/Latin combo "???decimal". > Just in case it didn't show up correctly in your ng/mail client, it does > on groups.google.com (the post was in UTF-8, dammit! --excuse my romance > language) It did show up correctly, but was garbled in the response through technical incompetence of the poster. Peter From deetsNOSPAM at web.de Wed Jan 12 11:00:08 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 12 Jan 2005 17:00:08 +0100 Subject: Iteration over two sequences References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> Message-ID: <34kvs0F4bqiviU1@individual.net> zip or izip is your friend: import itertools a = [1,2,3] b = ['a', 'b', 'c'] for a,b in itertools.izip(a, b): print a, b -- Regards, Diez B. Roggisch From ark at acm.org Wed Jan 12 13:07:47 2005 From: ark at acm.org (Andrew Koenig) Date: Wed, 12 Jan 2005 18:07:47 GMT Subject: counting items References: Message-ID: "It's me" wrote in message news:ukdFd.10645$5R.2000 at newssvr21.news.prodigy.com... > What's the best way to count number of items in a list? > > For instance, > > a=[[1,2,4],4,5,[2,3]] > > I want to know how many items are there in a (answer should be 7 - I don't > want it to be 4) How about this? def totallen(x): if isinstance(x, (list, tuple, dict)): return sum(map(totallen, x)) return 1 From fperez.net at gmail.com Sat Jan 29 04:58:43 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Sat, 29 Jan 2005 02:58:43 -0700 Subject: Installing Numeric with ATLAS and LAPACK References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> <1106940704.164253.134630@c13g2000cwb.googlegroups.com> <1106971706.986114.26420@c13g2000cwb.googlegroups.com> Message-ID: drife wrote: > Could you clarify this please? > > Let's say that I want to make a call to the LAPACK > routine sspevd, and pass it a matrix, and get the result. How do I > accomplish this? I just had a quick look, and it seems that sspevd is NOT one of the already wrapped LAPACK functions. Try dir(scipy.linalg.flapack) and dir(scipy.linalg.clapack) to see what's been already wrapped. From what I understand, wrapping more of lapack is rather easy, it's just that nobody has committed the time to 100% coverage. But this question is much better posed on the scipy list, where the people who wrote the lapack wrapping code can give you a better answer (I didn't). Cheers, f From weblord at gmail.com Sat Jan 1 23:08:48 2005 From: weblord at gmail.com (weblord at gmail.com) Date: 1 Jan 2005 20:08:48 -0800 Subject: Mailing list hosting? In-Reply-To: <87d67lwxv6.fsf@pobox.com> References: <8765dhd2dr.fsf@pobox.com> <878yibccyz.fsf@pobox.com> <87d67lwxv6.fsf@pobox.com> Message-ID: <1104638928.465176.206870@z14g2000cwz.googlegroups.com> free mailing list offer - limited time http://nabaza.com/autoresponders.htm From anno4000 at lublin.zrz.tu-berlin.de Tue Jan 11 12:59:17 2005 From: anno4000 at lublin.zrz.tu-berlin.de (Anno Siegel) Date: 11 Jan 2005 17:59:17 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: It's me wrote in comp.lang.perl.misc: [reply moved to bottom into context] > "J?rgen Exner" wrote in message > news:Fm6Ed.3556$u47.321 at trnddc09... > > xah at xahlee.org wrote: > > > #python supports complex numbers. > > [...] > > > > So? > > > > The world would come to a halt if all of a sudden nobody understands complex > numbers anymore. :-) > > > > # Perl doesn't support complex numbers. But there are packages that > > > supports it. > > > > The Math::Complex module is part of the standard installation already, no > > need for any "packages" (whatever that might be). > > Did you check "perldoc Math::Complex" > > > > NAME > > Math::Complex - complex numbers and associated mathematical functions > > [...] > For those of us that works with complex numbers, having complex number as a > natively supported data type is a big advantage. Non-native add-ons are not > sufficient and lead to very awkward program code. Like this? use Math::Complex; my $z = sqrt( -1); print 1 + $z, "\n"; # prints "1+i" Operator overloading makes it possible to work with complex numbers as if they were a native data type. Anno From phr at localhost.localdomain Fri Jan 28 06:35:59 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Fri, 28 Jan 2005 11:35:59 GMT Subject: Elliptic Code References: Message-ID: "Philip Smith" writes: > Does anyone have/know of a python implementation of the elliptic curve > factoring algorithm (lenstra) which is both: > > simply and cleanly coded > functional It's not in Python but take a look at Mike Scott's C++ implementation in MIRACL, http://indigo.ie/~mscott/ It's the simplest and most direct implementation I know of, just the bare essentials. It could probably be translated into Python pretty straightforwardly. > I'm aware of William Stein's code (from elementary number theory > book) but I don't understand his coding style and the algorithm > doesn't seem to work efficiently. A high performance implementation means complicated code, e.g. Peter Montgomery has done a few of those. If it's for instructional purposes I think the MIRACL version is far more understandable even if it's slower. If you mean you don't understand the algorithm, try Neal Koblitz's book "A Course in Number Theory and Cryptography". It has no code but it explains the algorithm in a pretty accessible way. From steve at holdenweb.com Thu Jan 6 09:42:42 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Jan 2005 09:42:42 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> <1gpwrh7.b7z8qtablx7gN%aleaxit@yahoo.com> Message-ID: <41DD4E62.1020404@holdenweb.com> Bulba! wrote: > On Wed, 5 Jan 2005 11:19:56 +0100, aleaxit at yahoo.com (Alex Martelli) > wrote: [...] > You see, I'm not disagreeing with you that your model applies > _where it applies_. I only disagree that it applies in face of > stronger forces. Now what kind of forces is dominant in > most frequent scenarios would have to be worked out in tedious > empirical research I think. Which I haven't done, because > learning some economics is just a hobby to me. > Yes, by all means let's just spout our opinions without any of that inconvenient tedious empirical research which might invalidate them. > [...] >>Italian, at most German and French, and not Polish or Russian, closeness >>to good international airports and other good transportation, closeness >>to partner firms and potential customers' decision-makers, all appeared >>to point to Warsaw, if I recall correctly. Mechanical engineers with >>some programming experience or viceversa, good translators, and good >>salespeople with connections in the mechanical industry, are not as >>ultra-specialized as all that, after all. > > > Most sales offices in Warsaw do not employ esp. educated people in > my impression. OTOH, the carmaking facilities nowadays require > more much more know-how and specialized workforce than a sales > office does. Or at least that was my impression when I worked at > the construction machine manufacturer in Berlin. > Again you are forming impressions form rather limited evidence: I might agree with you about the relative intelligence and education of engineers over sales people, but that might be *my* bias showing. > Capital investments per worker in auto industries are reportedly > very high. Simple physical tasks are done largely by machines, > like this 100 million Deutschmark costing laser-cutting installation > that I've seen there, where a pile of iron bars is pulled in at one > end and the pile of ready components is spitted out of the other end > (unlike typical thermal cutting, laser has the advantage of not > destroying the metal structure adjacent to the cut, so the parts > of the machines subject to high-stress are oft produced this way). > The same is true of plasma-arc cutting for thicker steels, and I believe it's still not possible to cut 3-inch stainless with a laser. But what's your point? > Oh, and by the way that installation doesn't get used much. > Somebody at the office didn't check carefully enough the > energy prices before ordering it and later someone discovered > that off-site specialized cutting firms that take advantage of > energy available at low prices at special times in other countries > can get it produced cheaper. Moving it elsewhere or selling > is not an option, since it is a specially constructed, low, 50-meters > long hall that stands inside the huge manufacturing hall of the > company. > And you are using this example to try and argue that engineers are better-educated than sales people? Who sold this installation? Who bought it? How much, therefore, is education worth? > 100 million DM (when 1 DM was worth some half of Euro > back then) down the drain. When the company was in rather > bad financial situation (later I've learned it was finally bought > out by Americans). Oh well. No big deal. > > I was utterly shocked. Having grown up in Soviet times I have > been used to seeing precious resources wasted by organizations > as if resources were growing on trees, but smth like this?! In a > shining ideal country of Germany?! Unthinkable. > Indeed not. Quite often the brown paper bag is a factor in purchases like this. I wouldn't be at all surprised if somebody with a major input to the decision-making process retired to a nice place in the country shortly afterwards. You appear to be making the mistake of believing that people will act in the larger interest, when sadly most individuals tend to put their own interests first (some would go as far as to define self-interest as the determinant of behavior). > >>The firm I was working for had a consensus decision-making process (even >>I was involved) and managers (and other employees) and stockholders were >>mostly the same people -- it wasn't all that large a firm at the time. >>Nobody needed to practice risk avoidance. > > > Again, you may have had good luck. Where I worked (including > some places in Germany and UK) it was almost the only factor > that seemed to matter to people - they'd do ANYTHING not to > take a risky decision, to "pass the buck", not to stick their necks > out, not to declare doing some work that involved challenges. > Some people are like that. I chose a long time ago to try not to work with them whenever I could avoid it and, while that may have had negative economic consequences I an convinced it has improved my quality of life immensely. Of course, I have no proof for such an assertion. > [and on, and on, and on ...] regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From ariza at flexatone.com Thu Jan 13 05:53:15 2005 From: ariza at flexatone.com (ariza) Date: 13 Jan 2005 02:53:15 -0800 Subject: site.here on python 2.4 References: <1105609399.915874.71150@z14g2000cwz.googlegroups.com> Message-ID: <1105613595.725326.9950@z14g2000cwz.googlegroups.com> i am not sure where i found site.here documented as used prior to 2.4. the issue is that i do not need sys.path, as in the list of all paths that python searches. sys.prefix is close to what i need: >>> sys.prefix '/System/Library/Frameworks/Python.framework/Versions/2.3' but the old site.here gave sys.prefix, plus the additional directories to get into the actual python library: >>> site.here '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3' can we assume that, on all platforms, the old site.here is the same as: >>> os.path.join(sys.prefix, 'lib', 'python%s' % sys.version[:3]) '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3' or is it better to use, as you suggest, >>> import os >>> os.path.dirname(os.__file__) '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3' this is useful for a few reasons. the first was i needed a cross platform way to find the complete path to the idle directory; the second was the complete path to the 'site-packages' directory. thanks! From macrocosm at fastmail.fm Thu Jan 13 14:09:46 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Thu, 13 Jan 2005 14:09:46 -0500 Subject: Python.org, Website of Satan In-Reply-To: References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: <41E6C77A.40803@fastmail.fm> Jane wrote: >"Lucas Raab" wrote in message >news:UsuFd.5434$KJ2.1253 at newsread3.news.atl.earthlink.net... > > >>Jane wrote: >> >> >>> wrote in message >>>news:1105495569.479185.166340 at z14g2000cwz.googlegroups.com... >>> >>> >>> >>>>python.org = 194.109.137.226 >>>> >>>>194 + 109 + 137 + 226 = 666 >>>> >>>>What is this website with such a demonic name and IP address? What >>>>evils are the programmers who use this language up to? >>>> >>>> >>>> >>>Some people have too much time on their hands... >>> >>>Jane >>> >>> >>> >>> >>Better get some ointment for that burn!! >> >> > >Huh??? > >Jane > > > > You said that people have too much "time" on their "hands", so he suggested ointment to prevent the irritation etc... He was probably also getting at the topic of this thread (hint: Satan = Hell = Fire), so the ointment puts out the burn. Have fun folks! - Arich From jacek.generowicz at cern.ch Mon Jan 17 03:26:53 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 17 Jan 2005 09:26:53 +0100 Subject: from __future__ import decorators References: Message-ID: Tim Roberts writes: > Jacek Generowicz wrote: > > > >I have some code, which makes copious use of the @decorator syntax > > I'm very curious to know what kind of application you are writing in which > "copious use of the @decorator syntax" actually solved a problem > productively. An application in which, before python2.4, I used to have lots of code that looked like def somefun(...): ... somefun = somedecorator(somefun) :-) It's not interesting to discuss what "somedecorator" actually represents. But being able to see that the function is decorated right next to the "def", as opposed to having to look beyond the end of the definition certianly makes a significant difference to me. From carribeiro at gmail.com Sat Jan 8 14:25:40 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 8 Jan 2005 17:25:40 -0200 Subject: Recent infoworld column In-Reply-To: References: <41DEEF0F.5000300@nospamyahoo.com> Message-ID: <864d3709050108112538052455@mail.gmail.com> On Sat, 08 Jan 2005 13:14:17 -0500, Peter Hansen wrote: > Dwarf Electrician wrote: > > from a long time listener... > > > > http://www.infoworld.com/article/04/12/30/01OPstrategic_1.html > > Kudos for Roger Binns! >From Mr. Udell himself: """ When people talk about the heroes of open source, you tend to hear such familiar names as Linus Torvalds, Larry Wall, Brendan Eich, Guido van Rossum, Monty Widenius, Miguel de Icaza, and Rasmus Lerdorf. No question about it: These people are my heroes. But so is Roger Binns, and so are the countless other unsung heroes of open source. For solving a host of vexing problems with quiet competence, and for doing it in ways that invite others to stand on their shoulders, I salute them all. """ That's recognition. Wow. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From Scott.Daniels at Acm.Org Mon Jan 17 12:15:34 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 17 Jan 2005 09:15:34 -0800 Subject: platform independent kbhit() In-Reply-To: References: Message-ID: <41ebef6e$1@nntp0.pdx.net> Hans Georg Krauthaeuser wrote: > I use msvcrt.kbhit() to check for a user keyboard event on windows. But > now, I would prefer to make the module independent from the platform > used. This is not in general possible; many machines do not have keyboards. You can, perhaps, build one for yourself from a pair of implementations or more. Portable software seldom comes from adding one platform at a time that the software works on. Portable software comes from working using only features common (or in rare circumstances available) on all machines in your target set, and then adding enough tests to believe the portability. CPython starts with the C89-supported environment as its base. It tries hard to stick to that abstract machine. I assume Jython does a similar thing using Java VM semantics that it trusts will be common across implementations. > I already know that I can use curses (on linux/unix) or Tkinter. > Also, I found this http://my.execpc.com/~geezer/software/kbhit.c C > source that has a kbhit() and a getch() for linux/unix that I can SWIG > to python. Either of these might be a good basis for your personal "all machines I care about" semantics. If you use curses, make sure it doesn't impose an extra constraint on all terminal access. --Scott David Daniels Scott.Daniels at Acm.Org From golux at comcast.net Sun Jan 23 03:52:14 2005 From: golux at comcast.net (Stephen Waterbury) Date: Sun, 23 Jan 2005 03:52:14 -0500 Subject: [OT] XML design intent ... further musings In-Reply-To: <7xhdl8pz1j.fsf@ruckus.brouhaha.com> References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> <41F2C840.2050304@comcast.net> <7xhdl8pz1j.fsf@ruckus.brouhaha.com> Message-ID: <41F365BE.20102@comcast.net> Paul Rubin wrote: > Stephen Waterbury writes: >>I should note that I have to deal with XML a lot, but always >>kicking and screaming (though much less now because of Fredrik's >>Elementtree package ;). Thanks, Fredrik and Peter, for the >>references. ;) > > I love this old rant about XML: > > http://groups-beta.google.com/group/comp.lang.lisp/msg/9a30c508201627ee Yep, Erik Naggum is one of my heroes for that! :) From tchur at optushome.com.au Mon Jan 10 16:44:35 2005 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 11 Jan 2005 08:44:35 +1100 Subject: Python and Tsunami Warning Systems Message-ID: <41E2F743.90807@optushome.com.au> Boc Cringely's column on the need for a grassroots (seaweed roots?) tsunami warning system for the Indian Ocean (and elsewhere) makes some very good points - see http://www.pbs.org/cringely/pulpit/pulpit20041230.html In his following column ( http://www.pbs.org/cringely/pulpit/pulpit20050107.html ), he notes: "Now to last week's column about tsunamis and tsunami warning systems. While my idea may have set many people to work, only a couple of them have been telling me about it. Developer Charles R. Martin and Canadian earth scientist Darren Griffith met through this column, and are in the initial stages of building an Open Tsunami Alerting System (OTAS). Although work has just started, they've established a few basic principles: OTAS will be very lightweight; will use openly available geophysical or seismic data sources; will be highly distributed and decentralized; and will be built to run on very low-powered commodity hardware. They currently foresee using Python and Java, but aren't religious about it. Anyone who wants to help out is welcome and their OTAS blog can be found in this week's links." See http://otasblog.blogspot.com/ It seems to me that this would be a valuable and feasible type of project for the Python community to get involved in (or perhaps take the lead on). Something the PSF might even consider resourcing to some degree? Tim C From rkern at ucsd.edu Tue Jan 4 20:16:30 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 04 Jan 2005 17:16:30 -0800 Subject: coding conventions, PEP vs. practice In-Reply-To: References: Message-ID: Roman Roelofsen wrote: > Dear python-list, > > while looking for some coding conventions for python programs, i found the > PEP8 at http://www.python.org/peps/pep-0008.html. It defines the rules very > well and leaves no space for interpretations. I guess thats a good thing :-) > But when i started playing a bit with python and frameworks like Zope, > Webworks, etc., i noticed, that a lot frameworks are using a different > convention for methodnames. Note the first sentence of the PEP: "This document gives coding conventions for the Python code comprising the standard library for the main Python distribution." It is not intended to be a style guide for all Python code although many groups do adopt all or part of it for their own style guides. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From moshebg at shamaut.co.il Mon Jan 17 00:57:46 2005 From: moshebg at shamaut.co.il (moshebg at shamaut.co.il) Date: 16 Jan 2005 21:57:46 -0800 Subject: fefinining % of c'm'y and k Message-ID: <1105941466.596034.166370@f14g2000cwb.googlegroups.com> hello i need a program (and pleas shoe me the modol in the softwar) that : if i have a scaned photo i want to define out of each poligon color ,as it seems in the photo, the cmyk in % (percets) of the color/ 4 exampl from poligon color orang defin the cmyk in % like that: (example) c: 30% m:56% y:78% k: 10% moshe thanks From belred at gmail.com Thu Jan 20 20:58:27 2005 From: belred at gmail.com (Bryan) Date: Thu, 20 Jan 2005 17:58:27 -0800 Subject: PyCon Preliminary Program Announced! In-Reply-To: <20050121000607.DE1261E4010@bag.python.org> References: <20050121000607.DE1261E4010@bag.python.org> Message-ID: <41F061C3.3000802@gmail.com> can anyone tell me how the talks work? there are between 9 and 12 talks for each time slot. do all talks start at the same time? or are there just four talks at a time and the columns show what talks are in a given room? is it easy to go to the talks you want? thanks, bryan From tim.peters at gmail.com Mon Jan 24 11:13:01 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 24 Jan 2005 11:13:01 -0500 Subject: Memory Usage In-Reply-To: References: Message-ID: <1f7befae050124081327f0c5bd@mail.gmail.com> [] > Would a Python process consume more memory on a PC with lots of > memory? > > For example, say I have the same Python script running on two WinXP > computers that both have Python 2.4.0. One computer has 256 MB of Ram > while the other has 2 GB of Ram. On the machine with less Ram, the > process takes about 1 MB of Ram. On the machine with more Ram, it uses > 9 MB of Ram. > > Is this normal and expected behavior? [and later confirms he's looking at Mem Usage in Task Manager] 256MB is on the low end for an XP system, and will generally cause lots of swap space (virtual memory residing on disk -- kinda) to get used. Mem Usage doesn't count swap space, just RAM currently in use. Under Task Manager it's better to look at the VM Size column, which tells roughly how much virtual address space is assigned to the process, and regardless of how it's currently split between RAM and disk. You may need to use View -> Select Columns to get this statistic displayed. If your process is in fact using a fixed amount of address space, the VM Size column will stay steady but Mem Usage may jump all over the place as time goes on. In general, I would expect VM Size to be about the same on your two boxes; I would not expect Mem Usage to be the same. From abigail at abigail.nl Wed Jan 12 03:22:04 2005 From: abigail at abigail.nl (Abigail) Date: 12 Jan 2005 08:22:04 GMT Subject: 20050111: list basics References: <1105512773.543336.29930@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee (xah at xahlee.org) wrote on MMMMCLII September MCMXCIII in : :: :: # in perl, list is done with paren (). Wrong. Except in a few cases, parens don't make lists. Parens are used from precedence. *Context* makes lists. :: # the at sign in front of variable is necessary. The at sign in front of a variable means the variable is an array. Arrays are *NOT* lists. :: # it tells perl that it is a list. :: @a = (0,1,2,'three',4,5,6,7,8,9); :: :: # perl can't print lists. To show a list content, :: # load the package Data::Dumper, e.g. :: use Data::Dumper; :: print '@a is:', Dumper(\@a); Utter bullshit. Perl's print statement has no problem accepting a list. In fact, YOUR EXAMPLE PASSES A LIST to print. But this works fine too: @a = ('Xah ', 'Lee ', 'does ', 'not ', 'know ', 'Perl'); print @a; __END__ Xah Lee does not know Perl :: # the backslash in front of @a is to tell Perl :: # that "get the "address" of the "array" @a". Wrong. Perl is not C. You get a reference, not a pointer. :: # it is necessary in Dumper because Dumper is :: # a function that takes a memory address. Wrong. Perl functions don't take memory addresses. Perl doesn't allow the programmer to do direct memory access. :: # see perldoc -t Data::Dumper for the intricacies :: # of the module. Please do so yourself. :: # to join two lists, just enclose them with () :: @b = (3,4); :: @c = (@a, at b); :: print '\@c is', Dumper \@c; :: # note: this does not create nested list. There is no such thing as "nested lists". :: # to extrat list element, append with [index] :: # the index can be multiple for multiple elements :: @b = @a[3,1,5]; :: print Dumper \@b; Why are you printing to the Dumper filehandle? :: # to replace parts, do :: $a[3]= 333; :: print ' is', Dumper \@a; :: # note the dollar sign. :: # this tells Perl that this data is a scalar :: # as opposed to a multiple. :: # in perl, variable of scalars such as numbers and strings :: # starts with a dollar sign, while arrays (lists) starts with Again, arrays are NOT lists. :: # a at @ sign. (and harshes/dictionaries starts with %) :: # all perl variables must start with one of $,@,%. Or *, or &. And some variables don't have a sigil in front of them. :: # one creates nested list by :: # embedding the memory address into the parent list :: @a=(1,2,3); :: @b = (4,5, \@a, 7); :: print 'nested list is', Dumper \@b; Rubbish. That's not a nested list. @b is an *ARRAY*, whose third element is a *REFERENCE* to another *ARRAY*. :: # to extrat element from nested list, :: $c = $b[2]->[1]; :: print '$b[2]=>[1] is', $c; :: :: # the syntax of nested lists in perl is quite arty, see :: # perldoc -t perldata :: Xah Please Xah, do the Perl and Python communities a favour, and stop posting bullshit. Abigail -- perl -e '* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % % %; BEGIN {% % = ($ _ = " " => print "Just Another Perl Hacker\n")}' From mordaha at gmail.com Fri Jan 14 16:55:48 2005 From: mordaha at gmail.com (mr_little) Date: 14 Jan 2005 13:55:48 -0800 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: <1105739748.306557.72120@z14g2000cwz.googlegroups.com> Brian Eable wrote: > perl -e '$a="194.109.137.226"; @a = reverse split /\./, $a; for $i (0..3) { $sum += $a[$i]*(256**$i) } print "sum = $sum\n"' > > 226 + 35072 + 7143424 + 3254779904 = 3261958626 > > http://3261958626/ > > Which is NOT 666. Comrade, why perl here? :) Are you afraid python? :) From wjiang at gmail.com Mon Jan 17 17:35:11 2005 From: wjiang at gmail.com (Wen Jiang) Date: 17 Jan 2005 14:35:11 -0800 Subject: pyMPI momory leak Message-ID: <1106001311.306343.53840@c13g2000cwb.googlegroups.com> Hi, I have been using pyMPI to parallelize my code and found that the function mpi.send() leaks memory a lot and thus is not really working for large amount fo data communication. It actually fails after the leak accumulates more than 2G. I wonder if others have the same experience or I did something wrong. I compiled python 2.4, mpich 1.2.6, pyMPI 2.1b4 on Opteron cluster running Rocks 3.3. Here is a small test script with 2 CPUs to demo the memory leak: import mpi n = 10000 i=0 data = [0]*40000 while i < n: if mpi.rank==1: mpi.send(data, 0) elif mpi.rank==0: msg, status = mpi.recv() n+=1 if one watchs the memory usage using 'top', one can see one process use little and constant amount of memory (recv for rank=0) and the other process uses more and more memory (send for rank=1). From tjreedy at udel.edu Wed Jan 5 00:38:45 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 5 Jan 2005 00:38:45 -0500 Subject: coding conventions, PEP vs. practice References: Message-ID: "Robert Kern" wrote in message news:crff5d$noi$1 at news1.ucsd.edu... > Note the first sentence of the PEP: "This document gives coding > conventions for the Python code comprising the standard library for the > main Python distribution." Even that should say "from now on". Some library code was written before PEP8. And Guido has so far discouraged purely stylistic patches to functioning code (because of the risk on introducing bugs where none exist). TJR From danperl at rogers.com Tue Jan 25 12:10:55 2005 From: danperl at rogers.com (Dan Perl) Date: Tue, 25 Jan 2005 12:10:55 -0500 Subject: [perl-python] 20050125 standard modules References: <1106669614.666772.17750@z14g2000cwz.googlegroups.com> Message-ID: I sent the following feedback message to Yahoo! Groups about this abusive use of their service. Feel free to also report this as an abuse of the Yahoo! Groups service until the problem is resolved. Dan ----------- As the owner of the perl-python group, p0lyglut (aka Xah Lee), has added two newsgroups to the mailing list of the group: comp.lang.perl.misc and comp.lang.python. First of all, I don't think anyone could have given Xah Lee an authorization on behalf of the newsgroups. I am not sure, but that is probably a violation of the Terms of Service in itself. I will leave this matter up to you to investigate. The daily messages of the perl-python group are unwanted by the two newsgroups. Just take a look at the follow-ups in the newsgroups that the perl-python postings have generated. I hope that not only the newsgroups will be removed from the perl-python group but that such an abuse will also be prevented in the future. Thanks, Dan Perl From rschroev_nospam_ml at fastmail.fm Sat Jan 8 04:40:07 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 08 Jan 2005 09:40:07 GMT Subject: Getting List Of All Filesystem Mounts In-Reply-To: References: Message-ID: Tim Daneliuk wrote: > Is there some pure Python/portable way to get a list > of all currently mounted filesystems? Check out MtPython: http://bebop.bigasterisk.com/python/docs/MtPython -- "Codito ergo sum" Roel Schroeven From http Wed Jan 19 12:45:10 2005 From: http (Paul Rubin) Date: 19 Jan 2005 09:45:10 -0800 Subject: [OT] Good C++ book for a Python programmer References: <1106136496.719185.87850@c13g2000cwb.googlegroups.com> Message-ID: <7x4qhdia8p.fsf@ruckus.brouhaha.com> "rick_muller at yahoo.com" writes: > I was wondering whether anyone could recommend a good C++ book, with > "good" being defined from the perspective of a Python programmer. I > realize that there isn't a book titled "C++ for Python Programmers", > but has anyone found one that they think goes particularly well with > the Python way? I think it's not possible to really grok C++ without having worked on large multi-person C projects and understood what problems C++ tried to solve. The only good book I know about C++ is by Stroustrup, "The C++ Programming Language" or something like that; it's not an easy book though. From news at guessmysurname.net Thu Jan 6 21:18:13 2005 From: news at guessmysurname.net (Lorenzo Bolognini) Date: Fri, 07 Jan 2005 02:18:13 +0000 Subject: wxPython clipboard In-Reply-To: <1105054966.693860.59270@f14g2000cwb.googlegroups.com> References: <1105010770.911397.278520@c13g2000cwb.googlegroups.com> <1105054966.693860.59270@f14g2000cwb.googlegroups.com> Message-ID: <3469sbF46es8jU1@individual.net> flaxeater at gmail.com wrote: > Ok well you should look at this module > http://www.rutherfurd.net/python/sendkeys/#id1 > I then you could take frequent snapshots and use and OCR to find your > stuff. Then use the above library to type to the window. > Ok the problem on Windows looks like solved but still I would have to check if Windows Scripting Host is enabled. Anyway I'll keep u updated Cheers Lorenzo -- Get my PGP Public Key @ http://www.bolognini.net/LBolognini.txt From jstroud at mbi.ucla.edu Mon Jan 24 20:19:22 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 24 Jan 2005 17:19:22 -0800 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <1106615822.2400.122.camel@lipscomb.mbi.ucla.edu> References: <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <1106615822.2400.122.camel@lipscomb.mbi.ucla.edu> Message-ID: <1106615961.2400.126.camel@lipscomb.mbi.ucla.edu> I was purposefully making an illogical statement to illustrate the lapse in reason of Martin's statement. Users have crypto needs, not applications. Applications are presumably not anthropomorphic enough to have needs--hence the lack of logic. However, I am not an application (as far as you or I know) and thus can not truly speak to the needs of applications in general, if indeed they have any. Applications that lack features force users to accept a limited feature set or they use an alternative program with other limitations. Putting the possibility for cryptographic storage increases the utility of any application that stores data, and it could be done without much work if it were properly included in the core distribution. I have found it amazing how few programs include encryption as an option. I believe this is because its hard for programmers to include it and/or they falsely reason that "if I don't need it, the user doesn't", which is up there with "if I can't see them, then they can't see me" in terms of bad logic. James On Mon, 2005-01-24 at 17:17, James Stroud wrote: > I was purposefully making an illogical statement to illustrate the lapse > in reason of Martin's statement. Users have crypto needs, not > applications. Applications are presumably not anthropomorphic enough to > have needs--hence the lack of logic. > > However, I am not an application (as far as you or I know) and thus can > not truly speak to the needs of applications in general, if indeed they > have any. > > Applications that lack features force users to accept a limited feature > set or they use an alternative program with other limitations. Putting > the possibility for cryptographic storage increases the utility of any > application that stores data, and it could be done without much work if > it were properly included in the core distribution. I have found it > amazing how few programs include encryption as an option. I believe this > is because its hard for programmers to include it and/or they falsely > reason that "if I don't need it, the user doesn't", which is up there > with "if I can't see them, then they can't see me" in terms of bad > logic. From http Sat Jan 29 04:57:27 2005 From: http (Paul Rubin) Date: 29 Jan 2005 01:57:27 -0800 Subject: Pystone benchmark: Win vs. Linux (again) References: <7xhdl0ll3t.fsf@ruckus.brouhaha.com> <1gr59wv.9tx8a21g2kdv9N%aleaxit@yahoo.com> Message-ID: <7xllac36d4.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > ...or (just as hypothetically) purchasing some commercial compiler might > help, under the assumption that the optimization and code generation of > the compiler are the issues here. I have nothing but hearsay to go on, > but IBM's compiler for PPC chips, and Intel's compiler for Intel chips, > appear to claim that they have excellent code generation, for example. Perhaps so. Actually that benchmark difference may have come from differing Python versions. I've heard that Intel cc typically beats gcc by 5% or so for integer code. There are various benchmarks floating around. But that Pystone measurement differed by considerably more. From ncoghlan at iinet.net.au Fri Jan 7 10:26:44 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 01:26:44 +1000 Subject: 2 versions of python on 1 machine In-Reply-To: References: <0fydnX5CmoCCwkDcRVn-2w@powergate.ca> Message-ID: <41DEAA34.8020800@iinet.net.au> flupke wrote: > Peter Hansen wrote: >> The content of each batch file is like this: >> @echo off >> c:\python23\python.exe %1 %2 %3 %4 %5 %6 %7 %8 %9 More recent versions of Windows should allow you to use %* for "all the arguments to the batch file". > Where did you find more info on PYTHONHOME and PYTHONPATH because > the docs don't seem to contain a whole lot of info. I think PYTHONPATH is discussed in the tutorial. PYTHONHOME, I'm not so sure on (PYTHONPATH and PYTHONSTARTUP are the only two you're likely to care about, though - and I think the Tutorial covers both of them). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From export at hope.cz Fri Jan 7 03:14:26 2005 From: export at hope.cz (export at hope.cz) Date: 7 Jan 2005 00:14:26 -0800 Subject: Asyncore Message-ID: <1105085666.634359.33640@z14g2000cwz.googlegroups.com> Is there any tutorial and docs with samples how to use asyncore module? Thanks Lad From aleaxit at yahoo.com Fri Jan 7 09:21:22 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 15:21:22 +0100 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41dcf582.122188317@news.oz.net> <7xd5wh7qdf.fsf@ruckus.brouhaha.com> <1gq0odo.1x1uyr2kgdgiyN%aleaxit@yahoo.com> <7xu0ptjtv3.fsf@ruckus.brouhaha.com> Message-ID: <1gq0xda.12eqd291540i5tN%aleaxit@yahoo.com> Paul Rubin wrote: ... > > GUI/IDEs for Python, > > I remember there was a gud interface for Python but it didn't work > pretty well. There's also IDLE which is pretty crude and flaky. I > think I'll just wait for Pypy deployment before worrying about this > situation too much. Is there something else I can download? eric3 seems pretty good. > > Python add-ons such as numarray, > > gmpy, ctypes, ...) -- all of those you still have to download and > > install, just as you would for the satanware. > > That's unfortunate, that stuff should be included with Python. numarray aims to be, WHEN they will be sufficiently complete and stable. As for predictions of when that will be, I'm not qualified to offer one. I think ctypes would be a _great_ addition to the standard Python library in 2.5, if Thomas Heller agrees. gmpy is LGPL (because so is the GMP library that gmpy wraps and extends), so that including it with the standard Python library is very iffy/problematic. As gmpy's author I'd be delighted to do anything possible to help this happen, but it just doesn't seem likely. Besides, I wonder how large a fraction of Python's user base really needs something as specialized as gmpy -- unlimited-precision integers which are _slightly_ faster than Python 2.4's built-in longs and offer a few more highly specialized functions, etc. Even if all of these were included in Python 2.5, how long will it be before standard distributions and operating systems start including 2.5? I don't agree with your general stance that the standard Python distribution should be "sumo", including _everything_ that could possibly be of _some_ interest to _some_ Python users, or thereabouts. "Sumo distributions" have their place; enthought currently makes an excellent one for scientific use of Python on Windows, and, I hear, it is planning a similar one for Macintosh. But the vast majority of what's in it will be of no interest to somebody who doesn't care for scientific applications -- and it will STILL be missing something that some scientific users might like, such as gmpy. Moreover, it's important to distinguish between standard Python, and enriched distributions made of components that grow and change at different speeds and with different groups of maintainers -- just the same important distinction that must be drawn between Linux, and any of the many distributions based on and including Linux. Asking standard Python to include dozens of third-party modules is just as silly as asking the Linux kernel to be distributed with, say, gimp... anybody's free to make a distribution including several components, but it's best for the various components, including the core ones, to stay separate. Alex From ed at leafe.com Mon Jan 17 10:37:51 2005 From: ed at leafe.com (Ed Leafe) Date: Mon, 17 Jan 2005 10:37:51 -0500 Subject: Native widgets for Python In-Reply-To: References: <41EBC7F3.5050807@web.de> <87oefom7at.fsf@mrbun.watterson> Message-ID: On Jan 17, 2005, at 10:19 AM, Steve Holden wrote: >> It looks like dabo uses, not replaces, wxPython >> http://dabodev.com/about > > Actually I think it *layers* wxPython, with the intention of being > able to replace wxPython with other GUI kits at a later date. So, > there should be a simpler graphical API, but since I haven't yet done > more than dabble (dabole?) with dabo I can't be sure. That's correct. We are basing the UI on wxPython initially, but wrapping wx for two reasons: to make it simpler to code UIs, and to make it possible to use other UI toolkits instead of wx. The first reason is by far the more important of the two, but an eventual goal for Dabo post-1.0 release (we're at 0.3 now!) will be to allow TkInter and other toolkits to be used as well. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From tjreedy at udel.edu Wed Jan 12 15:44:19 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Jan 2005 15:44:19 -0500 Subject: Another look at language comparisons References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> <1105188426.955508.263030@c13g2000cwb.googlegroups.com><41e00ac1$0$265$edfadb0f@dread12.news.tele.dk> <34kaf5F4ag9k6U1@individual.net> Message-ID: >>> http://www.tbray.org/ongoing/When/200x/2004/12/08/-big/IMG_3061.jpg Here is the link giving the context for that picture http://tbray.org/ongoing/When/200x/2004/12/08/DynamicJava The other person is Larry Wall. Samuele Pedroni is in the next one. A rather interesting meeting. Terry J. Reedy From tim.peters at gmail.com Sun Jan 9 01:11:13 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 9 Jan 2005 01:11:13 -0500 Subject: time module precision In-Reply-To: References: Message-ID: <1f7befae05010822117f566baf@mail.gmail.com> [Jane Austine] > What is the precision (and accuracy) of time module on a Windows XP > machine? There are many functions in the time module. You shouldn't assume that any two have similar behavior (because, in fact, they may not). > threading module depends on time module so it's precision(and > accuracy) is up to time module's. > > | for i in xrange(1000): > | time.sleep(0.001) > > This sleeps for awhile, which means 0.001 sec is not ignored. On the > other hand, > > | for i in xrange(10000): > | time.sleep(0.0001) > > This returns right away. It may or may not, depending on what other threads are trying to do. > 0.0001 sec is ignored and lost in the air. > > So can I tell the time.sleep's precision is 1ms? Any other way to > increase the precision? (Using busy waiting -- spinning loop -- is not > a good option, it makes over 90% cpu usage) Python's time.sleep() calls the Win32 API Sleep() function on Windows. All behavior is inherited from the latter. See MS's docs: In particular, MS Sleep() takes an integer argument, giving the number of milliseconds to sleep. Your 0.0001 case falls under the special Sleep(0) case due to truncation in float->int conversion. Also Google on sleep thread deviation to find an interesting CodeProject article quantifying behavior on one particular tester's Windows box. Also see an article it references for approaches to the question "how do I handle small intervals?" (short course: you probably can't, unless we're willing to throw money at it). From http Fri Jan 21 23:44:39 2005 From: http (Paul Rubin) Date: 21 Jan 2005 20:44:39 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> Message-ID: <7xbrbiqdhk.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > > I'm going by newsgroup messages from around the time that I was > > proposing to put together a standard block cipher module for Python. > > Ah, newsgroup messages. Anybody could respond, whether they have insight > or not. Here's the message I had in mind: http://groups-beta.google.com/group/comp.lang.python/msg/adfbec9f4d7300cc It came from someone who follows Python crypto issues as closely as anyone, and refers to a consensus on python-dev. I'm not on python-dev myself but I feel that the author of that message is credible and is not just "anyone". From exarkun at divmod.com Tue Jan 4 11:43:34 2005 From: exarkun at divmod.com (Jp Calderone) Date: Tue, 04 Jan 2005 16:43:34 GMT Subject: Hlelp clean up clumpsy code In-Reply-To: <41dabf3d$1@nntp0.pdx.net> Message-ID: <20050104164334.25734.201508819.divmod.quotient.750@ohm> On Tue, 04 Jan 2005 08:18:58 -0800, Scott David Daniels wrote: >Nick Coghlan wrote: > > A custom generator will do nicely: > > > > Py> def flatten(seq): > > ... for x in seq: > > ... if hasattr(x, "__iter__"): > > ... for y in flatten(x): > > ... yield y > > ... else: > > ... yield x > > Avoiding LBYL gives you: > def flatten(seq): > for x in seq: > try: > for y in flatten(x): > yield y > except TypeError: > yield x But totally messes up on error handling. Instead: def flatten(seq): for x in seq: try: subseq = iter(x) except TypeError: yield x else: for subx in flatten(subseq): yield subx to avoid catching TypeErrors from .next(). Jp From aahz at pythoncraft.com Fri Jan 14 16:54:07 2005 From: aahz at pythoncraft.com (Aahz) Date: 14 Jan 2005 16:54:07 -0500 Subject: Threading Or Other Suggestions?!? References: Message-ID: In article , wrote: > > I have a wxPython application that does a lot of things. One of them, >in particular, I have doubts on how to implement it. Essentially, this part >of my application calls an external executable (an oil reservoir >simulator). What I would like to do, is to give the user the possibility to >run more than 1 simulation at the same time. This means: > >1) Writing the executable "data file" needed by the simulator >2) Run the executable file (and wait until completion) >3) Examine the simulation results > >For this, I was thinking about threads... does anyone have other/better >suggestion(s)? Does anyone see any difficulty/memory problems in using >threads? If you're not on Windows, this will be much easier with multiple processes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From deetsNOSPAM at web.de Wed Jan 26 07:04:00 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 26 Jan 2005 13:04:00 +0100 Subject: add indexes on the fly to lists References: <41f69f0b$0$6606$8fcfb975@news.wanadoo.fr> Message-ID: <35pf5tF4nmm25U1@individual.net> > If you want only "search and found" element, look dictionnary ; if you > want also to have the order, see the module set. Erg - no. Sets are mathematically defined as having no order. -- Regards, Diez B. Roggisch From mcturra2000 at yahoo.co.uk Sun Jan 2 13:46:23 2005 From: mcturra2000 at yahoo.co.uk (Mark Carter) Date: Sun, 02 Jan 2005 18:46:23 +0000 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: <41d8417e$0$14596$ed2619ec@ptn-nntp-reader01.plus.net> Cameron Laird wrote: > In article <41d7def6$0$74273$ed2619ec at ptn-nntp-reader03.plus.net>, > Mark Carter wrote: > . > [tale of *very* > typical experience > with non-software > engineers] > . > . > Don't start me! Dammit, too late ... I've noticed that they have an overwhelming obsession with GUIs, too. They design wizards for everything. Damn pretty they are, too. Albeit a bit flakey. They seem to conflate pretty interfaces with good interfaces and good software. I used to joke that since our software wasn't particularly magical, it didn't need wizards. But I think I just ended up sounding bitter. We once had a bit of software that we thought we'd like to turn into a generic application. The focus on improvements was, predictably enough, that we should design a GUI that could do anything a client would likely to want to do. It was my opinion, though, having seen the very "special-cases" nature required in the original software, that it was almost impossible to predict exactly how a customer might want the product tailored. I suggested that what they really needed was a library (Python would have been good for this, Lisp might have been even better) that could be extended as required. GUIs second, functionality first. But hey, what would I know. Fortunately, the whole thing's been put on the back burner. And trying to get through to them why source control makes sense, that when more than one person works on a project, some form of coordination is required, that copying and pasting code is evil, and that Excel probably isn't the hammer for every nail. Honestly, I thought (real) engineers were supposed to be clever. From bdesth.quelquechose at free.quelquepart.fr Fri Jan 7 09:22:00 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 07 Jan 2005 15:22:00 +0100 Subject: Getting rid of "self." In-Reply-To: References: Message-ID: <41de998e$0$10263$626a14ce@news.free.fr> BJ?rn Lindqvist a ?crit : > I think it would be cool if you could refer to instance variables > without prefixing with "self." I know noone else thinks like me so > Python will never be changed, but maybe you can already do it with > Python today? > (snip code) > > It works! exec(magic()) does the needed hi = self.hi. Not so > impressive in this case but much cooler when there is more instance > variables around. But the solution is very ugly because you have to > write exec(magic()) in every method. So I'm asking here if someone > knows a better way, maybe using decorators or metaclasses or other > black magic? > The better way is definitively to forget about black magic and understand why mandatory 'self' is Good Thing (tm). (Tip : even when [this|self|@|whatsoever] is not mandatory, using it makes for much more readable code.) Bruno From MAILsweeper at hibernian.ie Fri Jan 28 18:33:51 2005 From: MAILsweeper at hibernian.ie (MAILsweeper at hibernian.ie) Date: Fri, 28 Jan 2005 23:33:51 +0000 (GMT) Subject: Mail sent to Hibernian has a virus !!! Message-ID: <20050128233253.BB6441E5328@bag.python.org> Mail sent to Hibernian was received with a computer virus infected attachment. The mail has been intercepted and did not reach the intended recipient. Sender please remove the virus from the message and resend the mail. From: python-list at python.org To: mailsweeper at hibernian.ie Subject: Mail Delivery (failure mailsweeper at hibernian.ie) Virus: Scenarios/Incoming/Content Scanner: Threat: 'W32/Netsky-P' detected by 'Sophos AV Interface for MIMEsweeper'. Scenarios/Incoming/Blocking .SCR file types incoming: A filename matching the file mask was detected: 'message.scr'. Scenarios/Incoming/Restrict Attachments In: 'ItemLength.GE.0'. was blocked at Fri, 28 Jan 2005 23:30:42 +0000 From kent3737 at yahoo.com Wed Jan 26 10:08:23 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Wed, 26 Jan 2005 10:08:23 -0500 Subject: fast list lookup In-Reply-To: <3e96ebd7.0501260641.159e007f@posting.google.com> References: <3e96ebd7.0501260641.159e007f@posting.google.com> Message-ID: <41f7afd8_3@newspeer2.tds.net> Klaus Neuner wrote: > Hello, > > what is the fastest way to determine whether list l (with > len(l)>30000) contains a certain element? If you can use a set or dict instead of a list this test will be much faster. Kent From clpy at a-nugget.de Fri Jan 28 15:59:26 2005 From: clpy at a-nugget.de (Guido Goldstein) Date: Fri, 28 Jan 2005 21:59:26 +0100 Subject: handling xls with pyuno References: Message-ID: Hi! On Fri, 28 Jan 2005 12:59:11 -0600 John Hunter wrote: > Does anyone have any example scripts using the OpenOffince > python-bridge module pyuno to load xls, extract the data, and/or save > to another format such as xsc or csv. There is something called BlueDCS which can do that. See here: http://cvs.bluedynamics.org/viewcvs/BlueDCS/ HIH Guido -- Guido Goldstein PGP Key: http://www.a-nugget.de/public-key.txt From pdemb at illx.org Sun Jan 2 16:32:14 2005 From: pdemb at illx.org (Peter Dembinski) Date: Sun, 02 Jan 2005 22:32:14 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> <7xsm5kfyse.fsf@ruckus.brouhaha.com> <41d7941f$1_3@127.0.0.1> <7x8y7cjo57.fsf@ruckus.brouhaha.com> <87zmzsax12.fsf@hector.domek> <87pt0na5zf.fsf@hector.domek> Message-ID: <87llbba55t.fsf@hector.domek> Peter Dembinski writes: > Peter Dembinski writes: > > [...] > >> str = foo(x) > > (ick!) it should be: > > bar = foo(x) Besides, shouldn't str be a reserved word or something? From jerf at jerf.org Wed Jan 26 19:06:49 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 26 Jan 2005 19:06:49 -0500 Subject: What's so funny? WAS Re: rotor replacement References: <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: On Thu, 27 Jan 2005 04:04:38 +0000, phr wrote: > Skip Montanaro writes: >> Because good requirements specification is difficult and testing improves >> the breed. Better to have the major API changes and bugs taken care of, and >> to have its popularity demonstrated *before* it gets into the Python >> distribution. The best way to do something isn't always obvious at the >> outset. > > That is sometimes true, but not always. Sometimes the best way is > obvious. With all due respect, you aren't arguing very well. Your posts are, like this quote, more reactionary than thought-out. You need to stop arguing for the sake of argument, read more carefully, and think more about your global goals in this conversation than your local ones. I'm 99% certain that you've already gotten all the answers you're going to get and all the answers you need in this thread, but you're so busy arguing the local points like this, you haven't noticed. (Either that, or it's the "you haven't answered me because you haven't given the exact answer I want" bit, which I find quite tiresome; there's another list where there are these three teenagers that don't even realize they've defined "answer" that way and keep bitching that they aren't being "answered" when the "answer" is, basically, "it's nice that you feel that way." But I digress.) > I don't need your permission to do that. What I'm looking for is an > indication that it's worth my while, before I spend the effort. The policy has been laid out, multiple times, by multiple people now. The answer is, you are not going to get any such indication that will satisfy you. Note that I am not a Python contributor of any kind. Also note that I figured this out about two days ago. You can wheedle these guys all you want, but they are too experienced for you to extract a promise from them. From mahs at telcopartners.com Fri Jan 28 02:53:56 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 27 Jan 2005 23:53:56 -0800 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <7x3bwmggi3.fsf@ruckus.brouhaha.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> <6PKdnVpD-4f3CGvcRVn-gQ@comcast.com> <7x3bwmggi3.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Francis Girard writes: > >>Thank you Nick and Steven for the idea of a more generic imerge. > > > If you want to get fancy, the merge should use a priority queue (like > in the heapsort algorithm) instead of a linear scan through the > incoming iters, to find the next item to output. That lowers the > running time to O(n log k) instead of O(n*k), where k is the number of > iterators and n is the length. I looked at a heapq solution but didn't see any clean way of dealing with multiple iterators having equal values. The dict solution below deals cleanly with that, since one key can be shared by any number of iterators. Extracting the minimum, and the associated iterables is fast, but the overall solution is still slower than the brute force approach for the 3 hamming iterators. >>> def imerge(*iterables): ... cache = {} ... iterators = map(iter,iterables) ... number = len(iterables) ... exhausted = 0 ... while 1: # First time through, looked at all of them # Subsequently, update only the minimum iterators ... for it in iterators: ... try: # Key each iterator by its next() value # Multiple iterators may share the same key ... cache.setdefault(it.next(),[]).append(it) ... except StopIteration: ... exhausted += 1 ... if exhausted == number: ... raise StopIteration # Get the lowest value ... val = min(cache) # and all the iterators that have that value ... iterators = cache.pop(val) ... yield val >>> list(imerge([1, 2, 3, 6], [1, 2, 3, 7], [1, 2, 3, 4, 5])) [1, 2, 3, 4, 5, 6, 7] >>> Michael From fumanchu at amor.org Thu Jan 13 00:30:12 2005 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 12 Jan 2005 21:30:12 -0800 Subject: why are people still using classic classes? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33981A9@exchange.hqamor.amorhq.net> Simon Wittber wrote: > Is there a legitimate use for classic classes that I am not aware of? As was pointed out to me when I asked on this list just a short while ago ;) classic classes can be faster. Robert Brewer MIS Amor Ministries fumanchu at amor.org From tjreedy at udel.edu Wed Jan 26 13:55:16 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Jan 2005 13:55:16 -0500 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: "Peter Maas" wrote in message news:ct8517$m03$1 at swifty.westend.com... > Davor schrieb: >> so initially I was hoping this is all what Python is about, but when I >> started looking into it it has a huge amount of additional (mainly OO) >> stuff which makes it in my view quite bloated now. > > So you think f.write('Hello world') is bloated and file_write(f,'Hello > world') > is not? This is the minimum amount of OO you will see when using Python. Now that we have gently teased Davor for his OO fear, I think we should acknowledge that his fears, and specifically his bloat fear, are not baseless. In Python, one can *optionally* write a+b as a.__add__(b). That is bloat. I believe, in some strict OO languages, that bloat is mandatory. For one operation, the bloat is minor. For ever a relatively simple expression such as b**2-4*a*c, it becomes insanity. If we were to have to write sin(x) instead as x.sin(), there would not be syntax bloat. And it would be easier to write generic float-or-complex math functions, just as your print example shows how __str__ methods facilitate generic print operations. But if the class method syntax were manditory, there would be class and/or class hierarchy bloat due to the unlimited number of possible functions-of-a-float and large number of actual such functions that have been written. On the other hand... curryleft(list.append, somelist) is a bit more to type than somelist.append. > print "*** Davor's evolution towards an OO programmer ***" Your Four Steps to Python Object Oriented Programming - vars, lists, dicts, and finally classes is great. It makes this thread worthwhile. I saved it and perhaps will use it sometime (with credit to you) to explain same to others. Terry J. Reedy From jbperez808 at wahoo.com Wed Jan 12 17:08:43 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Thu, 13 Jan 2005 06:08:43 +0800 Subject: Another look at language comparisons In-Reply-To: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> Message-ID: <34llf5F4apou6U2@individual.net> Anyone know of a cached copy where the photos are present? The whole thing makes little sense with the photos gone. Pierre Quentel wrote: > http://khason.biz/blog/2004/12/why-microsoft-can-blow-off-with-c.html From francis.girard at free.fr Wed Jan 26 14:39:20 2005 From: francis.girard at free.fr (Francis Girard) Date: Wed, 26 Jan 2005 20:39:20 +0100 Subject: python without OO In-Reply-To: <10vdt2bpr0m84db@corp.supernews.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <10vdt2bpr0m84db@corp.supernews.com> Message-ID: <200501262039.23260.francis.girard@free.fr> Le mercredi 26 Janvier 2005 02:43, Jeff Shannon a ?crit?: > In statically typed languages like C++ and Java, inheritance trees are > necessary so that you can appropriately categorize objects by their > type. Since you must explicitly declare what type is to be used > where, you may need fine granularity of expressing what type a given > object is, which requires complex inheritance trees. In Python, an > object is whatever type it acts like -- behavior is more important > than declared type, so there's no value to having a huge assortment of > potential types. Deep inheritance trees only happen when people are > migrating from Java. ;) > > Jeff Shannon > Technician/Programmer > Credit International These lines precisely express my thoughts. Most of the difficulties in OO in Java/C++ comes from the all mighty goal of preserving type safety. Type safety is certainly a very desirable goal but it, sometimes, leads to very complex code only to achieve it. The prize is just too high. The design patterns that were supposed to save time through high code reuse oftenly becomes a maintenance nightmare. Something that no one in the company can understand except a few. Instead of trying to fix some domain specific code, you end up trying to fix a supposedly highly reusable code that, oh well, you have to adapt. This is espeacially true if the system had been designed by a big OO-design-patterns enthusiastic programmer geek. I am not saying that design patterns are bad. I think that they are an invaluable gift to OO. I'm only saying that they have indeed a perniciuous and pervert effect in the real world industry. People become religious about it and forget to think about a simple solution ... Being dynamically typed, these kind monster patterns are much less probable. And the Python philosophy and culture is the very contrary to that trend. I've been involved in C++/Java projects for the last 8 years. The first time I met Python, I've been frigthen by its lack of static type safety. But over the time, I've been convinced by seeing clean Python code over and over again. In the end, I could appreciate that being simple leads the way to less bugs, which type safety was supposed to prevent ... Coming from the C++ community, Python had been just like fresh air. It changed me from the nightmare derscribed in that discussion thread. When I think that comapnies pay big money for these kind of monsters after having seen a few ppt slides about it, it makes me shiver. Regards, Francis Girard FRANCE From ville at spammers.com Mon Jan 3 06:05:48 2005 From: ville at spammers.com (Ville Vainio) Date: 03 Jan 2005 13:05:48 +0200 Subject: Python! Is! Truly! Amazing! References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: >>>>> "jfj" == jfj writes: jfj> There were functional and non-functional programming jfj> languages (the first being *much* simpler to jfj> implement). There is a *reason* people chose C over jfj> lisp. It's not that we were all blind and didn't see the jfj> amazingness of lisp. Procedural languages are simply better, jfj> and I'm not replying to this flamewar. You did already ;). Lisp is not a functional programming language, if that was the case it would be even less popular than it is now. Lisp had it's heyday, while pure FP languages didn't even have that much. Hey, it's 2005, I don't think we've used up our yearly Lisp flamewar quota yet. -- Ville Vainio http://tinyurl.com/2prnb From marklists at mceahern.com Sun Jan 2 15:43:34 2005 From: marklists at mceahern.com (Mark McEahern) Date: Sun, 02 Jan 2005 14:43:34 -0600 Subject: Rebinding stdout In-Reply-To: <41D85CAF.2090505@mceahern.com> References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <41D85CAF.2090505@mceahern.com> Message-ID: <41D85CF6.9070004@mceahern.com> Ron Garret wrote: > But this topic does bring up a legitimate question: I have a bunch of > code that generates HTML using PRINT statements. I need to convert > all this code to return strings rather than actually printing them (so > I can use the results to populate templates). In Lisp I could do this: > > (with-output-to-string (s) > (let ( (*standard-output* s) ) > (call-html-generating-code) > s)) > > Is there an equivalent Python trick to capture a function call's > output as a string? > > Just to make sure I understand, I'm going to restate your question: Is there a way to capture stdout? The answer: Sure, replace it with something file-like: >>> import sys, StringIO >>> default = sys.stdout >>> writer = StringIO.StringIO() >>> sys.stdout = writer >>> print 'Whatever' >>> sys.stdout = default >>> print writer.getvalue() Whatever >>> // m From aleaxit at yahoo.com Wed Jan 26 03:04:42 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 26 Jan 2005 09:04:42 +0100 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> Message-ID: <1gqznmh.8tvy67o59lppN%aleaxit@yahoo.com> Davor wrote: > no one ever had to document structured patterns - which definitely > exist - but seem to be obvious enough that there is no need to write a > book about them... You _gotta_ be kidding -- what do you think, e.g., Wirth's "Algorithms plus Data Structures Equals Programs" *IS* all about? Alex From bokr at oz.net Fri Jan 14 18:30:49 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 14 Jan 2005 23:30:49 GMT Subject: Class initialization from a dictionary, how best? References: <1105677379.632236.17020@z14g2000cwz.googlegroups.com> <41e7b80e.827352389@news.oz.net> <1105716725.996023.255800@c13g2000cwb.googlegroups.com> Message-ID: <41e84a4f.864793467@news.oz.net> On 14 Jan 2005 07:32:06 -0800, "brianobush at gmail.com" wrote: >Yes, my examle here is a tiny part of a larger more complex issue. My >application is an DOM XML parser that is reading attributes one at a you mean like blah blah and you are grabbing things of interest out of a stream of info you are getting from call-backs? Or the equivalent? >time. My class that I am creating is used elsewhere and must have >certain arguments for those uses to continue working. So, I seem to be >left with creating an intermediate object. Before, I was simply Unless the "intermediate object" accumulates information for multiple Test() instances, why couldn't t= Test() be its own "intermediate object"? If you are accumulating info for multiple instances before creating them it is not clear from your description. >creating an object: > >t = Test() >for attr_name in mapping.keys(): >setattr(t, attr_name, value_from_source) > >This I feel was ellegant, efficient and clear. However, what I have now >works but is not clear. >BTW, t1 is just for example and was just being printed What about giving Test some methods to do what you'd like? E.g., a micro-step in that direction from the above would let you write t = Test() ... t.load_info(infosource) Then the question becomes what infosource should be, or whether you really need it at all. IOW, if you are doing infosource.add_info(info_id, info_value) why couldn't you do t.add_info(info_id, info_value), unless you have to do t2.add_info(...) alternately with t.add_info(...), and if that's the case, what is the criterion for choosing t vs t2? Maybe that could be done by something that automatically manufactures t's as needed in a pool of partially complete t's. But your real requirements are not clear enough here, so you may get help crossing a stream, but no one will be able to say you are already on the side of the stream you want to be later, and there's an easy path without need of crossing twice ;-) Regards, Bengt Richter From jurgenex at hotmail.com Sun Jan 9 03:58:13 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sun, 09 Jan 2005 08:58:13 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: xah at xahlee.org wrote: > #python supports complex numbers. [...] So? > # Perl doesn't support complex numbers. But there are packages that > supports it. The Math::Complex module is part of the standard installation already, no need for any "packages" (whatever that might be). Did you check "perldoc Math::Complex" NAME Math::Complex - complex numbers and associated mathematical functions [...] jue From noone at nowhere.com Wed Jan 12 18:28:38 2005 From: noone at nowhere.com (Simon Foster) Date: Wed, 12 Jan 2005 23:28:38 -0000 Subject: Release date for 2nd edn. Cookbook Message-ID: <41e5b2b3$0$330$cc9e4d1f@news.dial.pipex.com> Does anyone have any idea on this date? Any chance of a signed copy for contributors? From rnd at onego.ru Mon Jan 10 03:28:54 2005 From: rnd at onego.ru (Roman Suzi) Date: Mon, 10 Jan 2005 11:28:54 +0300 (MSK) Subject: interpreter Py_Initialize/Py_Finalize mem leak? In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE0252027E@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE0252027E@au3010avexu1.global.avaya.com> Message-ID: On Mon, 10 Jan 2005, Delaney, Timothy C (Timothy) wrote: >Roman Suzi wrote: > >> In pure curiosity I tried to compile loop.c from Demo/embed >> and started it with 'print 2+2'. It seems, that both 2.3 and 2.4 >> pythons have memory leaks in Py_Initialize/Py_Finalize calls. >> (That is, interpreter doesn't clean up well after itself). > >What's your evidence for this (i.e. what are the symptoms)? - memory usage grows over time. >If you have a repeatable test case, please raise a bug report on >SourceForge. I tested only under Linux. And it is 100% repeatable. >Tim Delaney > Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From fumanchu at amor.org Fri Jan 7 16:23:26 2005 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 7 Jan 2005 13:23:26 -0800 Subject: switching an instance variable between a property and a normal value Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398133@exchange.hqamor.amorhq.net> Steven Bethard wrote: > I'd like to be able to have an instance variable that can > sometimes be > accessed as a property, and sometimes as a regular value, > e.g. something > like: ... > py> c.x is c.x # I'd like this to be False You'd like 'c.x is c.x' to be FALSE? You can't be serious. Must be a typo. If you want C._x to return something other than the property descriptor, you can. Grab the sample code for Property from http://users.rcn.com/python/download/Descriptor.htm#properties and modify the __get__ method: def __get__(self, obj, objtype=None): if obj is None: return self # Return whatever you like here if self.fget is None: raise AttributeError, "unreadable attribute" return self.fget(obj) That might be one way to get what you want. Robert Brewer MIS Amor Ministries fumanchu at amor.org From FBatista at uniFON.com.ar Tue Jan 11 13:49:12 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 11 Jan 2005 15:49:12 -0300 Subject: Game programming in Python Message-ID: [Baza] #- I'm looking for any books or on-line resources on game #- programming using #- Python. Does anyone have any advice? Check PyGame: http://www.pygame.org/ . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From carl.lowenstein at gmail.com Wed Jan 12 00:10:05 2005 From: carl.lowenstein at gmail.com (carl.lowenstein at gmail.com) Date: 11 Jan 2005 21:10:05 -0800 Subject: stopping the sound server in PySol code -- how? In-Reply-To: References: Message-ID: <1105506605.004416.314560@z14g2000cwz.googlegroups.com> # chmod 000 /usr/lib/python2.3/site-packages/pysolsoundserver.so crude but very effective. carl From iwcook58 at gmail.com Sun Jan 9 19:44:10 2005 From: iwcook58 at gmail.com (iwcook58 at gmail.com) Date: 9 Jan 2005 16:44:10 -0800 Subject: xml.sax._exceptions.SAXReaderNotAvailable Message-ID: <1105317850.406005.74980@c13g2000cwb.googlegroups.com> I am having a problem running py2exe on my computer. When running the exe that has been generated by py2exe the following error comes up. C:\MyPython\dist>kirbyutils.exe kirby350.xml Traceback (most recent call last): File "kirbyutils.py", line 292, in ? File "kirbyutils.py", line 261, in main File "xml\sax\sax2exts.pyc", line 37, in make_parser File "xml\sax\saxexts.pyc", line 77, in make_parser xml.sax._exceptions.SAXReaderNotAvailable: No parsers found I'm baffled. I have searched google. There are lots of threads about "xml.sax._exceptions.SAXReaderNotAvailable: No parsers found" but I do not understand what is wrong. There is thread http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/4cb60885adde0cf3/f47d9aeaa584b8c6?q=xml.sax._exceptions.SAXReaderNotAvailable&_done=%2Fgroup%2Fcomp.lang.python%2Fsearch%3Fq%3Dxml.sax._exceptions.SAXReaderNotAvailable%26start%3D0%26scoring%3Dd%26&_doneTitle=Back+to+Search&&d#f47d9aeaa584b8c6 that made a suggestion or two basically to check xml has been installed. Here are my results.. C:\MyPython>\Python23\python.exe Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import xml >>> print xml >>> import xml.dom >>> print xml.dom >>> import xml.dom.minidom >>> print xml.dom.minidom >> I have installed pyxml and everything I can think of.. Setup.cmd is... setup.py py2exe -i xml.sax.drivers2.drv_pyexpat -i win32com.gen_py.* Setup.py is... # setup.py from distutils.core import setup import py2exe setup(console=["kirbyutils.py"], options = {"py2exe": {"packages": ["encodings"], "dll_excludes":["mfc71.dll"]}} ) The imports in kirbyutils.py are.... import os import zipfileext import zipfile import sys import xml.sax as sax import xml.sax.handler import fnmatch import shutil import binascii import time import filecmp What am I missing?? Thanks in advance. Ian Cook (Freeware author of Kirby Alarm And Task Scheduler www.kirbyfooty.com) From steven.bethard at gmail.com Tue Jan 25 14:54:00 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Jan 2005 12:54:00 -0700 Subject: How to input one char at a time from stdin? In-Reply-To: References: Message-ID: <-qudnR5aSc1FPmvcRVn-sg@comcast.com> Swaroop C H wrote: > On Tue, 25 Jan 2005 12:38:13 -0700, Brent W. Hughes > wrote: > >>I'd like to get a character from stdin, perform some action, get another >>character, etc. If I just use stdin.read(1), it waits until I finish typing >>a whole line before I can get the first character. How do I deal with this? > > > This is exactly what you need: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 > Title: "getch()-like unbuffered character reading from stdin on both > Windows and Unix" > > This recipe was a lifesaver for me once :-) Thanks for the link! I've seen this question before a few times, but no one had pointed out the recipe. Steve From mike.kreiner at gmail.com Sun Jan 16 18:53:06 2005 From: mike.kreiner at gmail.com (mike kreiner) Date: 16 Jan 2005 15:53:06 -0800 Subject: import problems *newbie* In-Reply-To: References: <1105682316.601321.118820@f14g2000cwb.googlegroups.com> <41e7959b$0$385$636a15ce@news.free.fr> Message-ID: <1105919586.453157.42550@c13g2000cwb.googlegroups.com> Thanks for your help Steve and F. Petitjean. Sorry for taking so long to get back, I was away from my lab for a few days. The path to my directory was not included in the sys.path list. Adding a my.pth file to the site-packages directory fixed the import problem. F. Petitjean, I originally edited the PYTHONPATH because "Learning Python," the O'Reilly book, says to do so. I like your and Steve's solutions better--editing the PYTHONPATH seems a little unwieldy--but just to satisfy my curiosity, what are some of the reasons these methods are preferable? Steve, as far as finding out the cause of this problem, I muddled around python and the registry for a while, but nothing jumped out at me. The only thing I can think of is that I have both Python 2.3 and 2.4 installed, and I'm currently working in 2.3. I thought that PYTHONPATH was an environment variable, so having two different versions wouldn't affect it, but I was wondering...should I bother uninstalling 2.4 to see if the prob gets fixed? Other than that I'm still something of a newbie, but I'd love to actually help fix this bug if you can think of anything for me to try (oh joy, my first open source contribution!). Thanks. ~mike From bulba at bulba.com Fri Jan 7 07:40:14 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 13:40:14 +0100 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <7xsm5et0rb.fsf@ruckus.brouhaha.com> Message-ID: <370tt0deerdah8tm15rnv3q98ccerpsq3g@4ax.com> On 06 Jan 2005 18:46:00 -0800, Paul Rubin wrote: >"Terry Reedy" writes: >> Would it be possible, at least for Windows, to write a Python script >> implementing a 'virtual distribution'? IE, download Python, install it, >> download next package, install it, etc. -- prefereably table driven? >I just don't understand why you'd want to do that, instead of putting >all the files in the distro in the first place. Plus there would be maddening dependencies - "oh, in order to use this I need dl that". "oh, that package is missing", "why that doesn't work?" - and time gets wasted. On Linux, quite a lot of code had to be written to resolve dependencies like "a.rpm depends on b.rpm depends on c.rpm ...". Sure, apt is a wonderful tool for resolving such stuff - but I've seen even apt choking sometimes on dependencies it couldn't resolve, esp. when the package you attempt to dl is broken in some way. Reason - apt-get says "sorry, what this package depends on is broken and I can't find anything else in your /etc/apt/sources.list that would be appropriate". Result? Nobody gets to use Pine on this machine, unless I compile it myself (which I finally did). Sure it _can_ be done, but essentially it's a waste of time that this person could devote to doing smth else. It doesn't happen often, but it happens. Why get into resolving such complexity if you don't have to? There are good reasons to use tools like apt-get or yum or up2date on Linux: you can't fit the bugfixes on a CD that come every day, obviously, there's too much of it all to fit simply everything anybody could ever need on the media, etc, etc. However, with Python that's not a problem, because distro is smaller and it doesn't change _that_ often, as lots of packages on Linux are updated almost daily. One of the options for Python could be to have two distributions: one standard, basic distribution, and the "Stuffed Python" based on the standard, created simply by piling all the good stuff on top of standard distro. -- It's a man's life in a Python Programming Association. From fredrik at pythonware.com Thu Jan 13 10:26:08 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 13 Jan 2005 16:26:08 +0100 Subject: python 2.3.4 for windows: float("NaN") throws exception References: <1105629033.442397.124820@c13g2000cwb.googlegroups.com> Message-ID: wrote: > my python 2.3.4 for windows refuse to execute line float("NaN"). It > says: > >>>> float("NaN") > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for float(): NaN > > The same line works as expected on Linux and Solaris with python 2.3.4. > Could anybody explain what is possibly wrong here? is it bug or > feature? feature, sort of. see http://www.python.org/peps/pep-0754.html : "Currently, the handling of IEEE 754 special values in Python depends on the underlying C library. Unfortunately, there is little consistency between C libraries in how or whether these values are handled. For instance, on some systems "float('Inf')" will properly return the IEEE 754 constant for positive infinity. On many systems, however, this expression will instead generate an error message." the PEP includes a pointer to a module that lets you replace that "float" with the fully portable: import fpconst def myfloat(x): if x == "NaN": return fpconst.NaN return float(x) From lcatalin at siadv.com Wed Jan 5 10:45:34 2005 From: lcatalin at siadv.com (Catalin Lungu) Date: Wed, 5 Jan 2005 16:45:34 +0100 Subject: Image capture References: <1104939479.011181.147650@f14g2000cwb.googlegroups.com> Message-ID: Hi, I want to capture a no visible area of a wxFrame of Python. This area contain a wxGrid object. In VB6 this code work very good. Thanks. "Kartic" escribi? en el mensaje news:1104939479.011181.147650 at f14g2000cwb.googlegroups.com... > Catalin, > > Some explanation about what you are tring to do will be of immense > help. > > Did you want to capture some other Windows object from Python or do you > want to capture a Python GUI application from Python? > > I might be able to help out, but please send more details. > Thank you, > --Kartic > From aleaxit at yahoo.com Sat Jan 1 17:46:29 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 1 Jan 2005 23:46:29 +0100 Subject: What can I do with Python ?? References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> Message-ID: <1gpqhbl.125l3evz09uefN%aleaxit@yahoo.com> BOOGIEMAN wrote: > Beginners question, but really what can you do with it ? You can write application programs, big or small, of just about any kind you may imagine, on just about any platform you may imagine (from mainframes and supercomputers down to powerful cellphones such as Nokia's S-60 series). > How hard is Python to learn compared with other languages > (let's say C#). Python is among the simplest languages to learn. > Can you make fullscreen game with it (for example) ? Sure! Have you thought of using google? The first 2 hits for python games are on www.pygame.org, "This allows you to create fully featured games and multimedia programs in the python language", as the google snippet says. The third hit is for the book "Game Programming With Python" on the amazon site. The 4th one is about Month Python, but the fifth is back to our subject -- a "Python Game Programming" page full of useful links. Then you get another link to the same book, a link to a different book, &c. > I've looked at http://www.python.org but nothing concrete there You _gotta_ be kidding, right...? The Beginner's Guide link takes you right to the BeginnersGuide page which starts with the reassurance that Python is easy to learn even if you're new to programming and continues with a zillion useful links. The Python Books link takes you to a huge list of books, and the FIRST subheading under "specific applications" is for game programming, leading you to the two books I already mentioned. There's a Search bar, enter Game there, and the FIRST hit is http://www.python.org/moin/GameProgramming which STARTS with the reassurance that, yes, you CAN "write whole games in Python", and besides PyGame also points you to PyKira, "a fast game development framework for Python" (which) "also supports MPEG video, sound (MP3, Ogg Vorbis, Wav and Multichannel module files), direct images reading and much more". Etc, etc, ...!!! How much more "concrete" could you expect *ANY* blessed website to BE, for Pete's sake?!??! Alex From simon.alexandre at cetic.be Tue Jan 11 07:19:11 2005 From: simon.alexandre at cetic.be (simon.alexandre) Date: Tue, 11 Jan 2005 13:19:11 +0100 Subject: [csv module] duplication of end of line character in output file generated Message-ID: Hi all, I use csv module included in python 2.3. I use the writer and encouter the following problem: in my output file (.csv) there is a duplication of the end of line character, so when I open the csv file in Ms-Excel a blank line is inserted between each data line. OS: W2k Someone has an idea ? thanks in advance the source code is the following: --------------------------------------------------> import csv class CsvDumper: def __init__(self): self.object = [['la','mb','mc','md'],['ma','mb','mc','md'],['ma','mb','mc','md']] self.writer = csv.writer(file("Test.csv", "w")) def DumpCsvFile(self): for row in self.object: self.writer.writerow(row) c = CsvDumper() c.DumpCsvFile() From daniel at bowettsolutions.com Wed Jan 12 15:39:56 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Wed, 12 Jan 2005 20:39:56 +0000 Subject: encryption/decryption help In-Reply-To: References: Message-ID: <41E58B1C.7030100@bowettsolutions.com> MD5 and SHA are by their very nature one way encryption. You cannot decrypt them. A quick google for other encrytion methods found this: http://www.amk.ca/python/code/crypto.html What you will need to do is find an encryption methos that uses a key which you use to encrypt and decrypt the data. You could get hold of something like GPG which has a command line interface and encrypt and decrypt that way.... drs wrote: >Hi, I need to send secure data over an insecure network. To that end, I am >needing to encrypt serialized data and then decrypt it. Is there a builtin >way to do this in Python? MD5, SHA, etc encrypt, but I am not seeing a way >to get back my data. Encryption is totally new to me, so any pointers of >what to read up on would be appreciated. > >As a side note, I understand that I could use https, but this would involve >changing things that I may not be at liberty to change -- though if this >turns out to be the best solution, then I'll find a way to use it. > >Thanks > > > > From steven.bethard at gmail.com Mon Jan 31 01:25:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 30 Jan 2005 23:25:17 -0700 Subject: Problem with loading textfiles into dictionaries. In-Reply-To: References: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> Message-ID: Kartic wrote: > mercuryprey at gmail.com said the following on 1/30/2005 7:43 PM: > >> Hello, >> I want to do the following: >> >> def do_load(self, arg): >> sitefile = file('sitelist', 'r+', 1) >> while True: >> siteline = sitefile.readline() >> site_rawlist = siteline.split() >> sitelist[site_rawlist[0]] = site_rawlist[1:] >> if len(siteline) == 0: >> break >> > You should move "if len(siteline) == 0" part right after your readline. > The way you have done it really does not help. Or better yet, don't use "if len(siteline) == 0" -- use "if siteline". See this an other examples of dubious Python: http://www.python.org/moin/DubiousPython Specifically, see the section on Overly Verbose Conditionals. Steve From tim.peters at gmail.com Mon Jan 10 14:12:29 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 10 Jan 2005 14:12:29 -0500 Subject: Writing huge Sets() to disk In-Reply-To: <41E2CE0E.5000704@ribosome.natur.cuni.cz> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> Message-ID: <1f7befae050110111239496b07@mail.gmail.com> [Martin MOKREJ?] > just imagine, you want to compare how many words are in English, German, > Czech, Polish disctionary. You collect words from every language and record > them in dict or Set, as you wish. Call the set of all English words E; G, C, and P similarly. > Once you have those Set's or dict's for those 4 languages, you ask > for common words This Python expression then gives the set of words common to all 4: E & G & C & P > and for those unique to Polish. P - E - G - C is a reasonably efficient way to compute that. > I have no estimates > of real-world numbers, but we might be in range of 1E6 or 1E8? > I believe in any case, huge. No matter how large, it's utterly tiny compared to the number of character strings that *aren't* words in any of these languages. English has a lot of words, but nobody estimates it at over 2 million (including scientific jargon, like names for chemical compounds): http://www.worldwidewords.org/articles/howmany.htm > My concern is actually purely scientific, not really related to analysis > of these 4 languages, but I believe it describes my intent quite well. > > I wanted to be able to get a list of words NOT found in say Polish, > and therefore wanted to have a list of all, theoretically existing words. > In principle, I can drop this idea of having ideal, theoretical lexicon. > But have to store those real-world dictionaries anyway to hard drive. Real-word dictionaries shouldn't be a problem. I recommend you store each as a plain text file, one word per line. Then, e.g., to convert that into a set of words, do f = open('EnglishWords.txt') set_of_English_words = set(f) f.close() You'll have a trailing newline character in each word, but that doesn't really matter. Note that if you sort the word-per-line text files first, the Unix `comm` utility can be used to perform intersection and difference on a pair at a time with virtually no memory burden (and regardless of file size). From newsgroups at jhrothjr.com Mon Jan 17 12:55:18 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 17 Jan 2005 11:55:18 -0600 Subject: PyChecker messages References: <1105983271.574296.37740@c13g2000cwb.googlegroups.com> Message-ID: <10unv167p6l9335@news.supernews.com> "Ben Sizer" wrote in message news:1105983271.574296.37740 at c13g2000cwb.googlegroups.com... > But you could use a dict of return values, or even just assigning a > different return value in each if clause. The end result is that you > have a single well-defined exit point from the function, which is > generally considered to be preferable. Preferable, but not any form of an absolute. "Single Exit" was one of the recommendations from the early structured program work back in the 70s, and the industry has long since sent it to the dustbin of history. The issue is a simple one of clarity, and woodenly applying the single exit rule where it doesn't belong frequently winds up creating nested if-elif-else structures and extranious flag variables. If an embedded return isn't clear, the method probably needs to be refactored with "extract method" a few times until it is clear. John Roth > From kp8 at mac.com Tue Jan 11 12:25:45 2005 From: kp8 at mac.com (kpp9c) Date: 11 Jan 2005 09:25:45 -0800 Subject: Time script help sought! Message-ID: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> I am kind of in a bit of a jam (okay a big jam) and i was hoping that someone here could give me a quick hand. I had a few pages of time calculations to do. So, i just started in on them typing them in my time calculator and writing them in by hand. Now i realize, that i really need a script to do this because: 1. It turns out there are hundreds of pages of this stuff. 2. I have to do something similar in again soon. 3. By doing it by hand i am introducing wonderful new errors! 4. It all has to be typed up anyway (which means weeks of work and even more typos!) The input would like so: Item_1 TAPE_1 1 00:23 8:23 Item_2 TAPE_1 2 8:23 9:41 Item_3 TAPE_1 3 9:41 10:41 Item_3 TAPE_1 4 10:47 11:19 Item_3 TAPE_1 5 11:21 11:55 Item_3 TAPE_1 6 11:58 12:10 Item_3 TAPE_1 7 12:15 12:45 Defect in analog tape sound. Item_3 TAPE_1 8 12:58 24:20 Defect in analog tape sound. Item_4 TAPE_1 9 24:33 Item_4 TAPE_1 10 25:48 Item_4 TAPE_1 11 29:48 Item_4 TAPE_1 12 31:46 Item_4 TAPE_1 13 34:17 Electronic sounds. Item_4 TAPE_1 14 35:21 Item_4 TAPE_1 15 36:06 Item_4 TAPE_1 16 37:01 37:38 These are analog tapes that were digitized (on to CD or a digital tape) that have now been exported as individual files that are meant to be part of an on-line audio archive. The timings refer to the time display on the CD or digital tape. The now all have to adjusted so that each item starts at 0.00 since they have all been edited out of their context and are now all individual items that start at 00:00. So Item_1 which was started at 00:23 on the tape and ended at 8:23 needs to have 23 seconds subtracted to it so that it says: Item_1 TAPE_1 1 00:00 08:00 Item_2 TAPE_1 2 08:23 09:41 would change to: Item_2 TAPE_1 2 00:00 01:18 etc. but as always you may notice a wrinkle.... some items have many times (here 6) indicated: Item_3 TAPE_1 3 9:41 10:41 Item_3 TAPE_1 4 10:47 11:19 Item_3 TAPE_1 5 11:21 11:55 Item_3 TAPE_1 6 11:58 12:10 Item_3 TAPE_1 7 12:15 12:45 Defect in analog tape sound. Item_3 TAPE_1 8 12:58 24:20 Defect in analog tape sound. This is all a single sound file and these separate times mark where there was a break, defect, or edit in the individual item. These have to be adjusted as well to show where these events would appear in the new sound file which now starts at 00:00. Item_3 TAPE_1 3 00:00 01:00 ---- Item_3 TAPE_1 4 01:00 01:38 ---- Item_3 TAPE_1 5 01:38 02:14 ---- Item_3 TAPE_1 6 02:14 02:29 ---- Item_3 TAPE_1 7 02:29 03:04 Defect in analog tape sound. Item_3 TAPE_1 8 03:04 14:39 Defect in analog tape sound. Further wrinkles: Some have start and end times indicated, some only start times. I suppose that the output would ideally have both.... some have comments and others don't ... and I need these comments echo-ed or since i probably need to make a database or table eventually non comments just have some place holder. I'd have a lot of similar type calculations to do... I was hoping and praying that some one here was feeling generous and show me the way and then, of course i could modify that to do other tasks... Usually i am happy to take the long road and all but i'll be honest, i am in a big jam here and this huge task was just dumped on me. I am frankly a little desperate for help on this and hoping someone is feeling up to spoon feeding me a clear modifiable example that works. Sorry..... cheers, kevin From kent3737 at yahoo.com Sun Jan 9 20:54:45 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Sun, 09 Jan 2005 20:54:45 -0500 Subject: Please Contribute Python Documentation! In-Reply-To: References: Message-ID: <41e1de2d$1_1@newspeer2.tds.net> Aahz wrote: > In article , > Tony Meyer wrote: > >>I don't think I've seen such a statement before - the stuff I've seen >>all indicates that one should be submitting proper LaTeX docs/patches. >>If plain-text contributions are welcome, could this be added to the doc >>about contributing to the docs? (I suppose I could submit a patch, but >>that seems overkill ). > > > It *is* in the docs now -- see the top of > http://www.python.org/doc/2.4/doc/doc.html It's also spelled out pretty clearly in the "About this document" document you get by clicking on the link at the bottom of every page. Kent > > (This has been the official policy for some time, but you're right that > it wasn't earlier documented. So I filed a bug report. ;-) If you > think this still isn't enough, file another.) From http Fri Jan 28 07:07:44 2005 From: http (Paul Rubin) Date: 28 Jan 2005 04:07:44 -0800 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> Message-ID: <7x3bwlsqnj.fsf@ruckus.brouhaha.com> Duncan Booth writes: > In other words, I'm intrigued how you managed to come up with something you > consider to be a security issue with Python since Python offers no > security. Perhaps, without revealing the actual issue in question, you > could give an example of some other situation which, if it came up in > Python you would consider to be a security issue? Until fairly recently, the pickle module was insufficiently documented as being unsafe to use with hostile data, so people used it that way. As a result, the Cookie module's default settings allowed remote attackers to take over Python web apps. See SF bug 467384. From dbickett at gmail.com Tue Jan 11 20:02:16 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Tue, 11 Jan 2005 20:02:16 -0500 Subject: shutil.move has a mind of its own In-Reply-To: <41e46e0d@usenet01.boi.hp.com> References: <41e46e0d@usenet01.boi.hp.com> Message-ID: <1d6cdae30501111702e71bdfc@mail.gmail.com> Don wrote: > I don't know if this is the problem or, not, but: > [snip] As I said, that was simply an error when typing the example, and it is not present in my code. See below. Neil Benn wrote: > >Oh, I'm sorry, that was my mistake. The example contained that error, > >but my code does not. > > > > [snip] > > > To be fair though - I would have expected the method to throw an error > rather than default to cwd. > > Neil > Which is why I found this so strange, and also why I provided my code. The paths are user-inputed, and only referenced as variables, so this is clearly not a matter of escape sequences. Daniel Bickett From bob_smith_17280 at hotmail.com Sun Jan 9 21:56:45 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Sun, 09 Jan 2005 21:56:45 -0500 Subject: a new Perl/Python a day In-Reply-To: References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: Scott Bryce wrote: > Xah Lee wrote: > >> frustrated constantly by its inanities and incompetences.) > > I don't see what this has to do with Perl. You're joking, right? From gabriel.cooper at mediapulse.com Mon Jan 24 10:40:29 2005 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Mon, 24 Jan 2005 10:40:29 -0500 Subject: Finding a script's home directory? Message-ID: <41F516ED.3090503@mediapulse.com> In one of my python programs has a data file I need to load. My solution was to say: if os.path.exists(os.path.join(os.getcwd(), "config.xml")): self.cfgfile = os.path.join(os.getcwd(), "config.xml") Which works fine... as long as you're *in* the script's home directory when you run it (as in, run it as: ./startApp.py as opposed to ./myApp/startApp.py). If I run it from an alternate directory the program looks for the config.xml file in my current directory not the app's home directory. So how do I get the script's home directory? From a at b.c Thu Jan 6 22:02:46 2005 From: a at b.c (Doug Holton) Date: Thu, 06 Jan 2005 21:02:46 -0600 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: Message-ID: Alan Gauld wrote: >>GvR has commented that he want to get rid of the lambda keyword for Python 3.0. >>Getting rid of lambda seems like a worthy goal, > > > Can I ask what the objection to lambda is? > 1) Is it the syntax? > 2) Is it the limitation to a single expression? > 3) Is it the word itself? > > I can sympathise with 1 and 2 but the 3rd seems strange since a > lambda is a well defined name for an anonymous function used in > several programming languages and originating in lambda calculus > in math. Lambda therefore seems like a pefectly good name to > choose. I agree with keeping lambda functionality, and I don't care what name is used, but there are people who do not like "lambda": http://lambda-the-ultimate.org/node/view/419#comment-3069 The word "lambda" is meaningless to most people. Of course so is "def", which might be why Guido van Robot changed it to "define": http://gvr.sourceforge.net/screen_shots/ Even a simple word like "type" can be difficult to explain to beginners: http://lambda-the-ultimate.org/node/view/337 Python is easier for beginners to learn than other mainstream programming languages (like java or C++), but that's not to say it doesn't have some stumbling blocks for beginners of course: http://www.linuxjournal.com/article/5028 > So why not retain the name lambda but extend or change the syntax > to make it more capable rather than invent a wholly new syntax > for lambdas? Yes, I agree, and either keep the "lambda" keyword or else reuse the "def" keyword for anonymous methods. See this page Steven Bethard created: http://www.python.org/moin/AlternateLambdaSyntax I really don't think anyone should worry about lambda disappearing. By the way, you've done great work with your learning to program site and all the help you've given on the python-tutor list: > Alan G. > Author of the Learn to Program website > http://www.freenetpages.co.uk/hp/alan.gauld From mg.mailing-list at laposte.net Mon Jan 24 04:00:11 2005 From: mg.mailing-list at laposte.net (mg) Date: Mon, 24 Jan 2005 10:00:11 +0100 Subject: PyWin32 installation Message-ID: <41F4B91B.2060307@laposte.net> Hi all, I have reinstalled my Win32 computer last week and I did an update of the project PyWin32 to complete my Python installation. (I have to use sources from CVS for my project !) So, when I run 'python setup.py' in my PyWin32 directory, I have two problem : the version indacated in windows.h and some symbols who are not defined. See the trace : running install running build running build_py running build_ext Warning - can't find an installed platform SDK Found WINDOWS.H version 0x501 in C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\PlatformSDK\include building 'win32print' extension C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH:C:\ext_projects\python\dist\src\libs /LIBPATH:C:\ext_projects\python\dist\src\PCBuild /LIBPATH:build\temp.win32-2.5\Release winspool.lib user32.lib /EXPORT:initwin32print build\temp.win32-2.5\Release\win32\src\win32print\win32print.obj /OUT:build\lib.win32-2.5\win32\win32print.pyd /IMPLIB:build\temp.win32-2.5\Release\win32\src\win32print\win32print.lib /MACHINE:ix86 Creating library build\temp.win32-2.5\Release\win32\src\win32print\win32print.lib and object build\temp.win32-2.5\Release\win32\src\win32print\win32print.exp win32print.obj : error LNK2019: unresolved external symbol __imp__StartDocA at 8 referenced in function "struct _object * __cdecl PyStartDoc(struct _object *,struct _object *)" (?PyStartDoc@@YAPAU_object@@PAU1 at 0@Z) win32print.obj : error LNK2019: unresolved external symbol __imp__EndDoc at 4 referenced in function "struct _object * __cdecl PyEndDoc(struct _object *,struct _object *)" (?PyEndDoc@@YAPAU_object@@PAU1 at 0@Z) Then, I don't kwnow how to solve theses problem ! Is there someone tho help me ? Thank, Mathieu G. From stephan.diehl at gmx.net Tue Jan 4 09:17:04 2005 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Tue, 04 Jan 2005 15:17:04 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> <1104846212.355098.186400@c13g2000cwb.googlegroups.com> Message-ID: On Tue, 04 Jan 2005 05:43:32 -0800, michele.simionato wrote: > Holger: > >> FWIW, i added the recipe back to the online cookbook. It's not > perfectly >> formatted but still useful, i hope. > >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361742 > > Uhm... on my system I get: > >>>> german_ae = unicode('\xc3\xa4', 'utf8') >>>> print german_ae # dunno if it will appear right on Google groups > ? > >>>> german_ae.decode('latin1') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in > position 0: ordinal not in range(128) > ?? What's wrong? I'd rather use german_ae.encode('latin1') ^^^^^^ which returns '\xe4'. > > Michele Simionato From aleaxit at yahoo.com Thu Jan 6 09:45:09 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 6 Jan 2005 15:45:09 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> Roel Schroeven wrote: > Can you point to closed-source licenses that allow using the code *at > all*? As I recall, for example, Microsoft Visual C++ came with sources for various libraries; all that the (closed-source) license for those libraries forbade you from doing was to further distribute the _sources_ themselves. You could do modifications big or small to those libraries for whatever purposes, and redistribute the _compiled_ form of the code as a DLL, or statically linked into your own programs, etc, etc. Is this what you mean by "allow using the code *at all*"? I think it's a pretty common arrangement when the code being sold under closed-source terms is a set of libraries, or a development system part of whose value is a set of accompanying libraries. Alex From ruses at users.ch Mon Jan 17 15:28:43 2005 From: ruses at users.ch (more i squawed) Date: Mon, 17 Jan 2005 21:28:43 +0100 Subject: hash patent by AltNet; Python is prior art? In-Reply-To: References: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> Message-ID: <352l07F4cvej3U1@individual.net> Tim Churches a ?crit : > Provided other countries don't recognise software and business method > patents, the litigation will be confined within US borders, where > resources can be productivelt spent making television dramas about > attractive young patent attorneys and plodding, tram-riding patent > clerks who are really brilliant physicists if only someone would > recognise their potential. Nicely put. From http Thu Jan 13 11:29:07 2005 From: http (Paul Rubin) Date: 13 Jan 2005 08:29:07 -0800 Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> Message-ID: <7x7jmh1eek.fsf@ruckus.brouhaha.com> "hanz" writes: > > But wait if I do that, people will tell me how bad that it is, > > because it will keep a reference to the value which will prevent > > the garbage collector from harvesting this memory. > > Nobody will tell you that it's bad. Python was never about super > performance, but about readability. Besides, using such temporaries > won't consume much memory (relatively). That completely depends on the objects in question. Compare temp = all_posters[:] temp.sort() top_five_posters = temp[-5:] to: top_five_posters = all_posters.sorted()[-5:] which became possible only when .sorted() was added to Python 2.4. This is another reason it would be nice to be able to create very temporary scopes. From dderakon at hotmail.com Sun Jan 30 18:22:08 2005 From: dderakon at hotmail.com (Chris Weisiger) Date: Sun, 30 Jan 2005 23:22:08 -0000 Subject: PyGame not working(?) (was: trouble installing numeric) References: <20050129232540162-0800@news.claremont.edu> Message-ID: <20050130152208505-0800@news.claremont.edu> On 1/29/05 11:38 PM, Robert Kern wrote: > Chris Weisiger wrote: >> I'm trying to install numeric on my MacOS X box using Darwin, with >> the eventual goal of satisfying all of PyGame's dependencies so I >> can finally start working on my semester project. I would be using >> MacPython, except that I can't seem to get its Package Manager to >> work. > > This is fixed in CVS. > Thanks; I've now successfully installed Numeric, as well as all of the other dependencies listed for PyGame. However, PyGame appears to still not be working. When I try to run the program at the top of this page: http://www.pygame.org/docs/tut/tom/games2.html I get the following error: % python main.py Fatal Python error: Interpreter not initialized (version mismatch?) Abort Is this a problem with PyGame or with something else? I can run a simple Hello World program, so I'm assuming that Python itself is fine. Any ideas? -- "Don't take life so serious, son - it ain't nohow permanent." - Porkypine http://www.cs.hmc.edu/~cweisige From mcfletch at rogers.com Tue Jan 11 23:38:15 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 11 Jan 2005 23:38:15 -0500 Subject: Help Optimizing Word Search In-Reply-To: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Message-ID: <41E4A9B7.7040201@rogers.com> To search for a word which is a jumble of a given set of characters in a (sizable) lexicon, see this posting: http://blog.vrplumber.com/427 your alterations would be to check for length == to length - number-of-wildcards (with the wildcards removed from the translation table, of course) and then some tweaks to the "expensive" loop to allow for up to wildcard-count ValueErrors. There's some (informal) analysis in the comments of that post regarding why its a fairly good mechanism for searching large sets of words. HTH, Mike Case Nelson wrote: ... >Basically, the program needs to take in a random list of no more than >10 letters, and find all possible mutations that match a word in my >dictionary (80k words). However a wildcard letter '?' is also an >acceptable character which increases the worst case time significantly. >So if the letters are ['a','b','c'] check a, b, c, ab, ac, ba, bc, ca, >cb, abc, acb, bac, bca, cab, cba where only a, ba and cab would be >added to the dict of words. If the letters are ['?','?'] check a-z, aa, >ab, ac, ad, ..., az, ba, bb, bc, bd, ..., zz > > ... ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From asda at sdarta.com Wed Jan 5 08:46:08 2005 From: asda at sdarta.com (worzel) Date: Wed, 5 Jan 2005 21:46:08 +0800 Subject: is python more popular than coldfusion? References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au><41dbe722$0$23057$5a62ac22@per-qv1-newsreader-01.iinet.net.au><41dbec00$0$23064$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41dbefa2$0$23052$5a62ac22@per-qv1-newsreader-01.iinet.net.au> thanks, thats pretty much what I expected to hear. "Premshree Pillai" wrote in message news:mailman.195.1104932572.22381.python-list at python.org... > On Wed, 5 Jan 2005 21:30:40 +0800, worzel wrote: >> Wth respect to coldfusion, is there much doubt about the fact that Python >> is >> a more prominent and important technology? > > No doubt in my mind at least. > >> >> How is colfusion percieved by the Python community? Many people belive >> coldfusion is becomeing irrelavant and is on its death bed - do Python >> folk >> generally feel this way about it? > > I have no much idea about Coldfusion, but as far as its *use* is > concerned, it definitely isn't much. > >> >> Thanks for your input on this by the way. >> >> "Premshree Pillai" wrote in message >> news:mailman.192.1104931284.22381.python-list at python.org... >> > On Wed, 5 Jan 2005 21:09:54 +0800, worzel wrote: >> >> How seriuosly do folk take the TIOBE index? Is it a good way to ague >> >> what >> >> you should be keeping up to speed with or just a 'vague' guide? >> > >> > I use the TIOBE index -- sometimes -- when I give presentations on >> > Python (and Ruby) to people who haven't heard of the languages. >> > >> > The index is not something to be relied upon (take a look at the >> > calculation mechanism). However, more often than not, the indices >> > seems to reflect what *I* perceive the indices are in reality. So I >> > kinda use them. >> > >> > The thing about introducing a "new" language to a bunch of folks used >> > to their "favorite" language is that they wouldn't care much for a >> > language it isn't popular, or if it isn't "growing in popularity". >> > >> > Beyond these things, I don't think anybody uses the index. I mean I >> > wouldn't tell people to learn languages that hold the top position on >> > TIOBE ;). >> > >> >> >> >> "Premshree Pillai" wrote in message >> >> news:mailman.189.1104927428.22381.python-list at python.org... >> >> > On Wed, 5 Jan 2005 19:59:21 +0800, worzel wrote: >> >> >> >> >> >> >> >> >> >> >> >> is python more popular than coldfusion? >> >> > >> >> > I don't know if Coldfusion _was_ ever more "popular" than Python, >> >> > but >> >> > Python is definitely more "popular" _now_. >> >> > >> >> > This might be of some help: http://www.tiobe.com/tpci.htm >> >> > >> >> >> >> >> >> I realsie that is a very general question as one thing does not >> >> >> directly >> >> >> relate to the other. My issue is that I am ditching coldfusion due >> >> >> to >> >> >> there >> >> >> being next to no work for it, and I am thinking of taking on python >> >> >> as >> >> >> a >> >> >> second language to java in the hope of improving my resume. >> >> >> -- >> >> >> http://mail.python.org/mailman/listinfo/python-list >> >> >> >> >> >> >> >> > >> >> > >> >> > -- >> >> > Premshree Pillai >> >> > http://www.livejournal.com/~premshree >> >> >> >> -- >> >> http://mail.python.org/mailman/listinfo/python-list >> >> >> > >> > >> > -- >> > Premshree Pillai >> > http://www.livejournal.com/~premshree >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > -- > Premshree Pillai > http://www.livejournal.com/~premshree From claird at lairds.us Thu Jan 27 12:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 27 Jan 2005 17:08:04 GMT Subject: Please suggest on the book to follow References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> <1106829519.540737.164210@z14g2000cwz.googlegroups.com> <1106836611.862211.283470@c13g2000cwb.googlegroups.com> Message-ID: In article <1106836611.862211.283470 at c13g2000cwb.googlegroups.com>, santanu wrote: . . . >>From what you and Fyzzyman said, I guess when I am done with >Programming Python, graduating to the latest features would >be quite easy. Isn't it? . . . Yes. From luisXX_lupe2XX at netvisaoXX.pt Fri Jan 21 12:55:55 2005 From: luisXX_lupe2XX at netvisaoXX.pt (Luis P. Mendes) Date: Fri, 21 Jan 2005 17:55:55 +0000 Subject: xml parsing escape characters In-Reply-To: References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efedf2$0$11622$9b622d9e@news.freenet.de> <35adg4F4jgvpnU1@individual.net> <41F01A86.2040805@v.loewis.de> Message-ID: <35ctgpF4ktmgoU2@individual.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 ~From your experience, do you think that if this wrong XML code could be meant to be read only by somekind of Microsoft parser, the error will not occur? I'll try to explain: xml producer writes the code in Windows platform and 'thinks' that every client will read/parse the code with a specific Windows parser. Could that (wrong) XML code parse correctly in that kind of specific Windows client? Or in other words: Do you know any windows parser that could turn that erroneous encoding to a xml tree, with four or five inner levels of tags? I'd like to thank everyone for taking the time to answer me. Luis -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFB8UIOHn4UHCY8rB8RAgK4AKCiHjPdkCKnirX4gEIawT9hBp3HmQCdGoFK 3IEMLLXwMZKvNoqA4tISVnI= =jvOU -----END PGP SIGNATURE----- From ncoghlan at iinet.net.au Sun Jan 9 02:19:13 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 17:19:13 +1000 Subject: python3: accessing the result of 'if' In-Reply-To: <1105249487.644698.309100@c13g2000cwb.googlegroups.com> References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> <1105236383.521393.40680@c13g2000cwb.googlegroups.com> <1105249487.644698.309100@c13g2000cwb.googlegroups.com> Message-ID: <41E0DAF1.8080306@iinet.net.au> Carl Banks wrote: > I'm sorry, I really can't agree that this helper function "solves" it. > IMO, it's a workaround, not a solution. And, if I may be frank, it's a > pretty ugly one. Heck, I thought it was ugly and I wrote it :) So in reality, I'd continue to use the nested-if approach that works right now if I wanted access to part of the condition instead of the whole thing. However, being able to bind a name to the conditions would be handy for many cases. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tmohr at s.netic.de Tue Jan 11 01:34:41 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 11 Jan 2005 07:34:41 +0100 Subject: reference or pointer to some object? Message-ID: Hi, i'd like to pass a reference or a pointer to an object to a function. The function should then change the object and the changes should be visible in the calling function. In perl this would be something like: sub func { $ref = shift; $$ref += 123; # change } $a = 1; func(\$a); is something like this possible in python? The keyword "global" does NOT fit this purpose to my understanding as it only makes the variables of the UPPERMOST level visible, not the ones of ONE calling level above. Is this somehow possible with weakref? I don't want to pass the parameter to a function and then return a changed value. Is there some other mechanism in python available to achieve a behaviour like this? Thanks for any hints, Torsten. From fumanchu at amor.org Sat Jan 8 14:04:58 2005 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 8 Jan 2005 11:04:58 -0800 Subject: there's a socket.sendall(), so why no socket.recvall()? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398146@exchange.hqamor.amorhq.net> Irmen de Jong wrote: > Subject says it all; > there's a socket.sendall(), so why no socket.recvall()? Good question! Something like: # Receive reply. data = [] while True: try: chunk = conn.recv(8192) except Exception, x: if x.args[0] != 10035: raise x else: if chunk == '': break data.append(chunk) If you call .makefile() and then .read() the _fileobject, you get the same behavior (only better). Adding recvall would just duplicate that, I think. But that's desirable IMO. Robert Brewer MIS Amor Ministries fumanchu at amor.org From steve at holdenweb.com Wed Jan 12 18:36:46 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 12 Jan 2005 18:36:46 -0500 Subject: else condition in list comprehension In-Reply-To: References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: Nick Coghlan wrote: > Luis M. Gonzalez wrote: > >> Hi there, >> >> I'd like to know if there is a way to add and else condition into a >> list comprehension. I'm sure that I read somewhere an easy way to do >> it, but I forgot it and now I can't find it... >> >> for example: >> z=[i+2 for i in range(10) if i%2==0] >> what if I want i to be "i-2" if i%2 is not equal to 0? >> > > Hmm: > > z = [newval(i) for i in range(10)] using: > def newval(x): > if x % 2: > return x - 2 > else: > return x + 2 > > Just some more mental twiddling relating to the thread on statement > local namespaces. > I presume the point of this is to avoid polluting the local namespace with "newval". I further presume you also have plans to do something about "i"? ;-) regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From http Sat Jan 8 03:15:35 2005 From: http (Paul Rubin) Date: 08 Jan 2005 00:15:35 -0800 Subject: How to read/write blobs with mysqldb? References: Message-ID: <7xr7kwpc9k.fsf@ruckus.brouhaha.com> "Christopher J. Bottaro" writes: > That doesn't sound very efficient to me. What if my computer only has 64 MB > of memory and the data I want to insert is 128 MB? Don't use such large blobs. From pythongnome at hotmail.com Thu Jan 27 08:12:07 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Thu, 27 Jan 2005 13:12:07 GMT Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: > > As long as we are discussing cryptography, what's wrong with m2crypto? > > http://sandbox.rulemaker.net/ngps/m2/ > > Why not incorporate it into the standard distribution? > > Or, what about Andrew Kuchling's crypto toolkit? > > http://www.amk.ca/python/code/crypto.html > Umm, is it just me or did we just discuss the legal issues of that?? From simon.brunning at gmail.com Wed Jan 12 10:43:44 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 12 Jan 2005 15:43:44 +0000 Subject: Excel module for Python In-Reply-To: References: Message-ID: <8c7f10c605011207434ee6b078@mail.gmail.com> On Wed, 12 Jan 2005 23:19:44 +0800, sam wrote: > > No, I don't use MS windows. I need to generate Excel file by printing > data to it, just like Perl module Spreadsheet::WriteExcel. If it's just data that needs to go into your spreadsheet, then I'd just build a CSV file if I were you. Excel opens them perfectly happily. If you need to write out formulae, formratting, that kind of thing, then I think you'll need to write a 'real' Excel file. I don't have a clue how to do that - sorry. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From steve at holdenweb.com Wed Jan 5 15:01:03 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 05 Jan 2005 15:01:03 -0500 Subject: modpython, apache and windows In-Reply-To: References: Message-ID: Sam wrote: > Hi All, > > I am interested in learning python since I am hearing more and more > about python for use in web development > > I am starting out on python, with knowledge of PHP some perl > > my current hurdle is setting up either apache 1 or 2 with python 2.3.3 I > have installed modpython fine > > which informed me that I need to make some configuration changes to > httpd.conf > These changes are relatively easy, but of course making them requires access to the files, not always available unless you are managing your own server. Note, though, that it's easliy possible to use Python as a CGI language on most Apache installations. > I have not had it working yet, searches on the web give conflicting > suggestions and so far has confused me > Perhaps if you could explain what it is you are failing to do, you might eleicit some explicit help. > some forums mention spyce and serving .spy files > > so far I one explanation worked in that a .py file was parsed but I had > to set the name of the actual file within apache.conf > this seems strange > > thanks in advance >> SS > > Try creating a Python file (.py file, with world-executable permissions) in a cgi-bin directory: #!/usr/bin/env python print """Content-Type: text/plain Hello, world""" and see if you can call it from a web browser. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From devries at idolstarastronomer.com Wed Jan 12 08:13:45 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: 12 Jan 2005 05:13:45 -0800 Subject: distutils linux script installation broken? References: Message-ID: <1105535625.443343.326560@z14g2000cwz.googlegroups.com> I just installed python2.4 and used it to install a set of scripts I had previously been using distutils with. It worked fine, and replaced the first line with: #!/usr/local/bin/python2.4 distutils should replace that first line with the location of the binary used to run setup.py. Are you running setup with the following command line? python setup.py install From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sun Jan 2 18:38:38 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Mon, 3 Jan 2005 00:38:38 +0100 Subject: ctypes NULL pointers; was: Python To Send Emails Via Outlook Express References: Message-ID: <41d8f228$0$2742$8fcfb975@news.wanadoo.fr> Ok ; thank you. From kylotan at gmail.com Mon Jan 3 20:13:50 2005 From: kylotan at gmail.com (Ben Sizer) Date: 3 Jan 2005 17:13:50 -0800 Subject: Integrating Python into a C++ app Message-ID: <1104801230.728736.83970@f14g2000cwb.googlegroups.com> I know the conventional wisdom is to write the whole app in Python and only extend with C++ where speed is an issue, but I already have a large C++ app that I'd like to add Python to. Ideally I'd rewrite the whole app in Python but I don't have time to do that and maintain the old system at the same time. So my next thought was to perhaps integrate the two and slowly migrate modules and classes across from C++ to Python. If it matters, the main reason I'm interested in doing this is because I appreciate the productivity of Python and would like to take advantage of that as I add features to the current code, to reduce bugs and cut development time. I've read a few good things in this group about Elmer (http://elmer.sourceforge.net), but I'm not sure how simply that accommodates calls in the reverse direction (from Python code back into C++). Are there any other options that would require a minimum of rewriting of code? Does anybody have any experience of such a project? -- Ben Sizer From ncoghlan at iinet.net.au Thu Jan 20 05:08:05 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 20 Jan 2005 20:08:05 +1000 Subject: Freezing a mutable (was Re: lambda) In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> <41ed8c13.1209309354@news.oz.net> Message-ID: <41EF8305.1070202@iinet.net.au> Antoon Pardon wrote: > Interesting idea. But I think you are wrong when you say that two lists > that compare equal at the time they are frozen, will get the same > dictionary entry. The problem is an object must compare equal to > the key in the dictionary to get at the same entry. So if you freeze > a list and its copy but then mutate them differently, they no longer > are equal and so wont get you at the same entry. The trick is that the result of the freezing operation is cached until such time as you explicitly unfreeze the object. Output: x: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] y: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Write via x, read via y: Hi there! x: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y: [0, 1, 2, 3, 4, 5, 6, 7, 8] Read via mutated x: Hi there! Read via mutated y: Hi there! x: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] y: [0, 1, 2, 3, 4, 5, 6, 7, 8] Found unfrozen x: False Found unfrozen y: False Produced by: class mylist(list): def __init__(self, arg): super(mylist, self).__init__(arg) self._tuple = None def frozen(self): if self._tuple is None: self._tuple = tuple(self) return self._tuple def unfreeze(self): self._tuple = None x = mylist(range(10)) y = mylist(range(10)) dct = {} dct[x.frozen()] = "Hi there!" print "x:", x print "y:", y print "Write via x, read via y:", dct[y.frozen()] x.append(10) del y[-1] print "x:", x print "y:", y print "Read via mutated x:", dct[x.frozen()] print "Read via mutated y:", dct[y.frozen()] x.unfreeze() y.unfreeze() print "x:", x print "y:", y print "Found unfrozen x:", x.frozen() in dct print "Found unfrozen y:", y.frozen() in dct -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ialbert at mailblocks.com Mon Jan 17 13:12:47 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 17 Jan 2005 13:12:47 -0500 Subject: pychecker - sets.Set need to be overridden In-Reply-To: References: Message-ID: Peter Otten wrote: > The Set class has implementations for __cmp__() and __hash__() that > unconditionally raise an exception. pychecker assumes that these methods > are "abstract", i. e. meant to be overriden by a subclass, and warns that > you are instantiating an abstract base class, while the intention of the I see. Thanks! Istvan. From cjbottaro at alumni.cs.utexas.edu Sat Jan 1 23:06:14 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Sat, 01 Jan 2005 22:06:14 -0600 Subject: HTTP GET request with basic authorization? Message-ID: How do I do this using httplib.HTTPConnection and httplib.HTTPConnection.request()? The library reference only gives a simple GET example with no header stuff. I tried this, but it didn't work: conn.request("GET", "/somepage.html", None, {"AUTHORIZATION": "Basic username:password"}) Thanks for the help. P.S. I know nothing about HTTP, I'm just piecing this stuff together from examples on the internet, please be gentle with your responses. From fuzzyman at gmail.com Wed Jan 5 11:22:11 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jan 2005 08:22:11 -0800 Subject: How to make executable file ? In-Reply-To: References: Message-ID: <1104942131.727332.76380@c13g2000cwb.googlegroups.com> An alternative way is to use Movable Python. It's a frozen distribution of python that can run without being 'installed'. See http://sourceforge.net/projects/movpy To display things in a 'window' you'll need to use a GUI toolkit like Tkinter or wxPython. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From fredrik at pythonware.com Thu Jan 20 02:46:05 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jan 2005 08:46:05 +0100 Subject: iteritems() and enumerate() References: <1106206068.867004.195010@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > Python has iteritems() and enumerate() to be used in for loops. > > can anyone tell me what these are by themselves, if anything? iteritems() is a dictionary method, which returns a lazily constructed sequence of all (key, value) pairs in the dictionary. enumerate(seq) is a function that returns a lazily constructed list of (index, value) pairs for all values in a sequence. check the relevant sections of the library reference for details. From tim.peters at gmail.com Fri Jan 21 14:54:28 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 21 Jan 2005 14:54:28 -0500 Subject: Zen of Python In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> Message-ID: <1f7befae05012111543cc0b81c@mail.gmail.com> [Paul Rubin] >> You snipped out the examples I gave, like [x*x for x in range(5)] >> leaving unnecessary residue in the name space. Was it not >> obvious from the beginning that that was a kludge? If it was >> obviously a kludge, was it not obvious that there would be >> reason to want to fix it someday? I'm saying that if some new >> feature is going to need a fix later, it's better to fix it before >> releasing it in the first place. [Steve Holden] > Well no, I certainly have never thought the name droppings from > list comprehensions to be anything other than a wart. > > But my parting shot was simply to point out that you don't > always know where you're going until you're at least part of the > way there. Until the feature exists, how do you know it needs > fixing? > > The fact that a bright bunch like the Python developers didn't > realize that it would be sensible to have a local scope for the list > comprehension variable is a perfect demonstration of that point. Well, language design issues aren't really that mysterious. It was, for example, _always_ obvious that Scheme-heads would complain about the way listcomps got implemented (wrt the scope of the iteration vrbl). But at that time, Python didn't have lexical scoping, and it wasn't clear that it ever would. So what's the bigger wart? Making listcomps exactly equivalent to an easily-explained Python for-loop nest, or introducing a notion of lexical scope unique to listcomps, hard to explain in terms of the way the rest of the language worked? The former was thought to be the lesser evil at the time, and for truly obvious reasons. Except, perhaps, to those looking at Python as if it were a flawed approximation to some other language -- as Lispers and Schemers are notoriously prone to do, even wrt each others' favorite dialects. At the time, the right decision was made. From danb_83 at yahoo.com Sun Jan 2 21:10:15 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 2 Jan 2005 18:10:15 -0800 Subject: Calling Function Without Parentheses! References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> Message-ID: <1104718215.795501.83450@f14g2000cwb.googlegroups.com> Kamilche wrote: > What a debug nightmare! I just spent HOURS running my script through > the debugger, sprinkling in log statements, and the like, tracking down > my problem. > > I called a function without the ending parentheses. I sure do WISH > Python would trap it when I try to do the following: > MyFunc > > instead of: > > MyFunc() You're a former Pascal programmer, aren't you? ;-) In Python, it's not an error, because you can do things like: >>> def simpson(f, a, b): ... "Simpson's Rule approximation of the integral of f on [a, b]." ... return (b - a) * (f(a) + 4 * f((a + b) / 2.0) + f(b)) / 6.0 ... >>> simpson(math.sin, 0.0, math.pi) # Note that math.sin is a function 2.0943951023931953 From asda at sdarta.com Wed Jan 5 06:59:21 2005 From: asda at sdarta.com (worzel) Date: Wed, 5 Jan 2005 19:59:21 +0800 Subject: is python more popular than coldfusion? Message-ID: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> is python more popular than coldfusion? I realsie that is a very general question as one thing does not directly relate to the other. My issue is that I am ditching coldfusion due to there being next to no work for it, and I am thinking of taking on python as a second language to java in the hope of improving my resume. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam at nospam.com Mon Jan 3 10:41:39 2005 From: nospam at nospam.com (3c273) Date: Mon, 3 Jan 2005 07:41:39 -0800 Subject: Tkinter (OOP?) help References: <863bxnry43.fsf@guru.mired.org> Message-ID: "Mike Meyer" wrote in message news:863bxnry43.fsf at guru.mired.org... > Every time you call newwindow, you rebind self.new to the window just > created. So any close button that works will close the last window opened. > > You need to create a separate class for new windows, each with it's > own self.new (or self.window) that it's self.closeme will call destroy > on. > > Message-ID: Pro Grammer writes: > Hello, all, > I am not sure if this is the right place to ask, but could you kindly tell me > how to "load" a shared object (like libx.so) into python, so that the methods in > the .so can be used? That too, given that the shared object was written in c++, > compiled with g++ ? > Thanks, > Pro Grammer Will the dl standard library module help you? From the Python docs at: http://docs.python.org/lib/module-dl.html Example: >>> import dl, time >>> a=dl.open('/lib/libc.so.6') >>> a.call('time'), time.time() (929723914, 929723914.498) I'm guessing that there might be some C++ issues, but maybe it's worth looking into. Rick From apardon at forel.vub.ac.be Fri Jan 14 03:12:29 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Jan 2005 08:12:29 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> Message-ID: Op 2005-01-13, hanz schreef : > > Antoon Pardon wrote: >> So if I have a call with an expression that takes more than >> one line, I should assign the expression to a variable and >> use the variable in the call? > > Yes, that's sometimes a good practice and can clarify > the call. > >> But wait if I do that, people will tell me how bad that it >> is, because it will keep a reference to the value which >> will prevent the garbage collector from harvesting this >> memory. > > Nobody will tell you that it's bad. Sorry, someone already did. If I recall correctly it was Alex Martelli. -- Antoon Pardon From fuzzyman at gmail.com Tue Jan 25 09:17:35 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Jan 2005 06:17:35 -0800 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <1106564799.011057.181280@c13g2000cwb.googlegroups.com> Message-ID: <1106662655.352239.151790@z14g2000cwz.googlegroups.com> I've already downloaded p3 - thanks :-) I wonder how long it took (in reality) an average hacker to break the algorithm used by rotor ? Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From mt at 3planes.com Mon Jan 31 11:19:19 2005 From: mt at 3planes.com (Michael Tobis) Date: 31 Jan 2005 08:19:19 -0800 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> Message-ID: <1107188359.375703.110590@f14g2000cwb.googlegroups.com> With all due respect, I think "so go away if you don't like it" is excessive, and "so go away if you don't like it and you obviously don't like it so definitely go away" is more so. The writer is obviously neither a native speaker of English nor an accomplished user of Python, so there are two language issues here. Try expressing your reply in Russian before deciding that "very ugly" means exactly what you think it does. I think just saying that "experienced Python users have not found the lack of declarations to be a major hindrance" would have been more appropriate. Also, the assertion that "Python has no declarations whatsoever" is no longer obviously true. In the 2.4 decorator syntax, a decorator line is not executable, but rather a modifier to a subsequent symbol binding. I call it a declaration. I found this disappointing in that it seems to me a violation of "Special cases aren't special enough to break the rules" but on further reflection it enables consideration of what a whole slew of declarative constructs could achieve. To begin with, now that the design constraint of "no declarations" has been shown to be less than absolute, why not allow for perl-style ('use strict') declarations? It actually is very useful in the small-script space (up to a few hundred lines) where the best Perl codes live. Let me add that I remain unconvinced that a language cannot combine the best features of Python with very high performance, which is ultimately what I want. It seems to me that such a language (possibly Python, possibly a Python fork, possibly something else) will need substantial programmer control over references as well as referents. It seems to me that Python has a weaker case for purity in this regard now that the dam has been breached with decorator syntax, which is, I think, a declaration. Let me conclude with the confession that I'm still on the steep part of the learning curve (if it ever flattens out at all...). Python has definitely significantly modified how I think about things, and I deeply appreciate all the efforts of you veterans. So I say this all with some trepidation, because I don't want to join Alexander in inadvertently offending you. And since I presumably missed some intense flame wars about decorators by only a couple of months, this may be a real hornet's nest I am poking. In summary, again with all due respect and gratitude for the spectacularly excellent product that Python is today, I wonder *why* this strong aversion to declarative statements, and *whether* decorator syntax constitutes a violation of it. I'd appreciate any responses or links. -- mt From cdieterich at geosci.uchicago.edu Thu Jan 27 13:53:37 2005 From: cdieterich at geosci.uchicago.edu (Christian Dieterich) Date: Thu, 27 Jan 2005 12:53:37 -0600 Subject: inherit without calling parent class constructor? In-Reply-To: Message-ID: On D? C?adaoin, Ean 26, 2005, at 17:02 America/Chicago, Steven Bethard wrote: > Just a note of clarification: > > The @deco syntax is called *decorator* syntax. > Classes with a __get__ method are called *descriptors*. Okay, I think I get the idea. I didn't know about the @deco syntax, but it seems to be straightforward. And I got myself updated a little bit on descriptors and static methods. On D? C?adaoin, Ean 26, 2005, at 17:09 America/Chicago, Jeff Shannon wrote: > You could try making D a container for B instead of a subclass: Thank you for the solution. I'll need to have a closer look at it. However it seems like the decision whether to do "some expensive calculation" or not is delegated to the exterior of class D. Different classes that instanciate D would need to know what has been going on elsewhere. That might complicate things. I'll go ahead and try with the descriptors first. Thanks for all the help, Christian From ville at spammers.com Wed Jan 5 02:05:54 2005 From: ville at spammers.com (Ville Vainio) Date: 05 Jan 2005 09:05:54 +0200 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> Message-ID: >>>>> "Paul" == Paul Rubin writes: Paul> inclusion in some bigger distro. E.g., I'm now running the Paul> Python Python into Fedora. So it's up to the Python Paul> maintainers, not the Fedora maintainers or the user, to make Paul> sure that the Python distro has everything that users need, Paul> without further downloading. To me, this seems to be the job for the Fedora maintainers, not Python maintainers. If something essential is not in the distro the distro maintainers have screwed up. Paul> And that was just about Tkinter, for which good docs exist Paul> but just don't happen to be in the distro. How about I think most people these days do a google search when they are learning how to use a feature to get the whole story. It's often also faster than finding the information in the bundled documentation - even if the first google hit often happens to refer to the page with the very documentation thu user would have looked up. Paul> The book is very good, but having to go buy a proprietary Paul> book is the opposite of what self-contained free software Paul> documentation is supposed to mean. I'm not sure the free software documentation is going to evolve to be more self-contained; the exact opposite is more likely. -- Ville Vainio http://tinyurl.com/2prnb From fredrik at pythonware.com Tue Jan 18 10:56:32 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Jan 2005 16:56:32 +0100 Subject: bind error!!!!! References: Message-ID: Perrin Aybara wrote: > my code was working pretty well until yesterday.suddenly it started > giving me bind error: address already in use. google has the details: http://hea-www.harvard.edu/~fine/Tech/addrinuse.html > but i have logged out and again logged in, but still the problem is not solved > can somebody give me solution for this and you're sure that nobody else on this computer is running a process that's using the same port? on most platforms, you can use "netstat" to list all active connections and ports. From craig at postnewspapers.com.au Fri Jan 21 10:06:54 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 21 Jan 2005 23:06:54 +0800 Subject: need help on generator... In-Reply-To: <1106318290.19065.11.camel@bucket.localnet> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> Message-ID: <1106320014.19065.14.camel@bucket.localnet> On Fri, 2005-01-21 at 22:38 +0800, Craig Ringer wrote: > consecutive_sets = ( x[offset:offset+subset_size] > for subset_size in xrange(2, len(x)) > for offset in xrange(0, len(x) + 1 - subset_size) ) Where 'x' is list to operate on, as I should've initially noted. Sorry for the reply-to-self. I did say "awful" for a reason ;-) -- Craig Ringer From chris.cavalaria at free.fr Tue Jan 25 15:00:30 2005 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Tue, 25 Jan 2005 21:00:30 +0100 Subject: Help on project, anyone? References: <35ienhF4lu88lU1@individual.net> <1106561458.167373.303270@c13g2000cwb.googlegroups.com> <1106640690.817073.248670@c13g2000cwb.googlegroups.com> Message-ID: <35nmr8F4lnbfvU1@individual.net> Fuzzyman wrote: > > Miki Tebeka wrote: >> Hello Fuzzyman, >> >> > 3) Simple Version Control program for single programmer. A very > simple >> > way of doing version control/releases for small projects with only > a >> > single programmer. [3] >> Subversion (and CVS) are dead simple to install and use. > > I've heard *lots* of people say exactly the opposite. Let's see : # First we prepare the local cvs storage : mkdir ~/cvsroot export CVSROOT=~/cvsroot cvs init # Now we import the existing source code in the cvs "server" cd path/to/project/to/import cvs import ModuleName VendorName START cd ~ cvs co ModuleName And voila, the folder ModuleName is ready for a local cvs usage : cvs update, commit etc... You only need to do once the mkdir ~/cvsroot and the cvs init but don't forget to specify the CVSROOT each time you need to do a cvs import or a cvs checkout. From fredrik at pythonware.com Sat Jan 22 17:13:50 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 23:13:50 +0100 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net><46ednYMe9-q4Om_cRVn-tQ@comcast.com><35fo4iF4maov2U1@individual.net><35fpq0F4mh1ffU1@individual.net> <7xoefhtavd.fsf@ruckus.brouhaha.com> <1gqtawv.omj416ues6jN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: >> [1, 2, 'Joe Smith', 8237972883334L, # comment >> {'Favorite fruits': ['apple', 'banana', 'pear']}, # another comment >> 'xyzzy', [3, 5, [3.14159, 2.71828, []]]] >> >> I don't see what YAML accomplishes that something like the above wouldn't. >> >> Note that all the values in the above have to be constant literals. >> Don't suggest using eval. That would be a huge security hole. > > I do like the idea of a parser that's restricted to "safe expressions" > in this way. Once the AST branch merge is done, it seems to me that > implementing it should be a reasonably simple exercise, at least at a > "toy level". for slightly more interop, you could plug in a modified tokenizer, and use JSON: http://www.crockford.com/JSON/xml.html > I wonder, however, if, as an even "toyer" exercise, one might not > already do it easily -- by first checking each token (as generated by > tokenize.generate_tokens) to ensure it's safe, and THEN eval _iff_ no > unsafe tokens were found in the check. Accepting just square brackets, > braces, commas, constant strings and numbers, and comments, should be > pretty safe -- we'd no doubt want to also accept minus (for unary > minus), plus (to make complex numbers), and specifically None, True, > False or you could use a RE to make sure the string only contains safe literals, and pass the result to eval. > but that, it appears to me, still leaves little margin for an attacker to prepare > an evil string that does bad things when eval'd... besides running out of parsing time or object memory, of course. unless you check the size before/during the parse. From ialbert at mailblocks.com Mon Jan 10 15:44:49 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 10 Jan 2005 15:44:49 -0500 Subject: Writing huge Sets() to disk In-Reply-To: References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> Message-ID: Martin MOKREJ? wrote: > Istvan Albert wrote: > So you say 1 million words is better to store in dictionary than > in a set and use your own function to get out those unique or common > words? I have said nothing even remotely like that. > Fine, that's what I wanted to hear. How do you improve the algorithm? > Do you delay indexing to the very latest moment or do you let your > computer index 999 999 times just for fun? I think that you need to first understand how dictionaries work. The time needed to insert a key is independent of the number of values in the dictionary. Istvan. From danperl at rogers.com Wed Jan 26 17:50:59 2005 From: danperl at rogers.com (Dan Perl) Date: Wed, 26 Jan 2005 17:50:59 -0500 Subject: 20050126 find replace strings in file References: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> <1106776836.679242.167880@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1106776836.679242.167880 at c13g2000cwb.googlegroups.com... > I guess there is no way to check if the file opened fine? What if the > filesystem or file is locked for this user/session. Pretty puny > language if it cannot tell you that it cannot do what you tell it to. > .......... > Same for the close. Is there no way check a good close? An exception (IOError) is raised when a file operation fails. The open() and and close() statements should be enclosed in a try-except statement. Please, take Xah Lee's postings with more than just a grain of salt. As a matter of fact, you are better off ignoring them than trying to learn from them. He is an egomaniac who is learning python and who thinks that he can already teach others. Personally I doubt he will ever learn python well enough to teach others. Just look at his English. He has a similar list with a-word-a-day just like the perl-python a-lesson-a-day and he seems indeed to know a lot of words. But his grammar is horrendous (there's a word for you, Xah Lee!). And according to his own website he's been living in North America for more than 15 years! English is a second language for me too but you won't see me writing something like "this groups is for Perlers who wants to learn Python". It may be unfair to pick on his English, but it is the best way I can make the point to someone who does not know python that Xah Lee does not know what he's talking about. I find Xah Lee annoying and I could just ignore him, but I am concerned that some people may actually take his statements seriously and learn from them. I can't imagine why or how, but there are actually 26 members in the perl-python Yahoo! group who have registered to get these bogus lessons sent to them daily! Dan From len-1 at telus.net Wed Jan 26 17:27:02 2005 From: len-1 at telus.net (Lenard Lindstrom) Date: Wed, 26 Jan 2005 22:27:02 GMT Subject: Subclassed dict as globals References: Message-ID: Evan Simpson writes: > In Python 2.4 the following works: > > >>> class G(dict): > ... def __getitem__(self, k): > ... return 'K' + k > ... > >>> g = G() > >>> exec 'print x, y, z' in g > Kx Ky Kz > >>> > [snip] > [Is] there a way to do this (intercept global variable accesses) > in Python 2.3? > One can emulate it in a rather limited way in pre 2.4 releases: >>> cd = compile("print x, y, z", '', 'exec') >>> glbs = dict(globals()) >>> for id in cd.co_names: glbs[id] = 'K' + id >>> exec cd in glbs Kx Ky Kz Special names can be used only as constants. It is better suited for eval() than exec. Lenard Lindstrom From http Thu Jan 6 19:31:57 2005 From: http (Paul Rubin) Date: 06 Jan 2005 16:31:57 -0800 Subject: Securing a future for anonymous functions in Python References: <10trlbqnb86tbb0@corp.supernews.com> Message-ID: <7xvfaaaxky.fsf@ruckus.brouhaha.com> Jeff Shannon writes: > It seems to me that in other, less-dynamic languages, lambdas are > significantly different from functions in that lambdas can be created > at runtime. What languages are those, where you can create anonymous functions at runtime, but not named functions?! That notion is very surprising to me. From simon.brunning at gmail.com Fri Jan 21 07:42:31 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 21 Jan 2005 12:42:31 +0000 Subject: map in Python In-Reply-To: <8c7f10c605012104373199e615@mail.gmail.com> References: <1106310327.213874.305660@f14g2000cwb.googlegroups.com> <8c7f10c605012104373199e615@mail.gmail.com> Message-ID: <8c7f10c6050121044212f6fc3@mail.gmail.com> On Fri, 21 Jan 2005 12:37:46 +0000, Simon Brunning wrote: > This what you want? > > >>> import re > >>> test = ["a1", "a2", "a3"] > >>> test = [re.sub("[a-z]", "", item) for item in test] > >>> test > ['1', '2', '3'] Or, if you *must* use map, you can do: >>> test = map(lambda item: re.sub("[a-z]", "", item), test) >>> test ['1', '2', '3'] I much prefer the first list comprehension form myself, but reasonable men can differ... -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From claudio.grondi at freenet.de Mon Jan 24 10:12:32 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 24 Jan 2005 15:12:32 -0000 Subject: is there better 32 clock() timing? References: <7xbrbgxjxs.fsf@ruckus.brouhaha.com> Message-ID: <35ke4eF4mbj1fU1@individual.net> On my 2.8GHz P4, Windows 2000 SP4 with Python 2.3.4 I am getting totally different results compared to Ray. Does Python 2.3.4 already use the Pentium RTDSC instruction for clock()? Claudio # \> Claudio Grondi, 2.8GHz P4 Python 2.3.4 (2005-01-24 14:32) # time of taking time: # 0.000001396825574200073100 # 0.000001676190689040086400 # 0.000001396825574200074000 # 0.000001676190689040088100 # 0.000001955555803880100500 # 0.000001620317666072084300 (average) # statistics of 1.000.000 times of taking time in a while loop: # 0.000001396825573429794100 (min) # 0.002370692364532356300000 (max) # 0.000001598858514140937100 (avg) # >>> Ray Schumacher, 2.4GHz P4 Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 # 0.000321028401686 # 0.00030348379596 # 0.000297101358228 # 0.000295895991258 # 0.000342754564927 (average) Here my code: # Tests show, that the first call takes longer than subsequent calls, # so it makes sense to run t = clock() just one time before the next calls # are used: t = clock() t0 = clock() t1 = clock() t2 = clock() t3 = clock() t4 = clock() t5 = clock() print 'time of taking time: ' print ' %25.24f'%((t1-t0),) print ' %25.24f'%((t2-t1),) print ' %25.24f'%((t3-t2),) print ' %25.24f'%((t4-t3),) print ' %25.24f'%((t5-t4),) print ' %25.24f (average)'%( ((-t0+t5)/5.),) intCounter=1000000 fltTotTimeOfTakingTime = 0.0 fltMaxTimeOfTakingTime = 0.0 fltMinTimeOfTakingTime = 1.0 while(intCounter > 0): t1 = clock() t2 = clock() timeDiff = t2-t1 if(timeDiff < fltMinTimeOfTakingTime): fltMinTimeOfTakingTime = timeDiff if(timeDiff > fltMaxTimeOfTakingTime): fltMaxTimeOfTakingTime = timeDiff fltTotTimeOfTakingTime+=timeDiff intCounter-=1 #:while fltAvgTimeOfTakingTime = fltTotTimeOfTakingTime / 1000000.0 print 'statistics of 1.000.000 times of taking time in a while loop:' print ' %25.24f (min)'%(fltMinTimeOfTakingTime,) print ' %25.24f (max)'%(fltMaxTimeOfTakingTime,) print ' %25.24f (avg)'%(fltAvgTimeOfTakingTime,) "Ray Schumacher" schrieb im Newsbeitrag news:mailman.1120.1106491193.22381.python-list at python.org... > I have a need for a time.clock() with >0.000016 second (16us) accuracy. > The sleep() (on Python 2.3, Win32, at least) has a .001s limit. > > Are they lower/better on other's platforms? > > Test code, 2.4GHz P4 > Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 > > import time > t0 = time.clock() > t1 = time.clock() > t2 = time.clock() > t3 = time.clock() > t4 = time.clock() > t5 = time.clock() > print (-t0+t5)/5. > print t1-t0 > print t2-t1 > print t3-t2 > print t4-t3 > print t5-t4 > > >>> > ave 0.000342754564927 > 0.000321028401686 > 0.00030348379596 > 0.000297101358228 > 0.000295895991258 > > I had also considered forking a thread that would spin a loop checking time.clock() and firing the TTL pulse after the appropriate interval, but the real, ultimate resolution of time.clock() appears to be ~.00035s. If I increase process priority to real-time, it is ~.00028s > The alternative appears to be more C code... > > Ray > BCI/Congitive Vision > "Paul Rubin" schrieb im Newsbeitrag news:7xbrbgxjxs.fsf at ruckus.brouhaha.com... > Ray Schumacher writes: > > I have a need for a time.clock() with >0.000016 second (16us) accuracy. > > The sleep() (on Python 2.3, Win32, at least) has a .001s limit. > > > > Are they lower/better on other's platforms? > > > > The alternative appears to be more C code... > > C code is your best bet. The highest resolution timer on x86's these > days is the Pentium RTDSC instruction which counts the number of cpu > cycles since power-on. There's various C routines floating around > that let you access that instruction. From aleaxit at yahoo.com Sat Jan 29 09:34:27 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 29 Jan 2005 15:34:27 +0100 Subject: limited python virtual machine References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> Message-ID: <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> Aahz wrote: ... > >>>> object.__subclasses__() ... > One thing my company has done is written a ``safe_eval()`` that uses a > regex to disable double-underscore access. will the regex catch getattr(object, 'subclasses'.join(['_'*2]*2)...?-) Alex From fla.liu at gmail.com Thu Jan 20 13:51:04 2005 From: fla.liu at gmail.com (fla liu) Date: Fri, 21 Jan 2005 02:51:04 +0800 Subject: What's the best python web-developer's editor In-Reply-To: <41EFFCD9.7060302@wild-flower.co.uk> References: <41EFFCD9.7060302@wild-flower.co.uk> Message-ID: <7c157e36050120105127f58fdd@mail.gmail.com> Try to use Eclipse + pydev On Thu, 20 Jan 2005 18:47:53 +0000, andy wrote: > Anybody like to comment on which editor they use for python web app > development - for both discrete and mixed python and html code, and why? > > I'm comfortable with IDLE (used it for years) but of course it lacks ftp > or webDAV abilities, obviously because it's not intended for that type > of use. > > I've had a look at Screem - and that seems to do python syntax > highlighting, but it dosn't seem to be python syntax aware (unless > there's a hidden option somewhere). Although I can live without auto > indent, I'd rather not... > > I'm sure emacs, xemacs, vi, elvis and so on can do the same, but I have > no experience with them for heavy python or html coding, nor the time > to trip off down a blind-alley to find out! I know Enough Vi To Get > By(tm) but it's by no means my favourite editor. Emacs is a complete > mystery to me. > > I guess I *could* use IDLE and Screem together, but that's a clunky > solution! > > all opinions greatfully received, > -andyj > -- > http://mail.python.org/mailman/listinfo/python-list > From Mark.English at liffe.com Tue Jan 25 08:02:18 2005 From: Mark.English at liffe.com (Mark English) Date: Tue, 25 Jan 2005 13:02:18 -0000 Subject: threading.py Condition wait overflow error Message-ID: <40E605146701DE428FAF21286A97D309174515@wphexa02.corp.lh.int> Every once in a while since I moved to Python 2.4 I've been seeing the following exception in threading.py Condition: File "mctest3.py", line 1598, in WaitForMessages self.condResponses.wait(1.0) File "C:\Program Files\Python24\lib\threading.py", line 221, in wait delay = min(delay * 2, remaining, .05) OverflowError: long int too large to convert to int Is there something I'm doing wrong here ? I've looked at my code, and glanced at threading.py, and I can't see any obvious errors (multiplying a float by 2, using the result of the time.time() call none of which use longs as far as I know). I added some print statements to threading.py and the exception is thrown on the first iteration when delay is 0.0005 and remaining is 1.0 However the code does keep running... ----------------------- Delay: 0.0005 Remaining: 1.0 Traceback (most recent call last): File "", line 1, in ? File "mctest3.py", line 2665, in getLogonResponse respLogon.WaitForMessages() File "mctest3.py", line 1598, in WaitForMessages self.condResponses.wait(1.0) File "C:\Program Files\Python24\lib\threading.py", line 222, in wait delay = min(delay * 2, remaining, .05) OverflowError: long int too large to convert to int Delay: 0.016 Remaining: 8.07899999619 Delay: 0.032 Remaining: 8.01600003242 Delay: 0.05 Remaining: 7.95399999619 Done Message response handler got message ----------------------- Is this something to do with min ? Converting 1.0 ? Thanks for any help. Mark ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From brent.hughes at comcast.net Tue Jan 25 14:38:13 2005 From: brent.hughes at comcast.net (Brent W. Hughes) Date: Tue, 25 Jan 2005 12:38:13 -0700 Subject: How to input one char at a time from stdin? Message-ID: I'd like to get a character from stdin, perform some action, get another character, etc. If I just use stdin.read(1), it waits until I finish typing a whole line before I can get the first character. How do I deal with this? Brent From antbyte.The.Flow at gmail.com Thu Jan 27 20:39:00 2005 From: antbyte.The.Flow at gmail.com (The Flow) Date: 27 Jan 2005 17:39:00 -0800 Subject: [perl-python] 20050127 traverse a dir References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> <1106875259.426213.252030@z14g2000cwz.googlegroups.com> Message-ID: <1106876340.013509.296840@f14g2000cwb.googlegroups.com> Sorry about that... (I forgot what he was trying to teach) Thanks for the clarification -- The Flow From sara_fwd at yahoo.com Thu Jan 13 07:51:22 2005 From: sara_fwd at yahoo.com (Sara Fwd) Date: Thu, 13 Jan 2005 04:51:22 -0800 (PST) Subject: module on files & directories Message-ID: <20050113125122.43539.qmail@web50504.mail.yahoo.com> Hi all Can anybody help me find a module or a function that looks in a directory and defines whether the objects in there are files or directories? Thanks, Sara __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 11:50:48 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?ISO-8859-2?Q?Martin_MOKREJ=A9?=) Date: Mon, 10 Jan 2005 17:50:48 +0100 Subject: Writing huge Sets() to disk In-Reply-To: References: Message-ID: <41E2B268.1020803@ribosome.natur.cuni.cz> Batista, Facundo wrote: > [Martin MOKREJ?] > > #- > At least you'll need a disk of 34694 EXABYTES!!! > #- > #- Hmm, you are right. So 20E15 then? I definitely need to be > > Right. Now you only need 355 PETABytes. Nowadays disk is cheap, but... > > > #- in range 1-14. ;-) > > Why? I need to test for occurence every such combination in some real-world examples. Many many will be missing, and those I have to keep. I've no clue what size will be the drop, so I rather expect full size. So, the generated, theoretical lexicon I could generate on the fly, but the results I have to keep. Even if I give up on this, can I write Sets onto a disk while keeping their nice, built-in methods? M. From jerf at jerf.org Sun Jan 23 06:35:25 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 23 Jan 2005 06:35:25 -0500 Subject: File objects? - under the hood question References: <20050119034955.75129.qmail@web50306.mail.yahoo.com> <20050118225310.1939807216.whereU@now.com> Message-ID: On Sun, 23 Jan 2005 08:27:49 -0800, EP wrote: > >> My brain-teaser: What I'd like to do is read the last ~2K of a large >> number of large files on arbitrary servers across the net, without >> having to read each file from the beginning (which would be slow and >> resource inefficient)... >> >> > Proper googling would have revealed that HTTP 1.1 includes a Range > Request. My bad. > > http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html > > Before I reinvent the wheel (and make it a little squarer than it has to > be) has anyone seen a "cookbook" recipe for adding the HTTP 1.1 range > request to a urllib urlopener (or something similar)? I posted a followup already to your previous message, I just changed the subject since it no longer applied, and it is the type of thing one would google for. (Those need proper subjects.) See: "Retrieving the last bit Re: File objects? - under the hood question". From itsme at yahoo.com Wed Jan 5 19:19:32 2005 From: itsme at yahoo.com (It's me) Date: Thu, 06 Jan 2005 00:19:32 GMT Subject: Another PythonWin Excel question References: <1104968382.403653.267060@f14g2000cwb.googlegroups.com> Message-ID: "Kartic" wrote in message news:1104968382.403653.267060 at f14g2000cwb.googlegroups.com... > I am not sure about this but I believe you can give a parameter > after="sheet1". to Add(), like so, Add(after="sheet1"). > I get a "got an expected keyword argument 'after'" from Add(). > Unfortunately I do not have Excel installed on this machine to confirm > this. > > A tip: if you have VBA (which you should if you have Excel) installed, > lookup the Add method for the Worksheets collection. VBA will show the > code completion, with all the arguments for the method call. Try the > same for any of the methods. > Yes, I read about that but unfortunately I have no experience with VBA *at all*. :=( > Thanks, > --Kartic > From vze4rx4y at verizon.net Sun Jan 30 00:25:52 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 30 Jan 2005 05:25:52 GMT Subject: is this sort method the same as the one in python 2.4 References: Message-ID: "Lowell Kirsh" > I'm trying to emulate the sorted() method introduced in python 2.4. The > only difference is that it takes a sequence as one of its arguments > rather than being a method of the sequence class. Does my method do the > same as the sorted()? Almost. This is closer to the mark: def sorted(iterable, cmp=None, key=None, reverse=False): "return a sorted copy of its input" if sys.version_info >= (2,4): return sorted(iterable, cmp, key, reverse) seq = list(iterable) if reverse: seq.reverse() # preserve stability if key is not None: seq = [(key(elem), i, elem) for i, elem in enumerate(seq)] seq.sort(cmp) if key is not None: seq = [elem for (key, i, elem) in seq] if reverse: seq.reverse() return seq Try it against the tests in Lib/test/test_builtin.py. The differences from your version: * >= 2.4 rather than just > 2.4 * renamed the parameter to iterable * handle the case where both cmp and key are defined * add an enumerated tie breaker to prevent full key comparisons * preserve by using reverse twice The real sorted() does the same thing but is implemented a bit differently. A custom key wrapper is applied to each object so that only the key value gets compared (no need for a full tuple with a tie breaker value). Raymond Hettinger From pythongnome at hotmail.com Sun Jan 16 18:20:01 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Sun, 16 Jan 2005 23:20:01 GMT Subject: List problems in C code ported to Python In-Reply-To: <41ead925$0$87061$a1866201@visi.com> References: <41ead925$0$87061$a1866201@visi.com> Message-ID: Grant Edwards wrote: > On 2005-01-16, Lucas Raab wrote: > >>I'm done porting the C code, but now when running the script I >>continually run into problems with lists. I tried appending and >>extending the lists, but with no avail. Any help is much appreciated >>Please see both the Python and C code at >>http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py > > > http://www.catb.org/~esr/faqs/smart-questions.html > I didn't expect to get bitched out just because I didn't follow "protocol." From petite.abeille at gmail.com Thu Jan 27 17:02:45 2005 From: petite.abeille at gmail.com (PA) Date: Thu, 27 Jan 2005 23:02:45 +0100 Subject: ANN: Tao Scripting Language 0.8.5 beta released! In-Reply-To: References: Message-ID: <397cc8578b5e9adf0e31f18ffa556593@gmail.com> On Jan 27, 2005, at 22:54, Limin Fu wrote: > I found that, a language with simple syntax, convenient text > processing functionality, powerful numeric computation capability, and > simple C/C++ interfaces would be very useful You bet. Have you looked at Lua? http://www.lua.org/about.html Or perhaps Io? http://www.iolanguage.com/About/ Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From ncoghlan at iinet.net.au Tue Jan 4 04:31:37 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 04 Jan 2005 19:31:37 +1000 Subject: Deferred expressions (was Re: Lambda as declarative idiom) In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> Message-ID: <41DA6279.1010105@iinet.net.au> Steven Bethard wrote: > Nick Coghlan: def-from syntax [4] > (def f(a) + o(b) - o(c) from (a, b, c)) > (def x * x from (x)) > (def x from ()) > (def x.bar(*a, **k) from (*a, **k)) > ((def x(*a, **k) from ()) for x, a, k in funcs_and_args_list) After a bit more musing, this is definitely my preferred syntax. I'd call it a 'deferred expression' rather than an anonymous function, though. The name change may seem minor, but it changes the emphasis of the feature from how it's implemented to what it is useful for (i.e. deferring evaluation of an expression until call time). It's also conducive to a clean no-argument syntax - simply make the 'from' claus optional when the argument list is empty. 'def' and 'from' are already keywords, so there shouldn't be any compatibility problems. Michael Spencer's idea of using 'for' instead of 'from' was quite interesting, but the use of 'for' without a corresponding 'in' feels a bit misleading :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From RajaSrinivasan at hotmail.com Tue Jan 4 16:59:28 2005 From: RajaSrinivasan at hotmail.com (RajaSrinivasan at hotmail.com) Date: 4 Jan 2005 13:59:28 -0800 Subject: Looking for CORBA (omniORB) examples Message-ID: <1104875968.342963.181970@z14g2000cwz.googlegroups.com> can we script CORBA objects/events with python. my search for simple examples has not yielded any results. any help appreciated. From http Wed Jan 5 07:00:44 2005 From: http (Paul Rubin) Date: 05 Jan 2005 04:00:44 -0800 Subject: Concepts RE: Python evolution: Unease References: <20050105002302.542768387.EP@zomething.com> <7xr7l06qfc.fsf@ruckus.brouhaha.com> Message-ID: <7xwtus9jbn.fsf@ruckus.brouhaha.com> Paul Rubin writes: > There is nothing in Wikipedia about [Generic programming]. Oops: http://en.wikipedia.org/wiki/Generic_programming This helps. But I don't see how it's different from what used to be called polymorphism. From bokr at oz.net Thu Jan 13 17:25:40 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 22:25:40 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com><7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: <41e6f4b7.777345834@news.oz.net> On Thu, 13 Jan 2005 09:29:49 -0500, Steve Holden wrote: >Fredrik Lundh wrote: > >> Antoon Pardon wrote: >> >> >>>Well, it seems that Guido is wrong then. The documentation clearly >>>states that an expression is a statement. >> >> >> no, it says that an expression statement is a statement. if you don't >> understand the difference, please *plonk* yourself. >> >OK then, "The documentation clearly states that not all statements can >be expressions". Specifically Guido has justified the fact that an >assignment does not return any value, and therefore cannot be used as a >component of an expression. > Hm, that makes me wonder, is there an intermediate "returning of value" in x = y = z = 123 ? >Mea culpa, but I'm not going to *plonk* myself - then *nobody* would be >listening to me :-) Regards, Bengt Richter From craig at postnewspapers.com.au Thu Jan 13 15:20:07 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 14 Jan 2005 04:20:07 +0800 Subject: Free python server. In-Reply-To: <002301c4f99a$cb4dcd50$55a01d53@unqku4k1fl8nea7> References: <002301c4f99a$cb4dcd50$55a01d53@unqku4k1fl8nea7> Message-ID: <1105647607.4001.18.camel@albert.localnet> On Thu, 2005-01-13 at 19:07 +0100, rootshell at gazeta.pl wrote: > Thank you very much. > Arbornet.org seems to be ok > Unforutnately I was convinced that I only have to only copy my *.py file to > /public_hml directory and everything will be all right. Your file probably need to (a) be in the cgi-bin, not public_html, (b) be flagged executable ("chmod a+x file.py"), and (c) begin with the line: '#!/usr/bin/env python' If the server doesn't provide you with CGI (or, strongly preferable, SCGI or mod_python), you're probably out of luck. -- Craig Ringer From aleaxit at yahoo.com Sun Jan 30 03:52:07 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 30 Jan 2005 09:52:07 +0100 Subject: Need programming tip References: <1107071340.486489.146580@f14g2000cwb.googlegroups.com> Message-ID: <1gr74ck.kncteuqczambN%aleaxit@yahoo.com> wrote: ... > 1511156 As Requested 2000 adv server -2000AdvSrv.vol001+02.PAR2 (1/4) - > 21/27 > 1511157 As Requested 2000 adv server -2000AdvSrv.vol001+02.PAR2 (2/4) - > 21/27 ... > would be to look for (1/ in the subject string then find the > denominator and loop thru as many times as the denominator to create > the part of the nzb file. Is this the best way or is there an > easier method? Also what would be the best way to search for the (1/ > using string searches or RegExp? If REgExp could someone provide me > with the RegExp for searching for this string? If the only thing that identifies these posts as part of one logical post is that (n/m) in the subject then I guess there's nothing for it but analysis of the subject, and a re seems appropriate. import re re_n_of_m = re.compile(r'(.*)\s*\((\d+)/(\d+)\)') might be one approach. Then, somewhere in your loop, mo = re_n_of_m.search(subject) sets mo to None if it doesn't match the pattern; if it does match, then mo is a match object with three groups. mo.group(1) is the part of the subject before the (n/m) marker; mo.group(2) is n as a string; mo.group(3) is n as a string. You can use mo.group(1) as the key into a dictionary where you collect (n,m) pairs as values, so that once you've collected all posts you can tell which one are multipart and also check for inconsistency (different m values), duplicates, missing parts. What you need to do in each case, I don't know... Alex From 2004b at usenet.alexanderweb.de Tue Jan 25 16:08:01 2005 From: 2004b at usenet.alexanderweb.de (Alexander Schremmer) Date: Tue, 25 Jan 2005 22:08:01 +0100 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) References: Message-ID: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> On Tue, 25 Jan 2005 12:22:13 -0700, Steven Bethard wrote: > >>This is a serious issue. > >> > >>It's also one that brings Tcl, mentioned several > >>times in this thread, back into focus. Tcl presents > >>the notion of "safe interpreter", that is, a sub- > >>ordinate virtual machine which can interpret only > >>specific commands. It's a thrillingly powerful and > >>correct solution to the main problem Jeff and others > >>have described. > > > > A better (and of course *vastly* more powerful but unfortunately only > > a dream ;-) is a similarly limited python virutal machine..... > > Yeah, I think there are a lot of people out there who would like > something like this, but it's not quite clear how to go about it. If > you search Google Groups, there are a lot of examples of how you can use > Python's object introspection to retrieve "unsafe" functions. IMHO a safe Python would consist of a special mode that disallows all systemcalls that could spy/harm data (IO etc.) and imports of non-whitelisted modules. Additionally, a loop counter in the interpreter loop would ensure that the code does not stall the process/machine. >>> sys.safecall(func, maxcycles=1000) could enter the safe mode and call the func. I am not sure how big the patch would be, it is mainly a C macro at the begginning of every relevant function that checks the current "mode" and raises an exception if it is not correct. The import handler would need to check if the module is whitelisted (based on the path etc.). Python is too dynamic to get this working while just using tricks that manipulate some builtins/globals etc. Kind regards, Alexander From Mark.English at liffe.com Thu Jan 20 06:24:12 2005 From: Mark.English at liffe.com (Mark English) Date: Thu, 20 Jan 2005 11:24:12 -0000 Subject: Class introspection and dynamically determining function arguments Message-ID: <40E605146701DE428FAF21286A97D30917450D@wphexa02.corp.lh.int> I'd like to write a Tkinter app which, given a class, pops up a window(s) with fields for each "attribute" of that class. The user could enter values for the attributes and on closing the window would be returned an instance of the class. The actual application I'm interested in writing would either have simple type attributes (int, string, etc.), or attributes using types already defined in a c-extension, although I'd prefer not to restrict the functionality to these requirements. The only way I can imagine to do this is to create an instance of the class in question, and then start poking around in its attributes dictionary (initially just using dir). So firstly, if there is instead a way to do this without creating an instance I'd be interested. Secondly, the code won't know exactly how to initialise the class instance used to determinte the attributes. Do I need to make it a prerequesite that all instances can be created with no arguments ? Should I force/allow the user to pass an instance instead of a class ? Should I be using inspect.getargspec on the class __init__ method and then a loop with a try and a lot of except clauses, or is there a nicer way to do this ? Presumably the pickling code knows how do serialise/deserialise class instances but I'm not sure how I'd use this without already having a class instance to hand. Lastly, does such an app already exist ? Thanks for any help. ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From terti at mighty.co.za Tue Jan 18 13:43:44 2005 From: terti at mighty.co.za (tertius) Date: Tue, 18 Jan 2005 20:43:44 +0200 Subject: hex notation funtion Message-ID: Hi, Is there a builtin function that will enable me to display the hex notation of a given binary string? (example below) many thanks Tertius 0000(0000) 02 11 00 00 46 5A 1A 82 02 11 00 39 36 39 33 39 ....FZ.....96939 0016(0010) 36 39 33 00 0A 30 33 37 34 34 39 35 38 25 DD 01 693..03744958%.. From aleaxit at yahoo.com Sun Jan 2 18:19:40 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 3 Jan 2005 00:19:40 +0100 Subject: How to make executable file ? References: <33r5gcF449bt0U1@individual.net> <41d868ff@news.unimelb.edu.au> Message-ID: <1gpse2o.v5dt3254u05uN%aleaxit@yahoo.com> Maurice LING wrote: > Hi all, > > This may be OT but is there a way to do the same for *nix type of > system? Like cast a python interpreter with scripts together? Yes, but fortunately on the Mac you don't need that. > I'm running Mac OSX here. Assuming we're talking Mac OS X 10.3 or later, Python itself comes with the operating system (it's used somewhere in stuff provided with the system, such as fax handling). As I saw others suggest, google for py2app, it's probably the best way to handle this for the Mac today. Alex From matthew.garrish at sympatico.ca Sun Jan 9 13:19:19 2005 From: matthew.garrish at sympatico.ca (Matt Garrish) Date: Sun, 9 Jan 2005 13:19:19 -0500 Subject: unicode support References: <1105259315.471816.291600@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1105259315.471816.291600 at c13g2000cwb.googlegroups.com... # -*- coding: utf-8 -*- # python supports unicode in source code by putting a coding declaration # as the first line. print "look chinese chars: ?????" # Note, however, identifiers cannot use unicode chars. # e.g. you cannot define a function with unicode char. So why are you posting to a Perl newsgroup? You can "use utf8" if you want to write your Perl programs in utf-8 (though you should upgrade to 5.8 as well). Or is this your lame attempt at trolling at python group? Matt From http Fri Jan 28 21:12:37 2005 From: http (Paul Rubin) Date: 28 Jan 2005 18:12:37 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> Message-ID: <7xacqt56ga.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > > Let's see, the urandom module was recently released in 2.4, I think > > initially at my urging. > > There is no urandom module in Python 2.4. Oops, sorry, it's in the os module: http://docs.python.org/lib/os-miscfunc.html The difference is simply a matter of the packaging. It's important functionality and it was added after an amount of review and testing that was deemed to be reasonable. Unless you're saying that if I wanted to add AES to the string module (so you could say 'spam and sausage'.aes_encrypt('swordfish banana')) instead of writing a separate module, then we wouldn't need this discussion. (Putting it in the string module is not a serious proposal but it wouldn't be completely insane.) What matters is the code complexity, not whether something is in a separate module or not. > > If Guido says "no crypto", is that something other than a > > policy? And are you speaking for him when you say that? > > If he had said such a thing in general, it would be a policy > (although it best would be documented somewhere). I don't think > he said that, in general, and with the intent of stating a policy. Well, if he indicates that it's not a policy and that the question is still open, then I could see getting interested again in writing an AES module. At the moment I continue to see his python-dev post as quite discouraging. > We don't normally invite people to work on anything. People pick the > things they work on themselves. Not true. For example, you once invited me to work on an ancillary message feature for the socket module (SF bug 814689), and so it's been on my want-to-do-one-of-these-days list since then. I think it's reasonable for me to have taken your message there as an expression of interest, sufficient to get me to want to work on it. So it's bogus to say the Python developers should avoid expressing interest in something that hasn't already been written. > > IETF often decides and announces that a feature is good long before > > any such details are decided or agreed on. > > No. They decided that spam machinery in DNS would be a good thing, > people started to work on it, and then they decided that it is not > such a good thing, after all, because it causes too many problems. There's no contradiction. IETF decided something based on some reasonable beliefs that later turned out to be wrong, so they had to undo the original decision because the original expectations couldn't be met. That happens sometimes. Everyone has worked on projects that ended up failing and getting cancelled for reasons like that. There are few ironclad guarantees of anything, only reasonable beliefs. But real-world organizations are not afraid to start projects based on reasonable beliefs regardless. Otherwise, few things would ever get done. > It does matter for me, yet Python is still more than the core. > > You might be ignoring that, but it surely is more to the many > developers which create Python libraries and distribute them > themselves, see > > http://www.python.org/pypi > THIS IS ALL PYTHON. No. Those are programs people have written in Python or as Python extensions. I've written programs like that myself. I don't consider them to be part of Python. They are separate programs. If one of them gets accepted into the distro (as this thread is about), then it becomes part of Python. See : 1.1.6 How do I obtain a copy of the Python source? The latest Python source distribution is always available from python.org, at http://www.python.org/download/. The latest development sources can be obtained via anonymous CVS from SourceForge, at http://www.sourceforge.net/projects/python. Python is what you get from following the download instructions and installing the result. In , where it asks "why is Python installed on my machine?", that is what they are referring to by "Python". > > Obviously those require a different type of consideration. I'm > > talking about patches where there's a core developer with an interest. > > I though you were talking about the AES module... No, when this started you were talking about modules in general. From stefan at eischet.com Mon Jan 17 15:50:06 2005 From: stefan at eischet.com (Stefan Eischet) Date: Mon, 17 Jan 2005 21:50:06 +0100 Subject: Excel module for Python In-Reply-To: <87brbpdqct.fsf@andreasen.org> References: <87brbpdqct.fsf@andreasen.org> Message-ID: <5E8E534C-68C9-11D9-B712-000A95857E5C@eischet.com> Hi, I didn't catch older mails in this thread, so excuse me if this has already been pointed out: http://pyxlwriter.sourceforge.net/ "It's a port of John McNamara's Perl Spreadsheet::WriteExcel module" and it's really easy to use. I'm not sure if it does formulae, but it handles formatting fine. Putting together a file with complicated layout can be a lot of work, so for large prebuilt files (which I sometimes have to "fill in" programmatically), I just use COM with Excel. You'll have to run on Windows for that, of course. ;-) Cheers Stefan On 16.01.2005, at 22:19, Erwin S. Andreasen wrote: > Simon Brunning writes: > >> On Wed, 12 Jan 2005 23:19:44 +0800, sam wrote: >>> >>> No, I don't use MS windows. I need to generate Excel file by printing >>> data to it, just like Perl module Spreadsheet::WriteExcel. > >> If you need to write out formulae, formratting, that kind of thing, >> then I think you'll need to write a 'real' Excel file. I don't have a >> clue how to do that - sorry. > > There's actually an ancient open spreadsheet format called SYLK which > is a step above CSV: it allows formatting of data, formulas etc. > > Google for SYLK to get the rather sparse specification (and skip over > the first few links!) > > If you want to generate "real" Office files from UNIX, another > alternative is to automate OpenOffice (which has a COM-like interface > too) or generate OO XML files and feed them to OO asking to conver > them with a bit of OO macro magic. > From pinard at iro.umontreal.ca Thu Jan 13 11:18:18 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Thu, 13 Jan 2005 11:18:18 -0500 Subject: finding/replacing a long binary pattern in a .bin file In-Reply-To: <3e8ca5c80501122251483f4b8f@mail.gmail.com> References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> <3e8ca5c80501122251483f4b8f@mail.gmail.com> Message-ID: <20050113161818.GA21609@phenix.progiciels-bpi.ca> [Stephen Thorne] > On 12 Jan 2005 22:36:54 -0800, yaipa wrote: > > > What would be the common sense way of finding a binary pattern in > > a .bin file, say some 200 bytes, and replacing it with an updated > > pattern of the same length at the same offset? The file itself > > isn't so large, maybe 32 kbytes is all and the need for speed is not > > so great, but the need for accuracy in the search/replacement is > > very important. > Okay, given the requirements. > f = file('mybinfile') > contents = f.read().replace(oldbinstring, newbinstring) > f.close() > f = file('mybinfile','w') > f.write(contents) > f.close() > Will do it, and do it accurately. But it will also read the entire > file into memory. 32Kb is a small file indeed, reading it in memory is not a problem! People sometimes like writing long Python programs. Here is about the same, a bit shorter: :-) buffer = file('mybinfile', 'rb').read().replace(oldbinstring, newbinstring) file('mybinfile', 'wb').write(buffer) -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From simon.brunning at gmail.com Fri Jan 7 05:23:57 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 7 Jan 2005 10:23:57 +0000 Subject: python reading/writing ms-project files? In-Reply-To: <1105056307.322989.54930@z14g2000cwz.googlegroups.com> References: <1105056307.322989.54930@z14g2000cwz.googlegroups.com> Message-ID: <8c7f10c6050107022325e00192@mail.gmail.com> On 6 Jan 2005 16:05:07 -0800, zslist at gmail.com wrote: > any existing or pointers on how to do this? If you are running on Windows and have a copy of Project, then COM automation is probably your best bet. See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/279003 for a very basic example of COM scripting. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From __peter__ at web.de Wed Jan 26 06:11:06 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Jan 2005 12:11:06 +0100 Subject: string.atoi and string.atol broken? References: Message-ID: Peter Otten wrote: > def itoa(n, base): > assert 2 <= base <= 16 > if n < 0: > digits = ["-"] > n = -n > else: > digits = [] > while n: > n, m = divmod(n, base) > digits.append(string.hexdigits[m]) > digits.reverse() > return "".join(digits) This is junk, sorry. Doesn't handle n<=0 correctly (at least). Peter From pythonista at gmail.com Mon Jan 31 19:26:39 2005 From: pythonista at gmail.com (Sean Blakey) Date: Mon, 31 Jan 2005 16:26:39 -0800 Subject: Java Integer.ParseInt translation to python In-Reply-To: <008d01c507f4$451d9b30$2820790d@stso.xcdg.xerox.com> References: <008d01c507f4$451d9b30$2820790d@stso.xcdg.xerox.com> Message-ID: <372a762405013116263a4e93b7@mail.gmail.com> On Mon, 31 Jan 2005 19:23:35 -0500, jose isaias cabrera wrote: > > Greetings! > > I've looked through the internet (not long, though) but I have not been able > to find a python translation to > > buffer[0] = (byte)Integer.parseInt(string,16); > > Has anyone ported any java programs to python and has translated this? > > any help would be greatly appreciated. > > thanks. > > jos? > buffer[0] = int(string, 16) http://docs.python.org/lib/built-in-funcs.html -- Sean Blakey Saint of Mild Amusement, Evil Genius, Big Geek Python/Java/C++/C(Unix/Windows/Palm/Web) developer quine = ['print "quine =",quine,"; exec(quine[0])"'] ; exec(quine[0]) From richie at entrian.com Fri Jan 21 09:47:10 2005 From: richie at entrian.com (Richie Hindle) Date: Fri, 21 Jan 2005 14:47:10 +0000 Subject: ElementTree.findtext() In-Reply-To: References: Message-ID: [me] > >>> print tree.findtext("html/head/title") > None I realised what the problem was the second after I hit Send (why is it never the second *before*?) The tree represents the top-level element, so of course searching within it for 'html' fails. What I should say is this: >>> print tree.findtext("head/title") The title Sorry to waste people's time! -- Richie Hindle richie at entrian.com From irmen at -nospam-remove-this-xs4all.nl Sat Jan 8 15:04:29 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sat, 08 Jan 2005 21:04:29 +0100 Subject: there's a socket.sendall(), so why no socket.recvall()? In-Reply-To: References: Message-ID: <41e03ccc$0$6208$e4fe514c@news.xs4all.nl> Robert Brewer wrote: > Irmen de Jong wrote: > >>Subject says it all; >>there's a socket.sendall(), so why no socket.recvall()? > [...] > If you call .makefile() and then .read() the _fileobject, you get the > same behavior (only better). Adding recvall would just duplicate that, I > think. But that's desirable IMO. Hm, I didn't consider makefile(). But I'm not sure if that works in all cases. Until now, I've been using a loop rather like the one you posted. But, as I pointed out earlier, there is the MSG_WAITALL option on various platforms (Linux for instance). So instead of sticking it in an explicitly programmed loop in Python, or using an extension module such as this one: http://mail.python.org/pipermail/python-list/2003-January/143051.html , I'd rather have a recvall method on the socket object that essentially uses MSG_WAITALL if available, and uses a loop construction if not. I may even write a patch for socketmodule.c right now :-D --Irmen de Jong From aleaxit at yahoo.com Sat Jan 22 06:20:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 12:20:36 +0100 Subject: need help on need help on generator... References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> <1106387175.4103.16.camel@albert.localnet> Message-ID: <1gqshv6.linw9y1anlov0N%aleaxit@yahoo.com> Craig Ringer wrote: > .>>> data = ''.join(x for x in infile) Maybe ''.join(infile) is a better way to express this functionality? Avoids 2.4 dependency and should be faster as well as more concise. > Might it be worth providing a way to have file objects seek back to the > current position of the iterator when read() etc are called? If not, I It's certainly worth doing a patch and see what the python-dev crowd thinks of it, I think; it might make it into 2.5. > favour the suggestion in the referenced post - file should probably fail > noisily, or at least emit a warning. Under what conditions, exactly, would you want such an exception? Alex From daranrife at yahoo.com Mon Jan 10 14:35:33 2005 From: daranrife at yahoo.com (drife) Date: 10 Jan 2005 11:35:33 -0800 Subject: Reading Fortran binary files Message-ID: <1105385733.855390.83220@c13g2000cwb.googlegroups.com> Hello, I need to read a Fortran binary data file in Python. The Fortran data file is organized thusly: nx,ny,nz,ilog_scale # Record 1 (Header) ihour,data3D_array # Record 2 Where every value above is a 2 byte Int. Further, the first record is a header containing the dimensions of the data that follows, as well as the scaling factor of the data (log base 10). The second record contains the hour, followed by the 3D array of data, which is dimensioned by nx,ny,nz. I also need to convert all the 2 byte Int values to 'regular' Int. I realize that similar questions have previously been posted to the group, but the most recent inquiries date back to 2000 and 2001. I thought there may be newer and easier ways to do this. Thanks in advance for your help. Daran Rife daranrifeNOS at PAMyahoo.com From jeff at ccvcorp.com Mon Jan 3 15:06:49 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 03 Jan 2005 12:06:49 -0800 Subject: what is lambda used for in real code? In-Reply-To: References: <1gpngqs.gi6p511azrvn4N%aleaxit@yahoo.com> Message-ID: <10tj9677oetse30@corp.supernews.com> Steven Bethard wrote: > The only ones that make me a little nervous are examples like: > > inspect.py: def formatargspec(args, varargs=None, varkw=None, > ... > formatvarargs=lambda name: '*' + name, > formatvarkw=lambda name: '**' + name, > formatvalue=lambda value: '=' + repr(value), > > where the lambdas are declaring functions as keyword arguments in a def. At least in this case, a number of these can be handled with curry / partial(), I think -- ... formatvarargs = partial(operator.add, '*'), formatvarkw = partial(operator.add, '**'), ... The last is a bit more complicated, since it's got an extra (deferred) function call, so I'm not sure exactly how to deal with that cleanly. Actually, in this specific case, since these are all creating strings, it'd be pretty trivial to simply do this manipulation inside of the function body rather than inside of the arglist: def formatargspec(..., formatvarargs, formatkwargs, formatvalue, ...): formatvarargs = '*' + formatvarargs formatvarkw = '**' + formatvarkw formatvalue = '=' + repr(value) This has the disadvantage of having names typed multiple times, which is definitely a minus, but it's arguably a bit more clear to explicitly manipulate the strings within the function body rather than burying that manipulation somewhere in the argument list. Personally I'd call this a wash, though I expect that others will disagree with me. ;) And whatever the merits of this particular case, similar cases may not be so easy to avoid in this fashion... Jeff Shannon Technician/Programmer Credit International From tjreedy at udel.edu Sun Jan 9 21:53:47 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 9 Jan 2005 21:53:47 -0500 Subject: Long strings as function parameters References: <1105288564.441842.13060@c13g2000cwb.googlegroups.com> <1105290325.030128.146490@c13g2000cwb.googlegroups.com> Message-ID: "Dan Bishop" wrote in message news:1105290325.030128.146490 at c13g2000cwb.googlegroups.com... > In Python, *every* expression is a pointer. Minor but to me important nit: this should start "In the CPython implementation of Python" ... Humans can understand and execute Python code without knowing about computer memory addresses (pointers). Other computer languages can also do something slightly different from CPython, as I believe is the case with Jython. The Python language is defined by sematics, not by mechanisms, especially low-level interpreter-specific mechanisms. This is a large part of what makes it readable. To the OP: a Python function call binds argument objects to either local parameter names or slots within a named catchall list or dict. Like other binding (assignment) operations, there is no copying. Terry J. Reedy From jurgenex at hotmail.com Sun Jan 9 04:01:07 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Sun, 09 Jan 2005 09:01:07 GMT Subject: unicode support References: <1105259315.471816.291600@c13g2000cwb.googlegroups.com> Message-ID: xah at xahlee.org wrote: > # -*- coding: utf-8 -*- > # python supports unicode in source code by putting a coding > declaration > # as the first line. So? > In perl, support of unicode is very flaky. The language does not > support it, but packages that changes behaviors of string handling (in > its regex, for instance.) Really? You may want to check your sources. They seem to be a little bit outdated, like several years old? jue From ianb at colorstudy.com Mon Jan 3 16:36:36 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Mon, 03 Jan 2005 15:36:36 -0600 Subject: Ann: CherryPy-2.0-beta released In-Reply-To: <1104785774.524707.214290@f14g2000cwb.googlegroups.com> References: <1104774372.943278.302050@f14g2000cwb.googlegroups.com> <1104783888.664232.72720@f14g2000cwb.googlegroups.com> <1104785774.524707.214290@f14g2000cwb.googlegroups.com> Message-ID: <41D9BAE4.6050003@colorstudy.com> remi at cherrypy.org wrote: > Well, you can easily run CherryPy behind Apache (see > http://trac.cherrypy.org/cgi-bin/trac.cgi/wiki/BehindApache). > Since CherryPy provides a WSGI interface (although it's still > experimental), you can also run your CherryPy app with any > WSGI-compatible HTTP server (although I don't really see any advantage > to doing this). In the future when more WSGI environments are deployed, I think the benefits will be nice. For instance, under WSGIKit (http://svn.colorstudy.com/trunk/WSGIKit) you should be able to create a file: # cherry_app.py: from cherrypy import cpg, wsgiapp from my_cherry_app import root_instance cpg.root = root_instance wsgiapp.init() # This variable name is automatically picked up: application = wsgiapp.wsgiApp Then your application would be available under cherry_app/ (wherever you happened to put that file in the URL space). Note that WSGIKit isn't a server itself, just a set of middleware that delegates to different applications. It occurs to me that it would be considerably cleaner if it looked more like this: from cherrypy import wsgiapp from my_cherry_app import root_instance application = wsgiapp.Application(my_cheery_app) Otherwise you can only run one CherryPy application in a process...? That would be very limiting. Anyway, the idea is you can deploy a CherryPy-based application fairly easily alongside other WSGI Python web applications. The particulars still need some work -- I don't like the little Python file used to put the pieces together -- but I think it's a good direction. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From skip at pobox.com Thu Jan 13 09:06:56 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 13 Jan 2005 08:06:56 -0600 Subject: why not datetime.strptime() ? In-Reply-To: <16869.62773.572880.581805@montanaro.dyndns.org> References: <20050111021152.GA20127@yucs.org> <16867.59681.423983.244528@montanaro.dyndns.org> <20050111173335.GB26246@yucs.org> <16869.62773.572880.581805@montanaro.dyndns.org> Message-ID: <16870.32896.616979.730581@montanaro.dyndns.org> Skip> I just checked in your changes. Thanks for the effort. Jeez Skip... That reads poorly. How about "Thanks for your contribution"? In any case, thanks. Skip From hikenboots at yahoo.com Fri Jan 7 10:56:00 2005 From: hikenboots at yahoo.com (John French) Date: Fri, 7 Jan 2005 09:56:00 -0600 Subject: [Pyro] Newbie Question Regarding Pyro Message-ID: <2hyDd.1$Jh.0@bignews4.bellsouth.net> I'm putting together a new project which I'm using to learn Python and have questions about pyro. I like the idea of the abstraction that pyro offers from sockets programming but I cannot determine if I'm giving up some possibly needed functionality. If the server needs to send an unsolicited ad hoc message to a given client, is this possible? (New message or a reminder, for instance) I suppose I could poll a server side list from the client but I'm wondering if the server can initiate the exchange. Also, if a client wishes to converse with another particular client (in a chat or IM situation, for instance). What's a good mechanism for this? Does pyro create a persistent client/server connection? What happens if a pyro client goes down hard? Does it's process continue or is there a cleanup mechanism? Thanks in advance. From belred at gmail.com Sun Jan 30 21:18:57 2005 From: belred at gmail.com (Bryan) Date: Sun, 30 Jan 2005 18:18:57 -0800 Subject: Regarding exception handling In-Reply-To: References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> Message-ID: Dan Perl wrote: > "Aggelos I. Orfanakos" wrote in message > news:1107127179.863445.55310 at c13g2000cwb.googlegroups.com... > >>Thanks. This should now be OK: >> >>#try: >># try: >># s = ... # socket opens >># >># # various code ... >># except socket.error, x: >># # exception handling >>#finally: >># s.close() # socket closes >> > > > Why the nested try's? If I understand your intention correctly this should > do the same thing: > > try: > s = ... # socket opens > # various code ... > except socket.error, x: > # exception handling > s.close() # socket closes > > You would need the try-finally statement only if you expect it to handle > other exceptions than socket.error or if the socket.error is re-raised in > the "except" clause. Otherwise, the try-finally statement is redundant > because no socket.error are getting out of the try-except statement. > > Dan > > i always use the try/finally statement with resources, but in a slightly different way than the above two examples: s = ... # socket opens try: # various code ... finally: s.close() or, if i want to handle the socket.error if s gets successfully bound, s = ... # socket opens try: try: # various code except socket.error e: # exception handling finally: s.close() i disagree with the statement: "You would need the try-finally statement only if you expect it to handle other exceptions than socket.error or if the socket.error is re-raised in the "except" clause. Otherwise, the try-finally statement is redundant because no socket.error are getting out of the try-except statement." IMO, that is not the reason for the try/finally statement and it is not redundant. the try/finally statement guarantees the resource is closed and the try/finally statement only gets executed if and only if the opening of the resource doesn't raise an exception. it has nothing to do with exception handling. in the previous 2 examples s = ... was placed inside the try/finally, but if an exception occures and s doesn't get bound to an object, then s.close() in both examples will raise a NameError on s. bryan From tdelaney at avaya.com Sun Jan 16 17:45:56 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 17 Jan 2005 09:45:56 +1100 Subject: generator expressions: performance anomaly? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE025202AA@au3010avexu1.global.avaya.com> Raymond Hettinger wrote: > Check out the current source. The time machine beat you to it. Nick's other suggestion - that genexps propagate __len__ - might still be interesting. Of course, it would only be applicable for unconditional genexps(i.e. no if clause). Tim Delaney From steven.bethard at gmail.com Thu Jan 27 16:37:10 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 14:37:10 -0700 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: <2fCdnYr1l-CZwmTcRVn-ig@comcast.com> Francis Girard wrote: >>>>a = "10" >>>>b = 10 >>>>a > b > True > >>>>b > a > False > >>>>id(a) > 1077467584 > >>>>id(b) > 134536516 Just to thoroughly explain this example, the current CPython implementation says that numbers are smaller than everything but None. The reason you get such a small id for 'b' is that there is only one 10 object (for efficiency reasons): py> 10 is 5 + 5 True py> 99 is 50 + 49 True py> 100 is 50 + 50 False Note that there may be many different instances of integers 100 and above (again, in the current CPython implementation). So to get an integer id above a string id, your integer must be at least 100: py> a = "100" py> b = 100 py> id(a), id(b) (18755392, 18925912) py> a > b True py> b > a False So, even though b's id is higher than a's, b still compares as smaller because the current CPython implementation special-cases the comparison to guarantee that numbers are always smaller than all other non-None objects. Again, these are *all* implementation details of the current CPython, and depending on these details might run you into troubles if they change in a future version of CPython, or if you use a different implementation (e.g. Jython or IronPython). Steve From dave.benjamin at gmail.com Mon Jan 3 11:16:01 2005 From: dave.benjamin at gmail.com (Dave Benjamin) Date: Mon, 03 Jan 2005 09:16:01 -0700 Subject: Lambda as declarative idiom (was RE: what is lambda used for in real code?) In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> Message-ID: <%ceCd.6596$232.5209@fed1read05> Roman Suzi wrote: > I wish lambdas will not be deprecated in Python but the key to that is > dropping the keyword (lambda). If anybody could think of a better syntax for > lambdas _with_ arguments, we could develop PEP 312 further. Well, my vote is still with Ruby-style codeblock syntax, but as a compromise, what about the following: fun(a, b): a + b as a replacement for: lambda a, b: a + b Advantages: - Doesn't use the l-word - Uses parentheses always - "fun" is shorter and self-describing - Makes Python code more "fun" ;) Disadvantages: - Requires a new keyword, breaking backward compatibility (I'm assuming we're still talking about Py3k here) - (Still) doesn't interface statements with expressions Dave From segphault at sbcglobal.net Mon Jan 24 11:02:22 2005 From: segphault at sbcglobal.net (Ryan Paul) Date: Mon, 24 Jan 2005 16:02:22 GMT Subject: What is print? A function? References: Message-ID: On Sun, 23 Jan 2005 18:01:50 +0000, Frans Englich wrote: > > Nah, I don't think it's a function, but rather a builtin "statement". But > it's possible to invoke it as an function; print( "test" ) works fine. > > So I wonder, what _is_ exactly the print statement? The untraditional > way of invoking it(without paranteses) makes me wonder. > > The reason I thinks about this is I need to implement a debug print for > my program; very simple, a function/print statement that conditionally > prints its message whether a bool is true. Not overly complex. > > I tried this by overshadowing the print keyword, but that obviously > didn't work.. Is defining a two-liner function the right way to go, or > is there better ways to approach it? > > > Cheers, > > Frans Unfortunately, it isnt possible to add new kinds of statements to python. you might want to have a look at Ruby, in which paren are entirely optional. Ruby is similar to python in a lot of ways, but its also quite different. It provides lots of syntactic sugar and a superior object model, but its a resource hog compared to python. You may also be interested in Logix. Logix is a language framework built on top of python that allows you to dynamically extend python syntax at run-time. Unfortunately, Logix is still rather new, and its incredibly slow. http://logix.livelogix.com/ From kent3737 at yahoo.com Fri Jan 21 06:03:11 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Fri, 21 Jan 2005 06:03:11 -0500 Subject: Overloading ctor doesn't work? In-Reply-To: References: <35ab8oF4idc25U1@individual.net> Message-ID: <41f0defb$1_3@newspeer2.tds.net> Nick Craig-Wood wrote: > Martin H?cker wrote: > >> Now I thought, just overide the ctor of datetime so that year, month and >> day are static and everything should work as far as I need it. >> >> That is, it could work - though I seem to be unable to overide the ctor. :( > > Its a bug! > > http://sourceforge.net/tracker/index.php?func=detail&aid=720908&group_id=5470&atid=105470 > > However its been fixed in a recent Python 2.3. My example was developed in Python 2.4. The problem was the immutability of datetime. Kent > > (I was bitten by the same thing which used to fail but now works after > an upgrade of python 2.3!) From itsme at yahoo.com Wed Jan 12 13:42:24 2005 From: itsme at yahoo.com (It's me) Date: Wed, 12 Jan 2005 18:42:24 GMT Subject: counting items References: Message-ID: Yes, Mark, I came up with almost the same code (after reading back old answers from this list): def flatten(seq): for x in seq: if hasattr(x, "__iter__"): for subx in flatten(x): yield subx else: yield x def count_item(data): return len([(i,x) for i, x in enumerate(flatten(data))]) data = [[1,5,2],8,4] print count_item(data) Thanks everybody. "Mark McEahern" wrote in message news:mailman.579.1105554265.22381.python-list at python.org... > It's me wrote: > > >Okay, I give up. > > > >What's the best way to count number of items in a list [that may contain lists]? > > > > > a = [[1,2,4],4,5,[2,3]] > > def iterall(seq): > for item in seq: > try: > for subitem in iterall(item): > yield subitem > except TypeError: > yield item > > all = [x for x in iterall(a)] > print len(all) > From http Wed Jan 12 15:35:45 2005 From: http (Paul Rubin) Date: 12 Jan 2005 12:35:45 -0800 Subject: encryption/decryption help References: Message-ID: <7xwtuibd26.fsf@ruckus.brouhaha.com> "drs" writes: > Hi, I need to send secure data over an insecure network. To that end, I am > needing to encrypt serialized data and then decrypt it. Is there a builtin > way to do this in Python? MD5, SHA, etc encrypt, but I am not seeing a way > to get back my data. No, Python doesn't include any reversible encryption functions, because of regulatory obstacles in some countries. Here's a function based on SHA: http://www.nightsong.com/phr/crypto/p3.py It's not ideal and it's nonstandard, but it's written in pure Python and still has reasonable performance and should have ok security. It works on 32-bit processors but a simple fix is needed to make it work on 64-bit processors. I'll put that in when I get a chance. > Encryption is totally new to me, so any pointers of what to read up > on would be appreciated. Rule #1 is that there are a lot of subtle mistakes that can kill you. Try to use standard solutions when you can, instead of doing anything ad-hoc. The standard reference about crypto implementation is "Applied Cryptography" by Bruce Schneier. That's got all kinds of stuff about algorithms and protocols. You could also look at "Practical Cryptography" by Bruce Schneier and Niels Ferguson. That is more about what kinds of precautions you should take when implementing crypto. I disagree with some of what it says, but it's a start. Also, anyone implementing any type of security system (crypto or not) should read "Security Engineering" by Ross Anderson. > As a side note, I understand that I could use https, but this would involve > changing things that I may not be at liberty to change -- though if this > turns out to be the best solution, then I'll find a way to use it. Using https is almost certainly a better solution than rolling up something yourself. Do it if the option is available to you. From c.helmbold at gmx.de Mon Jan 24 05:16:02 2005 From: c.helmbold at gmx.de (Christian Helmbold) Date: Mon, 24 Jan 2005 11:16:02 +0100 Subject: Pointer: CfV de.comp.lang.python Message-ID: hi I ask german speaking python programmers to contest the election to establish the german python newsgroup de.comp.lang.python. You can find the ballot in de.admin.news.annouce or via Google http://tinyurl.com/5g5gf. Thank You! Christian From exogen at gmail.com Sat Jan 1 19:24:12 2005 From: exogen at gmail.com (Brian Beck) Date: Sat, 01 Jan 2005 19:24:12 -0500 Subject: What can I do with Python ?? In-Reply-To: <1gpqhbl.125l3evz09uefN%aleaxit@yahoo.com> References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> <1gpqhbl.125l3evz09uefN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > You _gotta_ be kidding, right...? The Beginner's Guide link takes you > right to the BeginnersGuide page which starts with the reassurance that > Python is easy to learn even if you're new to programming and continues > with a zillion useful links. The Python Books link takes you to a huge While I agree that there is much useful content on the official Python site, I particularly hate the BeginnersGuide and much of the resulting introduction pages. Often when I happily refer Python to someone who wants to learn a simple language, I go to the Python site and imagine where I would start if I were them. Once I get to the BeginnersGuide I don't see anything immediately useful, and when I look for it I get frustrated. -- Brian Beck Adventurer of the First Order From jeff at ccvcorp.com Thu Jan 6 13:38:53 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 06 Jan 2005 10:38:53 -0800 Subject: The Industry choice In-Reply-To: <41DD4E62.1020404@holdenweb.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> <1gpwrh7.b7z8qtablx7gN%aleaxit@yahoo.com> <41DD4E62.1020404@holdenweb.com> Message-ID: <10tr15fabtpnf97@corp.supernews.com> Steve Holden wrote: > Bulba! wrote: >> I was utterly shocked. Having grown up in Soviet times I have >> been used to seeing precious resources wasted by organizations >> as if resources were growing on trees, but smth like this?! In a >> shining ideal country of Germany?! Unthinkable. >> > Indeed not. Quite often the brown paper bag is a factor in purchases > like this. I wouldn't be at all surprised if somebody with a major input > to the decision-making process retired to a nice place in the country > shortly afterwards. You appear to be making the mistake of believing > that people will act in the larger interest, when sadly most individuals > tend to put their own interests first (some would go as far as to define > self-interest as the determinant of behavior). Indeed, it is almost expected that those in charge of any large organization (whether government, corporation, trade union, industry association, fan club, or whatever else) are likely to act in their personal interests at the expense of the organization's interests. This is why things like public-disclosure laws and oversight committees exist. As they say, power corrupts. (Of course, this is not at all limited to people in charge; it's just most notable there, since those people can direct the efforts of the rest of the organization for their personal gain, whereas a rank-and-file member can typically only direct their own efforts.) It's also noteworthy to consider that many times, waste happens not because of corruption or self-interest, but simply because of errors of judgement. Humans being as we are, it's inevitable that over time, some "obvious" important details will escape our attention, and the resulting imperfect information will result in poor decisions. This is a simple fact of human nature, and (ob-Python ;) ) it's one of the reasons that Python is designed as it is -- it makes a serious effort to reduce the number of details that might escape detection. (One should also consider that many business failures are a case of simply having played the odds and lost. Many ventures depend on outside events playing in a certain way; when by chance those events happen, the decision-makers are called "bold and insightful", but if things don't work out, they're called foolish or misguided. Often, though, it was not foolishness but shrewd risk-taking -- if you take a one-in-three chance of making a tenfold return on investment, then 66% of the time you'll lose.... but if you hit those odds just once, you'll come out way ahead.) Jeff Shannon Technician/Programmer Credit International From steven.bethard at gmail.com Mon Jan 31 11:21:55 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 31 Jan 2005 09:21:55 -0700 Subject: Nested scopes and class variables In-Reply-To: <1gr97zk.1nm8ijn3art4cN%aleaxit@yahoo.com> References: <1gr97zk.1nm8ijn3art4cN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: >>>>def f(x): > > ... class C: > ... x = x > ... return C > ... > [snip] > >>>>def f(x): > > ... def g(): > ... x = x > ... return x > ... return g > ... > [snip] > > See the difference? In a function, the 'x = x' compiles into LOAD_FAST, > STORE_FAST, which only looks at locals and nowhere else. In a > classbody, it compiles to LOAD_NAME, STORE_NAME, which looks at locals > AND globals -- but still not at closure cells... Is there a reason why the class body doesn't look at closure cells? That is, are there cases where this lookup scheme is preferred to one that checks locals, closure cells and globals? Steve P.S. Question disclaimer: My questions here are founded in a curiosity about language design, and are not intended as an attack on Python. =) From anu.shantha at wipro.com Tue Jan 25 14:47:29 2005 From: anu.shantha at wipro.com (anu.shantha at wipro.com) Date: Wed, 26 Jan 2005 01:17:29 +0530 Subject: Returned mail: Data format error Message-ID: <200501252003.j0PK3n9N003802@dbdp30.itg.ti.com> -------------- next part -------------- [Filename: file.zip, Content-Type: application/octet-stream] The original attachment to this message was of a file type currently being blocked in the TI environment. For more information, contact the sender of this message. From craig at postnewspapers.com.au Fri Jan 21 11:34:47 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 22 Jan 2005 00:34:47 +0800 Subject: need help on generator... In-Reply-To: <200501211654.52900.francis.girard@free.fr> References: <63b5e209.0501210558.686f5c10@posting.google.com> <1106318290.19065.11.camel@bucket.localnet> <1106320014.19065.14.camel@bucket.localnet> <200501211654.52900.francis.girard@free.fr> Message-ID: <1106325287.19065.50.camel@bucket.localnet> On Fri, 2005-01-21 at 16:54 +0100, Francis Girard wrote: > First, I think that you mean : > > consecutive_sets = [ x[offset:offset+subset_size] > for subset_size in xrange(2, len(x)) > for offset in xrange(0, len(x) + 1 - subset_size)] > > (with square brackets). > I'm just trying to understand and obviously I'm missing the point. Yep. This: ( x for x in xrange(10) ) will return a generator that calculates things as it goes, while this: [ x for x in xrange(10) ] will return a list. Check out: http://www.python.org/peps/pep-0289.html http://docs.python.org/whatsnew/node4.html http://www.python.org/dev/doc/newstyle/ref/genexpr.html for details. -- Craig Ringer From hanzspam at yahoo.com.au Thu Jan 13 11:20:39 2005 From: hanzspam at yahoo.com.au (hanz) Date: 13 Jan 2005 08:20:39 -0800 Subject: lambda In-Reply-To: References: Message-ID: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> Antoon Pardon wrote: > So if I have a call with an expression that takes more than > one line, I should assign the expression to a variable and > use the variable in the call? Yes, that's sometimes a good practice and can clarify the call. > But wait if I do that, people will tell me how bad that it > is, because it will keep a reference to the value which > will prevent the garbage collector from harvesting this > memory. Nobody will tell you that it's bad. Python was never about super performance, but about readability. Besides, using such temporaries won't consume much memory (relatively). > Besides python allows more than one statement on the same line. But it's discouraged in general. From nobody at invalid.domain Sat Jan 8 00:05:45 2005 From: nobody at invalid.domain (Dan Valentine) Date: Sat, 08 Jan 2005 05:05:45 GMT Subject: how to extract columns like awk $1 $5 References: Message-ID: <487rklcxbidr$.gwsa68us9f3a.dlg@40tude.net> On Fri, 07 Jan 2005 12:15:48 -0500, Anand S Bisen wrote: > Is there a simple way to extract words speerated by a space in python > the way i do it in awk '{print $4 $5}' . I am sure there should be some > but i dont know it. i guess it depends on how faithfully you want to reproduce awk's behavior and options. as several people have mentioned, strings have the split() method for simple tokenization, but blindly indexing into the resulting sequence can give you an out-of-range exception. out of range indexes are no problem for awk; it would just return an empty string without complaint. note that the index bases are slightly different: python sequences start with index 0, while awk's fields begin with $1. there IS a $0, but it means the entire unsplit line. the split() method accepts a separator argument, which can be used to replicate awk's -F option / FS variable. so, if you want to closely approximate awk's behavior without fear of exceptions, you could try a small function like this: def awk_it(instring,index,delimiter=" "): try: return [instring,instring.split(delimiter)[index-1]][max(0,min(1,index))] except: return "" >>> print awk_it("a b c d e",0) a b c d e >>> print awk_it("a b c d e",1) a >>> print awk_it("a b c d e",5) e >>> print awk_it("a b c d e",6) - dan From bpeng at rice.edu Sun Jan 9 16:53:45 2005 From: bpeng at rice.edu (Bo Peng) Date: Sun, 09 Jan 2005 15:53:45 -0600 Subject: compiler version mismatch when building ext_modules with MSVC Message-ID: Dear list, I was using autoconf/automake etc to build my python extension. Since distutil seems to be easier, I have switched to this method. However, when I build the module under windows, I am told that compiler version mismatch... I am using msvc 7 and python was build by msvc 6.0. I am not sure why compiler version matters here since 1. if proceed by removing corresponding lines in distutil, the generated module works fine (as far as I can tell). 2. I am told that I can use minGW gcc ... Isn't mingw differ more with msvc6 than msvc7? 3. I was using msvc7 (automake etc, not distutil) and everything was fine. I was not even warned about potential problems. Since there are many different Python out there (Official, ActivePython, Enthough), do I have to figure out which compiler they use to build my module for them? Currently, my MSVC7 built module works fine with all of them. Thanks. From paul at subsignal.org Thu Jan 27 11:23:31 2005 From: paul at subsignal.org (paul koelle) Date: Thu, 27 Jan 2005 17:23:31 +0100 Subject: Transparent (redirecting) proxy with BaseHTTPServer Message-ID: <35sfdaF4hka1hU1@individual.net> Hi list, My ultimate goal is to have a small HTTP proxy which is able to show a message specific to clients name/ip/status then handle the original request normally either by redirecting the client, or acting as a proxy. I started with a modified[1] version of TinyHTTPProxy postet by Suzuki Hisao somewhere in 2003 to this list and tried to extend it to my needs. It works quite well if I configure my client to use it, but using iptables REDIRECT feature to point the clients transparently to the proxy caused some issues. Precisely, the "self.path" member variable of baseHTTPRequestHandler is missing the and the host (i.e www.python.org) part of the request line for REDIRECTed connections: without iptables REDIRECT: self.path -> GET http://www.python.org/ftp/python/contrib/ HTTP/1.1 with REDIRECT: self.path -> GET /ftp/python/contrib/ HTTP/1.1 I asked about this on the squid mailing list and was told this is normal and I have to reconstuct the request line from the real destination IP, the URL-path and the Host header (if any). If the Host header is sent it's an (unsafe) nobrainer, but I cannot for the life of me figure out where to get the "real destination IP". Any ideas? thanks Paul [1] HTTP Debugging Proxy Modified by Xavier Defrang (http://defrang.com/) From tim.golden at viacom-outdoor.co.uk Thu Jan 20 04:26:24 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 20 Jan 2005 09:26:24 -0000 Subject: Automatic Windows printer creation? Message-ID: <9A28C052FF32734DACB0A288A35339910359D2@vogbs009.gb.vo.local> [Roger Upole] | | You can probably do it through WMI. (class is Win32_Printer) | WMI works well with win32com, and there's also a wrapper module | | http://tgolden.sc.sabren.com/python/wmi.html | | for simplified access. | I imagine getting all the device parameters and port | configuration right will be messy, though. | And here's a handy link (warning: long URL): http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/ wmi_tasks__printers_and_printing.asp (I got that by googling for Win32_Printer and then for AddPrinterConnection). But... you'd better be using XP or 2K3 because, almost comically, each of the examples is prefixed by a " does not work on Windows 2000, Windows NT, Windows 98, Windows 95". TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From bearophileHUGS at lycos.com Mon Jan 31 18:39:22 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 31 Jan 2005 15:39:22 -0800 Subject: set, dict and other structures Message-ID: <1107214762.198058.55680@f14g2000cwb.googlegroups.com> I'm frequently using Py2.4 sets, I find them quite useful, and I like them, even if they seem a little slower than dicts. Sets also need the same memory of dicts (can they be made to use less memory, not storing values? Maybe this requires too much code rewriting). I presume such sets are like this because they are kind of dicts. If this is true, then converting a dict to a set (that means converting just the keys; this is often useful for a successive processing with set operators like intersection, etc) can be a very quick operation; but this little code shows me that this isn't true, set-ify a dict is even slower than doing it on a list. Can this operation made faster (by people that writes Python interpreter)? .from time import clock .for p in xrange(16, 20): . n = 2**p . l = range(n) . t = clock() . set(l) . print n, round(clock()-t,3), . d = {}.fromkeys(xrange(n)) . t = clock() . set(d) . print round(clock()-t,3) ==> 65536 0.082 0.1 131072 0.205 0.218 262144 0.45 0.562 524288 1.014 1.029 ---------------------- Dicts and sets are two different data structures, but they share some similarities. So instead of always converting dicts to sets, maybe some fast set-like operations/methods can be added to dicts, like intersection, mass removal, etc. (The result of *some* of such operations between two dicts can be a regular set, and not a dict. This is maybe not very "clear" from an formal/theoretical point of view). ------------- I've studied the nice sets python module from Py2.3, and I am... well... writing something similar, a (python) graph module for sparse graphs. I've found 3 modules like that around on the Net, but I think they can be improved (even if I'm not an expert of Python, and I know, my code is probably quite rough/naive compared to "sets" module one...) Graphs are complex data structures, so probably one person needs from a graph data structure are different from other people needs, so it's probably not easy to define a "standard" graph module fit for everyone. Still, I think it can be useful to have a standard module to manage them. Do you think it be useful to add a (well made) standard module like that? Bear hugs, Bearophile From g.tagliarettiNO at SPAMparafernalia.org Sat Jan 22 08:04:19 2005 From: g.tagliarettiNO at SPAMparafernalia.org (Gian Mario Tagliaretti) Date: Sat, 22 Jan 2005 14:04:19 +0100 Subject: [perl-python] 20050121 file reading & writing References: <1106395060.211314.54530@f14g2000cwb.googlegroups.com> Message-ID: <35f1akF4n2t5mU1@individual.net> Xah Lee wrote: > # the second argument of open can be > # 'w' for write (overwrite exsiting file) > # 'a' for append (ditto) > # 'r' or read only are you sure you didn't forget something? > # reading the one line > # line = f.realine() wrong > [...] Maybe you didn't get the fact the you won't see a flame starting between python people and perl friends? throw yourself somewhere and... Xah.flush() -- Gian Mario Tagliaretti PyGTK GUI programming http://www.parafernalia.org/pygtk/ From timj at tolisgroup.com Mon Jan 17 14:10:47 2005 From: timj at tolisgroup.com (brucoder) Date: 17 Jan 2005 11:10:47 -0800 Subject: Adjusting the 1024 byte stdin buffer limit Message-ID: <1105989047.516986.59990@z14g2000cwz.googlegroups.com> Are there runtime settings that can be used to adjust the default 1024 byte stdin buffer limit or a buildtime setting in pyconfig.h? I have a need to pump this up to permit input of a large data block via stdin. Tim Jones From ncoghlan at iinet.net.au Fri Jan 7 12:55:24 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 03:55:24 +1000 Subject: Developing Commercial Applications in Python In-Reply-To: <41DD5B0B.6070901@comcast.net> References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> <87pt0iegga.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> <41DD5B0B.6070901@comcast.net> Message-ID: <41DECD0C.8010504@iinet.net.au> Stephen Waterbury wrote: > A notable example is Verity's search engine -- see > http://python.oreilly.com/news/PythonSS.pdf Not to mention the kind words of the current reigning king of the search engine world. . . Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From EP at zomething.com Mon Jan 31 02:19:13 2005 From: EP at zomething.com (EP) Date: Sun, 30 Jan 2005 23:19:13 -0800 Subject: variable declaration In-Reply-To: References: Message-ID: <20050130231913.1213891237.EP@zomething.com> > ------------Original Message------------ > From: Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org (Alexander Zatvornitskiy) > > Hello All! > > I'am novice in python, and I find one very bad thing (from my point of > view) in > language. There is no keyword or syntax to declare variable, like 'var' > in > Pascal, or special syntax in C. It can cause very ugly errors,like > this: > > epsilon=0 > S=0 > while epsilon<10: > S=S+epsilon > epselon=epsilon+1 > print S > > It will print zero, and it is not easy to find such a bug! Hmmm. I am surely an expert in writing buggy code, but I can not say I make this error in Python. Why is that? I'm not sure, but a couple things that may help me miss making this mistake in practice may be (somewhat informal in my case) unit testing - I test for correct results for at least a few cases. It may also help that with Python I can code at a somewhat higher conceptual level, or maybe it is just the syntax that helps avoid these problems: >>> for epsilon in range (0,10): S=S+epsilon >>> for epsilon in range (0,10): S=S+epselon Traceback (most recent call last): File "", line 2, in ? S=S+epselon NameError: name 'epselon' is not defined It may seem like jumping off a cliff, but the improvement in readability (the variable declarations being visual clutter) makes it much easier for me to see my code, and any typos in it. It seems it would be simple enough to have one's code, or another script, automatically print out a sorted list of the variables - which would make the error you note obvious. But I haven't needed this, yet at least. You might like Python and find the lack of variable declaration checking not a problem. It's worth a shot. From kartic.krishnamurthy at gmail.com Wed Jan 5 10:37:59 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 5 Jan 2005 07:37:59 -0800 Subject: Image capture In-Reply-To: References: Message-ID: <1104939479.011181.147650@f14g2000cwb.googlegroups.com> Catalin, Some explanation about what you are tring to do will be of immense help. Did you want to capture some other Windows object from Python or do you want to capture a Python GUI application from Python? I might be able to help out, but please send more details. Thank you, --Kartic From klachemin at comcast.net Sat Jan 22 01:05:34 2005 From: klachemin at comcast.net (Kamilche) Date: 21 Jan 2005 22:05:34 -0800 Subject: Reload Tricks In-Reply-To: References: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> Message-ID: <1106373934.652297.59210@z14g2000cwz.googlegroups.com> That's a powerful advantage - not having to track class instances. Thanks for the tip! I just got done doing it 'my way' though, now I'll have to change it. It took me all day! :-D From paul.kooistra at leaseplan.nl Mon Jan 31 18:32:59 2005 From: paul.kooistra at leaseplan.nl (Paul Kooistra) Date: Tue, 1 Feb 2005 00:32:59 +0100 Subject: Browsing text ; Python the right tool? References: <10vdpohm549g44a@corp.supernews.com> <1106707324.874852.208520@z14g2000cwz.googlegroups.com> <10vfqra5knegoa3@corp.supernews.com> <1106783975.472873.21420@z14g2000cwz.googlegroups.com> <10vgerafeom164b@corp.supernews.com> Message-ID: <41fec02f$0$28993$e4fe514c@news.xs4all.nl> Sorry to reply this late guys - I cannot access news from Work, and Google Groups cannot reply to a message so I had to do it at home. Let me address a few of the remarks and questions you guys asked: First of all, the example I gave was just that - an example. Yes, I know Python starts with 0, and I know that you cannot fit a 4-digit number in 2 positions, this was just to give the idea. To clarify, at THIS moment I need to browse 1-80 Mb size tekstfiles. At this moment, I have 16 different record definitions, numbered A,B, C1-C8, D-H. Each record definition has 20-60 different attributes. Not only that, but these formats change regularly; and I want to create or use something I can use on *other* applications or sites as well. As I said, I have encountered the type of problem I've described in numberous places already. > John wrote: > I have a Python script that takes layout info and an input file and can > produce an output file in one of two formats: Yes John, I was thinking along these lines myself. The problem is that I have to parse several of these large files each day (debugging) and browsing converted output seems just to tedious and inefficient. I would REALLY like a GIU, and preferable something portable I can re-use later on. > This should be pretty easy. If each record is CRLF terminated, then you > can get one record at a time simply by iterating over the file ("for line > in open('myfile.dat'): ..."). Jeff, this was indeed the way I was thinking. But instead of iterating I need the ability to browse forward and backward. > You can have a dictionary of classes or factory functions, one for each > record type, keyed off of the 2-character identifier. Each class/factory > would know the layout of that record type, and return a(n) > instance/dictionary with fields separated out into attributes/items. This is of course a clean approach, but would mean re-coding every time a records is changed - frequently! I really would like to edit only a data definition file. > The trickiest part would be in displaying the data; you could potentially > use COM to insert it into a Word or Excel document, or code your own GUI > in Python. The former would be pretty easy if you're happy with fairly > simple formatting; the latter would require a bit more effort, but if you > used one of Python's RAD tools (Boa Constructor, or maybe PythonCard, as > examples) you'd be able to get very nice results. I will at least look into Boa and PythonCard. Thanks for the hint. > This is plausible only under the condition that Santa Claus is paying > you $X per class/factory or per line of code, or you are so speed-crazy > that you are machine-generating C code for the factories. Unfortunately, neither is the case :) > I'd suggest "data driven" Yeah! > Then you need a function to load this layout file into dictionaries, > and build cross-references field_name -> field_number (0,1,2,...) and > vice versa. > As your record name is not in a fixed position in the record, you will > also need to supply a function (file_type, record_string) -> > record_name. I thought about supplying a flat ASCII definition such as: [record type] [fieldname] [start] [end] > Then you have *ONE* function that takes a file_type, a record_name, and > a record_string, and gives you a list of the values. That is all you > need for a generic browser application. I like this. > You *don't* have to hand-craft a class for each record type. And you > wouldn't want to, if you were dealing with files whose spec keeps on > having fields added and fields obsoleted. Exactly. > I think that's overly pessimistic. I *was* presuming a case where the > number of record types was fairly small, and the definitions of those > records reasonably constant. For ~10 or fewer types whose spec doesn't > change, hand-coding the conversion would probably be quicker and/or more > straightforward than writing a spec-parser as you suggest. Unfortunately, all wrong :) Lots of records, lots of changes, lots of different record types - hardcoding doesnt seem the right way. > "Parse"? No parsing, and not much code at all: The routine to "load" > (not "parse") the layout from the layout.csv file into dicts of dicts > is only 35 lines of Python code. The routine to take an input line and > serve up an object instance is about the same. It does more than the > OP's browsing requirement already. The routine to take an object and > serve up a correctly formatted output line is only 50 lines of which > 1/4 is comment or blank. John,do you have suggestions where I can find examples of these functions? I can program, but not being proficient in Python, any help or examples I can adapt would be nice > Also, files used to "create printed pages by > an external company" (especially by a company that had "leaseplan" in > its e-mail address) would indicate "many" and "complicated" to me. How right you are. Think about production runs of 150.000 invoices, each invoice consisting of 2-10 records, and you are on the right track. > I suspect > that we're both assuming a case similar to our own personal > experiences, which are different enough to lead to different > preferred solutions. ;) Seconded. > My personal experiences and attitudes: (1) extreme aversion to having > to type (correctly) lots of numbers (column positions and lengths), and > to having to mentally translate start = 663, len = 13 to [662:675] or > having ugliness like [663-1:663+13-1] (2) cases like 17 record types > and 112 fields in one file, 8 record types and 86 fields in a second -- > this being a new relatively clean simple exercise in exchanging files > with a government department (3) Past history of this govt dept is that >there are at least another 7 file types in regular use and they change > the _major_ version number of each file type about once a year on >average (3) These things tend to start out deceptively small and simple >and turn into monsters. Our experiences are remarkably similair... Cheers, Paul From Serge.Orlov at gmail.com Tue Jan 11 08:49:32 2005 From: Serge.Orlov at gmail.com (Serge.Orlov at gmail.com) Date: 11 Jan 2005 05:49:32 -0800 Subject: Locale confusion In-Reply-To: References: Message-ID: <1105451372.655977.165250@f14g2000cwb.googlegroups.com> Jorgen Grahn wrote: [snip] > > frailea> cat foo > import locale > print locale.getlocale() > locale.setlocale(locale.LC_CTYPE) > print locale.getlocale() > > When I paste it into an interactive Python session, the locale is already > set up correctly (which is what I suppose interactive mode /should/ do): > > >>> import locale > >>> print locale.getlocale() > ['sv_SE', 'ISO8859-1'] > >>> locale.setlocale(locale.LC_CTYPE) > 'sv_SE' > >>> print locale.getlocale() > ['sv_SE', 'ISO8859-1'] > >>> > > When I run it as a script it isn't though, and the setlocale() call does not > appear to fall back to looking at $LANG as it's supposed to(?), so my > LC_CTYPE remains in the POSIX locale: > > frailea> python foo > (None, None) > (None, None) > > The corresponding program written in C works as expected: > > frailea> cat foot.c > #include > #include > int main(void) { > printf("%s\n", setlocale(LC_CTYPE, 0)); > printf("%s\n", setlocale(LC_CTYPE, "")); > printf("%s\n", setlocale(LC_CTYPE, 0)); > return 0; > } > frailea> ./foot > C > sv_SE > sv_SE > > So, is this my fault or Python's? I realize I could just adapt and set > $LC_CTYPE explicitly in my environment, but I don't want to capitulate for a > Python bug, if that's what this is. Try locale.setlocale(locale.LC_CTYPE,"") as in your C program. It would be great if locale.setlocale with one parameter would be deprecated, because it suddenly acts like getlocale. It's unpythonic. By the way, since you took time to setup various LC_* variables there is no need to play with LC_CTYPE category. Just use the standard idiom. import locale locale.setlocale(LC_ALL,"") Serge. From steve at holdenweb.com Mon Jan 31 07:40:40 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 07:40:40 -0500 Subject: The next Xah-lee post contest In-Reply-To: <1107137465.973491.42050@f14g2000cwb.googlegroups.com> References: <20050130114008.797088857.whereU@now.com> <1107137465.973491.42050@f14g2000cwb.googlegroups.com> Message-ID: gene.tani at gmail.com wrote: > Tragi-comic. really. BTW you forgot cross-post to c.l.scheme, C, > smalltalk and C++ > Would there, I wonder, be any enthusiasm for a "Best Xah Lee impression" prize at PyCon? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From samantha7395 at hotmail.com Thu Jan 20 14:41:24 2005 From: samantha7395 at hotmail.com (Samantha) Date: Thu, 20 Jan 2005 11:41:24 -0800 Subject: Print to Windows default Printer References: <41efd18e$1@nntp0.pdx.net> Message-ID: Thanks Scott, Not wasting any paper yet. I can't seem to get the file to print at all yet. S "Scott David Daniels" wrote in message news:41efd18e$1 at nntp0.pdx.net... > Tim Golden wrote: >> [Samantha] >> | I am new to Python and I am having considerable trouble | trying to >> print | (using a simple script) to the default printer rather than the >> screen. >> | Thanks for any help. >> | S It may be that something here will help you: >> >> http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html >> >> Specifically, I think that the section print raw text is >> closest to what you're asking (although not necessarily >> to what you'll eventually want): >> >> http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html#win32print >> > You might be interested in using PDFCreator to save paper during > your tests. It is a windows printer driver that creates a PDF file: > > http://sourceforge.net/projects/pdfcreator/ > > --Scott David Daniels > Scott.Daniels at Acm.Org From http Mon Jan 10 06:36:14 2005 From: http (Paul Rubin) Date: 10 Jan 2005 03:36:14 -0800 Subject: Port blocking References: <34f6sgF4asjm7U1@individual.net> Message-ID: <7x3bx9sehd.fsf@ruckus.brouhaha.com> Mark Carter writes: > Supposing I decide to write a server-side application using something > like corba or pyro. > > What's the chance that in big corporations, the client's ports (in > both senses of the word: fee-paying, and application) will be blocked, > thereby immediately scuppering whatever I have written? Has this > problem ever arisen for anyone? Usually you wouldn't run a public corba or pyro service over the internet. You'd use something like XMLRPC over HTTP port 80 partly for the precise purpose of not getting blocked by firewalls. > Also, is there a good tool for writing database UIs? Yes, quite a few. From ncoghlan at iinet.net.au Wed Jan 19 08:53:28 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 19 Jan 2005 23:53:28 +1000 Subject: delay and force in Python In-Reply-To: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> Message-ID: <41EE6658.8000409@iinet.net.au> Will Stuyvesant wrote: > The program below creates a stream with the numbers 1..995 > and then filters the stream, keeping only the even numbers, > and then prints the second number in the stream (implemented > as the first number of the tail, just like in the 3.5 > Section in the Wizard book). How's this: Py> from itertools import islice Py> print islice((x for x in xrange(1, 996) if x % 2 == 0), 1, 2).next() 4 Breaking it into pieces: Py> from itertools import islice Py> stream = (x for x in xrange(1, 996) if x % 2 == 0) Py> second_item = islice(stream, 1, 2).next() Py> print second_item 4 And most of the stream hasn't been consumed yet: Py> print stream.next() 6 Py> unconsumed = list(stream) Py> len(unconsumed) 494 And this version has no problem with recursion limits: Py> print islice((x for x in xrange(1, sys.maxint) if x % 2 == 0), 1, 2).next() 4 (xrange can't handle Python longs, unfortunately, so we *are* constrained by sys.maxint. However, since my machine only has half a gig of RAM, the above is still a damn sight quicker than the equivalent list comprehension would be!) > Something else: this crashes with a "maximum recursion reached" > . print stream_enumerate_interval(1,998) > > while this does not crash > . print stream_enumerate_interval(1,900) > this means Python has a maximum of something like 900 > recursions? The CPython implementation is limited by the stack size allocated by the C runtime library. The exact recursion limit is platform dependent, but something around 1000 sounds fairly normal. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tchur at optushome.com.au Sat Jan 1 23:02:33 2005 From: tchur at optushome.com.au (Tim Churches) Date: Sun, 02 Jan 2005 15:02:33 +1100 Subject: Frameworks for "Non-Content Oriented Web Apps" In-Reply-To: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <41D77259.30004@optushome.com.au> mirnazim at gmail.com wrote: > Hi, > > There are great Python Web Application Framework. But most of them are > meant for content oriented web apps. > > Is there something that can ease the development of application that > are not content oriented(I call them "NON CONTENT-ORIENTED WEB > APPLICATIONS" because I don't know what else to call them). I mean the > applications like, accounting, high volume data entry apps, where > normally GUI clients have ruled. I know very high quality ERP and > similar packages have been implemented in a web based environment. But > problem is that they have been developed with the tools that were > actually meant for content oriented apps like Zope, PHP, etc. Can you give some URL for publicly accessible examples of what you mean by a "NON CONTENT-ORIENTED WEB APPLICATIONS", so we can get a better idea of what you mean? Tim C From michael.bierenfeld at web.de Fri Jan 21 09:43:27 2005 From: michael.bierenfeld at web.de (michael) Date: 21 Jan 2005 06:43:27 -0800 Subject: Dynamic properties Message-ID: Hello again, I have a dictionary with the following content : 'LZ': {'type': 'N', 'bytes': '00008'}, 'LVI000': {'type': 'N', 'bytes': '000010'} This could be seen as a interface description to deal with an external program that needs a 18 Byte communication area. 8 and 18 Bytes have to be interpreted as a "Number" String representation. eg like '00000180000000200' means LZ = 180 and LVI000 = 200 I am now thinking about doing the following class a .... def some_crap () ... for key in dict.keys (): setattr (self, key, value) so that pgm = a () pgm.LZ = 300 would cause the rekonstruktion of the byte field. ===>> Properties My first try is : fget = lambda self: mygetattr(self, attrname) fset = lambda self, value: mysetattr (self, attrname, value) fdel = lambda self: mydelattr(self, attrname) # fget, fset, fdel are used to reconstruct the byte field setattr (self, key, property (fget, fset, fdel)) :-) This inserts me pgm.LZ and pgm.LVI000 but when trying to access print pgm.LZ it gives me What am I doing wrong here Regards Michael From ajikoe at gmail.com Mon Jan 31 12:55:02 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 31 Jan 2005 09:55:02 -0800 Subject: stop program in komodo Message-ID: <1107194102.482439.272480@c13g2000cwb.googlegroups.com> Hello, How can we stop this peace of code in KOMODO: while 1: print "helo" I can't stop it, even using Ctrl+C pujo From jstroud at mbi.ucla.edu Wed Jan 12 18:24:26 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 12 Jan 2005 15:24:26 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <41E5097F.2070109@pcblokes.com> References: <41E5097F.2070109@pcblokes.com> Message-ID: <1105572266.26934.25.camel@lipscomb.mbi.ucla.edu> Don't fight it, lite it! You should parse the fasta and put it into a database: http://www.sqlite.org/index.html Then index by name and it will be superfast. James From JiggaHertz at nospam.com Fri Jan 7 13:07:19 2005 From: JiggaHertz at nospam.com (JiggaHertz) Date: Fri, 07 Jan 2005 13:07:19 -0500 Subject: pygtk swallowing external app Message-ID: I am trying to write a gui with pygtk that swallows an external application. I've tried the plug/sockets example in the documentation modifying the plug to be an xterm. However, the xterm isn't swallowed by the python script. I have seen some c code which accomplishes this via an X reparent call. I was wondering how I would implement this with pygtk? From donn at drizzle.com Fri Jan 21 00:37:37 2005 From: donn at drizzle.com (Donn Cave) Date: 20 Jan 2005 23:37:37 -0600 Subject: spawn syntax + os.P_WAIT mode behavior + spawn stdout redirection References: Message-ID: <41f09521$1_1@127.0.0.1> Quoth Derek Basch : | *First question* | | If the syntax of spawnl is: | | spawnl(mode, path, ...) | | Why does everyone write it like: | | os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') | | or: | | os.spawnl(os.P_WAIT, "/var/www/db/smm/smm_train", "smm_train", | "SMMTrainInput.xml") | | How is the first 'cp' a path to a file? As you may have guessed, 'cp' doesn't have to be a path because the spawnlp() variant finds that file among a list of directories in PATH. | why does the desired executable have to be named again as the first parameter? Because you're supplying the "argv" argument list, which for normal programs (i.e., not written in Python) includes argv[0] as specified by the invoker. This would be more obvious if you consider the spawnv() function, where these arguments are supplied as a list. You can look at the implementation in os.py for more insight into how all this works, particularly see the execve(2) function that is at the bottom of all this. I was recently quite cheesed to find that the Haskell "executeFile" function supplies its own argv[0], depriving the caller of the occasionally useful opportunity to set this value. Python system interface functions are generally pretty good about not watering down functionality. | *Second question* | | I have a script test.py which calls another script sleep.py using a spawn. | | -------------------------------------------------------------- | #test.py | import os | | os.spawnv(os.P_WAIT, "/var/www/db/cgi-bin/sleep.py", ["python", "sleep.py"]) | #pid = os.spawnl(os.P_WAIT, 'sh', 'sh', '-cv', 'sleep 10; echo fark > | /tmp/test.out') | -------------------------------------------------------------- | | -------------------------------------------------------------- | #sleep.py | import time | | time.sleep(10) | -------------------------------------------------------------- | | I would expect that the test.py script should take 10sec to return. However it | returns immediatly. Perhaps I am calling the sleep.py script incorrectly? | Shouldn't it take 10sec to execute since the spawn mode argument is os.P_WAIT? Might want to verify that it's really executing. I suspect it isn't, since your parameters are wrong (the file to invoke is python, not sleep.py.) If you're writing anything important, you need to do what you can to verify that the commands you're executing are actually successful. | *Third question* | | If I uncomment the second spawn call in test.py I do not get any output to | /tmp/test.out and it also returns immediatly. Can anyone tell me why? Might be a problem finding 'sh', since in this case you call spawnl(), not spawnlp(). Just a guess. Also you ought to know that the return from os.spawnl(os.P_WAIT, ...) will not be a pid, rather a status that carries a little (very little) information about the problem. Donn Cave, donn at drizzle.com From craig at postnewspapers.com.au Fri Jan 7 00:17:31 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 07 Jan 2005 13:17:31 +0800 Subject: Embedding a restricted python interpreter In-Reply-To: References: <41db7e8f$1@news.unimelb.edu.au> Message-ID: <1105075050.28776.43.camel@rasputin.localnet> On Thu, 2005-01-06 at 23:05, Peter Maas wrote: > Craig Ringer schrieb: > It would certainly be difficult to track all harmful code constructs. > But AFAIK the idea of a sandbox is not to look at the offending code > but to protect the offended objects: files, databases, URLs, sockets > etc. and to raise a security exception when some code tries to offend > them. That's a good point. I'm not sure it's really all that different in the end though, because in order to control access to those resources you have to restrict what the program can do. It'd probably be valid to implement a restricted mode at CPython level (in my still-quite-new-to-the-Python/C-API view) by checking at the "exit points" for important resources such as files, etc. I guess that's getting into talk of something like the Java sandbox, though - something Java proved is far from trivial to implement. Of course, CPython is just a /tad/ smaller than Java ;-) . Personally, I'd be worried about the amount of time it'd take and the difficulty of getting it right. One wouldn't want to impart a false sense of security. My original point, though, was that I don't think you can use the standard interpreter to create a restricted environment that will be both useful and even vaguely secure. I'd be absolutely delighted if someone could prove me wrong. > Python is a very well designed language but progress is made by > criticism not by satisfaction ;) Heh, I'm hardly complacent... I run into quite enough problems, especially with embedding and with the C API. Maybe one day I'll have the knowledge - and the time - to have a chance at tackling them. I'd love a restricted mode - it'd be great. I'm just not very optimistic about its practicality. -- Craig Ringer From invalidemail at aerojockey.com Sat Jan 8 18:55:49 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 8 Jan 2005 15:55:49 -0800 Subject: python3: 'where' keyword In-Reply-To: References: <3480qqF46jprlU1@individual.net> Message-ID: <1105228549.608275.148740@c13g2000cwb.googlegroups.com> Peter Hansen wrote: > Andrey Tatarinov wrote: > > >>> print words[3], words[5] where: > > >>> words = input.split() > > > > - defining variables in "where" block would restrict their visibility to > > one expression > > Then your example above doesn't work... print takes a > sequence of expressions, not a tuple as you seem to think. You misunderstand. There "where" is not part of the expression but the statement. The above example would be a modified print statement, a print...where statement, if you will. Under this suggestion, there would be modified versions of various simple statements. This wouldn't be a problem parsing, of course, because "where" would be a keyword. -- CARL BANKS From steve at holdenweb.com Fri Jan 28 13:24:03 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 28 Jan 2005 13:24:03 -0500 Subject: [PyCon] Reg: Registration In-Reply-To: <20050128182019.GB19054@panix.com> References: <3e475f5b0501280929717ce3b3@mail.gmail.com> <20050128182019.GB19054@panix.com> Message-ID: <41FA8343.8020007@holdenweb.com> Aahz, writing as pycon at python.org, wrote: > It's still January 28 here -- register now! I don't know if we'll be > able to extend the registration price beyond that. Just in case anybody else might be wondering when the early bird registration deadline is, I've asked the registration team to allow the early bird price as long as it's January 28th somewhere in the world. There have been rumors that Guido will not be attending PyCon this year. I am happy to scotch them by pointing out that Guido van Rossum's keynote address will be on its traditional Thursday morning. I look forward to joining you all to hear Guido speak on "The State of Python". regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From paritosh.mahana at gmail.com Mon Jan 24 14:05:04 2005 From: paritosh.mahana at gmail.com (paritosh mahana) Date: Tue, 25 Jan 2005 00:35:04 +0530 Subject: how to call python code from C# Message-ID: <15a90b2705012411051c4b36a6@mail.gmail.com> Hi all, How can I call python code from my C# code. One thing is to make an .exe file of the python program and then try to call it from my C# code. But I don't like that idea. Is there any other way to do this. Like making a .dll file from the python code and somehow call it from C# program.But I couldn't find anything on this topic on the net. Actually my GUI is in C# and rest part is in python, and i need to call python from my C# program. Please correct me if I am wrong anywhere. thanks paritosh. From mmokrejs at ribosome.natur.cuni.cz Mon Jan 17 07:32:27 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?windows-1252?Q?Martin_MOKREJ=8A?=) Date: Mon, 17 Jan 2005 13:32:27 +0100 Subject: Writing huge Sets() to disk In-Reply-To: References: Message-ID: <41EBB05B.8000108@ribosome.natur.cuni.cz> Duncan Booth wrote: > Martin MOKREJ? wrote: > > >>Hi, >> could someone tell me what all does and what all doesn't copy >>references in python. I have found my script after reaching some >>state and taking say 600MB, pushes it's internal dictionaries >>to hard disk. The for loop consumes another 300MB (as gathered >>by vmstat) to push the data to dictionaries, then releases >>little bit less than 300MB and the program start to fill-up >>again it's internal dictionaries, when "full" will do the >>flush again ... > > > Almost anything you do copies references. But what does this?: x = 'xxxxx' a = x[2:] b = z + len(x) dict[a] = b >> The point here is, that this code takes a lot of extra memory. >>I believe it's the references problem, and I remeber complains >>of frineds facing same problem. I'm a newbie, yes, but don't >>have this problem with Perl. OK, I want to improve my Pyhton >>knowledge ... :-)) >> >> >> >> > > > >> >> The above routine doesn't release of the memory back when it >>exits. > > That's probably because there isn't any memory it can reasonable be > expected to release. What memory would *you* expect it to release? Thos 300MB, they get allocated/reserved when the posted loop get's executed. When the loops exits, almost all is returned/deallocated. Yes, almost. :( > > The member variables are all still accessible as member variables until you > run your loop at the end to clear them, so no way could Python release > them. OK, I wanted to know if there's some assignment using a reference, which makes the internal garbage collector not to recycle the memory, as, for example, the target dictionary still keeps reference to the temporary dictionary. > > Some hints: > > When posting code, try to post complete examples which actually work. I > don't know what type the self._dict_on_diskXX variables are supposed to be. > It makes a big difference if they are dictionaries (so you are trying to > hold everything in memory at one time) or shelve.Shelf objects which would > store the values on disc in a reasonably efficient manner. The self._dict_on_diskXX are bsddb files, self._tmpdictXX are builtin dictionaries. > > Even if they are Shelf objects, I see no reason here why you have to I gathered from previous discussion it's faster to use bsddb directly, so no shelve. > process everything at once. Write a simple function which processes one > tmpdict object into one dict_on_disk object and then closes the That's what I do, but in the for loop ... > dict_on_disk object. If you want to compare results later then do that by OK, I got your point. > reopening the dict_on_disk objects when you have deleted all the tmpdicts. That's what I do (not shown). > > Extract out everything you want to do into a class which has at most one > tmpdict and one dict_on_disk That way your code will be a lot easier to > read. > > Make your code more legible by using fewer underscores. > > What on earth is the point of an explicit call to __add__? If Guido had > meant us to use __add__ he woudn't have created '+'. To invoke additon directly on the object. It's faster than letting python to figure out that I sum up int() plus int(). It definitely has helped a lot when using Decimal(a) + Decimal(b), where I got rid of thousands of Decimal(__new__), __init__ and I think few other methods of decimal as well - I think getcontext too. > What is the purpose of dict_on_disk? Is it for humans to read the data? If > not, then don't store everything as a string. Far better to just store a For humans is processed later. > tuple of your values then you don't have to use split or cast the strings bsddb creaps on me that I can store as a key or value only a string. I'd love to store tuple. >>> import bsddb >>> _words1 = bsddb.btopen('db1.db', 'c') >>> _words1['a'] = 1 Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/bsddb/__init__.py", line 120, in __setitem__ self.db[key] = value TypeError: Key and Data values must be of type string or None. >>> How can I record a number then? > to integers. If you do want humans to read some final output then produce > that separately from the working data files. > > You split out 4 values from dict_on_disk and set three of them to 0. If > that really what you meant or should you be preserving the previous values? No, overwrite them, i.e. invalidate them. Originally I recorded only first, but to compute the latter numbers is so expensive I have to store them. As walking through the dictionaries is so slow, I gave up on an idea to store just one, and a lot later in the program walk once again through the dictionary and 'fix' it by computing missing values. > > Here is some (untested) code which might help you: > > import shelve Why shelve? To have the ability to record tuple? Isn't it cheaper to convert to string and back and write to bsddb compared to this overhead? > > def push_to_disc(data, filename): > database = shelve.open(filename) > try: > for key in data: > if database.has_key(key): > count, a, b, expected = database[key] > database[key] = count+data[key], a, b, expected > else: > database[key] = data[key], 0, 0, 0 > finally: > database.close() > > data.clear() > > Call that once for each input dictionary and your data will be written out > to a disc file and the internal dictionary cleared without any great spike > of memory use. Can I use the mmap() feature on bsddb or any .db file? Most of the time I do updates, not inserts! I don't want to rewrite all the time 300MB file. I want to update it. What I do need for it? Know the maximal length of a string value keept in the .db file? Can I get rid of locking support in those huge files? Definitely I can improve my algorithm. But I believe I'll always have to work with those huge files. Martin From bokr at oz.net Wed Jan 12 23:13:11 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 04:13:11 GMT Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: <41e5ebee.709560864@news.oz.net> On 12 Jan 2005 14:46:07 -0800, "Chris Lasher" wrote: >Hello, >I have a rather large (100+ MB) FASTA file from which I need to >access records in a random order. The FASTA format is a standard format >for storing molecular biological sequences. Each record contains a >header line for describing the sequence that begins with a '>' >(right-angle bracket) followed by lines that contain the actual >sequence data. Three example FASTA records are below: > Others have probably solved your basic problem, or pointed the way. I'm just curious. Given that the information content is 2 bits per character that is taking up 8 bits of storage, there must be a good reason for storing and/or transmitting them this way? I.e., it it easy to think up a count-prefixed compressed format packing 4:1 in subsequent data bytes (except for the last byte which have less than 4 2-bit codes). I'm wondering how the data is actually used once records are retrieved. (but I'm too lazy to explore the biopython.org link). >>CW127_A01 >TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG >TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA >GCATTAAACAT >>CW127_A02 >TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG >TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA >GCATTAAACATTCCGCCTGGGGAGTACGGTCGCAAGATTAAAACTCAAAGGAATAGACGG >>CW127_A03 >TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG >TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA >GCATTAAACATTCCGCCTGGG >... Regards, Bengt Richter From antbyte.The.Flow at gmail.com Thu Jan 27 20:20:59 2005 From: antbyte.The.Flow at gmail.com (The Flow) Date: 27 Jan 2005 17:20:59 -0800 Subject: [perl-python] 20050127 traverse a dir In-Reply-To: References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> Message-ID: <1106875259.426213.252030@z14g2000cwz.googlegroups.com> Xah Lee, Do you want to be taken seriously? First, stop posting. Second, learn perl. Third, learn python. From jeff at ccvcorp.com Mon Jan 24 20:55:58 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 24 Jan 2005 17:55:58 -0800 Subject: is this use of lists normal? In-Reply-To: References: Message-ID: <10vb9e045d73v6b@corp.supernews.com> Gabriel B. wrote: > My object model ended up as > > DataStorageObj > |-itemsIndex (list, could very well be a set...) > | |-[0] = 0 > | |-[1] = 1 > | |-[2] = 5 > | '-[3] = 6 > '-Items (list) > |-[0] = ['cat food', '12,20'] > |-[1] = ['dog food', 8,00'] > |-[2] = ['dead parrot', '25,00'] > '-[3] = ['friendly white bunny', '12,25'] > > the list itemsindex has the DB index of the data, and the list items > has the data. > So if i want something like "SELECT * FROM items WHERE idx=5" i'd use > in my program > self.items[ self.itemsIndex.index(5) ] > i reccon that's not much nice to use when you're gona do /inserts/ but > my program will just read the entire data and never change it. > > Was i better with dictionaries? the tutorial didn't gave me a good > impression on them for custom data... > Tupples? the tutorial mentions one of it's uses 'employee records from > a database' but unfortunatly don't go for it... Yes, I think you'd be better off using dictionaries here. You can spare yourself a level of indirection. Tuples would be a good way to store the individual items -- instead of a list containing a name and a price (or so I presume), you'd use a tuple. Your data storage would then be a dictionary of tuples -- self.items = { 0: ('cat food', '12,20'), 1: ('dog food', '8,00'), 5: ('dead parrot', '25,00'), 6: ('friendly white bunny', '12,25') } Then your SELECT above would translate to my_item = self.items[5] and my_item would then contain the tuple ('dead parrot', '25,00'). Note that the most important difference between tuples and lists, for this example, is conceptual. Tuples generally express "this is a collection of different things that are a conceptual group", whereas lists express "this is a series of similar objects". > i think the 'ideal' data model should be something like > ({'id': 0, 'desc': 'dog food', 'price': '12,20'}, ...) > But i have no idea how i'd find some item by the ID within it withouy > using some loops You could use a dictionary for each item, as you show, and then store all of those in a master dictionary keyed by id -- in other words, simply replace the tuples in my previous example with a dict like what you've got here. You could also create a simple class to hold each item, rather than using small dicts. (You'd probably still want to store class instances in a master dict keyed by id.) Generally, any time your problem is to use one piece of information to retrieve another piece (or set) of information, dictionaries are very likely to be the best approach. Jeff Shannon Technician/Programmer Credit International From fuzzyman at gmail.com Tue Jan 25 04:29:31 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Jan 2005 01:29:31 -0800 Subject: how to ncurses on win32 platform In-Reply-To: References: Message-ID: <1106645371.925189.3740@z14g2000cwz.googlegroups.com> Tim Golden wrote: > [Jorgen Grahn] > | [Alan Gauld ] > | > You can use ncurses via cygwin. > | > There are DOS ports too but I couldn't get any of them to > | > work on my XP box, YMMV... > | > | Or, as Alex Martelli wrote in "Python in a nutshell": > | > | "The curses package works only on Unix-like platforms > | (there are persis- > | tent rumors of Windows ports of it, but I've never found a > | working one)." > > This is the only one I've seen which claims > (at least partial) compatibility. I've looked > it over, but never had a chance to try it out: > > http://flangy.com/dev/python/curses/ > > TJG It's a shame there isn't (as far as I can see) a source distribution, or a 2.4 binary. It works very well for the parts implemented. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ From steven.bethard at gmail.com Wed Jan 12 15:19:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 13:19:17 -0700 Subject: counting items In-Reply-To: <1105559439.538736.87370@z14g2000cwz.googlegroups.com> References: <1105559439.538736.87370@z14g2000cwz.googlegroups.com> Message-ID: Michael Hartl wrote: > (Once you can iterate over an arbitrary sequence, the > flattened version is just > [element for element in walk(sequence)].) Or, better yet: list(walk(sequence)) Steve From jeff at ccvcorp.com Tue Jan 18 18:52:41 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 18 Jan 2005 15:52:41 -0800 Subject: Assigning to self In-Reply-To: References: <10uo6hbn040qt24@news.supernews.com> Message-ID: <10ur80gf6utag00@corp.supernews.com> Marc 'BlackJack' Rintsch wrote: > Frans Englich wrote: > >>Then I have some vague, general questions which perhaps someone can reason >>from: what is then the preferred methods for solving problems which requires >>Singletons? > > As already mentioned it's similar to a global variable. If I need a > "Singleton" I just put it as global into a module. Either initialize it > at module level or define a function with the content of your __init__(). If one is determined to both use a Singleton and avoid having a plain module-global variable, one could (ab)use function default parameters: class __Foo: "I am a singleton!" pass def Foo(foo_obj = __Foo()): assert isinstance(foo_obj, __Foo return foo_obj Of course, this suffers from the weakness that one might pass an object as an argument to the factory function and thus temporarily override the Singleton-ness of __Foo... but a determined programmer will work around any sort of protection scheme anyhow. ;) In general, ISTM that if one wants a Singleton, it's best to create it via a factory function (even if that function then masquerades as a class). This gives you pretty good control over the circumstances in which your Singleton will be created and/or retrieved, and it also makes it trivial to replace the Singleton with some other pattern (such as, e.g., a Flyweight or Borg object) should the need to refactor arise. Jeff Shannon Technician/Programmer Credit International From pythongnome at hotmail.com Tue Jan 11 20:33:53 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Wed, 12 Jan 2005 01:33:53 GMT Subject: [OT] SciTe Message-ID: <58%Ed.4827$C52.2609@newsread2.news.atl.earthlink.net> I didn't want to go through the rigamole of adding myself to the SciTe mailing list, so I'm asking my question here. How do I choose a different C/C++ compiler to compile in?? I don't use the g++ compiler; I use the VC 7 compiler. TIA, Lucas From steve at holdenweb.com Fri Jan 14 17:24:37 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 17:24:37 -0500 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: <7xacrcdhzh.fsf@ruckus.brouhaha.com> References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Fredrik Lundh" writes: > >>>Huh? Expressions are not statements except when they're "expression >>>statements"? What kind of expression is not an expression statement? >> >>any expression that is used in a content that is not an expression statement, >>of course. > > > Come on, that is vacuous. The claim was "expressions are not > statements". But it turns out that expressions ARE statements. The > explanation is "well, that's because they're expression statements". > And there is no obvious case of an expression that can't be used as a > statement. So it's not inherently obvious that there needs to be any > kind of statement that can't be used as an expression. It's just an > artifact. Whether the artifact is a desirable one is a matter of > discussion. Excuse me, coould we get back to discussing how many angels can dance on the head of a pin? or-something-interesting-like-that-sly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From tim.peters at gmail.com Mon Jan 3 00:29:30 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 3 Jan 2005 00:29:30 -0500 Subject: thread/queue bug In-Reply-To: <41B9D041.5050200@anvilcom.com> References: <41B9D041.5050200@anvilcom.com> Message-ID: <1f7befae050102212962c58afb@mail.gmail.com> [phillip.watts at anvilcom.com] Note that python-bugs-list is a moderated list for use only by automated reports generated from SourceForge. I'm redirecting the reply to python-list at python.org. > I have a very strange bug. A thread in a .pyc stops dead. > > This program has many threads and queues and has worked > great for months. > One thread listens for UDP messages from other programs, > and puts the messages in listenq. > Procmsgs gets from listenq and for a certain kind of > message creates another mq = Queue(0). > > I don't wish to distribute the source to pnetx.py > so I have a short program pnet.py import it, that is > pnetx.pyc. > > Then the procmsgs thread dies at the Queue statement. > But if I run pnetx.py as the main program, all works fine. > > So if pnetx.py or .pyc is imported this thread dies. ??? > > I've tried this with 2.3.3 and 2.3.4. Anyone? Sounds like your module spawns a thread as a side effect of being imported. Don't do that -- you'll get in deadlock trouble with "the import lock" if you do (use Google to learn more about that). From jloden at toughguy.net Thu Jan 20 13:51:43 2005 From: jloden at toughguy.net (Jay Loden) Date: Thu, 20 Jan 2005 13:51:43 -0500 Subject: What's the best python web-developer's editor In-Reply-To: <41EFFCD9.7060302@wild-flower.co.uk> References: <41EFFCD9.7060302@wild-flower.co.uk> Message-ID: <200501201351.43884.jloden@toughguy.net> You didn't mention platform, but I'm guessing from the mention of Screem that you're using a Linux platform. On Linux I like kwrite and kate (both similar, kate includes some other features like a built in terminal where you can run some commands, ability to support projects, open multiple files tiled to read all the code at once, etc). They both use the same editing portion, which has syntax highlighting for Python and html both. Because of KDE network transparency, you can edit files over ftp/save to an ftp site. Just in case, I'll recommend my favorite Windows editor for those times when I'm stuck on Windows - Crimson Editor, http://www.crimsoneditor.com Has syntax highlights, and just about every feature I could possibly ask for in an editor. I actually missed this app the most when moving to Linux. -Jay On Thursday 20 January 2005 1:47, andy wrote: > Anybody like to comment on which editor they use for python web app > development - for both discrete and mixed python and html code, and why? > > I'm comfortable with IDLE (used it for years) but of course it lacks ftp > or webDAV abilities, obviously because it's not intended for that type > of use. > > I've had a look at Screem - and that seems to do python syntax > highlighting, but it dosn't seem to be python syntax aware (unless > there's a hidden option somewhere). Although I can live without auto > indent, I'd rather not... > > I'm sure emacs, xemacs, vi, elvis and so on can do the same, but I have > no experience with them for heavy python or html coding, nor the time > to trip off down a blind-alley to find out! I know Enough Vi To Get > By(tm) but it's by no means my favourite editor. Emacs is a complete > mystery to me. > > I guess I *could* use IDLE and Screem together, but that's a clunky > solution! > > all opinions greatfully received, > -andyj From mnations at gmail.com Wed Jan 19 12:16:35 2005 From: mnations at gmail.com (Mudcat) Date: 19 Jan 2005 09:16:35 -0800 Subject: How to fill available screen size then scroll In-Reply-To: <1106086897.788340.267550@f14g2000cwb.googlegroups.com> References: <1106086897.788340.267550@f14g2000cwb.googlegroups.com> Message-ID: <1106154995.830101.257430@z14g2000cwz.googlegroups.com> bump From jeff at ccvcorp.com Mon Jan 17 13:11:23 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 17 Jan 2005 10:11:23 -0800 Subject: hash patent by AltNet; Python is prior art? In-Reply-To: References: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> Message-ID: <10unvkgh02aiab1@corp.supernews.com> Robert Kern wrote: > I don't know the details [...] Neither do I, but... > I'm also willing to bet that the patent won't > hold up in court because there's quite a lot of prior art with respect > to cryptographic hashes, too. The problem with that is that someone needs to be able to *afford* to challenge it in court. Even patents that are blatantly non-original on the face of things can be difficult and expensive to challenge. Most companies would rather just avoid the legal risks involved in making such a challenge, and most individuals can't afford the kind of legal team that'd be necessary. I'll join in encouraging Europeans to do their best to reject these styles of patents. It's a bit too late for the US, but maybe if we have concrete examples of the benefits of limiting patents then there might be hope for the future. And if things get too bad here, I'd like to have somewhere pleasant to emigrate to. ;) Jeff Shannon Technician/Programmer Credit International From evan at tokenexchange.com Mon Jan 17 13:00:42 2005 From: evan at tokenexchange.com (Evan Simpson) Date: Mon, 17 Jan 2005 12:00:42 -0600 Subject: Producer/consumer Queue "trick" In-Reply-To: <41E945EA.4040507@iinet.net.au> References: <7xmzvbnigr.fsf@ruckus.brouhaha.com> <41E945EA.4040507@iinet.net.au> Message-ID: <41EBFD4A.1090707@tokenexchange.com> Nick Coghlan wrote: > Paul Rubin wrote: > >> That's weird. Preemption should happen every few dozen milliseconds >> unless you've purposely increased the preemption delay. > > > To me, it smells like a call into a C extension which isn't releasing > the GIL before starting a time-consuming operation. Sorry, I think I misled you both -- "a long time" is actually the few dozen milliseconds of a normal preemption, which is only long relative to the single millisecond that the consumer typically takes to handle a request. Cheers, Evan @ 4-am From michele.simionato at gmail.com Wed Jan 12 00:56:19 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 11 Jan 2005 21:56:19 -0800 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: <7xmzvfn096.fsf@ruckus.brouhaha.com> References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: <1105509379.301556.178130@z14g2000cwz.googlegroups.com> Paul Rubin: > michele.simion... at gmail.com writes: >> > It wasn't obvious how to do it in Scheme either. There was quite > a bit of head scratching and experimental implementation before > there was consensus. Actually I am not convinced there is consensus yet, i.e. there is a non-negligible minority of schemers convinced that original Lisp macros where better, not to talk of common lispers ;) >> 3. We would add to Python the learning curve of macros and their >> subtilities and we do not want it. > I can't imagine how it could be worse than the learning curve of > __metaclass__, which we already have. To me, learning macros *and their subtilities* was much more difficult than learning metaclasses. >> 4. Macros would complicate a lot Python module system. > I don't see how, but maybe I'm missing something. Go to comp.lang.scheme and google for "macros and module system"; you will get everything you want to know and much more! >> 5. We have Guido providing a good syntax for us all, why we should be >> fiddling with it? More seriously, if some verbosity is recognized >> in the language (think to the "raison d'etre" of decorators, for >> instance) I very much prefer to wait for Guido to take care of >> that, once and for all, than having 100 different custom made >> solutions based on macros. > Every time some newbie asks an innocent "how do I ..." question, we > see unbelievably horrid answers from gurus. Just check the FAQ about > conditional expressions, etc. I just don't see Python syntax changes > as forthcoming. Well, I see this as a positive fact. If a syntax is contrived (such as a ternary operator, for instance) it is better *not* to have it than to have one hundred custom made syntaxes. At the end, we are just talking about syntax sugar here, not about lack of functionality. >> What I would be interested in is a Lisp/Scheme implementation >> compiling to Python bytecode, but I am not aware of any project >> in that direction. > But that sounds like a bizarre idea. Python bytecode is just a > CPython artifact, not part of the language. And it's not even that > good an artifact. Good Lisp/Scheme implementations compile to native > code that beats the pants off of CPython bytecode. It would make much > more sense to have a Python implementation that compiles Python to > S-expressions and then lets a high performance Lisp or Scheme system > take care of the rest. This is a bizarre idea if you want to make Python run faster. It is not so bizarre if what you want is to have access to Python from Lisp/Scheme in the same sense Jython has access to Java. Michele Simionato From http Mon Jan 31 23:18:57 2005 From: http (Paul Rubin) Date: 31 Jan 2005 20:18:57 -0800 Subject: need for binary floats (except performance)? References: <81300027.0501312006.72454fd6@posting.google.com> Message-ID: <7xmzuoq5e6.fsf@ruckus.brouhaha.com> kartik_vad at yahoo.com (kartik) writes: > Since the Decimal type can represent any given fractional number > exactly, It can't. For example, it can't represent 1/3 exactly. > including all IEEE binary floating-point numbers, wouldn't it be > advisable to use Decimals for all floating point numbers (except > possibly for performance)? The notion has some appeal, though algorithms on binary floats have been studied a lot over the past several decades, while decimal floats are not used very much at the moment. It will get more interesting if and when we start seeing decimal floating point hardware again. From b at b.b Tue Jan 11 03:59:49 2005 From: b at b.b (Roose) Date: Tue, 11 Jan 2005 08:59:49 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> <7xu0ppyjjg.fsf@ruckus.brouhaha.com> <9yzEd.9081$wZ2.6859@newssvr13.news.prodigy.com> <7xr7ksrf17.fsf@ruckus.brouhaha.com> Message-ID: <9AMEd.9356$wZ2.1350@newssvr13.news.prodigy.com> > Huh? I'm just baffled why you think writing a scheduler in an OS is > harder than writing one in an application. You have some means of > doing a coroutine switch in one situation, and some means of doing a > hardware context switch in the other. Aside from that the methods are > about the same. Because of performance. Task schedulers and device drivers tend to be timing sensitive. Go look up "task schedular latency". The longer your scheduler spends trying to figure out which thread to run, the longer the latency will be. I mean in the worst case, if you are interpreting everything, what if you change the task scheduler code? Then an interrupt happens, and oh shit we have to parse and recompile all the scheduling code. Oh wait now we ran out of kernel memory -- now we have to run the garbage collector! Let your interrupt wait, no? It just seems nonsensical. Maybe not impossible, as I've already said. I haven't tried it. But go ahead and try it -- I would honestly be interested in the results, all kidding aside. It shouldn't be too time-consuming to try, I suppose. Get Python running in the Linux kernel, and then replace the task scheduling algorithm with some Python code. See how it works. I suspect you will degrade the performance of an average system significantly or unacceptably. But who knows, I could be wrong. Of course, hardware is getting faster as you say. But multitasking performance is still an active and important area of OS research, and I doubt that any designer of an OS (that is actually meant to be used) would spend any cycles to have their task scheduler in Python -- and that will be probably be true for a very long time. Or maybe I'm wrong -- go bring it up on comp.os.linux or whatever the relevant newsgroup is. I'd like to hear what they have to say. > > Why do you think there's anything difficult about doing this stuff in > Python, given the ability to call low level routines for some hardware > operations as needed? From mwm at mired.org Mon Jan 3 17:42:38 2005 From: mwm at mired.org (Mike Meyer) Date: Mon, 03 Jan 2005 16:42:38 -0600 Subject: input record sepArator (equivalent of "$|" of perl) References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> <1103657476.495700.191020@f14g2000cwb.googlegroups.com> <1103671235.093738.198680@z14g2000cwz.googlegroups.com> Message-ID: <86wtuup21t.fsf@guru.mired.org> Christos "TZOTZIOY" Georgiou writes: > [1] through the French "m?tre" of course; great job, those > revolutionaries did with the metric system. As Asimov put it, "how many > inches to the mile?" Trivia question: Name the second most powerfull country on earth not using the metric system for everything. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From ods at strana.ru Tue Jan 11 12:05:26 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Tue, 11 Jan 2005 20:05:26 +0300 Subject: os.spawnv & stdin trouble In-Reply-To: <20050111163036.808E91C00CE9@mwinf0108.wanadoo.fr> References: <20050111163036.808E91C00CE9@mwinf0108.wanadoo.fr> Message-ID: <20050111200526.1bd60ebd.ods@strana.ru> On Tue, 11 Jan 2005 17:31:07 +0100 "Jelle Feringa // EZCT / Paris" wrote: > ##I know I should be using 2.4 and os.Popen, I know, I know. > ##However, since most modules I need, I'm using 2.3 for this script There is os.popen in 2.3, as well as popen2 module. Did you mean subprocess? I guess it's ported to 2.3 too. > Here's where I run into trouble. > In my os.system version, I'm perfectly able to pipe into another file, > since the process has no real connection to python whatsoever. > Would someone be able to explain me how to do this, all the tools I'm > using for this script are unix-like tools and heavily rely on piping. os.system passes commend to shell, which handles redirect for you instead of passing '>' to xform.exe as parameter. Use os.system or subprocess (a.k.a. popen5). > program = 'xform.exe' > path = 'c:\Radiance\bin\' ^^ Syntax error here. Did you mean 'c:\\Radiance\\bin\\xform.exe'? > args = ['-t 0 8 0', 'wall0.rad', '>', 'wall0.TRANS.rad'] > os.spawnv(os.P_WAIT, path, ('xform', args)) This corresponds to c:\Radiancein\ '-t 0 8 0' wall0.rad '>' wall0.TRANS.rad' command line. > here's the cmd error message: > xform: cannot find file ">" Don't understand how you got this error having syntax error and wrong path to executable. > ##for your info I'm on win/xp, python 2.3.4 BTW, you are trying to redirect stdout. Wrong subject? -- Denis S. Otkidach http://www.python.ru/ [ru] From nid_oizo at yahoo.com_remove_the_ Tue Jan 4 11:15:23 2005 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Tue, 04 Jan 2005 11:15:23 -0500 Subject: python 3000 and removal of builtin callable In-Reply-To: <33v6l6F40l7hqU1@individual.net> References: <33v6l6F40l7hqU1@individual.net> Message-ID: Mirko Zeibig wrote: > This is not an option for e.g. IDEs as some functions might actually do > something when called ;-) and I like `callable` for introspection. > > Other ways would be to check for the `__call__` attribute or use several > methods of the `inspect`-Module, both of which are not better than > `callable` IMHO. I totally agree with you. The callable function could be moved to a module and be built-in, but it cannot really be removed. Calling a callable and know if an object is a callable without calling it is definitely not the same thing. Regards, Nicolas From rnd at onego.ru Wed Jan 5 09:54:03 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 5 Jan 2005 17:54:03 +0300 (MSK) Subject: Python evolution: Unease In-Reply-To: <1gpx56v.yb9ubn188tj2yN%aleaxit@yahoo.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> <1gpx56v.yb9ubn188tj2yN%aleaxit@yahoo.com> Message-ID: On Wed, 5 Jan 2005, Alex Martelli wrote: >Dave Brueck wrote: > ... >> No, not at all - I'm just trying to better understand what you mean. Words >> like "generic" and "concepts" don't yet have a widely recognized, strict >> definition in the context of programming. If somebody has assigned some >> specific definition to them, that's great, it's just not universal yet so >> references and additional explanations are helpful. > >Googling for "generic programming" (with the quotes) gets 100,000 + >hits. The first couple pages of hits, at least, seem to all be speaking >about exactly the same thing. The terminology appears to be settled >enough that Oxford's St Anne College feels they can organize a "Summer >School on Generic Programming", Nottingham University a "Workshop on >Generic Programming", etc, etc, without fearing ambiguity. That is why I was pretty sure people undestand me. >Exactly what extra support Roman would want from Python for 'concepts', >beyond that offered by, say, C++, I'm not sure. Protocols, interfaces >and design-by-contract are other terms often used to try and capture >pretty similar issues. I just happen to like the term 'concept' more than Protocols, interfaces, and design-by-contract ;-) Alex, I think you are +10 for adding interfaces into Python. "Concept" is more compact word and I am sure it is not used as a name in existing projects, unlike other words. Also, Python concept collection could be used as a teaching example or templates for high quality code. Concepts need not appear in every script out there, but as a result of design. What else Python needs to support GP? A possibility to formally define a concept (and concept relations) with (optionally) checks of implementations. I do not even insist in making it all run-time! Perhaps concepts could be checked in PyChecker. And (perhaps) the whole type-checking could be done this way. However sweety it is, I also hope to have keystrokes saved when I use ready-maid concept in my program. Just imagine we have a concept for table and use (as adaptor) it for db-connectivity, CSV-readers/writers, XML/HTML parsers/writers, arrays, lists, ... Right now Python _almost_ has it. However, small differences in small details do not allow to interchange even different dbm-modules! I remember getting into trouble when I switched from bsddb to gdbm: some places needed 'r' to be explicitly specified! Same problems with db-api 2.0 "almost" conformant modules, datetime types and other small details which are similar but differ in small details at the same time. I think the same has place with XML-DOM implementations and such. I think concepts could be guards against such things and also make life easier for those who implement some standard protocols. That is, concepts could be internal (Python) standardizing and quality control technique. We can use constant publicId, systemId a-la XML for concepts, so upgrade path will be similar to HTMLs. This will make concept-changing visible between versions. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From google at smilechaser.com Thu Jan 20 18:06:36 2005 From: google at smilechaser.com (smilechaser) Date: 20 Jan 2005 15:06:36 -0800 Subject: Embedding: Question about modules Message-ID: <1106258999.633728.203400@z14g2000cwz.googlegroups.com> Hi All, A question about embedding: If I take the example code on embedding (Section 5.3 of Extending and Embedding the Python Interpreter 2.4) and add the lines: PyRun_SimpleString("import sys"); PyRun_SimpleString("print globals()"); Just after the part where the code loads the module, and then I have a script that looks like: # mod_test.py def foo(x): for g in globals(): print g The first printout of the globals shows the sys module, but the second one does not. Can someone explain why this is ? And how do I make the sys module accessible to the module I load (as per the 5.3 example). TIA, smilechaser From timr at probo.com Sun Jan 23 00:19:07 2005 From: timr at probo.com (Tim Roberts) Date: Sat, 22 Jan 2005 21:19:07 -0800 Subject: getting file size References: Message-ID: <6qc6v0hhfedf0uncp9gieahj38srh46khk@4ax.com> Bob Smith wrote: >Are these the same: > >1. f_size = os.path.getsize(file_name) > >2. fp1 = file(file_name, 'r') > data = fp1.readlines() > last_byte = fp1.tell() > >I always get the same value when doing 1. or 2. Is there a reason I >should do both? When reading to the end of a file, won't tell() be just >as accurate as os.path.getsize()? On Windows, those two are not equivalent. Besides the newline conversion done by reading text files, the solution in 2. will stop as soon as it sees a ctrl-Z. If you used 'rb', you'd be much closer. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From abpillai at gmail.com Wed Jan 5 08:16:04 2005 From: abpillai at gmail.com (Anand) Date: 5 Jan 2005 05:16:04 -0800 Subject: Using python to deploy software In-Reply-To: <1104326227.266388.224060@z14g2000cwz.googlegroups.com> References: <1104295227.491861.207050@z14g2000cwz.googlegroups.com> <1104300281.832625.138070@f14g2000cwb.googlegroups.com> <1104326227.266388.224060@z14g2000cwz.googlegroups.com> Message-ID: <1104930964.467419.293540@c13g2000cwb.googlegroups.com> Hmm... did not watch this thread. Regarding sharing code, well I am sure you will be able to quickly produce some working client/server using Pyro for doing your task. Pyro makes it very easy to do RMI due to its network broadcast way of querying the name server. If you are not able to make any headway, mail me and I can give you his email address. Rgds -Anand From http Sat Jan 29 10:35:41 2005 From: http (Paul Rubin) Date: 29 Jan 2005 07:35:41 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <7xzmysqmxk.fsf@ruckus.brouhaha.com> Message-ID: <7xr7k4qmcy.fsf@ruckus.brouhaha.com> Paul Rubin writes: > actually: mxCrypto is the most capable of these packages and might be > the one with the most users, but it's completely unsuitable for the > core because of its size). Oops, I should say, mxCrypto itself isn't that large; the issue is that it needs OpenSSL which is a big unwieldy program. Having mxCrypto in the core as an OpenSSL interface is a legitimate notion. But there should be something that doesn't depend on OpenSSL. From samantha7395 at hotmail.com Thu Jan 20 16:17:35 2005 From: samantha7395 at hotmail.com (Samantha) Date: Thu, 20 Jan 2005 13:17:35 -0800 Subject: Print to Windows default Printer References: <9A28C052FF32734DACB0A288A35339910359DA@vogbs009.gb.vo.local> Message-ID: Thanks for the URL. I finally am able to print the temp file. Not exactly what I wanted, but it will work. The code I used to print was this: os.system ("start /min notepad /P temp.txt") Thanks ALL! S "Kristian Zoerhoff" wrote in message news:mailman.970.1106248792.22381.python-list at python.org... > On Thu, 20 Jan 2005 19:14:10 -0000, Tim Golden > wrote: >> [Kristian Zoerhoff] >> | >> | On Thu, 20 Jan 2005 18:58:25 -0000, Tim Golden >> | wrote: >> | > >> | > Can anyone else try a "PRINT blah" or a "COPY blah LPT1:" >> | > on XP SP2? >> | >> | The printer is probably connected via USB, not the parallel port >> | (LPT1), so the above won't work. I googled, and found some sage advice >> | here: >> | >> | http://www.winnetmag.com/Article/ArticleID/39674/39674.html >> | >> | that may assist the OP. From abpillai at gmail.com Thu Jan 6 04:53:43 2005 From: abpillai at gmail.com (Anand) Date: 6 Jan 2005 01:53:43 -0800 Subject: Contributor's List Message-ID: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> A list of contributors to Python Cookbook (Second Edition) is available at the following links. Original list courtesy Alex Martelli. Since the book is not yet in print, the lists are still tentative because of potential last minute editing changes. List of first authors o http://harvestman.freezope.org/cookbook/credau.html List of all authors o http://harvestman.freezope.org/cookbook/creds.html -Anand From eric_brunel at despammed.com Tue Jan 11 04:00:51 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 11 Jan 2005 10:00:51 +0100 Subject: PyChecker messages In-Reply-To: References: Message-ID: <41e393f0$0$25812$8fcfb975@news.wanadoo.fr> Frans Englich wrote: > Hello, > > I take PyChecker partly as an recommender of good coding practice, but I > cannot make sense of some of the messages. For example: > > runner.py:878: Function (main) has too many lines (201) > > What does this mean? Cannot functions be large? Or is it simply an advice that > functions should be small and simple? This is an advice. You can set the number after which the warning is triggered via the maxLines option in your .pycheckrc file. > runner.py:200: Function (detectMimeType) has too many returns (11) > > The function is simply a long "else-if" clause, branching out to different > return statements. What's wrong? It's simply a "probably ugly code" advice? Same thing; the corresponding option in .pycheckrc is maxReturns. Other options that may interest you are maxBranches, maxArgs, maxLocals and maxReferences. Please see PyChecker's documentation for more details. > A common message is these: > > runner.py:41: Parameter (frame) not used > > But I'm wondering if there's cases where this cannot be avoided. For example, > this signal handler: > > #------------------------------------------- > def signalSilencer( signal, frame ): > """ > Dummy signal handler for avoiding ugly > tracebacks when the user presses CTRL+C. > """ > print "Received signal", str(signal) + ", exiting." > sys.exit(1) > #------------------------------------------- > > _must_ take two arguments; is there any way that I can make 'frame' go away? See/set the unusedNames option in .pycheckrc; this is a list of names for which this kind of warnings are not triggered. If you set for example: unusedNames = [ 'dummy' ] in .pycheckrc and if you define your function with: def signalSilencer(signal, dummy): ... the warning will not be triggered. BTW, if your signal handler is just here to catch Ctrl-C, you'd better do a try/except on KeyboardInterrupt... HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From orjan at switchcore.com Mon Jan 24 09:18:39 2005 From: orjan at switchcore.com (=?ISO-8859-1?Q?=D6rjan_Gustavsson?=) Date: Mon, 24 Jan 2005 15:18:39 +0100 Subject: pylibpcap and multiple threads Message-ID: Hi All! Sorry if this is not the correct forum for this kind of question (I did not find any pylibpcap related lists). I am trying to use pylibpcap to capture network traffic from several ethernet devices at the same time, each nic having a separate thread assigned to it. My problem is that when one thread is blocking inside pcap.loop() for instance, it seems to have acquired the GIL, so that no other threads can run. Does anyone know a way to do this with threads, or is the only way to have separate processes for each NIC? Regards, ?rjan Gustavsson From anon at anon.com Fri Jan 28 15:20:22 2005 From: anon at anon.com (Todd_Calhoun) Date: Fri, 28 Jan 2005 12:20:22 -0800 Subject: Where can I find sample "beginner" programs to study? Message-ID: <_6CdnWIOB8AaA2fcRVn-rg@speakeasy.net> I'm trying to learn Python (and programming), and I'm wondering if there are any places where I can find small, simple programs to study. Thanks. From steven.bethard at gmail.com Mon Jan 24 14:59:07 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 24 Jan 2005 12:59:07 -0700 Subject: Tuple slices In-Reply-To: References: <35kn4mF4o44ufU1@individual.net> Message-ID: <-cWdndzlhLgYzmjcRVn-vw@comcast.com> Fredrik Lundh wrote: > Steven Bethard wrote: >> >>My impression was that full tuple copies didn't actually copy, but that slicing a subset of a >>tuple might. Not exactly sure how to test this, but: >> >>py> a = 1, 2, 3 >>py> a[:2] is a[:2] >>False > > yup. and to figure out why things are done this way, consider this case: > > >>> a = give_me_a_huge_tuple() > >>> len(a) > (a rather large number) > >>> b = a[:2] > >>> del a > > (IIRC, I proposed to add "substrings" when I implemented the Unicode string > type, but that idea was rejected, for the very same "and how do you get rid of > the original object" reason) Ahh. Yeah, that seems sensible. I don't think I've ever written code like that, but if I did, I'd almost certainly want it to work as it does now... Steve From BOOGIEMANPN at YAHOO.COM Sat Jan 1 15:57:32 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Sat, 1 Jan 2005 21:57:32 +0100 Subject: What can I do with Python ?? Message-ID: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> Beginners question, but really what can you do with it ? How hard is Python to learn compared with other languages (let's say C#). Can you make fullscreen game with it (for example) ? I've looked at http://www.python.org but nothing concrete there From firstname.lastname at iki.fi-spam Mon Jan 3 04:34:06 2005 From: firstname.lastname at iki.fi-spam (Simo Melenius) Date: 03 Jan 2005 11:34:06 +0200 Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: <87u0py6elt.fsf@sme.intra.citec.fi> Ron Garret writes: > (with-output-to-string (s) > (let ( (*standard-output* s) ) > (call-html-generating-code) > s)) > > Is there an equivalent Python trick to capture a function call's output > as a string? I've sometimes replaced sys.stdout (and/or sys.stderr) to capture/redirect debugging information in existing code that has unwisely just "print"ed error and warning messages, instead of using sys.stderr or error logging modules. py> def with_output_to_string (func): ... try: ... sys.stdout = StringIO.StringIO () ... func () ... return sys.stdout.getvalue () ... finally: ... sys.stdout = sys.__stdout__ ... py> def printing_code (): ... print "Foobar" ... py> with_output_to_string (printing_code) 'Foobar\n' py> br, S From grante at visi.com Sun Jan 16 16:14:13 2005 From: grante at visi.com (Grant Edwards) Date: 16 Jan 2005 21:14:13 GMT Subject: List problems in C code ported to Python References: Message-ID: <41ead925$0$87061$a1866201@visi.com> On 2005-01-16, Lucas Raab wrote: > I'm done porting the C code, but now when running the script I > continually run into problems with lists. I tried appending and > extending the lists, but with no avail. Any help is much appreciated > Please see both the Python and C code at > http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py http://www.catb.org/~esr/faqs/smart-questions.html -- Grant Edwards grante Yow! Did an Italian CRANE at OPERATOR just experience visi.com uninhibited sensations in a MALIBU HOT TUB? From tim.peters at gmail.com Fri Jan 7 12:31:46 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 7 Jan 2005 12:31:46 -0500 Subject: sorting on keys in a list of dicts In-Reply-To: <41DEC423.3030506@iinet.net.au> References: <10tr9ejf05pv660@corp.supernews.com> <41DEC423.3030506@iinet.net.au> Message-ID: <1f7befae0501070931699c5996@mail.gmail.com> [Nick Coghlan] ... > Python 2.3 has a stable sort, and Python 2.4 brought the guarantee that it shall > remain that way. I'm not sure about Python 2.2 and earlier. No list.sort() implementation before 2.3 was stable. It was confusing, though, because the samplesort/binary_insertion_sort hybrid Python used for the 4 years preceding 2.3 *was* stable for all "small enough" lists. More than one person got fooled by guessing that stability observed in small test cases meant it was always stable. From t-meyer at ihug.co.nz Sun Jan 9 19:05:58 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 10 Jan 2005 13:05:58 +1300 Subject: Please Contribute Python Documentation! In-Reply-To: Message-ID: > I'm changing the subject so that hopefully people who have > long ago tuned out the "Python evolution: Unease" subject > will read this note. Worked for me :) Two other pages that are probably of use to people interested in this are: These document the current (well, current when the wiki page was last updated) state of various document patches, and list things that people have noticed need work. There's also a place for volunteers to put their name if they are willing to provide module documentation, so that work isn't duplicated. (I don't know how up-to-date the latter one is. I think the former is reasonably so). > You do not (repeat, *do not*) > need to install any tools to contribute content to the > documentation. Just whip out your favorite text editor and > type plain old text. There are plenty of us around who know > enough LaTeX to markup anything you contribute. Don't let > lack of a specific set of tools be a barrier to contribution! I don't think I've seen such a statement before - the stuff I've seen all indicates that one should be submitting proper LaTeX docs/patches. If plain-text contributions are welcome, could this be added to the doc about contributing to the docs? (I suppose I could submit a patch, but that seems overkill ). > In either case, select "Documentation" as the category. There is > no need to assign it to anyone. It will get seen shortly. > The correctness of a documentation fix is generally easier to > verify than that for a code fix, so they tend to get applied > pretty quickly. Is it a mistake to attach a patch to a bug report? Should it be a new patch tracker instead? I ask because I (ages ago) submitted documentation for zipimport (it's linked from the ModulesThatNeedDocs page above) and although it's been included on that wiki page and in discussion on python-dev about missing documentation, it's never been looked at, AFAIK. (If there are problems, I'm happy to amend the patch, as the comment says). This is somewhat at odds with the "shortly" and "pretty quickly" <0.5 wink>. =Tony.Meyer From nick at craig-wood.com Sat Jan 29 15:30:01 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 29 Jan 2005 20:30:01 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> <7xacqsbfk2.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > An AES or DES addition to an existing module that implements just one > call: > ECB(key, data, direction) > would be a huge improvement over what we have now. A more complete > crypto module would have some additional operations, but ECB is the > only one that's really essential. I would hate to see a module which only implemented ECB. Sure its the only operation necessary to build the others out of, but its the least secure mode of any block cipher. If you don't offer users a choice, then they'll use ECB and just that along with all its pitfalls, meanwhile thinking that they are secure because they are using AES/DES... For those people following along at home (I'm sure everyone who has contributed to thread knows this already) I tried to find a simple link to why ECB is bad, this PDF is the best I could come up with, via Google's Cache. http://www.google.com/search?q=cache:U5-RsbkSs0MJ:www.cs.chalmers.se/Cs/Grundutb/Kurser/krypto/lect04_4.pdf -- Nick Craig-Wood -- http://www.craig-wood.com/nick From aahz at pythoncraft.com Wed Jan 19 15:11:40 2005 From: aahz at pythoncraft.com (Aahz) Date: 19 Jan 2005 15:11:40 -0500 Subject: shelve to DB conversion? Message-ID: I'd like to hear some experiences about converting a shelf with pickles to database with pickles, particularly if someone has handy code for proxying shelve code. We're using PostgreSQL if that makes any difference. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From lance-news at augustmail.com Wed Jan 26 03:05:17 2005 From: lance-news at augustmail.com (Lance Hoffmeyer) Date: Wed, 26 Jan 2005 02:05:17 -0600 Subject: script to search ebay? References: <1106722674.838311.308520@z14g2000cwz.googlegroups.com> Message-ID: Thanks for the script. I haven't been on ebay for a while. Wasn't aware of the Favorite searches. Favorite Search is probably the way to go. Thanks for the info. Lance On Tue, 25 Jan 2005 22:57:54 -0800, Kamilche wrote: > This script works. But why not make a 'Favorite Search' in ebay, and > have it send you daily email for a year? > > --Kamilche > > |import urllib > |import smtplib > | > |def main(): > | # Perform the search > | results = SearchEbay(['So long and thanks for all the fish', > | 'NOMATCHFOUND', > | 'Python Programming']) > | > | # Email the results > | Email('me at somewhere.com', > | 'you at somewhere.com', > | 'eBay Search Results', > | results) > | > |def SearchEbay(searchstrings): > | ' Search eBay for the desired items' > | searchURL = "http://search.ebay.com/%s" > | results = "" > | s = "eBay Search Results:\n" > | print s, > | results += s > | for i in range(len(searchstrings)): > | > | # Build the search URL > | search = searchstrings[i].replace(' ', '-') > | s = searchURL % search + " : " > | print s, > | results += s > | > | # Download the URL > | url = urllib.urlopen(searchURL % search) > | data = url.read() > | url.close() > | > | # Write the URL to a file for debugging > | fd = open('ebay %d.html' % i, 'w') > | fd.write(data) > | fd.close() > | > | # Search for the number of items found > | c = data.find('items found for') > | if c >= 0: > | start = data.rfind('', 0, c) + 3 > | stop = data.find('', start + 1) > | cnt = data[start:stop] > | else: > | cnt = '0' > | s = "%s items found.\n" % cnt > | print s, > | results += s > | > | return results > | > |def Email(fromaddr, toaddr, subject, msg): > | ' Send email' > | msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % \ > | (fromaddr, toaddr, subject, msg)) > | server = smtplib.SMTP('your.smtp.server.here') > | server.set_debuglevel(1) > | server.sendmail(fromaddr, toaddr, msg) > | server.quit() > | > |main() From aleaxit at yahoo.com Sat Jan 22 04:10:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 10:10:36 +0100 Subject: need help on need help on generator... References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> Message-ID: <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> Francis Girard wrote: ... > But besides the fact that generators are either produced with the new "yield" > reserved word or by defining the __new__ method in a class definition, I > don't know much about them. Having __new__ in a class definition has nothing much to do with generators; it has to do with how the class is instantiated when you call it. Perhaps you mean 'next' (and __iter__)? That makes instances of the class iterators, just like iterators are what you get when you call a generator. > In particular, I don't know what Python constructs does generate a generator. A 'def' of a function whose body uses 'yield', and in 2.4 the new genexp construct. > I know this is now the case for reading lines in a file or with the new > "iterator" package. Nope, besides the fact that the module you're thinking of is named 'itertools': itertools uses a lot of C-coded special types, which are iterators but not generators. Similarly, a file object is an iterator but not a generator. > But what else ? Since you appear to conflate generators and iterators, I guess the iter built-in function is the main one you missed. iter(x), for any x, either raises an exception (if x's type is not iterable) or else returns an iterator. > Does Craig Ringer answer mean that list > comprehensions are lazy ? Nope, those were generator expressions. > Where can I find a comprehensive list of all the > lazy constructions built in Python ? That's yet a different question -- at least one needs to add the built-in xrange, which is neither an iterator nor a generator but IS lazy (a historical artefact, admittedly). But fortunately Python's built-ins are not all THAT many, so that's about it. > (I think that to easily distinguish lazy > from strict constructs is an absolute programmer need -- otherwise you always > end up wondering when is it that code is actually executed like in Haskell). Encapsulation doesn't let you "easily distinguish" issues of implementation. For example, the fact that a file is an iterator (its items being its lines) doesn't tell you if that's internally implemented in a lazy or eager way -- it tells you that you can code afile.next() to get the next line, or "for line in afile:" to loop over them, but does not tell you whether the code for the file object is reading each line just when you ask for it, or whether it reads all lines before and just keeps some state about the next one, or somewhere in between. The answer for the current implementation, BTW, is "in between" -- some buffering, but bounded consumption of memory -- but whether that tidbit of pragmatics is part of the file specs, heh, that's anything but clear (just as for other important tidbits of Python pragmatics, such as the facts that list.sort is wickedly fast, 'x in alist' isn't, 'x in adict' IS...). Alex From steve at holdenweb.com Fri Jan 14 17:46:31 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 17:46:31 -0500 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <41e5ebee.709560864@news.oz.net> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <41e5ebee.709560864@news.oz.net> Message-ID: Bengt Richter wrote: > On 12 Jan 2005 14:46:07 -0800, "Chris Lasher" wrote: > [...] > Others have probably solved your basic problem, or pointed > the way. I'm just curious. > > Given that the information content is 2 bits per character > that is taking up 8 bits of storage, there must be a good reason > for storing and/or transmitting them this way? I.e., it it easy > to think up a count-prefixed compressed format packing 4:1 in > subsequent data bytes (except for the last byte which have > less than 4 2-bit codes). > > I'm wondering how the data is actually used once records are > retrieved. (but I'm too lazy to explore the biopython.org link). > Revealingly honest. Of course, adopting an encoding that only used two bits per base would make it impossible to use the re module to search for patterns in them, for example. So the work of continuously translating between representations might militate against more efficient representations. Or, of course, it might not :-) it's-only-storage-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From ncoghlan at iinet.net.au Mon Jan 17 05:11:22 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 17 Jan 2005 20:11:22 +1000 Subject: (objects as) mutable dictionary keys In-Reply-To: References: Message-ID: <41EB8F4A.2080301@iinet.net.au> Antoon Pardon wrote: > What are good arguments or bad and how much weight they have depends > on the person and on the circumstances. So a simple rule like: > Never use a mutable as a key in a dictionary will sometimes not be > the best solution. True - but I think a purely identity based dictionary *is* the solution for most such cases where the standard Python rule doesn't apply :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ggg at zzz.it Thu Jan 6 13:27:18 2005 From: ggg at zzz.it (deelan) Date: Thu, 06 Jan 2005 19:27:18 +0100 Subject: File Handling Problems Python I/O In-Reply-To: <1105034789.700445.291380@z14g2000cwz.googlegroups.com> References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> <1105034789.700445.291380@z14g2000cwz.googlegroups.com> Message-ID: Josh wrote: > Peter, > > Thank you for the rookie correction. That was my exact problem. I > changed the address to use forward slashes and it works perfect. I did > not know that a backslash had special meaning within a string, but now > I do! Thanks again you may want to check "python gotchas" to avoid other typical newbie errors: HTH, deelan -- "Vedrai come ti tratteranno le mie TV" Berlusconi a Follini (Luglio 2004) From mt at 3planes.com Sun Jan 30 23:04:26 2005 From: mt at 3planes.com (Michael Tobis) Date: 30 Jan 2005 20:04:26 -0800 Subject: Fortran pros and cons (was Re: Coding style article with interesting section on white space) In-Reply-To: <1107124832.327010.181490@f14g2000cwb.googlegroups.com> References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> <1107105022.827941.114510@c13g2000cwb.googlegroups.com> <1107124832.327010.181490@f14g2000cwb.googlegroups.com> Message-ID: <1107144265.980844.9830@z14g2000cwz.googlegroups.com> beliavsky at aol.com wrote: > Michael Tobis wrote: > Fortran 90/95 is more expressive than Fortran 77 in many ways, as > described in ... > http://www.nr.com/CiP97.pdf . > > ... expresses more science per > line of code and per programming workday. The example shown on p 10 illustrates a shorter piece of code in f90 than in f77, but it is not obviously more expressive or less complex. Arguably the f77 code is easier to write and maintain, even though it has more linefeeds in it, so I find the example far from compelling. In fact, I find the f90 example impenetrable. Specifically, what does array_copy(source,dest,n,nn) do? I note that n and nn are uninitialized at call time. Are these outputs from array_copy(), appearing, in that inimitable Fortran way, in the call signature? Here it is in Python with NumArray: b = sort(compress(less(v,200.) * greater(v,100.),m )) result = b[(len(b)+3)//4] I certainly think this example is competitive for whatever that's worth. It has the added benefit of handling the case of an empty list with a nice catchable IndexError exception. However, if this were intended to be maintainable code I would find it most effectively expressed something like this: ... def magthresh(vel,mag,vmin=100.,vmax=200.): ... selector = less(vel,vmax) * greater(vel,vmin) ... sortedmags = sort(compress(selector,mag)) ... if len(sortedmags): ... index = (len(sortedmags) + 3) // 4 ... return sortedmags[index] ... else: ... raise IndexError,"No velocities in range." mt From francis.girard at free.fr Thu Jan 27 15:54:58 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 27 Jan 2005 21:54:58 +0100 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: <200501272154.58220.francis.girard@free.fr> Oops, I misunderstood what you said. I understood that it was now the case that objects of different types are not comparable by default whereas you meant it as a planned feature for version 3. I really hope that it will indeed be the case for version 3. Francis Girard Le jeudi 27 Janvier 2005 21:29, Steven Bethard a ?crit?: > Francis Girard wrote: > > Le jeudi 27 Janvier 2005 20:16, Steven Bethard a ?crit : > >>flamesrock wrote: > >>>The statement (1 > None) is false (or any other value above 0). Why is > >>>this? > >> > >>What code are you executing? I don't get this behavior at all: > >> > >>py> 100 > None > >>True > >>py> 1 > None > >>True > >>py> 0 > None > >>True > >>py> -1 > None > >>True > >>py> -100 > None > >>True > > > > Wow ! What is it that are compared ? I think it's the references (i.e. > > the adresses) that are compared. The "None" reference may map to the > > physical 0x0 adress whereas 100 is internally interpreted as an object > > for which the reference (i.e. address) exists and therefore greater than > > 0x0. > > > > Am I interpreting correctly ? > > Actually, I believe None is special-cased to work like this. From > object.c: > > static int > default_3way_compare(PyObject *v, PyObject *w) > { > ... > if (v->ob_type == w->ob_type) { > ... > Py_uintptr_t vv = (Py_uintptr_t)v; > Py_uintptr_t ww = (Py_uintptr_t)w; > return (vv < ww) ? -1 : (vv > ww) ? 1 : 0; > } > ... > /* None is smaller than anything */ > if (v == Py_None) > return -1; > if (w == Py_None) > return 1; > ... > } > > So None being smaller than anything (except itself) is hard-coded into > Python's compare routine. My suspicion is that even if/when objects of > different types are no longer comparable by default (as has been > suggested for Python 3.0), None will still compare as smaller than > anything... > > Steve From case.nelson at gmail.com Tue Jan 11 18:39:29 2005 From: case.nelson at gmail.com (Case Nelson) Date: 11 Jan 2005 15:39:29 -0800 Subject: Help Optimizing Word Search Message-ID: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Hi there I've just been playing around with some python code and I've got a fun little optimization problem I could use some help with. Basically, the program needs to take in a random list of no more than 10 letters, and find all possible mutations that match a word in my dictionary (80k words). However a wildcard letter '?' is also an acceptable character which increases the worst case time significantly. So if the letters are ['a','b','c'] check a, b, c, ab, ac, ba, bc, ca, cb, abc, acb, bac, bca, cab, cba where only a, ba and cab would be added to the dict of words. If the letters are ['?','?'] check a-z, aa, ab, ac, ad, ..., az, ba, bb, bc, bd, ..., zz I'm using a trie structure to load and query my dictionary, which returns a 1 if the word is found, 4 if a partial word is found, and 3 if there is no possible word. I guess I'm wondering if anyone could think of a faster way to deal with the wildcards, perhaps removing the inner for-loop or else something entirely different (iterative, don't use the trie?). Any other suggestions would be welcome findword recursion runs in 9.16300010681 secs words.log is simply my list of words: ['hats', 'easts', 'baizes',...,'sash'] --- Code Begin --- PY> import trie PY> import time PY> PY> print 'loading trie ...', PY> mytrie = trie.Trie('dicts.txt') PY> print 'done.' PY> PY> alpha = list('abcdefghijgklmnopqrstuvwxyz') PY> PY> words = {} PY> def findword(word, letters): PY> # run out of letters, recursion stop point PY> if letters == []: PY> return PY> PY> if word != "": PY> # Check if word is valid PY> result = mytrie.query(word) PY> PY> # Found a word, add it to the database PY> if result == 1: PY> words[word] = 1 PY> PY> # No other word starts with my current word, recursion stop point PY> if result == 3: PY> return PY> PY> # Run through every letter in our list PY> for i,letter in enumerate(letters): PY> # Remove current letter and recurse PY> newletters = letters[:] PY> newletters.pop(i) PY> PY> # if current letter is ? must recurse through all 26 letters PY> if letter == '?': PY> for c in alpha: PY> # recurse word+wildcard letter PY> findword(word+c,newletters) PY> else: PY> # recurse word+letter PY> findword(word+letter,newletters) PY> PY> letters = list('abae?s?') PY> s = time.time() PY> findword("",letters) PY> print time.time() - s PY> PY> output = open('words.log','w') PY> print >> output, words.keys() PY> output.close() PY> --- Code End --- Thanks (Hopefully google doesn't eat my whitespace) From info at dohnosoft.com Sat Jan 1 14:21:02 2005 From: info at dohnosoft.com (DohnoSoft) Date: Sat, 1 Jan 2005 11:21:02 -0800 Subject: Publish your program for free and enjoy worry free earning. 100% FREE (AND WE MEAN IT - FREE) Message-ID: Dear software developer!!! If you have some program or utility that you think may be interesting to somebody else, go ahead and submit it to www.DohnoSoft.com This is 100% FREE!!! and DohnoSoft will take care of all issues related to sales, payments and customer support. You will just enjoy worry free earning, which will be 89% of each sold program. NO CREDIT CARDS, BANK INFORMATION OR ANY OTHER PAYMENT INFORMATION IS REQUIRED. After DohnoSoft sends money with PayPal, you receive an email letting you know about your payment. After clicking on the link included in the email, you can log in to PayPal or sign up for a new account (100% FREE). The money will immediately appear in your account balance. Learn more about it on www.dohnosoft.com Thank you, Problems? Questions? From sjmachin at lexicon.net Sun Jan 23 16:59:31 2005 From: sjmachin at lexicon.net (John Machin) Date: 23 Jan 2005 13:59:31 -0800 Subject: Fuzzy matching of postal addresses [1/1] References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <1106517571.768306.23430@f14g2000cwb.googlegroups.com> Andrew McLean wrote: > In case anyone is interested, here is the latest. > def insCost(tokenList, indx, pos): > """The cost of inserting a specific token at a specific normalised position along the sequence.""" > if containsNumber(tokenList[indx]): > return INSERT_TOKEN_WITH_NUMBER + POSITION_WEIGHT * (1 - pos) > elif indx > 0 and containsNumber(tokenList[indx-1]): > return INSERT_TOKEN_AFTER_NUMBER + POSITION_WEIGHT * (1 - pos) > elif tokenList[indx][0] in minorTokenList: > return INSERT_MINOR_TOKEN > else: > return INSERT_TOKEN + POSITION_WEIGHT * (1 - pos) > > def delCost(tokenList, indx, pos): > """The cost of deleting a specific token at a specific normalised position along the sequence. > This is exactly the same cost as inserting a token.""" > return insCost(tokenList, indx, pos) Functions are first-class citizens of Pythonia -- so just do this: delCost = insCost Re speed generally: (1) How many addresses in each list and how long is it taking? On what sort of configuration? (2) Have you considered using pysco -- if not running on x86 architecture, consider exporting your files to a grunty PC and doing the match there. (3) Have you considered some relatively fast filter to pre-qualify pairs of addresses before you pass the pair to your relatively slow routine? Soundex?? To put it bluntly, the _only_ problem to which soundex is the preferred solution is genealogy searching in the US census records, and even then one needs to know what varieties of the algorithm were in use at what times. I thought you said your addresses came from authoritative sources. You have phonetic errors? Can you give some examples of pairs of tokens that illustrate the problem you are trying to overcome with soundex? Back to speed again: When you look carefully at the dynamic programming algorithm for edit distance, you will note that it is _not_ necessary to instantiate the whole NxM matrix -- it only ever refers to the current row and the previous row. What does space saving have to do with speed, you ask? Well, Python is not FORTRAN; it takes considerable effort to evaluate d[i][j]. A relatively simple trick is to keep 2 rows and swap (the pointers to) them each time around the outer loop. At the expense of a little more complexity, one can reduce this to one row and 3 variables (north, northwest, and west) corresponding to d[i-1][j], d[i-1][j-1], and d[i][j-1] -- but I'd suggest the simple way first. Hope some of this helps, John From Scott.Daniels at Acm.Org Mon Jan 10 16:35:42 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 10 Jan 2005 13:35:42 -0800 Subject: Writing huge Sets() to disk In-Reply-To: References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> Message-ID: <41e2f24d$1@nntp0.pdx.net> Tim Peters wrote: > [Martin MOKREJ?] >> just imagine, you want to compare how many words are in English, German, >>Czech, Polish disctionary. You collect words from every language and record >>them in dict or Set, as you wish. > > Call the set of all English words E; G, C, and P similarly. > >> Once you have those Set's or dict's for those 4 languages, you ask >>for common words > > This Python expression then gives the set of words common to all 4: > E & G & C & P >>and for those unique to Polish. > P - E - G - C One attack is to define a hash to get sizes smaller. Suppose you find your word sets are 10**8 large, and you find you need to deal with sets of size 10**6. Then if you define a hash that produces an integer below 100, you'll find: E & G & C & P == Union(E_k & G_k & C_k & P_k) for k in range(100) P - E - G - C == Union(P_k - E_k - G_k - C_k) for k in range(100) where X_k = [v for v in X if somehash(v) == k] This means, you can separate the calculation into much smaller buckets, and combine the buckets back at the end (without any comparison on the combining operations). For calculating these two expressions, you can dump values out to a file per hash per language, sort and dupe-elim the contents of the various files (maybe dupe-elim on the way out). Then hash-by-hash, you can calculate parts of the results by combining iterators like inboth and leftonly below on iterators producing words from files. def dupelim(iterable): source = iter(iterable) former = source.next() # Raises StopIteration if empty yield former for element in source: if element != former: yield element former = element def inboth(left, right): '''Take ordered iterables and yield matching cases.''' lsource = iter(left) lhead = lsource.next() # May StopIteration (and we're done) rsource = iter(right) for rhead in rsource: while lhead < rhead: lhead = lsource.next() if lhead == rhead: yield lhead lhead = lsource.next() def leftonly(left, right): '''Take ordered iterables and yield matching cases.''' lsource = iter(left) rsource = iter(right) try: rhead = rsource.next() except StopIteration: # empty right side. for lhead in lsource: yield lhead else: for lhead in lsource: try: while rhead < lhead: rhead = rsource.next() if lhead < rhead: yield lhead except StopIteration: # Ran out of right side. yield lhead for lhead in lsource: yield lhead break > Real-word dictionaries shouldn't be a problem. I recommend you store > each as a plain text file, one word per line. Then, e.g., to convert > that into a set of words, do > > f = open('EnglishWords.txt') > set_of_English_words = set(f) > f.close() > > You'll have a trailing newline character in each word, but that > doesn't really matter. > > Note that if you sort the word-per-line text files first, the Unix > `comm` utility can be used to perform intersection and difference on a > pair at a time with virtually no memory burden (and regardless of file > size). In fact, once you've sorted these files, you can use the iterators above to combine those sorted files. For example: Ponly = open('polishonly.txt', 'w') every = open('every.txt', 'w') for hashcode in range(100): English = open('english_%s.txt' % hashcode) German = open('german_%s.txt' % hashcode) Czech = open('czech_%s.txt' % hashcode) Polish = open('polish_%s.txt' % hashcode) for unmatched in leftonly(leftonly(leftonly(dupelim(Polish), dupelim(English)), dupelim(German)), dupelim(Czech)): Ponly.write(unmatched) English.seek(0) German.seek(0) Czech.seek(0) Polish.seek(0) for matched in inboth(inboth(dupelim(Polish), dupelim(English)), inboth(dupelim(German), dupelim(Czech))): every.write(matched) English.close() German.close() Czech.close() Polish.close() Ponly.close() every.close() --Scott David Daniels Scott.Daniels at Acm.Org From pierre.barbier at cirad.fr Tue Jan 18 08:29:56 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Tue, 18 Jan 2005 14:29:56 +0100 Subject: extension module, thread safety? In-Reply-To: References: <41ecbaae$0$1046$626a14ce@news.free.fr> <41eccfe4$0$16621$636a15ce@news.free.fr> Message-ID: <41ed0ee9$0$2522$636a15ce@news.free.fr> Nick Coghlan a ?crit : > The Python 2.4 docs claim the functions were added in Python 2.3, even > though they aren't documented in the 2.3.4 docs. > > The 2.3 release PEP (PEP 283) confirms that PEP 311 (which added these > functions) went in. Indeed, I just tested it and now it works fine :) Thanks a lot :) > > Cheers, > Nick. > From tim.golden at viacom-outdoor.co.uk Tue Jan 4 09:24:14 2005 From: tim.golden at viacom-outdoor.co.uk (Tim G) Date: 4 Jan 2005 06:24:14 -0800 Subject: Problem remotely shutting down a windows computer with python In-Reply-To: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> References: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> Message-ID: <1104848654.965978.63000@z14g2000cwz.googlegroups.com> > I have a problem when using the python script found here: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/360649 > > It is a script to remotely shutdown a windows computer. When I use it, > the computer shuts down, but doesn't power off like with a regular > shutdown. It stays on the "Safe to power off" screen and I have to push > the power button to actually power off. Anyone know why this happens > with this script? Thanks for any help. > > Eric I see that others have answered the question pretty completely, but just to add the obligatory WMI solution: [ assumes you're using the wmi module from http://tgolden.sc.sabren.com/python/wmi.html ] import wmi c = wmi.WMI (computer="other_machine", privileges=["RemoteShutdown"]) os = c.Win32_OperatingSystem (Primary=1)[0] os.Win32Shutdown (Flags=12) The Flags=12 bit should shut down all the way. TJG From skip at pobox.com Sun Jan 30 22:20:24 2005 From: skip at pobox.com (Skip Montanaro) Date: Sun, 30 Jan 2005 21:20:24 -0600 Subject: {Spam?} Re: naive doc question In-Reply-To: References: <5175a81c050129163826fcd734@mail.gmail.com> Message-ID: <16893.41976.351896.710133@montanaro.dyndns.org> >> I wanted a list of all the methods of dict for example... where can i >> find it? Terry> Lib Ref 2.3.8 Mapping Types. Do browse chapter 2 so you know Terry> what is there. I think the best doc page to bookmark is the global module index: http://docs.python.org/lib/modindex.html Not only does it give you a quick index to the modules, but if you click __builtin__ it will refer you to section 2.1. In the dev docs (2.5a0) it refers you to chapter 2, even better as far as I'm concerned. With the above bookmark I don't really have to remember where much else in the docs live. Skip From peter at engcorp.com Thu Jan 20 23:39:19 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Jan 2005 23:39:19 -0500 Subject: global variable, ok for string, bad for int In-Reply-To: <41f07e65$1_2@aeinews.> References: <41f07e65$1_2@aeinews.> Message-ID: francisl wrote: > I have a problem when I declare global variable. > If it is string, dict, array or tuple, everything goes fine, but with > int, I get an "used before declaration" error. > > here a sample : > vardict = {'un':1, 'deux':2} > > def print_value(): > print vardict['un'] > ######### ok, that works > > -------------------- > #!/bin/python > varint = 1 > > def print_value(): > print varint > ######### ok, that failed Please *always* post tracebacks, the actual traceback cut and pasted with the mouse from your session, when you are asking for help with errors like this. There is nothing called a "used before declaration" error... Was what you actually got an "UnboundLocalError: local variable 'varint' referenced before assignment", or something else? Don't retype: cut and paste. Also, please post only the actual code you are running, reduced to the simplest form which still reproduces the problem. The above code runs perfectly well, even if you add the missing call to print_value() at the end of the module. -Peter From cybermanxu at hotmail.com Fri Jan 21 17:59:55 2005 From: cybermanxu at hotmail.com (Jinming Xu) Date: Fri, 21 Jan 2005 16:59:55 -0600 Subject: Tuple size and memory allocation for embedded Python In-Reply-To: <1f7befae0501211451402a79aa@mail.gmail.com> Message-ID: >From: Tim Peters >Reply-To: Tim Peters >To: python-list at python.org >Subject: Re: Tuple size and memory allocation for embedded Python >Date: Fri, 21 Jan 2005 17:51:21 -0500 > >[Jinming Xu] > >> Python seems unstable, when allocating big memory. For > >> example, the following C++ code creates a tuple of tuples: > >> > >> PyObject* arCoord = PyTuple_New(n); > >> double d = 1.5; > >> for(int i=0; i >> { > >> PyObject* coord = PyTuple_New(2); > >> PyTuple_SetItem(coord,0, PyFloat_FromDouble(d));//x > >> PyTuple_SetItem(coord,1, PyFloat_FromDouble(d));//y > >> PyTuple_SetItem(arCoord,i, coord); > >> } > >> > >> When the n is small, say 100, the code works fine. when n > >> is big, say > 10,000, Python has trouble allocating > >> memory, saying: > >> > >> "Exception exceptions.IndexError: 'tuple index out of range' > >> in 'garbage collection' ignored > >> Fatal Python error: unexpected exception during garbage > >> collection > >> Aborted" > >[Craig Ringer] > > You're not checking for errors from PyTuple_SetItem. > >Or from PyTuple_New(), or from PyFloat_FromDouble(). They can all >fail, and indeed: > > > You need to do so, otherwise exceptions will go uncaught > > and may pop up at weird points later in your software's > > execution, or crash things. > >That's right. There's no point thinking about this at all before >every C API call is checked for an error return. > >BTW, since the error occurred during garbage collection, there's >really no reason to believe that the true cause of the problem is in >the code shown. It could simply be that allocating a whole lot of >tuples here triggers a round of garbage collection, which in turn >reveals an error in code we haven't been shown. In fact, I expect >that's actually the case. The possible errors the OP is ignoring here >are overwhemingly possible failures of malloc() to find more memory, >and in those cases the C API calls shown would return NULL, and a >segfault would be very likely soon after. >-- >http://mail.python.org/mailman/listinfo/python-list Hi folks, Thank you all for your prompt answers. I'll take a look for my code in the days coming. Have a good weekend! Jinming _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! hthttp://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From H.Duerer at gmx.net Thu Jan 27 11:44:44 2005 From: H.Duerer at gmx.net (Holger Duerer) Date: Thu, 27 Jan 2005 16:44:44 +0000 Subject: parsing WSDL References: <6bc0c3c.0501270529.5b9d8e00@posting.google.com> Message-ID: <87oefa7rer.fsf@ronaldann.demon.co.uk> >>>>> "Alessandro" == Alessandro Crugnola writes: Alessandro> Is there a way, maybe using 4suite, to read a wsdl Alessandro> file and find for every method all the input/output Alessandro> params and their type? Have you had a look at the Python WS tools? They do have some sort of WSDL support, so I assume you could get the info from those classes. http://pywebsvcs.sf.net/ Holger From oliver.eichler at dspsolutions.de Fri Jan 28 03:50:47 2005 From: oliver.eichler at dspsolutions.de (Oliver Eichler) Date: Fri, 28 Jan 2005 09:50:47 +0100 Subject: get list of member variables from list of class Message-ID: Hi what will be the fastest solution to following problem class a: def __init__(self): self.varA = 0 self.varB = 0 s.o. ... listA = [a]*10 varA = [] varB = [] for l in listA: varA.append(l.varA) varB.append(l.varB) s.o. ... I could think of: [varA.append(l.varA) for l in listA] [varB.append(l.varB) for l in listA] s.o. ... But is this faster? After all I have to iterate over listA several times. Any better solutions? Oliver From zhen.ren at gmail.com Thu Jan 27 14:04:55 2005 From: zhen.ren at gmail.com (Blues) Date: 27 Jan 2005 11:04:55 -0800 Subject: gnuplot on Canvas widget Message-ID: <1106852695.371569.234820@f14g2000cwb.googlegroups.com> Hey, I have used two great models - Tkinter and Gnuplot.py - for a while. I can display an image on a Canvas widget using Tkinter and I can also generate a gnuplot from Python on the fly in a separate window. Does anyone know how to display such a gnuplot on the Canvas widget with an image in it? Thanks. Michael From jtr at ofb.net Mon Jan 3 18:56:31 2005 From: jtr at ofb.net (John Reese) Date: Mon, 3 Jan 2005 23:56:31 +0000 (UTC) Subject: using HTTP Digest auth with arbitrary HTTP methods? References: Message-ID: On 03 Jan 2005 18:11:06 +0000, John J. Lee wrote: > (Re ternary operator: Everybody who read this list at certain times in > the past is painfully aware of that fact, and of precisely why it's > not quite true, and of all the syntax alternatives for real ternary > conditionals that will never be part of Python ;-) Yeah, I ran across the PEP after I posted this. Sorry to bring up a sore subject.... > Nobody is really in charge: just go ahead and submit a patch. Drop me > an email when you do, and I'll try to review it. The only reason > urllib2 doesn't already do arbitrary HTTP methods is that nobody has > spent the time to think carefully if a .set_method() really is the > right way to do it, then followed through with the work needed to get > a patch applied. Patch id #1095362 on Sourceforge. It turns out one of the bugs had already been fixed in CVS -- the digest bug was the only one left, so this is a one-line fix. > > As always, a precondition for change is that somebody thinks something > through carefully, writes tests, documentation, patch and submits all > three to the SF patch tracker with a brief explanation like the one > you give above. > > BTW, Greg Stein started work on adding the stuff you need at the > httplib level (as module httpx). He seems too busy to finish it, but > see modules httpx and davlib (one or both are in the Python CVS > sandbox). He thinks httplib is a better place for DAV than urllib2, > and he should know. But go ahead and fix urllib2 anyway... :-) These files are 2 and 3 years old. He's probably right that an interface more like httplib would be more appropriate for a DAV client; urllib2 is more about generalizing open() to use URLs than fully exposing the protocol. But urllib2 does have all those convenient handler-chains, and a good DAV client needs to handle a lot of those same situations, so it might be a good idea to at least find a way to share the handler classes. From kp8 at mac.com Tue Jan 11 15:58:04 2005 From: kp8 at mac.com (kpp9c) Date: 11 Jan 2005 12:58:04 -0800 Subject: Time script help sought! In-Reply-To: <1105474524.083536.129220@f14g2000cwb.googlegroups.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> Message-ID: <1105477084.525279.312970@f14g2000cwb.googlegroups.com> I also notice that there is the is the 'datetime' module, which is new to version 2.3, which i now have access to. My feeling is that this will do much of what i want, but i can't get my head round the standard library reference stuff http://www.python.org/doc/lib/module-datetime.html I don't have any texts with me either and it probably is too new to be in the Python Standard Library book by Fredrik Lundh or the Python Essential Reference by David Beazley -kevin- From frank at chagford.com Sat Jan 29 11:03:45 2005 From: frank at chagford.com (frank at chagford.com) Date: 29 Jan 2005 08:03:45 -0800 Subject: Line graphics on Linux console Message-ID: <1107014625.348051.239750@f14g2000cwb.googlegroups.com> Hi all I don't think this is strictly a Python problem, but as it manifests itself in one of my Python programs, I am hoping that somebody in this group can help me. The following is a message I sent to co.os.linux.setup - "My question concerns line graphics on a text-based console. ?My actual problem relates to a [Python] program I have written using ncurses, b?ut you can easily test it by running a program like minicom. If you call up the minicom menu, it should be surrounded by ?a nice box made up of horizontal and vertical lines, corners, etc. It used to work up until Redhat 7. Since upgrading to Redhat 9, and now Fedo?ra, it (and my program) has stopped working." I received the following reply from Thomas Dickey - "That's because Redhat uses UTF-8 locales, and the Linux cons?ole ignores vt100 line-drawing when it is set for UTF-8. (screen also d?oes this). ncurses checks for $TERM containing "linux" or "screen" (sin?ce there's no better clues for the breakage) when the encoding is UTF-8?, and doesn't try to use those escapes (so you would get +'s and -'s). co?mpiling/linking with libncursesw would get the lines back for a properly-wri?tten program." I don't really understand the last sentence. Does anyone know if it is possible to do this (or anything else) or am I stuck. TIA for any advice. Frank Millman From skip at pobox.com Mon Jan 17 10:01:25 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 17 Jan 2005 09:01:25 -0600 Subject: strange note in fcntl docs In-Reply-To: <20050117053949.GA28456@grulic.org.ar> References: <20050117053949.GA28456@grulic.org.ar> Message-ID: <16875.54085.712019.524951@montanaro.dyndns.org> John> In the fnctl docs for both python 2.3 and 2.4 there is a note at John> the bottom that says John> The os.open() function supports locking flags and is available on John> a wider variety of platforms than the lockf() and flock() John> functions, providing a more platform-independent file locking John> facility. John> however, in neither of those versions does os.open support any John> kind of mysterious "locking flags", nor is there any reference in John> os to any kind of locking magic (nor do any C open()s I know of John> support any kind of locking semantics). The note seems bogus; am I John> missing something, or should it be elided? I could have sworn that os.open supported the O_SHLOCK and O_EXLOCK flags. I'm pretty sure I've used them in the past, but don't see them now. (They aren't in 2.2 either.) If you try this: O_SHLOCK = 0x0010 O_EXLOCK = 0x0020 (those are the definitions on my Mac - YMMV) does os.open("somefile", O_SHLOCK|) work? Skip From http Sat Jan 1 19:41:05 2005 From: http (Paul Rubin) Date: 01 Jan 2005 16:41:05 -0800 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> Message-ID: <7xsm5kfyse.fsf@ruckus.brouhaha.com> beliavsky at aol.com writes: > Overall I agree with you and would like to have OPTIONAL static type > declarations in Python, as has often been discussed. But without > facilities for generic programming, such as templates in C++, static > type declarations can force one to duplicate a LOT of code, with one > sorting routine each for integer, floats, strings, etc. I don't see that big a problem. The current Python sorting routine operates on instances of class "object" and calls the __cmp__ method to do comparisons. Every class of sortable objects either defines a __cmp__ method or inherits one from some superclass, and sort calls those methods. Static type declarations would not require writing any additional sorting routines. From fumanchu at amor.org Wed Jan 19 16:38:06 2005 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 19 Jan 2005 13:38:06 -0800 Subject: RuntimeError: dictionary changed size during iteration Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398208@exchange.hqamor.amorhq.net> Roman Suzi wrote: > I think, the behaviour below is misfeature: > > >>> [e for e in vars()] > Traceback (most recent call last): > File "", line 1, in ? > RuntimeError: dictionary changed size during iteration > >>> e = None > >>> [e for e in vars()] > ['e', '__builtins__', 'rlcompleter', '__file__', '_[1]', > 'atexit', '__name__', > 'readline', '__doc__'] But not unexpected, since vars() returns a dictionary, and binding 'e' changes that dictionary while you are iterating over it. Try either: [e for e in vars().keys()] or e = None [e for e in vars()] or the generator expression if you have Python 2.4. Robert Brewer MIS Amor Ministries fumanchu at amor.org From g.franzkowiak at web.de Sat Jan 15 13:37:54 2005 From: g.franzkowiak at web.de (G.Franzkowiak) Date: Sat, 15 Jan 2005 19:37:54 +0100 Subject: interpret 4 byte as 32-bit float (IEEE-754) In-Reply-To: <41e952b9$1@nntp0.pdx.net> References: <34t1p2F4foiplU1@individual.net> <41e952b9$1@nntp0.pdx.net> Message-ID: <41E96302.4020003@web.de> Scott David Daniels schrieb: > franzkowiak wrote: > >> I've read some bytes from a file and just now I can't interpret 4 >> bytes in this dates like a real value. An extract from my program: >> def l32(c): >> return ord(c[0]) + (ord(c[1])<<8) + (ord(c[2])<<16) + >> (ord(c[3])<<24) >> ... >> value = l32(f.read(4)) <--- 3F 8C CC CD should be 1.11 >> > OK, here's the skinny (I used blocks & views to get the answer): > > import struct > bytes = ''.join(chr(int(txt, 16)) for txt in '3F 8C CC CD'.split()) > struct.unpack('>f', bytes) > > I was suspicious of that first byte, thought it might be an exponent, > since it seemed to have too many on bits in a row to be part of 1.11. > > -Scott David Daniels > Scott.Daniels at Acm.Org Ok, I the string exist with "mystr = f.read(4)" and the solution for this case is in your line "struct.unpack('>f', bytes)" But what can I do when I want the interpret the content from the Integer myInt (*myInt = 0x3F8CCCCD) like 4-byte-real ? This was stored with an othes system in a binary file to CD CC 8C 3F and now is it in python in value. The conversion is not possible. It's right... one of this bytes is an exponent. I want copy the memory content from the "value address" to "myReal address" and use print "%f" %myReal. Is myReal then the right format ? What can I do with python, in FORTH is it simple ( >f f. ) gf From sean_mcilroy at yahoo.com Mon Jan 10 22:48:44 2005 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 10 Jan 2005 19:48:44 -0800 Subject: unicode mystery Message-ID: I recently found out that unicode("\347", "iso-8859-1") is the lowercase c-with-cedilla, so I set out to round up the unicode numbers of the extra characters you need for French, and I found them all just fine EXCEPT for the o-e ligature (oeuvre, etc). I examined the unicode characters from 0 to 900 without finding it; then I looked at www.unicode.org but the numbers I got there (0152 and 0153) didn't work. Can anybody put a help on me wrt this? (Do I need to give a different value for the second parameter, maybe?) Peace, STM PS: I'm considering looking into pyscript as a means of making diagrams for inclusion in LaTeX documents. If anyone can share an opinion about pyscript, I'm interested to hear it. Peace From takarov2003 at yahoo.com Wed Jan 26 17:00:36 2005 From: takarov2003 at yahoo.com (takarov2003 at yahoo.com) Date: 26 Jan 2005 14:00:36 -0800 Subject: 20050126 find replace strings in file In-Reply-To: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> References: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> Message-ID: <1106776836.679242.167880@c13g2000cwb.googlegroups.com> Xah Lee wrote: > ? # -*- coding: utf-8 -*- > ? # Python > ? > ? import sys > ? > ? nn = len(sys.argv) > ? > ? if not nn==5: > ? print "error: %s search_text replace_text in_file out_file" % > sys.argv[0] > ? else: > ? stext = sys.argv[1] > ? rtext = sys.argv[2] > ? input = open(sys.argv[3]) > ? output = open(sys.argv[4],'w') I guess there is no way to check if the file opened fine? What if the filesystem or file is locked for this user/session. Pretty puny language if it cannot tell you that it cannot do what you tell it to. > ? > ? for s in input: > ? output.write(s.replace(stext,rtext)) > ? output.close() > ? input.close() Same for the close. Is there no way check a good close? > > ------------------------- > save this code as find_replace.py > run it like this: > python find_replace.py findtext replacetext in_file out_file > > the sys.argv is from sys. sys.argv[0] is the program's name itself. > > note the idiom > "for variable_name in file_object" > > note that since this code reads each > line in turn, so huge file is of no-problemo > > the code is based from Python > Cookbook of Alex Martelli & David > Ascher, page 121 > > in Python terminal, type help() then > 'FILES' and or 'sys' > for reference. > > try to modify this file for your > needs. > -------------------------------------- > In perl, similar code can be achieved. > the following code illustrates. > > if (scalar @ARGV != 4) {die "Wrong arg! Unix BNF: $0 > \n"} > $stext=$ARGV[0]; > $rtext=$ARGV[1]; > $infile = $ARGV[2]; > $outfile = $ARGV[3]; > open(F1, "<$infile") or die "Perl fucked up. Reason: $!"; > open(F2, ">$outfile") or die "Perl fucked up. Reason: $!"; In 7 years of perl programming, I have never seen an open error that had anything to do with perl processing. Normally, if I get an error, the file does not exist, or has permissions set so that the current user/session is not allowed to open the file. > while ($line = ) { > chomp($line); > $line =~ s/$stext/$rtext/g; > print F2 "$line\n"; > } > close(F1) or die "Perl fucked up. Reason: $!"; > close(F2) or die "Perl fucked up. Reason: $!"; Same here. Never seen Perl fuck up on closing a file. Usually something in the OS or file system that does it. > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html From Dennis.Benzinger at gmx.net Thu Jan 27 03:35:06 2005 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Thu, 27 Jan 2005 09:35:06 +0100 Subject: String Fomat Conversion In-Reply-To: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> Message-ID: <41f8a7b9$1@news.uni-ulm.de> mcg wrote: > Investigating python day 1: > > Data in file: > x y > 1 2 > 3 4 > 5 6 > > > Want to read file into an array of pairs. > > in c: scanf("%d %d",&x,&y)---store x y in array, loop. > > How do I do this in python?? > In the actual application, the pairs are floating pt i.e. -1.003 > Either do what the other posters wrote, or if you really like scanf try the following Python module: Scanf --- a pure Python scanf-like module http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/ Bye, Dennis From tmohr at s.netic.de Thu Jan 13 15:20:06 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Thu, 13 Jan 2005 21:20:06 +0100 Subject: reference or pointer to some object? References: Message-ID: Hi, > Could you give us a more concrete use case? My suspicion is that > anything complicated enough to be passed to a method to be modified will > probably be more than a simple int, float, str or tuple... In which > case, it will probably have methods to allow you to update it... yes, to be more explicit: I'm quite new to python and i wrote a small function that does a hexdump of a string. That string can be quite large, so i suspected a large overhead when the string would be copied and handed over to the function. But i think my understanding was wrong (though it is not yet clear). If i hand over a large string to a function and the function had the possibility to change it, wouldn't that mean that it is necessary to hand over a _copy_ of the string? Else, how could it be immutable? Thinking about all this i came to the idea "How would i write a function that changes a string with not much overhead?". def func(s): change s in some way, remove all newlines, replace some charaters by others, ... return s s = func(s) This seems to be a way to go, but it becomes messy if i hand over lots of parameters and expect some more return functions. Maybe it is because i did lots of perl programming, but func(\$s) looks easier to me. > In my case, rather than your original example, which you want to look > something like: > > def func(x): > x += 123 > > x = 5 > func(x) > > I'd just write: > > x = 5 > x += 123 You're right, of course. I'm sorry the second example is still a bit constructed, but i came across it by writing the hexdump utility and wanted to reduce overhead. Best regards, Torsten. From tonino.greco at gmail.com Fri Jan 21 06:46:13 2005 From: tonino.greco at gmail.com (Tonino) Date: 21 Jan 2005 03:46:13 -0800 Subject: tkinter socket client ? In-Reply-To: <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> Message-ID: <1106307973.536723.297940@z14g2000cwz.googlegroups.com> thanks for the reply . just one problem - I do not know how to sit in a "loop" accepting messages on the socket connection - writting them to the Text() widget - refreshing the the GUI - and then starting all over .... where do I put the loop for the socket ? Thanks Tonino From dave at pythonapocrypha.com Fri Jan 28 15:20:47 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Fri, 28 Jan 2005 13:20:47 -0700 Subject: Best python postgres module? In-Reply-To: <41fa75ef_1@news.arcor-ip.de> References: <41fa75ef_1@news.arcor-ip.de> Message-ID: <41FA9E9F.1070401@pythonapocrypha.com> Roland Heiber wrote: > i recently migrated from mysql to postgresql and did use severel python > postgres-modules. All do what they are designed for, so which one would > you use? psycopg, pygresql, pypgsql? psycopg seems to be the best > solution for heavy traffic/multiple connections .... i have no real > testing environment, so any advice which one to use for different > usecases would be nice. Hi Roland, We've been using psycopg (via Zope and straight Python programs) for about a year and haven't had any problems at all. We don't store much binary data so I don't know how well psycopg handles blobs and what-not, but performance and reliability has been fine. I have no idea how psycopg stacks up against the others; in the end we chose it because the project appeared to be active, it was easy enough to set up, and a few test scripts we made all worked (how's that for rigorous evaluation? ;-) ). HTH, Dave From reinhold-birkenfeld-nospam at wolke7.net Tue Jan 18 12:45:49 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 18 Jan 2005 18:45:49 +0100 Subject: [perl-python] 20050118 keyed list In-Reply-To: References: <1106027360.920787.321590@z14g2000cwz.googlegroups.com> Message-ID: <3550aeF4hi6bhU1@individual.net> J?rgen Exner wrote: >> ? # see "perldoc perldata" for an unix-styled course. > > Excuse me? Do you mind explaining where exactly perldata is "Unix-styled"? Remember: Perl == Unix == Satan. Reinhold From jtr at ofb.net Mon Jan 3 19:30:29 2005 From: jtr at ofb.net (John Reese) Date: Tue, 4 Jan 2005 00:30:29 +0000 (UTC) Subject: HTTP GET request with basic authorization? References: <7c60b60505010215123462c90e@mail.gmail.com> Message-ID: On 03 Jan 2005 18:27:52 +0000, John J. Lee wrote: > Jonas Galvez writes: > >> Christopher J. wrote: >> > I tried this, but it didn't work: >> > conn.request("GET", "/somepage.html", None, >> > {"AUTHORIZATION": "Basic username:password"}) > [...] >> import re, base64, urllib2 >> >> userpass = ('user', 'pass') >> url = 'http://somewhere' >> >> request = urllib2.Request(url) >> authstring = base64.encodestring('%s:%s' % userpass) >> authstring = authstring.replace('\n', '') >> request.add_header("Authorization", "Basic %s" % authstring) >> >> content = urllib2.urlopen(request).read() > > There are handlers in urllib2 to do this for you, you shouldn't need > to do it by hand. I rarely do, so I won't risk an example... > > > John > The way to do it with the handlers follows; oddly, it's just about as long. import urllib2 url = 'http://somewhere' realm, user, pass = 'realm', 'user', 'pass' hm = urllib2.HTTPPasswordMgrWithDefaultRealm() hm.add_password(realm, url, user, pass) od = urllib2.build_opener(urllib2.HTTPBasicAuthHandler(hm)) content = od.open(url).read() From simon.brunning at gmail.com Fri Jan 21 11:46:21 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 21 Jan 2005 16:46:21 +0000 Subject: circular iteration In-Reply-To: References: Message-ID: <8c7f10c6050121084633a474ae@mail.gmail.com> On 21 Jan 2005 08:31:02 -0800, Flavio codeco coelho wrote: > hi, > > is there a faster way to build a circular iterator in python that by doing this: > > c=['r','g','b','c','m','y','k'] > > for i in range(30): > print c[i%len(c)] I don''t know if it's faster, but: >>> import itertools >>> c=['r','g','b','c','m','y','k'] >>> for i in itertools.islice(itertools.cycle(c), 30): ... print i -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From maxm at mxm.dk Fri Jan 14 17:03:16 2005 From: maxm at mxm.dk (Max M) Date: Fri, 14 Jan 2005 23:03:16 +0100 Subject: oddities in the datetime module In-Reply-To: References: <41e79a1a$0$264$edfadb0f@dread12.news.tele.dk> Message-ID: <41e84175$0$258$edfadb0f@dread12.news.tele.dk> Serge Orlov wrote: > Max M wrote: > Yes, you did. datetime.timetuple is those who want *time module* format, you should use datetime.data, datetime.time, datetime.year > and so on... > > As they say, if the only tool you have is timetuple, everything looks like tuple > Try this: > >>>>dt = datetime(2005, 1, 1, 12, 0, 0) >>>>dt.date() > > datetime.date(2005, 1, 1) This doesn't solve it. I don't think you understand my issue. First of, it should be possible to easily convert between the datetime objects. And eg. the date object doesn't have a datetime() method. Which it could easily have. Neither does time. They could have. But I don't think that is the way to solve it. It is a problem if you make a subclass of datetime. Often you will ned to make datetime arithmetics with the new class. Like: datetime_subclass_1 + datetime_subclass_2 The result of that is a plain datetime In that case you will rather want your own subclass returned. But subclasses of datetime returns datetime objects. Not the subclass. So to do an add of your own objects you must convert the output to your own class "manually" class my_datetime(datetime): def __add__(self, other): result = datetime.__add__(self, other) return my_datetime(result.timetuple()[:6]) datetime(), time() etc. methods will not help with this. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From brianobush at gmail.com Thu Jan 13 23:36:19 2005 From: brianobush at gmail.com (brianobush at gmail.com) Date: 13 Jan 2005 20:36:19 -0800 Subject: Class initialization from a dictionary, how best? Message-ID: <1105677379.632236.17020@z14g2000cwz.googlegroups.com> # # My problem is that I want to create a # class, but the variables aren't known # all at once. So, I use a dictionary to # store the values in temporarily. # Then when I have a complete set, I want to # init a class from that dictionary. # However, I don't want to specify the # dictionary gets by hand # since it is error prone. # Thanks for any ideas, Brian # So I have a class defined that accepts a number of variables # and they must be all present at object creation time. class Test: def __init__(self, a, b, c): self.a = a self.b = b self.c = c def __str__(self): return '%s, %s, %d' % (self.a, self.b, self.c) # For example: t1 = Test('asd', 'sdf', 9) print t1 # However, due to parsing XML, I am # creating the values incrementally # and I want to store them in a dictionary # and then map them easily to a class dictionary = {} # a mapping from source to destination mapping = { 'a': str, 'b': str, 'c': int, } # a sample source of values test_source = { 'a': 'test', 'b': 'asdf', 'c': 45 } # now we go through and extract the values # from our source and build the dictionary for attr_name, function in mapping.items(): dictionary[attr_name] = function(test_source.get(attr_name)) print dictionary # Here is the problem I want to avoid: # Having to list the variable names # as strings in multiple places. It is enought to # have them in the 'mapping' # dictionary above t2 = Test(dictionary.get('a'), dictionary.get('b'), dictionary.get('c')) print t2 From tdelaney at avaya.com Mon Jan 3 17:54:17 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 4 Jan 2005 09:54:17 +1100 Subject: Developing Commercial Applications in Python Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE02520251@au3010avexu1.global.avaya.com> Christophe Cavalaria wrote: > eeykay at gmail.com wrote: > >> Hello All, >> I am trying to convince my client to use Python in his new product. >> He is worried about the license issues. Can somebody there to point >> me any good commercial applications developed using python ?. The >> licence clearly says Python can be used for commercial applications. >> Is there any other implications like that of GPL to make the source >> open ? Thanks for any help. eeykay > Troika games use Python in their games. It seems you can even get the > source .py files for Vampires: Bloodlines :) Absolutely - it's a slightly modified version of 2.1.2. Troika also used Python for the Temple of Elemental Evil. I even compiled psyco to work with Bloodlines and modified the .py source to call it - worked perfectly well, but didn't give me any significant performance improvement :( I'm CPU limited, so I thought it was worth a try. I'm wondering if I can hack Python 2.4 into Bloodlines ... the biggest problem is that Bloodlines used .vpk files for packaging, and I believe the major modifications to 2.1 are to allow these to be read. I've already extracted all of these though ... Anyway, back to the original question: http://www.python.org/doc/faq/general.html#are-there-copyright-restricti ons-on-the-use-of-python Tim Delaney From jeff at ccvcorp.com Thu Jan 27 20:25:29 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 27 Jan 2005 17:25:29 -0800 Subject: inherit without calling parent class constructor? In-Reply-To: References: Message-ID: <10vj4ovqee29oc9@corp.supernews.com> Christian Dieterich wrote: > On D?ardaoin, Ean 27, 2005, at 14:05 America/Chicago, Jeff Shannon wrote: > >> the descriptor approach does. In either case, the calculation happens >> as soon as someone requests D.size ... > > Agreed. The calculation happens as soon as someone requests D.size. So > far so good. Well, maybe I'm just not into it deep enough. As far as I > can tell, In your class D the calculation happens for every > instantiation of D, right? For my specific case, I'd like a construct > that calculates D.size exactly once and uses the result for all > subsequent instantiations. Okay, so size (and the B object) is effectively a class attribute, rather than an instance attribute. You can do this explicitly -- class D(object): _B = None def __getattr__(self, attr): if self._B is None: if myB is None: myB = B() D._B = myB return getattr(self._B, attr) Now, when the B object is first needed, it's created (triggering that expensive calculation) and stored in D's class object. Since all instances of D share the class object, they'll all share the same instance of B. Probably not worth the trouble in this particular case, but maybe in another case... :) Jeff Shannon Technician/Programmer Credit International From aleaxit at yahoo.com Sat Jan 1 15:38:54 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 1 Jan 2005 21:38:54 +0100 Subject: what is lambda used for in real code? References: <1gpq3nl.8f2klu80m2z0N%aleaxit@yahoo.com> Message-ID: <1gpqbfo.66l1sy191iqz8N%aleaxit@yahoo.com> Steve Holden wrote: ... > >>And you'd create an anonymous type how, exactly? > > > >>>>type('',(),{}) ... > Indeed. And then you'd insert all the methods as lambdas by .... > > We both know that the Python language framework has enough introspection > capabilities to do this, but I'm pretty sure you wouldn't try to pretend > that this would represent a realistic programming style. Or am I wrong? Calling 'type' to make a new type on the fly is occasionally neat -- not quite as often as (say) using 'lambda', maybe;-). Neither should be a 'programming _style_' as opposed to an occasional convenience -- of the two, lambda has more sensible use cases, but is also more prone to overuse in practice. Also, the ability to call 'type' to make a type adds zero complexity or issues to the language: it's basically zero cost, just like the ability to call 'int' to make an int, and so on. This can't be said of lambda, alas: it has a non-zero cost in terms of (slightly) 'fattening' the language. Alex From apardon at forel.vub.ac.be Thu Jan 13 03:39:13 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jan 2005 08:39:13 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-01-12, Steve Holden schreef : > > Given that Guido is on record as saying that expressions aren't > statements because he wants those things to be separate, I don't really > see why there's this consistent pressure to reverse that decision. Well, it seems that Guido is wrong then. The documentation clearly states that an expression is a statement. More specifically, everywhere you can use a statement, you can simply use an expression according to the python syntax. That makes the set of expressions a subset of the set of statements and thus makes an expression a statement. > Which would be a worthier goal than trying to graft macros on to Python. > You responded that macros would be difficult to implement in m4 because > (in essence) of the indented structure of Python. I'm not convinced > they'd be any easier in Python, and I'm *certainly* not convinced that > their addition would improve Python's readability. > > At best it would offer new paradigms for existing constructs (violating > the "there should be one obvious way to do it" zen); at worst it would > obfuscate the whole language. That zen is already broken. Look at the number of answers one gets if a newbee askes for a ternary operator. I think that a simple ternary operator or macro's with an official supported macro that implemented the ternary operator would have been far closer to the spirit of only having one obvious way than what we have now. -- Antoon Pardon From steven.bethard at gmail.com Mon Jan 24 17:40:10 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 24 Jan 2005 15:40:10 -0700 Subject: Instances of class object not modifiable? In-Reply-To: References: Message-ID: Krzysztof Stachlewski wrote: > I tried to run the following piece of code: > > Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>o = object() >>>>o.a = 5 > > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'object' object has no attribute 'a' > > But if I do: > >>>>class c(object): >>>> pass >>>>o = c() >>>>o.a = 5 > > > ...then it, of course, works. > So what's wrong with the first example? It's an instance of class object. ;) If my memory serves me right, instances of object have no __dict__. py> o = object() py> o.__dict__ Traceback (most recent call last): File "", line 1, in ? AttributeError: 'object' object has no attribute '__dict__' Yup, that looks right. As I understand it, the reason for this is so that classes which *really* need to be memory efficient can define __slots__ instead and save some overhead. If you're interested in having a builtin object that can be used as above, you should help me rally for my Bunch type PEP. They haven't given me a PEP number for it yet, but a patch is available[1] and I've included the current draft of the PEP below. [1]http://sourceforge.net/tracker/?func=detail&atid=305470&aid=1094542&group_id=5470 Steve ---------------------------------------------------------------------- PEP: XXX Title: Generic Object Data Type Version: $Revision: 1.0 $ Last-Modified: $Date: 2004/11/29 16:00:00 $ Author: Steven Bethard Status: Draft Type: Standards Track Content-Type: text/x-rst Created: 29-Nov-2004 Python-Version: 2.5 Post-History: 29-Nov-2004 Abstract ======== This PEP proposes a standard library addition to support the simple creation of 'generic' objects which can be given named attributes without the need to declare a class. Such attribute-value mappings are intended to complement the name-value mappings provided by Python's builtin dict objects. Motivation ========== Python's dict objects provide a simple way of creating anonymous name-value mappings. These mappings use the __getitem__ protocol to access the value associated with a name, so that code generally appears like:: mapping['name'] Occasionally, a programmer may decide that dotted-attribute style access is more appropriate to the domain than __getitem__ style access, and that their mapping should be accessed like:: mapping.name Currently, if a Python programmer makes this design decision, they are forced to declare a new class, and then build instances of this class. When no methods are to be associated with the attribute-value mappings, declaring a new class can be overkill. This PEP proposes adding a simple type to the collections module of the standard library that can be used to build such attribute-value mappings. Providing such a type allows the Python programmer to determine which type of mapping is most appropriate to their domain and apply this choice with minimal effort. Some of the suggested uses include: Returning Named Results ----------------------- It is often appropriate for a function that returns multiple items to give names to the different items returned. The type suggested in this PEP provides a simple means of doing this that allows the returned values to be accessed in the usual attribute-style access:: >>> def f(x): ... return Bunch(double=2*x, squared=x**2) ... >>> y = f(10) >>> y.double 20 >>> y.squared 100 Representing Hierarchical Data ------------------------------ The type suggested in this PEP also allows a simple means of representing hierarchical data that allows attribute-style access:: >>> x = Bunch(spam=Bunch(rabbit=1, badger=[2, 3, 4]), ham='neewom') >>> x.spam.badger [2, 3, 4] >>> x.ham 'neewom' Rationale ========= As Bunch objects are intended primarily to replace simple, data-only classes, simple Bunch construction was a primary concern. As such, the Bunch constructor supports creation from keyword arguments, dicts, and sequences of (attribute, value) pairs:: >>> Bunch(eggs=1, spam=2, ham=3) Bunch(eggs=1, ham=3, spam=2) >>> Bunch({'eggs':1, 'spam':2, 'ham':3}) Bunch(eggs=1, ham=3, spam=2) >>> Bunch([('eggs',1), ('spam',2), ('ham',3)]) Bunch(eggs=1, ham=3, spam=2) To allow attribute-value mappings to be easily combined, the update method of Bunch objects supports similar arguments. If Bunch objects are used to represent hierarchical data, comparison of such objects becomes a concern. For this reason, Bunch objects support object equality:: >>> x = Bunch(parrot=Bunch(lumberjack=True, spam=42), peng='shrub') >>> y = Bunch(peng='shrub', parrot=Bunch(spam=42, lumberjack=True)) >>> z = Bunch(parrot=Bunch(lumberjack=True), peng='shrub') >>> x == y True >>> x == z False Note that support for the various mapping methods, e.g. __(get|set|del)item__, __len__, __iter__, __contains__, items, keys, values, etc. was intentionally omitted as these methods did not seem to be necessary for the core uses of an attribute-value mapping. If such methods are truly necessary for a given use case, this may suggest that a dict object is a more appropriate type for that use. Examples ========= Converting an XML DOM tree into a tree of nested Bunch objects:: >>> import xml.dom.minidom >>> def getbunch(element): ... result = Bunch() ... if element.attributes: ... result.update(element.attributes.items()) ... children = {} ... for child in element.childNodes: ... if child.nodeType == xml.dom.minidom.Node.TEXT_NODE: ... children.setdefault('text', []).append( ... child.nodeValue) ... else: ... children.setdefault(child.nodeName, []).append( ... getbunch(child)) ... result.update(children) ... return result ... >>> doc = xml.dom.minidom.parseString("""\ ... ... ... a text 1 ... ... b text ... a text 2 ... ... c text ... """) >>> b = getbunch(doc.documentElement) >>> b.a[0].b[1] Bunch(attr_b=u'3', text=[u' b text ']) Reference Implementation ======================== The code is available as SourceForge patch 1094542 [1]_. Open Issues =========== What should the type be named? Some suggestions include 'Bunch', 'Record' and 'Struct'. Where should the type be placed? The current suggestion is the collections module. References ========== .. [1] http://sourceforge.net/tracker/index.php?func=detail&aid=1094542&group_id=5470&atid=305470 .. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 End: From nun at example.com Sat Jan 15 06:24:50 2005 From: nun at example.com (Mitja) Date: Sat, 15 Jan 2005 12:24:50 +0100 Subject: How to del item of a list in loop? References: Message-ID: On Sat, 15 Jan 2005 15:27:08 -0500, skull wrote: > lst = [1, 2, 3] > for i in lst: > print i > if i == 2: > lst.remove(i) > > the result is: > > 1 > 2 As others have suggested, you can use a copy of the list. Alternatively and depending on what you're trying to accomplish (how complicated it is), lst = [i for i in lst if i!=2] might look better. -- Mitja From g.horvath at gmx.at Thu Jan 27 13:14:48 2005 From: g.horvath at gmx.at (Gregor Horvath) Date: Thu, 27 Jan 2005 19:14:48 +0100 Subject: HTML Tree View with
        and Message-ID: Hi, Before I reinvent the wheel I`d like to ask if someone has done this before since I did not find an advice at Google. The goal is to create a dynamic Tree View in HTML. Say I have a data strucure like this: structList = {'Sun':{'Sun.1':['Sun1.1','Sun1.2'],'Sun.2':['Sun2.1','Sun2.2']},'Kupa':['Kupa1']} I want to transform this into HTML:
        1. Sun
          1. Sun.1
            1. Sun1.1
            2. Sun1.2
          2. Sun.2
            1. Sun2.1
            2. Sun2.2
        2. Kupa
          1. Kupa1
        If the user clicks on a branch-link say 'Sun.1' then the branch below opens/closes (not printed by the servlet). Like a tree view control in an native GUI app. Has this, or a similar approach, been done before in python ( I am using webware/cheetah)? -- Greg From ncoghlan at iinet.net.au Fri Jan 7 10:34:18 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 01:34:18 +1000 Subject: sorting on keys in a list of dicts In-Reply-To: <10tr9ejf05pv660@corp.supernews.com> References: <10tr9ejf05pv660@corp.supernews.com> Message-ID: <41DEABFA.2020006@iinet.net.au> Jeff Shannon wrote: > I suppose that your version has the virtue that, if the sortkey value is > equal, items retain the order that they were in the original list, > whereas my version will sort them into an essentially arbitrary order. > Is there anything else that I'm missing here? Stability in sorting is a property not to be sneezed at - it means switching to sorting by a second key gives the effect of "sort by key 1, then by key 2", whereas that doesn't hold with an unstable sort algorithm. If you've ever used an application with an unstable sorting process and that only allows sorting a table on one column at a time, you'll appreciate the frustration that can cause :) Also, it's required to match the behaviour of the Python 2.4 version (which gets to take advantage of the stability of the builtin sort). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From foo at bar.com Sun Jan 16 11:38:00 2005 From: foo at bar.com (Steve Menard) Date: Sun, 16 Jan 2005 11:38:00 -0500 Subject: Integration with java (Jpype vs. JPE) In-Reply-To: References: <34s5krF4c85d5U1@individual.net> Message-ID: <41EA9868.70806@bar.com> Cameron Laird wrote: > In article <34s5krF4c85d5U1 at individual.net>, > Jon Perez wrote: > >>Can someone summarize in a nutshell what is the >>difference between JPype and JPE? > > > JPE's the original. It provided more functionality than JPype has > achieved so far, I believe (though that could change any day). I > think no one now maintains JPE. > > Someone really ought to include a couple of sentences to that effect > on the front page of . Well, Cameron summed it up pretty good :) I'd add that The only major (and yes I know it is VERY major) funtionailty missing in JPype is the ability to subclass Java classes in Python. On the other hand JPype will (soon) have functionality that JPE doesnt have. Java arrays can already (in 0.4) be iterated as regular Python collections. Version 0.5 will add that same behavior for Java collections (Map, List, Set, Iterator). Of course, the above is based on the JPE documentation, because I havent been able to get JPE to work. About Cameron's suggestion, sure. I'll do it as soon as I (or someone else) can get both JPype and JPE to work so they can be compared through more than just their respective documentation. Steve a.k.a devilwolf on sourceforge From bokr at oz.net Tue Jan 25 23:44:43 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 26 Jan 2005 04:44:43 GMT Subject: Classical FP problem in python : Hamming problem References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> <41f6162f.1768893674@news.oz.net> <10vd84er6bjr2ad@corp.supernews.com> Message-ID: <41f71fef.1836924838@news.oz.net> On Tue, 25 Jan 2005 11:46:04 -0800, Jeff Shannon wrote: >Bengt Richter wrote: > >> On 25 Jan 2005 08:30:03 GMT, Nick Craig-Wood wrote: >> >>>If you are after readability, you might prefer this... >>> >>>def hamming(): >>> def _hamming(): >>> yield 1 >>> for n in imerge(imap(lambda h: 2*h, iter(hamming2)), >>> imerge(imap(lambda h: 3*h, iter(hamming3)), >>> imap(lambda h: 5*h, iter(hamming5)))): >>> yield n >>> hamming2, hamming3, hamming5, result = tee(_hamming(), 4) >>> return result >> >> Are the long words really that helpful? >> >> def hamming(): >> def _hamming(): >> yield 1 >> for n in imerge(imap(lambda h: 2*h, iter(hg2)), >> imerge(imap(lambda h: 3*h, iter(hg3)), >> imap(lambda h: 5*h, iter(hg5)))): >> yield n >> hg2, hg3, hg5, result = tee(_hamming(), 4) # four hamming generators >> return result > >Well, judging by the fact that shortening the identifiers made it so >that you felt the need to add a comment indicating what they were >identifying, I'd say that yes, the long words *are* helpful. ;) >Comments are good, but self-documenting code is even better. The comment was a conscious factoring decision, in terms of documentation ;-) Regards, Bengt Richter From gurpreet.sachdeva at gmail.com Tue Jan 11 06:04:04 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Tue, 11 Jan 2005 16:34:04 +0530 Subject: Upgraded to python2.3 but httpd taking old version Message-ID: I upgraded my python to 2.3 from 2.2 but Apache (V 2.0.4) is taking old libraries for processing. I also made a soft link redirecting the old files to new files but of no help... These error logs shows that it is still using 2.2 :o( [Tue Jan 11 16:18:45 2005] [error] [client 127.0.0.1] import cgi [Tue Jan 11 16:18:45 2005] [error] [client 127.0.0.1] File "/usr/lib/python2.2/cgi.py", line 38, in ? Please help -- Garry From fredrik at pythonware.com Sat Jan 22 15:35:11 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 21:35:11 +0100 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fpq0F4mh1ffU1@individual.net> Message-ID: "rm" wrote: > furthermore, "users will suffer too", I'm suffering if I have to use C++, with all its exceptions > and special cases. and when you suffer, your users will suffer. in the C++ case, they're likely to suffer from spurious program crashes, massively delayed development projects, obscure security holes, etc. From boisgera at isia.cma.fr Thu Jan 13 07:32:22 2005 From: boisgera at isia.cma.fr (Sebastien Boisgerault) Date: 13 Jan 2005 04:32:22 -0800 Subject: Pickling a class instead of an instance Message-ID: Hi, It seems to me that it's not possible with the pickle module to serialize a class rather than an instance, as in >> from pickle import * >> >> class C(object): >> "... doc ..." >> a = 1 >> >> pickstr = dumps(C) I mean, it does *something*, there is no error indeed, but from the string pickstr, I am unable to rebuild the class C in a brand new context (got a "you're really stupid, all you deserve is an AttributeError because you know there is no attribute 'C' in the 'module' object" error). Am I wrong ? Why would the "(new-style) classes are regular objects too" mantra not apply in this case ? Could we imagine a patch to the pickle module to handle this kind of situation ? SB From mike at hobbshouse.org Tue Jan 4 17:13:45 2005 From: mike at hobbshouse.org (Michael Hobbs) Date: Tue, 04 Jan 2005 22:13:45 -0000 Subject: Optional Static Typing: Part II References: <10tluavnqqufg07@news.supernews.com> Message-ID: <10tm58phn0spucd@corp.supernews.com> John Roth wrote: > Now, the base objective seems to be to incorporate PyChecker > functionality into the root. This in turn requires type inference, > which in turn strongly suggests type annotations to help the > inferencer out over rough spots. > > I like this approach a lot. If he makes the type inferencer "proud", that might help alleviate the fears around here that it will become standard practice to put type annotations on everything. That is, if you explicitly annotate a function in the same way that the inferencer would have inferenced it, the PyChecker thingie would emit a message saying: "I'm no dummy! I could have told you that foo() takes an 'int' and returns a 'bool'. What do you think I am, stupid? Duuu-uhhh!" :) From jeff at ccvcorp.com Thu Jan 27 14:15:09 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 27 Jan 2005 11:15:09 -0800 Subject: subprocess.Popen() redirecting to TKinter or WXPython textwidget??? In-Reply-To: <41f811fe$0$148$3a628fcd@reader1.nntp.hccnet.nl> References: <41f80b1b$0$148$3a628fcd@reader1.nntp.hccnet.nl> <1106775371.049857.36360@z14g2000cwz.googlegroups.com> <41f811fe$0$148$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <10vif2imjcnvne5@corp.supernews.com> Ivo Woltring wrote: > The output of mencoder is not readable with readlines (i tried it) because > after the initial informational lines You don't get lines anymore (you get a > linefeed but no newline) > The prints are all on the same line (like a status line) > something like > Pos: 3,1s 96f ( 0%) 42fps Trem: 0min 0mb A-V:0,038 [171:63] Hm, I'm inferring that what you mean is that you get a carriage return (ASCII 0x0C) but no linefeed (ASCII 0x0A) -- CR returns you to the beginning of the current line, and LF advances you to the next line. Rather than using readlines(), you could simply read() a few characters (or a single character) at a time, buffering it yourself and passing it on when you see the CR. You're likely to run into I/O blockage issues no matter how you do this, though -- even if you're reading a single character at a time, read(1) won't return until you've read that character, and if the program on the other end of the pipe isn't writing anything, then your app is stuck. The "simple" way to do this is by using an i/o thread, which does something like this: buffer = [] while 1: char = outpipe.read(1) if char == '\0x0A': notify_gui_thread( ''.join(buffer) ) buffer = [] else: buffer.append(char) if StopEvent.IsSet(): raise CustomStopException Note that you don't want to try to update your GUI widgets directly from the worker (i/o) thread -- very few GUI toolkits are threadsafe, so you need to make all GUI calls from a single thread. Jeff Shannon Technician/Programmer Credit International From phleum_nospam at chello.se Fri Jan 28 11:42:04 2005 From: phleum_nospam at chello.se (Carl) Date: Fri, 28 Jan 2005 17:42:04 +0100 Subject: Installing Numeric with ATLAS and LAPACK References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> Message-ID: drife wrote: > Hello, > > Could someone please provide instructions for install Numeric > with ATLAS and LAPACK? > > I've actually done this correctly, I think. But I don't see any > difference in the speed. > > I'm calculating eigenvalues for a 3600 X 3600 covariance matrix. > > Calculating the eigenvalues for this matrix requires a mere 7 min > in Matlab 6.5...which uses ATLAS and LAPACK. > > > Thanks, > > > Daran What functions from ATLAS and LAPACK are you using? Carl From steve at holdenweb.com Sat Jan 8 14:09:09 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 08 Jan 2005 14:09:09 -0500 Subject: The best way to do web apps with Python? In-Reply-To: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41E02FD5.5080703@holdenweb.com> worzel wrote: > What is the best way to web developemnt with Python? Is there anything > close to PHP style in-page script placement that can create and use > other Python objects? I am not really interested in Zope (I believe that > is more a CMS than anything else?) I am also looking for something a > little more structured than a series of CGI Scripts. > More ways than you can shake a stick at, but nowadays you should consider using WSGI if you want your code to be portable across many frameworks. The Web SIG worked very hard last year on defining this gateway interface, with the intention that it should become widely available, and implementations are available now on environments as diverse as mod_python and CherryPy. You can read about it in Philip Eby's excellent PEP at http://www.python.org/peps/pep-0333.html > While on the topic - what is the expectataion of Python for this kind of > stuff? Would one use Python for certain other things but turn to PHP for > web apps - or would one use their Python skills in place of PHP? > Python is a real programming language, whereas PHP was originally intended as a simple way of scripting web content. Since then it has grown to encompass many of the same features as Python, but since they were retrofitted rather than designed in they are sometimes kind of clunky (as, IMHO, is Perl, although in a different way). But there's a lot of good work been done in both PHP and Perl, and I'd usually recommend using existing functionality in either language over a just-for-the-sake-of-it rewrite in Python. But that could just be because I don't like re-inventing wheels. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From frans.englich at telia.com Sun Jan 23 13:01:50 2005 From: frans.englich at telia.com (Frans Englich) Date: Sun, 23 Jan 2005 18:01:50 +0000 Subject: What is print? A function? Message-ID: <200501231801.50080.frans.englich@telia.com> Nah, I don't think it's a function, but rather a builtin "statement". But it's possible to invoke it as an function; print( "test" ) works fine. So I wonder, what _is_ exactly the print statement? The untraditional way of invoking it(without paranteses) makes me wonder. The reason I thinks about this is I need to implement a debug print for my program; very simple, a function/print statement that conditionally prints its message whether a bool is true. Not overly complex. I tried this by overshadowing the print keyword, but that obviously didn't work.. Is defining a two-liner function the right way to go, or is there better ways to approach it? Cheers, Frans From hanchunhui at gmail.com Thu Jan 20 20:21:42 2005 From: hanchunhui at gmail.com (neutrino) Date: 20 Jan 2005 17:21:42 -0800 Subject: Print a string in binary format References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> Message-ID: <1106270502.219126.322790@f14g2000cwb.googlegroups.com> Mmm, the output format that I want is like: 0001110011111111000000001111111100000000.... I tried your code on Cygwin under Windows 2000, and on Linux, but it prints out ASCII characters. From cjbottaro at alumni.cs.utexas.edu Mon Jan 3 21:42:27 2005 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Mon, 03 Jan 2005 20:42:27 -0600 Subject: HTTP GET request with basic authorization? References: <7c60b60505010215123462c90e@mail.gmail.com> <652efjvb.fsf@pobox.com> Message-ID: John J. Lee wrote: > Jonas Galvez writes: > >> Christopher J. wrote: >> > I tried this, but it didn't work: >> > conn.request("GET", "/somepage.html", None, >> > {"AUTHORIZATION": "Basic username:password"}) > [...] >> import re, base64, urllib2 >> >> userpass = ('user', 'pass') >> url = 'http://somewhere' >> >> request = urllib2.Request(url) >> authstring = base64.encodestring('%s:%s' % userpass) >> authstring = authstring.replace('\n', '') >> request.add_header("Authorization", "Basic %s" % authstring) >> >> content = urllib2.urlopen(request).read() > > There are handlers in urllib2 to do this for you, you shouldn't need > to do it by hand. I rarely do, so I won't risk an example... > > > John > Thank you all. The webpage I was reading didn't say anything about base64 encoding the authentication string. Also thanks for the tip on the urllib2 handlers. From http Sat Jan 1 17:27:09 2005 From: http (Paul Rubin) Date: 01 Jan 2005 14:27:09 -0800 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xfz1lal5d.fsf@ruckus.brouhaha.com> Message-ID: <7xekh423b6.fsf@ruckus.brouhaha.com> Steve Holden writes: > > It seems to me > > that IDLE and a lot of the rest of Python are examples of someone > > having a cool idea and writing a demo, then releasing it with a lot of > > missing components and rough edges, without realizing that it can't > > reasonably be called complete without a lot more work. > > ^Python^open source^ I wouldn't say so. I'd say the Linux kernel, GCC, Emacs, Apache, Mozilla, etc. are all developed with a much more serious attitude than Python is. Of course there are lots of other FOSS programs that someone wrote for their own use and released, that are less polished than Python, but that are also the subject of less advocacy than Python. From zanesdad at bellsouth.net Mon Jan 10 13:13:37 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Mon, 10 Jan 2005 13:13:37 -0500 Subject: ftplib with unknown file names In-Reply-To: References: Message-ID: <41E2C5D1.6020605@bellsouth.net> rbt wrote: > How can I use ftplib to retrieve files when I do not know their names? > I can do this to get a listing of the directory's contents: > > ftp_server.retrlines('LIST') > > > The output from this goes to the console and I can't figure out how to > turn that into something I can use to actually get the files (like a > list of file names). I read a bit about the callback function that can > be passed to retrlines but I couldn't figure out how to use it. > > Any help is appreciated. > > Thanks! .nlst(argument) will return a list of file names. Here are the docs for the nlst command: http://www.python.org/doc/current/lib/ftp-objects.html HTH, Jeremy Jones From lee at example.com Wed Jan 26 16:26:09 2005 From: lee at example.com (Lee Harr) Date: Wed, 26 Jan 2005 21:26:09 GMT Subject: Inherting from object. Or not. References: Message-ID: > What is the difference between inherting form object, and not doing it? E.g, > what's the difference between the two following classes? > > class foo: > pass > > class bar(object): > pass > > Sometimes people inherit from it, and sometimes not. I don't see a pattern in > their choices. > > I think this is the best source: http://www.python.org/2.2.3/descrintro.html Subclassing object gets you a "new style" class and some additional capabilities. Maybe eventually it will not matter. From BOOGIEMANPN at YAHOO.COM Mon Jan 3 17:38:34 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Mon, 3 Jan 2005 23:38:34 +0100 Subject: How do I make Windows Application with Python ? References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> Message-ID: <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> On Mon, 03 Jan 2005 17:19:22 -0500, Peter Hansen wrote: > What do you mean by "Windows Applications"? I'm running > Python on Windows XP, so every program I write with > Python is a "Windows application" by my definition. Obviously > you are using a different one. > > (And if you just mean "it has a GUI", then my answer is > "I use wxPython with Python". There is also Tkinter, and > other options. Please ask a more specific, detailed question > to get useful answers.) Well, I programmed a little in MS Visual Studio 2003, and there you have Console apllication and Windows application (among others). Windows one is with buttons and other gadgets. So, I want to make applications that doesn't open console to display result, I want to display it into the message box. Also, I want to use that application on the computers where Python isn't installed From tjreedy at udel.edu Mon Jan 10 16:02:24 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 Jan 2005 16:02:24 -0500 Subject: Old Paranoia Game in Python References: <2005010903390916807%spk00@coxnet> Message-ID: Never saw this specific game. Some suggestions on additional factoring out of duplicate code. > def next_page(this_page): > print "\n" > if this_page == 0: > page = 0 > return The following elif switch can be replaced by calling a selection from a list of functions: [None, page1, pag2, ... page57][this_page]() > elif this_page == 1: > page1() > return > elif this_page == 2: > page2() > return ... > elif this_page == 57: > page57() > return Also, a chose3 function to complement your chose (chose2) function would avoid repeating the choose-from-3 code used on multiple pages. Terry J. Reedy From bill.mill at gmail.com Fri Jan 28 10:52:29 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 28 Jan 2005 10:52:29 -0500 Subject: Dynamic class methods misunderstanding In-Reply-To: <41fa5d3d$0$2024$626a14ce@news.free.fr> References: <41fa5d3d$0$2024$626a14ce@news.free.fr> Message-ID: <797fe3d4050128075213c34060@mail.gmail.com> On 28 Jan 2005 15:41:49 GMT, F. Petitjean wrote: > Le Fri, 28 Jan 2005 10:20:30 -0500, Bill Mill a ?crit : > > Hello all, > > > > I have a misunderstanding about dynamic class methods. I don't expect > > this behavior: > > > > In [2]: class test: > > ...: def __init__(self, method): > > ...: self.method = method > > ...: self.method() > > ...: > > > > In [3]: def m(self): print self > > ...: > > > > In [4]: test(m) > > --------------------------------------------------------------------------- > > exceptions.TypeError Traceback (most recent call > > last) > > > > /cygdrive/c/Documents and Settings/Wmill/ > > > > /cygdrive/c/Documents and Settings/Wmill/ in __init__(self, method) > > > > TypeError: m() takes exactly 1 argument (0 given) > > ----------------------------------------------------------------------------- > > > > Why doesn't m get the implicit self parameter in the self.method() > > call? How would I make it a proper member of the class, so that a > > self.method() call would work with the above "m" function? > The "def m(self):" was not properly indented. So here, "m" is a module level > function, not a method of your class. I know this; I should have been clearer. I want to define a function outside of a class, then pass it to a class and make it a method of that class. > > > > Peace > > Bill Mill > > bill.mill at gmail.com > -- > http://mail.python.org/mailman/listinfo/python-list > From devries at idolstarastronomer.com Mon Jan 3 20:50:46 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: 3 Jan 2005 17:50:46 -0800 Subject: How do I make Windows Application with Python ? References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> Message-ID: <1104803446.648811.253820@f14g2000cwb.googlegroups.com> There are several GUI toolkits for python. Tkinter comes with python, but wxPython, a binding to wxWindows is popular, as is pyQT, and pyGTK. You can also build native win32 GUIs using PythonWin, part of win32all. A more complete list of options is available here: http://www.python.org/cgi-bin/moinmoin/GuiProgramming . I have heard a couple good things about Boa Constructor (http://boa-constructor.sourceforge.net/) as an IDE. It includes a GUI designer. I have not used it though. Stand alone GUI designers such as wxGlade (http://wxglade.sourceforge.net/) are available as well. As far as packaging the application for use on computers where python is not installed. If you are distributing to windows computers you can use py2exe to make a windows executable from a python program. It will include dlls you need to distribute with your program. cx_Freeze and Gordon McMillan's Installer also can create windows executable files. Good luck... and be sure to read through the online tutorials and wikis, there is a wealth of information out there. A book isn't a bad investment either, I always feel better with a good reference book around. Python in a nutshell is a good reference book, while Learning Python gives you a good introduction to the language. Chris From ptmcg at austin.rr._bogus_.com Tue Jan 11 09:12:16 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 11 Jan 2005 14:12:16 GMT Subject: Old Paranoia Game in Python References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> <1105318366.966577.107460@c13g2000cwb.googlegroups.com> <1105400673.731851.87080@f14g2000cwb.googlegroups.com> Message-ID: <49REd.6654$RW3.4383@fe1.texas.rr.com> "McBooCzech" wrote in message news:1105400673.731851.87080 at f14g2000cwb.googlegroups.com... > Newbie in Python. > I did copy the whole script form the web and save it as para1.py. I did > download pyparsing module and save it to > C:\\Python23\\Lib\\pyparsing122. > I did run following script: > > import sys > sys.path.append('C:\\Python23\\Lib\\pyparsing122') > > from pyparsing import * > extraLineBreak = White(" ",exact=1) + LineEnd().suppress() > text = file("Para1.py").read() > newtext = extraLineBreak.transformString(text) > file("para2.py","w").write(newtext) > > I did try to run para2.py script, but following message > > File "para2.py", line 169 > choose(4,"You give your correct clearance",5,"You lie and claim > ^ > SyntaxError: EOL while scanning single-quoted string > > So my questions are: > Why pyparser didn't correct the script? > What I am doing wrong? > Is it necessary to correct the script by hand anyway? > > Petr > Petr - After running the little script, I still had to make one correction by hand, on line 1057. There was a line that needed to be indented that wasn't. This little pyparsing script only takes out the line-breaks that were added because of the news server's word wrapping algorithm, and does not catch indentation errors. After correcting that by hand, I ran the program para2.py successfully. Did you extract *just* the Python code in the previous post? I did not find the line you listed as line 169 in either my pre-pyparsing nor post-pyparsing versions of the program. In para1.py, your line 169 shows up as my line 159, in para2.py, it is line 152, and it looks like: choose(4,"You give your correct clearance",5,"You lie and claim Ultraviolet clearance") (of course, this is likely to get word-wrapped again, but the point is, it includes the rest of the quoted string after the word 'claim'). What encoding are you using? I am currently working on a Unicode-compatible pyparsing, and this may help resolve your problem. Since your e-mail domain country code is cz, it's possible that the encoding for spaces and/or line breaks is treated differently. This is just a wild guess. Anyway, in the interest of tracking down a potential pyparsing problem, could you please e-mail me your para1.py file? -- Paul From steve at holdenweb.com Mon Jan 10 19:44:42 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Jan 2005 19:44:42 -0500 Subject: Securing a future for anonymous functions in Python In-Reply-To: <1105381339.922714.23200@c13g2000cwb.googlegroups.com> References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <1105381339.922714.23200@c13g2000cwb.googlegroups.com> Message-ID: <1oFEd.71967$Jk5.45632@lakeread01> Anna wrote: > You cut something from that... > > """It's not, after all, the word "lambda" itself; I would still > have some issues with using, say "function", instead of "lambda", but > at least then I would immediately know what I was looking at...""" > > I would have fewer ambiguities about using, say "func" rather than > lambda. Lambda always makes me feel like I'm switching to some *other* > language (specifically, Greek - I took a couple of semesters of Attic > Greek in college and quite enjoyed it.) But, the fact that lambda Good God, you mean there's a language just for the attic? Those Greeks certainly believed in linguistic specialization, didn't they? > doesn't MEAN anything (and has come - I mean - DELTA at least has a > fairly commonly understood meaning, even at high-school level math. > But, lambda? If it was "func" or "function" or even "def", I would be > happier. At least that way I'd have some idea what it was supposed to > be... > Well, I suspect that Church originally chose lambda precisely because of its meaninglessness, and I'm always amused when mathematical types try to attribute an intuitive meaning to the word. It's purely a learned association, which some arrogantly assume simply *everyone* knows or should know. Not that I'm trying to write off lambda supporters as arrogant (though I *do* have a suspicion that many of them break the wrong end of their boiled eggs). > BTW - I am *quite* happy with the proposal for "where:" syntax - I > think it handles the problems I have with lambda quite handily. > Whereas I find it to be an excrescence, proving (I suppose) that one man's meat is another person's poison, or something. regards Steve [who only speaks Ground Floor English] -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From tim.golden at viacom-outdoor.co.uk Thu Jan 20 12:05:40 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 20 Jan 2005 17:05:40 -0000 Subject: Print to Windows default Printer Message-ID: <9A28C052FF32734DACB0A288A35339910359D8@vogbs009.gb.vo.local> [Samantha] [... snip my explanation of PRINT / COPY LPTx: ...] | Thanks Tim, | That is exactly what I want to do. | How do I map the printer to LPT1? | S Depends on a lot of things: whether the printer is local or networked; what version of Windows you're running, &. As a very basic starting point: if it's a local printer (ie plugged into the back of your machine) it's probably on LPT1: already, or you could go to the Add Printer wizard and tell it to configure it for LPT1: there. If it's networked, then something like: NET USE LPT1: \\servername\printerqueue should achieve the right effect. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From farcepest at gmail.com Sun Jan 30 14:39:11 2005 From: farcepest at gmail.com (Andy Dustman) Date: 30 Jan 2005 11:39:11 -0800 Subject: An mysql-python tutorial? In-Reply-To: References: Message-ID: <1107113951.790582.184140@z14g2000cwz.googlegroups.com> It definitely looks like an access control problem; recheck your grants. From nothanks at nothere.com Mon Jan 17 09:50:34 2005 From: nothanks at nothere.com (Emiliano Molina) Date: Mon, 17 Jan 2005 14:50:34 GMT Subject: PUG in Melbourne Australia? Message-ID: <_gQGd.122103$K7.32923@news-server.bigpond.net.au> Does anyone here know if there is a Python Users Group in Melbourne Australia? A google search shows an attempt to start one at meetups.com or something like that but it now seems defunct. From case.nelson at gmail.com Wed Jan 12 00:58:49 2005 From: case.nelson at gmail.com (snoe) Date: 11 Jan 2005 21:58:49 -0800 Subject: Help Optimizing Word Search In-Reply-To: References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Message-ID: <1105509529.664370.16080@f14g2000cwb.googlegroups.com> Mike, Thanks, this worked great, and was 4x faster than my method! Thanks everyone for replying! The changes I made were: !rest = ''.join([chr(i) for i in range(256) if chr(i).upper() not in WORD]) !# a wildcard in the word means that we check all letters !if '?' in WORD: ! rest = '' !translator = string.maketrans('','') and ! try: ! pool.remove( char ) ! except ValueError: ! # nested try to remove possible wildcard ! try: ! pool.remove( '?' ) ! except ValueError: ! return False From fu.limin.tao at gmail.com Thu Jan 27 06:34:56 2005 From: fu.limin.tao at gmail.com (Limin Fu) Date: Thu, 27 Jan 2005 12:34:56 +0100 Subject: ANN: Tao Scripting Language 0.8.5 beta released! Message-ID: Dear all, I am glad to announce in this mailing list that the lastest version of a new scripting language has come out. Welcome to try it out. Comments are welcome. Suggestions are appreciated. ======================= Here are some details: ======================= Design Goals: 1. Simple and efficient. 2. Integrate nice features of other languages whenever possible. Implementation language: C++ with STL. Designer: Fu Limin Email: fu [dot] limin [dot] tao [at] gmail.com Key features have been supported: 1. Dynamic-typing variables, supporting complex data structures such as array/list, hash/dictionary and matrix etc. 2. Object-oriented programming ( multi-inheritance not supported yet ). 3. Basic string regular expression matching. 4. Automatic garbage collection capable of collecting cyclically referenced objects. 5. Numeric data types: complex number and matrix, and their basic operations. 6. Convenient namespacing and dynamic creation of subroutines and classes. 7. Dynamic loading of C/C++ modules ( not complete, but enough for playing with it ^_^ ). 8. An embedded tiny XML parser. ToBeDone: More string operations, multi-inheritance of classes, improvements on C/C++ module loading, more on regular expression matching and possible optimizations etc. Documentation: http://taoscript.sourceforge.net/brief_tao.php Sample scripts: http://taoscript.sourceforge.net/sample.php Download: http://taoscript.sourceforge.net/downloads.php Best regards, Limin -- Homepage for Tao Language: http://taoscript.sourceforge.net Tao Language project at sourceforge.net: http://sourceforge.net/projects/taoscript From jerf at jerf.org Mon Jan 24 11:45:34 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 24 Jan 2005 11:45:34 -0500 Subject: Why I use private variables (WAS: RE:"private" variables a.k.a. name mangling?) References: Message-ID: On Mon, 24 Jan 2005 15:35:11 -0600, Philippe C. Martin wrote: > The real reason behind my using private variables is so they do not appear > in the epydoc generated documentation and confuse my users. You mean single or double underscores? I just checked and at least epydoc 2.1 doesn't include single-underscore values, but those aren't "private" in sense we're talking in this thread (some form of compiler enforcement). From lmhaskins at yahoo.com Fri Jan 28 19:03:08 2005 From: lmhaskins at yahoo.com (lmhaskins at yahoo.com) Date: 28 Jan 2005 16:03:08 -0800 Subject: move bugs from Zope BITS into Bugzilla? Message-ID: <1106956988.391329.320610@z14g2000cwz.googlegroups.com> I inherited a bug reporting system at work, and it's currently in Zope BITS (Bug Information Tracking System). This version of BITS uses ZODB -- not the RDBMS version. I would like to export all the incident reports from BITS to later import into Bugzilla, but as of yet I haven't quite figured it out. As soon as I'm done with this, that's it for BITS and Zope, so I'd like to avoid writing a Zope app just for this. Anyone solved this problem, or at least the part about exporting from BITS? I'd hand-enter the open issues, but they also want the closed ones for tracking & posterity. Thanks! -lmh From Jared.Cohen at noaa.gov Wed Jan 5 17:24:41 2005 From: Jared.Cohen at noaa.gov (Jared Cohen) Date: Wed, 05 Jan 2005 17:24:41 -0500 Subject: Please help -- Pmw PanedWidget inside ScrolledFrame Message-ID: <41DC6929.9080704@noaa.gov> Almost forgot, here's the code sample: #!/usr/bin/env python import sys, os, Tkinter, types, tkFont, Pmw def makeResizable(widget): for i in range(0, widget.grid_size()[0]): widget.columnconfigure(i, weight=1) for i in range(0, widget.grid_size()[1]): widget.rowconfigure(i, weight=1) def main(): root = Tkinter.Tk() root.geometry("500x500+0+0") Pmw.initialise(root) scrolledFrame = Pmw.ScrolledFrame(root, usehullsize=1, borderframe=0, hscrollmode='static', vscrollmode='static') scrolledFrame.grid(row=0, rowspan=20, column=0, columnspan=20, sticky='nsew') panes = Pmw.PanedWidget(scrolledFrame.interior(), orient='horizontal', hull_borderwidth=2, hull_relief='sunken') panes.grid(row=0, rowspan=20, column=0, columnspan=20, sticky='nsew') for i in range(5): pane = panes.add("pane"+str(i), size=1/5.0) button = Tkinter.Button(pane, text="This Is A Very Long Name For A Button") button.grid(row=0, rowspan=1, column=i, columnspan=1, sticky='nsew') makeResizable(root) makeResizable(scrolledFrame.interior()) makeResizable(panes) root.mainloop() if __name__=='__main__': main() From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Jan 20 02:56:20 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Do Re Mi chel La Si Do) Date: Thu, 20 Jan 2005 08:56:20 +0100 Subject: ElementTree cannot parse UTF-8 Unicode? References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> <1106181323.553028.290370@z14g2000cwz.googlegroups.com> Message-ID: <41ef646a$0$19406$8fcfb975@news.wanadoo.fr> Hi ! >>> ...Usenet to transmit it properly newsgroups (NNTP) : yes, it does it usenet : perhaps (that depends on the newsgroups) clp : no Michel Claveau From ncoghlan at iinet.net.au Fri Jan 28 06:21:51 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 28 Jan 2005 21:21:51 +1000 Subject: Inherting from object. Or not. In-Reply-To: References: <1106774681.501533.156220@f14g2000cwb.googlegroups.com> <200501262214.40597.frans.englich@telia.com> Message-ID: <41FA204F.3050403@iinet.net.au> Nick Craig-Wood wrote: > Nick Coghlan wrote: > >> Exactly. My advice is to use new-style classes unless you have a >> reason not to (if you're inheriting from a builtin type, then there >> is no need to inherit from object as well - the builtin types >> already have the correct basic type). > > > Except for Exception! > > Exception and anything that inherits from it is an old style class. And 'classobj' is the correct basic type for an Exception, since, as you mentioned, new-style classes are currently unraisable :) Cheers, Nick. I think there *is* work in progress to change that. . . -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steven.bethard at gmail.com Wed Jan 12 19:37:50 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 17:37:50 -0700 Subject: else condition in list comprehension In-Reply-To: References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: Steve Holden wrote: > Nick Coghlan wrote: >> z = [newval(i) for i in range(10)] using: >> def newval(x): >> if x % 2: >> return x - 2 >> else: >> return x + 2 >> >> Just some more mental twiddling relating to the thread on statement >> local namespaces. >> > I presume the point of this is to avoid polluting the local namespace > with "newval". I further presume you also have plans to do something > about "i"? ;-) Well, while I'm not at all a fan of the "using" syntax, getting rid of 'i' is simple: z = list(newval(i) for i in range(10)) =) Steve From jeff at ccvcorp.com Wed Jan 26 18:09:43 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 26 Jan 2005 15:09:43 -0800 Subject: inherit without calling parent class constructor? In-Reply-To: References: Message-ID: <10vg8ecra1anp9f@corp.supernews.com> Christian Dieterich wrote: > Hi, > > I need to create many instances of a class D that inherits from a class > B. Since the constructor of B is expensive I'd like to execute it only > if it's really unavoidable. Below is an example and two workarounds, but > I feel they are not really good solutions. Does somebody have any ideas > how to inherit the data attributes and the methods of a class without > calling it's constructor over and over again? You could try making D a container for B instead of a subclass: class D(object): def __init__(self, ...): self._B = None def __getattr__(self, attr): if self._B is None: self._B = B() return getattr(self._B, attr) Include something similar for __setattr__(), and you should be in business. If it will work for numerous D instances to share a single B instance (as one of your workarounds suggests), then you can give D's __init__() a B parameter that defaults to None. Jeff Shannon Technician/Programmer Credit International From simoninusa2001 at yahoo.co.uk Sat Jan 29 02:05:48 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 28 Jan 2005 23:05:48 -0800 Subject: Pystone benchmark: Win vs. Linux (again) In-Reply-To: References: Message-ID: <1106978997.909778.272440@z14g2000cwz.googlegroups.com> Franco Fiorese wrote: > Is there any way, that you know, to get better performance under Linux? Build Python yourself, using relevant CFLAGS and TARGET for your processor? I've always noticed that Windows Python takes a lot longer to startup than Linux, but never really looked at runtime performance. From notvalid at email.com Mon Jan 17 01:38:42 2005 From: notvalid at email.com (Ala Qumsieh) Date: Mon, 17 Jan 2005 06:38:42 GMT Subject: [perl-python] 20050116 defining a function In-Reply-To: <1105886753.149519.194980@z14g2000cwz.googlegroups.com> References: <1105886753.149519.194980@z14g2000cwz.googlegroups.com> Message-ID: Xah Lee wrote: > ? my $n= @_[0]; Do you ever test your code before making fun of yourself in front of millions? *plonk* --Ala From kent3737 at yahoo.com Fri Jan 7 15:50:03 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Fri, 07 Jan 2005 15:50:03 -0500 Subject: Tkinter: passing parameters to menu commands In-Reply-To: References: Message-ID: <41def3cd$1_1@newspeer2.tds.net> Philippe C. Martin wrote: > I have many menu items and would like them all to call the same method > -However, I need the method called to react differently depending on the > menu item selected. Since the menu command functions do not seem to > receive any type of event style object, is there some type of Tkinter > call that would let my method know the menu id selected ? Much as it seems to be out of favor, IMO this is a place where a lambda expression is very handy. You can make a callback for each menu item that binds an extra parameter to the handler: # Based on an example by Fredrik Lundh from Tkinter import * def callback(code): print "called the callback with code", code root = Tk() # create a menu menu = Menu(root) root.config(menu=menu) filemenu = Menu(menu) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="New", command=lambda: callback('New')) filemenu.add_command(label="Open...", command=lambda: callback('Open')) filemenu.add_separator() filemenu.add_command(label="Exit", command=lambda: callback('Exit')) mainloop() Of course you could do this with named forwarding functions if you prefer. Kent From 2004b at usenet.alexanderweb.de Tue Jan 11 10:39:32 2005 From: 2004b at usenet.alexanderweb.de (Alexander Schremmer) Date: Tue, 11 Jan 2005 16:39:32 +0100 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> Message-ID: On 10 Jan 2005 18:45:16 -0800, Paul Rubin wrote: > I need to set up a wiki for a small group. I've played with MoinMoin > a little bit and it's reasonably straightforward to set up, but > limited in capabilities and uses BogusMarkupConventions. At which point do you see limitations? And what of the markup don't you like? > In the larger world, though, there's currently One True wiki package, > namely Mediawiki (used by Wikipedia). It is just very famous because of Wikipedia IMHO. > Mediawiki is written in PHP and > is far more complex than MoinMoin, plus it's database backed, meaning > you have to run an SQL server as well as the wiki software itself > (MoinMoin just uses the file system). Having a DBMS backend is good in your opinion? It has some severe disadvantages like not easy to scale (you would need to setup DBMS replication), two potential points of failure, more complex setup, bigger memory requirements, etc. > Plus, I'll guess that it really > needs mod_php, while MoinMoin runs tolerably as a set of cgi's, at > least when traffic is low. Both should run fine in CGI mode I guess. > What I'm getting at is I might like to install MoinMoin now and > migrate to Mediawiki sometime later. Anyone have any thoughts about > whether that's a crazy plan? If you really want to use the wiki for content, you have to agree on a markup style. You could use an independent one (like RestructuredText) and hope that MediaWiki supports it (MoinMoin does). Or you end up writing complex migration scripts just for the markup. Finding some script which just imports the data files into the DB should be rather easy. > Should I just bite the bullet and run Mediawiki from the beginning? IMHO you should not bite it but choose MoinMoin. :-) > Is anyone here actually running Mediawiki who can say just how > big a hassle it is? A few months I tried to install it. I got it running. But I did not like the necessary complex administration tasks. > The other one will be public and is planned grow to medium size (a few > thousand active users), but which I don't need immediately. I > definitely want the second one to eventually run Mediawiki. I can > probably keep the first one on MoinMoin indefinitely, but that would > mean I'm eventually running two separate wiki packages, which gets > confusing. There are even MoinMoin sites that are as big as that. Maybe you should rethink your kind of prejudice and re-evaluate MoinMoin. Kind regards, Alexander From peter at engcorp.com Wed Jan 26 10:38:24 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 Jan 2005 10:38:24 -0500 Subject: smtplib bug with Windows XP In-Reply-To: References: <1106614880.586616.19780@f14g2000cwb.googlegroups.com> <1106673048.851591.324490@f14g2000cwb.googlegroups.com> Message-ID: Steve Christensen wrote: > In article <1106673048.851591.324490 at f14g2000cwb.googlegroups.com>, stewart.midwinter at gmail.com wrote: >>thank Peter, elbert, for the suggestions. I hadn't thought of using >>telnet to try to connect to the SMTP server. and when I do try, telnet >>can't connect either, at least on port 25. On port 110, it has no >>problem. So, perhaps the IT people have made some configuration >>changes; I'll have a chat with them. I'm relieved that it's not a >>Python problem, though. > > We had similar issues when our systems were upgraded to McAfee VirusScan > 8.0. If you're running that locally (on the system trying to connect to > the SMTP server), try disabling the rule in the Access Control dialog > that's labeled 'Prevent mass mailing worms from sending email' How do such tools still allow the sending of valid emails? -Peter From hpk at trillke.net Tue Jan 4 04:50:06 2005 From: hpk at trillke.net (holger krekel) Date: Tue, 4 Jan 2005 10:50:06 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) In-Reply-To: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> Message-ID: <20050104095006.GA32217@solar.trillke.net> On Fri, Dec 31, 2004 at 19:18 +0100, Alex Martelli wrote: > Cameron Laird wrote: > ... > > Yippee! The martellibot promises to explain Unicode for Pythoneers. > > http://groups-beta.google.com/group/comp.lang.python/msg/6015a5a05c206712 > > Uh -- _did_ I? Eeep... I guess I did... mostly, I was pointing to > Holger Krekel's very nice recipe (not sure he posted it to the site as > well as submitting it for the printed edition, but, lobby _HIM_ about > that;-). FWIW, i added the recipe back to the online cookbook. It's not perfectly formatted but still useful, i hope. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361742 cheers, holger P.S: happy new year. From genezhang at gmail.com Sun Jan 9 19:06:08 2005 From: genezhang at gmail.com (Gene) Date: 9 Jan 2005 16:06:08 -0800 Subject: path to python file given module Message-ID: <1105315568.887724.260370@c13g2000cwb.googlegroups.com> Is there a way to get a relative or absolute path to a python file once it's been imported as a module? For example, I type: >>> import filegen and I want a string that represents the path to filegen.py (either relative to current working directory or the absolute path) From bokr at oz.net Wed Jan 26 03:11:38 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 26 Jan 2005 08:11:38 GMT Subject: is there better 32 clock() timing? References: <41f61372.1768192005@news.oz.net> <41f63d79.1778950866@news.oz.net> Message-ID: <41f746c3.1846865602@news.oz.net> On Tue, 25 Jan 2005 15:46:30 +0000, Stephen Kellett wrote: >In message <41f63d79.1778950866 at news.oz.net>, Bengt Richter > writes >>I believe that is quite wrong as a general statement. > >Actually my initial statement should have been written >"accessing a resource, the accuracy of which is no better than 10ms.". I >was thinking of the 1ms multimedia timer but wrote about clock() >instead. > >10ms, coincidentally is the approx minimum scheduling granularity for >threads unless you are in a multimedia thread (or real time thread - not >sure about real time threads in NT). > >>If the "resource" only had ~1ms granularity, >>the minimum would be zero, as it is if you call time.time() in a tight loop, > >Correct. Write your app in C and call clock(). Thats what you get. You >can call clock 20000 times and still get a delta of zero. The next delta >(on my system) is 10ms at about 22000 calls. > >>>There are various timers available, documented and undocumented, all of >>>which end up at 1ms or 1.1ms, give or take. For anything shorter you > >Whoops here we go, same typo - should have been 10ms or 11ms. There is a >1ms timer in the multimedia timing group. > >>>need QueryPerformanceCounter() (but that *is* a slow call), or use the >>Have you timed it, to make that claim? > >Yes. > >>What do you mean by "slow"? > >Slower than any other Win32, CRT or Undocumented NT function you can use >to get timer information. Yes, I have timed them all, a few years ago. > >QueryPerformanceCounter is 47 times slower to call than clock() on my >1Ghz Athlon. That really makes me wonder. Perhaps the Athlon handles RDTSC by way of an illegal instruction trap and faking the pentium instruction? That might explain the terrible timing. Try it on a pentium that supports RDTSC. The clock() usually gets high resolution bits from a low order 16 bits of the timer chip that drives the old 55ms clock that came from IBM using cheap TV crystal based oscillators instead of defining an OS-implementer-friendly time base, I think. The frequency was nominally 1193182 hz I believe. Obviously the OS didn't get interrupted that often, but if you divide by 2**16, you get the traditional OS tick of ~55ms: >>> 1193182./2**16 18.206512451171875 >>> (1193182./2**16)**-1 0.054925401154224583 So that's a clue. By grabbing tick count and bits read from the fast-counting harware clock register, you can compute time fairly accurately for the moment you are sampling that register. IIRC, you couldn't get the whole 16 bits because it was a toggling trigger or some such. > >QueryPerformanceCounter may have finer granularity, but called in a >tight loop it'll crush your program. Maybe on your Athlon, but my experience is different ;-) > >>>RDTSC instruction which is fast but gives a count of instruction cycles >>>executed and is thus not totally accurate (multiple execution pipelines, >>>plus multithreading considerations). >>Accurate for what. > >See below - you haven't taken things into account, despite my comment in >brackets above which gives a big hint. I've absorbed a lot of hints since around '59 when I began to work with computers and timing issues ;-) > >>A single clock AFAIK drives RDTSC > >Correct. > >>The main problem with a CPU clock based reading is that it's very stable unless >>there's variable clock rate due to power management. > >Try running multiple apps at the same time you are doing your >measurement, each of which has a variable loading. Each of these apps is >contributing to the count returned by RDTSC. That is what I was >referring to. Ok, but that's another issue, which I also attempted to draw attention to ;-) Quoting myself: """ > >Even with the attribute lookup overhead, it's not several hundred microseconds >as a *minimum*. But on e.g. win32 you can get preempted for a number of milliseconds. >E.g., turn that to a max instead of a min: > >I see a couple 20-30 ms ones ;-/ > > >>> max(abs(time.clock()-time.clock()) for i in xrange(10**5)) > 0.0085142082264155761 > >>> max(abs(time.clock()-time.clock()) for i in xrange(10**5)) > 0.0088125700856949152 > >>> max(abs(time.clock()-time.clock()) for i in xrange(10**5)) > 0.0022125710913769581 > >>> max(abs(clock()-clock()) for i in xrange(10**5)) > 0.023374472628631793 > >>> max(abs(clock()-clock()) for i in xrange(10**5)) > 0.030183995400534513 > >>> max(abs(clock()-clock()) for i in xrange(10**5)) > 0.0017130664056139722 > >>> max(abs(clock()-clock()) for i in xrange(10**5)) > 0.0070844179680875641 > """ Depending on what your timing requirements are, you may be able to run a zillion trials and throw out the bad data (or plot it and figure out some interesting things about timing behavior of your system due to various effects). E.g., timeit presumably tries to get a minimum and eliminate as many glitches as possible. But as mentioned, the big picture of requirements was not clear. Certainly you can't expect to control ignition of a racing engine reliably with an ordinary windows based program ;-) Regards, Bengt Richter From http Wed Jan 19 23:38:32 2005 From: http (Paul Rubin) Date: 19 Jan 2005 20:38:32 -0800 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> Message-ID: <7xis5szpdj.fsf@ruckus.brouhaha.com> Tim Peters writes: > Python's basic list type is a flat vector instead of a > recursively-defined S-expression, and that there's no direct way to > break out of a containing loop from a nested loop. Huh? [1,2,[3,4,5],[6,[[[[7]],8]]]] is a perfectly valid Python list. And you can break out of a containing loop from a nested loop with try/raise. More troublesome is not being able to see a variable in a containing scope from a nested scope, unless the containing scope is the global one. Why bother debating lexical scope for years before deciding to add it, only to stop halfway? From RajaSrinivasan at hotmail.com Tue Jan 4 16:57:06 2005 From: RajaSrinivasan at hotmail.com (RajaSrinivasan at hotmail.com) Date: 4 Jan 2005 13:57:06 -0800 Subject: Bad Interpreter In-Reply-To: <1104784496.231137.117250@f14g2000cwb.googlegroups.com> References: <1104783849.754892.47560@c13g2000cwb.googlegroups.com> <1104784496.231137.117250@f14g2000cwb.googlegroups.com> Message-ID: <1104875826.291380.94330@c13g2000cwb.googlegroups.com> sounds like it. vi sock.py shows '$' at the end of each line. however when i went to a unix machine and recreated the file, the problem went away. thanks for all the help regards From stephen.thorne at gmail.com Thu Jan 20 01:06:48 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 20 Jan 2005 16:06:48 +1000 Subject: list item's position In-Reply-To: References: Message-ID: <3e8ca5c8050119220669d6c87c@mail.gmail.com> On Wed, 19 Jan 2005 22:04:44 -0500, Bob Smith wrote: > Hi, > > I have a Python list. I can't figure out how to find an element's > numeric value (0,1,2,3...) in the list. Here's an example of what I'm doing: > > for bar in bars: > if 'str_1' in bar and 'str_2' in bar: > print bar > > This finds the right bar, but not its list position. The reason I need > to find its value is so I can remove every element in the list before it > so that the bar I found somewhere in the list becomes element 0... does > that make sense? Given a list and a function: def dropPredicate(x): return not 'somecontents' in x mylist = ['a', 'b', 'c', 'xxxxsomecontentsxxx', 'd', 'e', 'f'] import itertools mylist = list(itertools.dropwhile(dropPredicate, mylist)) assert mylist == ['xxxxsomecontentsxxx', 'd', 'e', 'f'] This will drop everything at the start of the list for which 'dropPredicate' returns true. This will mean that even if dropPredicate returns false for more than one element of the list, it will stop at the first element. If there are no elements for which dropPredicate returns true, the result will be an empty list. Regards, Stephen Thorne. From mahs at telcopartners.com Tue Jan 25 19:20:27 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 25 Jan 2005 16:20:27 -0800 Subject: python without OO In-Reply-To: <1106694083.199064.240680@f14g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> Message-ID: Davor wrote: > Thanks, > > I do not hate OO - I just do not need it for the project size I'm > dealing with - and the project will eventually become open-source and > have additional developers - so I would prefer that we all stick to > "simple procedural" stuff rather than having to deal with a developer > that will be convincing me that his 50 layers inheritance hierarchy is > good since it exists in some weird pattern that he saw somewhere on > some Java design patterns discussion board :-) and other "proper" OO > design issues... Once I opted for C++ in a very small project and > believed everyone will stick with C subset + better type checking > offered through C++ - but I simply could not manage to keep them off > using OO stuff which was just making program more complicated than it > should have been. (note, I am not an experienced developer, nor the > others I'll be working with (even though some think they are:-)), so I > prefer preemptively dealing with issue of everyone showing off their OO > design skills) > > Davor > Perhaps pylint (http://www.logilab.org/projects/pylint) or its ilk can help you enforce a coding style Michael From richie at entrian.com Mon Jan 24 10:33:11 2005 From: richie at entrian.com (Richie Hindle) Date: Mon, 24 Jan 2005 15:33:11 +0000 Subject: Weakref.ref callbacks and eliminating __del__ methods In-Reply-To: <41F510E0.40301@rogers.com> References: <41F427EB.3000200@rogers.com> <1f7befae0501231720428ca3c@mail.gmail.com> <5lr9v0tg2i16irskb798f7rcti955j0c64@4ax.com> <41F510E0.40301@rogers.com> Message-ID: [me] > why the `self.btree = None` in the last line? [Mike] > It's to allow the Closer object to act as a substitute for a .close() > method on the object [...] If the user explicitly calls storage.close() > we don't want the __del__ trying to re-close the storage later. In > other words, its an explicit requirement for *this* __del__, not a general > requirement. I see, yes. Very clever - thanks for the explanation! -- Richie Hindle richie at entrian.com From FBatista at uniFON.com.ar Thu Jan 20 13:46:53 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 20 Jan 2005 15:46:53 -0300 Subject: RuntimeError: dictionary changed size during iteration Message-ID: [Terry Reedy] #- You must be having a bad day ;-). From Lib Ref 2.1 Built-in Well, that's actually true, :( #- corresponding to the object's symbol table. The returned #- dictionary should #- not be modified: the effects on the corresponding symbol table are #- undefined I actually read that, but didn't understood that it returns THE dictionary (well, that another name binding for the same object was happening). Whatever, I don't get divorced every week, so forgive me. I think that, as it's normal to do... l = list(...) for e in l[:]: l.remove(e) ...insted of... l = list(...) for e in l: l.remove(e) ..., in this case we should do... >>> [e for e in vars().copy()] ['_[1]', 'e', 'v', '__builtins__', '__name__', '__doc__'] . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Sun Jan 2 14:33:49 2005 From: exarkun at divmod.com (Jp Calderone) Date: Sun, 02 Jan 2005 19:33:49 GMT Subject: Continuations Based Web Framework - Seaside. In-Reply-To: <20050102183402.GC8357@monkeyfist.com> Message-ID: <20050102193349.26823.1129392051.divmod.quotient.1041@ohm> On Sun, 2 Jan 2005 13:34:02 -0500, Kendall Clark wrote: >On Sun, Jan 02, 2005 at 10:03:10AM -0500, Steve Holden wrote: > > > I did actually do some sort-of-related work in this area, which I > > presented at PyCon DC 2004 - you can access the paper at > > > > http://www.python.org/pycon/dc2004/papers/18/Setting_A_Context.pdf > > > > An audience member mentioned the Smalltalk and Scheme-based work on web > > continuation frameworks, and I was sorry my answer at the time seemed > > unduly dismissive. > > That was me, actually. I remain surprised that there isn't a move > afoot either to implement something like Seaside or Borges in Python > or to adapt one of the existing web frameworks to be > modal/continuation style. There is at least one. I'm sure I could find several, if I looked. The problem is that there are dozens of "web frameworks" in Python, all off in their separate corners ignoring each other for the most part, and for the most part being ignored by everyone outside their immediate community. Maybe PEP 333 will help by making movement between frameworks simpler for application developers. Of course, it may not, since it ignores complex things (it certainly comes nowhere close to addressing the requirements for a Seaside-alike), and any developer who wants to remain portable will not be able to take advantage of this technique. Jp From yaipa at yahoo.com Fri Jan 14 18:40:27 2005 From: yaipa at yahoo.com (yaipa) Date: 14 Jan 2005 15:40:27 -0800 Subject: finding/replacing a long binary pattern in a .bin file In-Reply-To: <41e7a190.821594009@news.oz.net> References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> <41e6293f.725257715@news.oz.net> <10udjc3fmnhro9d@corp.supernews.com> <41e7a190.821594009@news.oz.net> Message-ID: <1105746027.819673.236650@c13g2000cwb.googlegroups.com> Bengt, and all, Thanks for all the good input. The problems seems to be that .find() is good for text files on Windows, but is not much use when it is binary data. The script is for a Assy Language build tool, so I know the exact seek address of the binary data that I need to replace, so maybe I'll just go that way. It just seemed a little more general to do a search and replace rather than having to type in a seek address. Of course I could use a Lib function to convert the binary data to ascii and back, but seems a little over the top in this case. Cheers, --Alan Bengt Richter wrote: > On Thu, 13 Jan 2005 11:40:52 -0800, Jeff Shannon wrote: > > >Bengt Richter wrote: > > > >> BTW, I'm sure you could write a generator that would take a file name > >> and oldbinstring and newbinstring as arguments, and read and yield nice > >> os-file-system-friendly disk-sector-multiple chunks, so you could write > >> > >> fout = open('mynewbinfile', 'wb') > >> for buf in updated_file_stream('myoldbinfile','rb', oldbinstring, newbinstring): > >> fout.write(buf) > >> fout.close() > > > >What happens when the bytes to be replaced are broken across a block > >boundary? ISTM that neither half would be recognized.... > > > >I believe that this requires either reading the entire file into > >memory, to scan all at once, or else conditionally matching an > >arbitrary fragment of the end of a block against the beginning of the > >oldbinstring... Given that the file in question is only a few tens of > >kbytes, I'd think that doing it in one gulp is simpler. (For a large > >file, chunking it might be necessary, though...) > > > Might as well post this, in case you're interested... warning, not very tested. > You want to write a proper test? ;-) > > ----< sreplace.py >------------------------------------------------- > def sreplace(sseq, old, new, retsize=4096): > """ > iterate through sseq input string chunk sequence treating it > as a continuous stream, replacing each substring old with new, > and generating a sequence of retsize returned strings, except > that the last may be shorter depedning on available input. > """ > inbuf = '' > endsseq = False > out = [] > start = 0 > lenold = len(old) > lennew = len(new) > while not endsseq: > start, endprev = old and inbuf.find(old, start) or -1, start > if start<0: > start = endprev # restore find start pos > for chunk in sseq: inbuf+= chunk; break > else: > out.append(inbuf[start:]) > endsseq = True > else: > out.append(inbuf[endprev:start]) > start += lenold > out.append(new) > if endsseq or sum(map(len, out))>=retsize: > s = ''.join(out) > while len(s)>= retsize: > yield s[:retsize] > s = s[retsize:] > if endsseq: > if s: yield s > else: > out = [s] > > if __name__ == '__main__': > import sys > args = sys.argv[:] > usage = """ > Test usage: [python] sreplace.py old new retsize [rest of args is string chunks for test] > where old is old string to find in chunked stream and new is replacement > and retsize is returned buffer size, except that last may be shorter""" > if not args[1:]: raise SystemExit, usage > try: > args[3] = int(args[3]) > args[0] = iter(sys.argv[4:]) > print '%r\n-----------\n%s\n------------' %(sys.argv[1:], '\n'.join(sreplace(*args[:4]))) > except Exception, e: > print '%s: %s' %(e.__class__.__name__, e) > raise SystemExit, usage > -------------------------------------------------------------------- > > As mentioned, not tested very much beyond what you see: > > [ 2:43] C:\pywk\ut>py24 sreplace.py x _XX_ 20 This is x and abcxdef 012x345 zzxx zzz x > ['x', '_XX_', '20', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] > ----------- > Thisis_XX_andabc_XX_ > def012_XX_345zz_XX__ > XX_zzz_XX_ > ------------ > > [ 2:43] C:\pywk\ut>py24 sreplace.py x _XX_ 80 This is x and abcxdef 012x345 zzxx zzz x > ['x', '_XX_', '80', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] > ----------- > Thisis_XX_andabc_XX_def012_XX_345zz_XX__XX_zzz_XX_ > ------------ > > [ 2:43] C:\pywk\ut>py24 sreplace.py x _XX_ 4 This is x and abcxdef 012x345 zzxx zzz x > ['x', '_XX_', '4', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] > ----------- > This > is_X > X_an > dabc > _XX_ > def0 > 12_X > X_34 > 5zz_ > XX__ > XX_z > zz_X > X_ > ------------ > > [ 2:44] C:\pywk\ut>py24 sreplace.py def DEF 80 This is x and abcxdef 012x345 zzxx zzz x > ['def', 'DEF', '80', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] > ----------- > ThisisxandabcxDEF012x345zzxxzzzx > ------------ > > If you wanted to change a binary file, you'd use it something like (although probably let > the default buffer size be at 4096, not 20, which is pretty silly other than demoing. > At least the input chunks are 512 ;-) > > >>> from sreplace import sreplace > >>> fw = open('sreplace.py.txt','wb') > >>> for buf in sreplace(iter(lambda f=open('sreplace.py','rb'):f.read(512), ''),'out','OUT',20): > ... fw.write(buf) > ... > >>> fw.close() > >>> ^Z > > > [ 3:00] C:\pywk\ut>diff -u sreplace.py sreplace.py.txt > --- sreplace.py Fri Jan 14 02:39:52 2005 > +++ sreplace.py.txt Fri Jan 14 03:00:01 2005 > @@ -7,7 +7,7 @@ > """ > inbuf = '' > endsseq = False > - out = [] > + OUT = [] > start = 0 > lenold = len(old) > lennew = len(new) > @@ -17,21 +17,21 @@ > start = endprev # restore find start pos > for chunk in sseq: inbuf+= chunk; break > else: > - out.append(inbuf[start:]) > + OUT.append(inbuf[start:]) > endsseq = True > else: > - out.append(inbuf[endprev:start]) > + OUT.append(inbuf[endprev:start]) > start += lenold > - out.append(new) > - if endsseq or sum(map(len, out))>=retsize: > - s = ''.join(out) > + OUT.append(new) > + if endsseq or sum(map(len, OUT))>=retsize: > + s = ''.join(OUT) > while len(s)>= retsize: > yield s[:retsize] > s = s[retsize:] > if endsseq: > if s: yield s > else: > - out = [s] > + OUT = [s] > > if __name__ == '__main__': > import sys > > > Regards, > Bengt Richter From peter at engcorp.com Sat Jan 29 21:58:43 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 29 Jan 2005 21:58:43 -0500 Subject: cx_freeze error In-Reply-To: <1107048210.548048.152870@z14g2000cwz.googlegroups.com> References: <1107048210.548048.152870@z14g2000cwz.googlegroups.com> Message-ID: zyqnews at 163.net wrote: > I am new to Python. I made a script, and compiled it with cx_freeze, > but I got the following message from it: > > [cxfreeze]$./FreezePython hello.py > Traceback (most recent call last): > File "initscripts/ConsoleKeepPath.py", line 15, in ? > exec code in m.__dict__ > File "FreezePython.py", line 1, in ? > File "optparse.py", line 72, in ? > File "textwrap.py", line 32, in ? > File "textwrap.py", line 81, in TextWrapper > AttributeError: 'module' object has no attribute 'compile' > Does anyone know what I should do ? Possibly do not use the name "re.py" for your own module, as it is the name of a standard library module as well. At least, that's what an analysis of line 81 of "textwrap.py" suggests might be your problem. Do you have a module named "re.py"? -Peter From timj at tolisgroup.com Mon Jan 17 14:21:36 2005 From: timj at tolisgroup.com (brucoder) Date: 17 Jan 2005 11:21:36 -0800 Subject: Adjusting the 1024 byte stdin buffer limit In-Reply-To: References: <1105989047.516986.59990@z14g2000cwz.googlegroups.com> Message-ID: <1105989696.900138.108260@z14g2000cwz.googlegroups.com> Currently, when sending a data stream that exceeds 1024 bytes via stdin, the stream blocks at the 1024th byte. This precludes completion of the submission of the data stream. Tim From daranrife at yahoo.com Fri Jan 28 17:41:22 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 14:41:22 -0800 Subject: Installing Numeric with ATLAS and LAPACK In-Reply-To: References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> <1106940704.164253.134630@c13g2000cwb.googlegroups.com> Message-ID: <1106952082.259581.260410@z14g2000cwz.googlegroups.com> Hi John, When I built Numeric with ATLAS and LAPACK, the eigenvalue calculation took the same amount of time. Per your suggestion, I will capture the output of the build and post it to the Numpy discussion group. Thanks, Daran From jzgoda at gazeta.usun.pl Mon Jan 3 16:57:22 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Mon, 03 Jan 2005 22:57:22 +0100 Subject: How do I make Windows Application with Python ? In-Reply-To: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> Message-ID: BOOGIEMAN wrote: > Well that's it, how do I make Windows Application with Python ??? > Is there simple way that works 100% ? How can I rework visual design > done in VS 2003 to use it for my python program ? Close your eyes, see this model-view-controller in your application, rewrite it in Python using one of its MVC frameworks. You see? It's easy, like that! -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From theller at python.net Tue Jan 11 16:15:36 2005 From: theller at python.net (Thomas Heller) Date: Tue, 11 Jan 2005 22:15:36 +0100 Subject: Windows GUIs from Python References: Message-ID: Luke Skywalker writes: > On Tue, 11 Jan 2005 12:55:42 -0600, Doug Holton wrote: >>You might also be interested in PyGUI although it doesn't have a native >>Windows implementation yet: >>http://nz.cosc.canterbury.ac.nz/~greg/python_gui/ > > Generally speaking, appart from MFC-style programming with Python32, > what are the non-alpha alternatives to write purely Windows apps in > Python today, ie. without the weight of extra bagage like wxWidgets? > > I'm not looking at fancy options, since the apps I write would be fine > with just the core Windows widgets along with a few add-ons like a > grid and the extended Win95 widgets. Well, venster. Although it is most certainly alpha. But with some work... Thomas From mail at tuxipuxi.org Mon Jan 24 04:03:56 2005 From: mail at tuxipuxi.org (Michael Goettsche) Date: Mon, 24 Jan 2005 10:03:56 +0100 Subject: Alternative Ways to install Python 2.4? In-Reply-To: <41F43373.4020003@v.loewis.de> References: <41F43373.4020003@v.loewis.de> Message-ID: <200501241003.56860.mail@tuxipuxi.org> On Monday 24 January 2005 00:29, "Martin v. L?wis" wrote: > Michael Goettsche wrote: > > I convinced my CS teacher to use Python in school. We currently have 2.2 > > installed on a Windows 2000 Terminal server. I asked the system > > administrator to upgrade to Python 2.4, but he didn't succeed in doing > > it. He used the microsoft installer package, which according to him > > crashed when starting. So my question is if there's an alternative way to > > install it(must be easy). Would it be an option to remove 2.2 first and > > then try to install 2.4 again? > > That would be an option, but I doubt it helps. Please have a look at > > http://www.python.org/2.4/bugs.html > > Most likely, you need to upgrade Visual Basic on that machine. > > Of course, without a precise error description, it is hard to tell. > > Regards, > Martin Hi Martin, thanks for your answer, I'll let him know! Michael From steven.bethard at gmail.com Tue Jan 11 02:22:08 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 11 Jan 2005 00:22:08 -0700 Subject: Python3: on removing map, reduce, filter In-Reply-To: References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> <-7mdndrwD_1qOHzcRVn-qQ@comcast.com> Message-ID: <2P2dndqyGbA8437cRVn-sQ@comcast.com> David M. Cooke wrote: > Steven Bethard writes: > >>Some timings to verify this: >> >>$ python -m timeit -s "def square(x): return x*x" "map(square, range(1000))" >>1000 loops, best of 3: 693 usec per loop >> >>$ python -m timeit -s "[x*x for x in range(1000)]" >>10000000 loops, best of 3: 0.0505 usec per loop > > > Maybe you should compare apples with apples, instead of oranges :-) > You're only running the list comprehension in the setup code... > > $ python2.4 -m timeit -s "def square(x): return x*x" "map(square, range(1000))" > 1000 loops, best of 3: 464 usec per loop > $ python2.4 -m timeit "[x*x for x in range(1000)]" > 1000 loops, best of 3: 216 usec per loop > > So factor of 2, instead of 13700 ... Heh heh. Yeah, that'd be better. Sorry about that! Steve From beable+unsenet at beable.com.invalid Fri Jan 14 20:18:13 2005 From: beable+unsenet at beable.com.invalid (Brian Eable) Date: 15 Jan 2005 11:18:13 +1000 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> <1105739748.306557.72120@z14g2000cwz.googlegroups.com> Message-ID: <6e1xcnjxre.fsf@dingo.beable.com> "mr_little" writes: > Brian Eable wrote: > > perl -e '$a="194.109.137.226"; @a = reverse split /\./, $a; for $i > (0..3) { $sum += $a[$i]*(256**$i) } print "sum = $sum\n"' > > > > 226 + 35072 + 7143424 + 3254779904 = 3261958626 > > > > http://3261958626/ > > > > Which is NOT 666. > > Comrade, why perl here? :) Huh? Alt.prophecies.nostradamus is ALL ABOUT PERL! And at the end of the age There shall be a mysterious language Filled with punctuation It will connect many things. > Are you afraid python? :) I asked you to stop calling me python. Feel free to write a python version if you want to. -- It's explained on my website.. but you have to have a bona fide degree in science to understand it Mr. Ruken Dukin Kookin. -- George Hammond http://beable.org From bulba at bulba.com Sun Jan 2 13:39:30 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 02 Jan 2005 19:39:30 +0100 Subject: Speed ain't bad References: <0189t05r3226bkp5e1vtmp0gd6odcsf2qp@4ax.com> <41d6a39b$0$33656$edfadb0f@dread16.news.tele.dk> Message-ID: On Sat, 1 Jan 2005 14:20:06 +0100, "Anders J. Munch" wrote: >> One of the posters inspired me to do profiling on my newbie script >> (pasted below). After measurements I have found that the speed >> of Python, at least in the area where my script works, is surprisingly >> high. > >Pretty good code for someone who calls himself a newbie. >One line that puzzles me: >> sfile=open(sfpath,'rb') >You never use sfile again. Right! It's a leftover from a previous implementation (that used bzip2). Forgot to delete it, thanks. >Another way is the strategy of "it's easier to ask forgiveness than to >ask permission". >If you replace: > if(not os.path.isdir(zfdir)): > os.makedirs(zfdir) >with: > try: > os.makedirs(zfdir) > except EnvironmentError: > pass >then not only will your script become a micron more robust, but >assuming zfdir typically does not exist, you will have saved the call >to os.path.isdir. Yes, this is the kind of habit that low-level languages like C missing features like exceptions ingrain in a mind of a programmer... Getting out of this straitjacket is kind of hard - it would not cross my mind to try smth like what you showed me, thanks! Exceptions in Python are a GODSEND. I strongly recommend to any former C programmer wanting to get rid of a "straightjacket" to read the following to get an idea how not to write C code in Python and instead exploit the better side of VHLL: http://gnosis.cx/TPiP/appendix_a.txt -- It's a man's life in a Python Programming Association. From apardon at forel.vub.ac.be Thu Jan 13 04:42:51 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jan 2005 09:42:51 GMT Subject: reference or pointer to some object? References: <10ubcp136drsu97@corp.supernews.com> Message-ID: Op 2005-01-12, Jeff Shannon schreef : > Torsten Mohr wrote: > >> I still wonder why a concept like "references" was not >> implemented in Python. I think it is (even if small) >> an overhead to wrap an object in a list or a dictionary. > > Because Python uses a fundamentally different concept for variable > names than C/C++/Java (and most other static languages). In those > languages, variables can be passed by value or by reference; neither > term really applies in Python. (Or, if you prefer, Python always > passes by value, but those values *are* references.) I would think the reference was the id. As such python always passes by reference, as the id of the parameter is the id of the argument. > Python doesn't > have lvalues that contain rvalues; Python has names that are bound to > objects. Passing a parameter just binds a new name (in the called > function's namespace) to the same object. > > It's also rather less necessary to use references in Python than it is > in C et. al. You use nothing but references in Python, that is the reason why if you assign a mutable to a new name and modify the object through either name, you see the change through both names. -- Antoon Pardon From cumontrealtrip*nospam* at yahoo.com Sun Jan 30 16:41:13 2005 From: cumontrealtrip*nospam* at yahoo.com (Ian) Date: Sun, 30 Jan 2005 16:41:13 -0500 Subject: Help! Host is reluctant to install Python References: Message-ID: On Wed, 26 Jan 2005 01:40:39 GMT, phr at localhost.localdomain wrote: ... >I think you should look into some type of virtual hosting that gives >you more ability to install your own software. Typing "uml hosting" >(UML is user-mode Linux) into Google finds a lot of such services. If >you find one that you like, post it here, I'm interested in this myself. I'm very happy with uml from tummy.com for 25 USD/month, with good support by email for configuring mod_python in my case. They are also a Pycon sponsor. Ian From harold.fellermann at upf.edu Wed Jan 12 13:16:35 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Wed, 12 Jan 2005 19:16:35 +0100 Subject: Why would I get a TypeEror? In-Reply-To: References: Message-ID: <17ED9138-64C6-11D9-B3E0-003065FB7B26@upf.edu> On 12.01.2005, at 18:35, It's me wrote: > For this code snip: > > a=3 > .... > b=(1,len(a))[isinstance(a,(list,tuple,dict))] > > Why would I get a TypeError from the len function? the problem is, that (1,len(a)) is evaluated, neither what type a actually has (python has no builtin lazy evaluation like ML). You have to do it this way instead: a=3 ... b = isinstance(a,(list,tuple,dict)) and len(a) or 1 - harold - -- The opposite of a correct statement is a false statement. But the opposite of a profound truth may be another profound truth. -- Niels Bohr From bjourne at gmail.com Sun Jan 30 17:33:43 2005 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sun, 30 Jan 2005 23:33:43 +0100 Subject: search engine In-Reply-To: <1107112770.301449.49070@c13g2000cwb.googlegroups.com> References: <1107112770.301449.49070@c13g2000cwb.googlegroups.com> Message-ID: <740c3aec05013014331d15e9d6@mail.gmail.com> > hi all, i?m doing a search engine using python for the spider and php > to make a web for the search. The Database i have choosen is > postgreSQL. Do you think it is a good choosen? Any suggestion? "Databases are implementation details! Considering the database should be deferred as long as possible. Far too many applications are inextricably tied to their databases because they were designed with the database in mind from the beginning. Remember the definition of abstraction: the amplification of the essential and the elimination of the irrelevant. The database is irrelevant at this stage of the project; it is merely a technique used for storing and accessing data, nothing more." (Robert C. Martin, Agile Software Development, p. 194) -- mvh Bj?rn From ajikoe at gmail.com Wed Jan 26 17:50:32 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 26 Jan 2005 14:50:32 -0800 Subject: access private field in python 2.4 In-Reply-To: References: <1106754371.637295.82160@z14g2000cwz.googlegroups.com> <4prkc2-ini.ln1@pluto.i.infosense.no> <1106769651.371856.107960@f14g2000cwb.googlegroups.com> Message-ID: <1106779832.759591.62320@c13g2000cwb.googlegroups.com> thanks Steve.... pujo From dbasch at yahoo.com Thu Jan 20 19:20:09 2005 From: dbasch at yahoo.com (Derek Basch) Date: Thu, 20 Jan 2005 16:20:09 -0800 (PST) Subject: spawn syntax + os.P_WAIT mode behavior + spawn stdout redirection Message-ID: <20050121002009.93434.qmail@web20825.mail.yahoo.com> Hello, *First question* If the syntax of spawnl is: spawnl(mode, path, ...) Why does everyone write it like: os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') or: os.spawnl(os.P_WAIT, "/var/www/db/smm/smm_train", "smm_train", "SMMTrainInput.xml") How is the first 'cp' a path to a file? why does the desired executable have to be named again as the first parameter? *Second question* I have a script test.py which calls another script sleep.py using a spawn. -------------------------------------------------------------- #test.py import os os.spawnv(os.P_WAIT, "/var/www/db/cgi-bin/sleep.py", ["python", "sleep.py"]) #pid = os.spawnl(os.P_WAIT, 'sh', 'sh', '-cv', 'sleep 10; echo fark > /tmp/test.out') -------------------------------------------------------------- -------------------------------------------------------------- #sleep.py import time time.sleep(10) -------------------------------------------------------------- I would expect that the test.py script should take 10sec to return. However it returns immediatly. Perhaps I am calling the sleep.py script incorrectly? Shouldn't it take 10sec to execute since the spawn mode argument is os.P_WAIT? *Third question* If I uncomment the second spawn call in test.py I do not get any output to /tmp/test.out and it also returns immediatly. Can anyone tell me why? Thank You Mighty Python Guru's, Derek Basch __________________________________ Do you Yahoo!? Yahoo! Mail - now with 250MB free storage. Learn more. http://info.mail.yahoo.com/mail_250 From philippe at philippecmartin.com Tue Jan 18 19:18:44 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Wed, 19 Jan 2005 00:18:44 GMT Subject: Tkinter in thread hangs on windows but not on Linux References: Message-ID: Actually, the following link: http://www.astro.washington.edu/owen/TkinterSummary.html seems to say my code is illegal - so I'm now just launching a modless window from the main thread - _seems_ to work On Tue, 18 Jan 2005 11:45:28 +0100, Philippe C. Martin wrote: > Hi, > > I need to pop-up in a "modless" manner some windows from an existing > Tkinter loop. The following code works OK under Linux: the second window > opens, shows the information, and quits cleanly when destroyed. However, > under windows, I get the second window without the content (so I hang in > run I guess), and both the thread and the calling process hang. > > Any clue ? > > Thanks > Philippe > > > > > > #******************************************************************************* > class SC_DOCS(threading.Thread): > __m_smg = None > __m_title = None > def __init__(self,p_msg,p_title): > threading.Thread.__init__(self) > self.__m_msg = p_msg > self.__m_title = p_title > > #******************************************************************************* > def run (self): > l_r = Tk() > l_r.title(self.__m_title) > l_f = Frame(l_r) > l_f.pack(side=TOP, expand=YES, fill=BOTH) > l_st = ScrolledText(l_f) > l_st.pack(side=TOP, expand=YES, fill=BOTH) > l_st.insert(END,self.__m_msg) > > l_r.mainloop() > > > . > . > . > > l_d = SC_DOCS('A MESSAGE', 'A TITLE') > l_d.start() > > > . > . > . From air_jlin at yahoo.com Fri Jan 21 14:13:20 2005 From: air_jlin at yahoo.com (Johnny Lin) Date: 21 Jan 2005 11:13:20 -0800 Subject: Unbinding multiple variables In-Reply-To: <35bnkeF4jpeetU1@individual.net> References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> <35bnkeF4jpeetU1@individual.net> Message-ID: <1106334800.868412.27650@f14g2000cwb.googlegroups.com> thanks everyone for the replies! John Hunter, yep, this is Johnny Lin in geosci :). re using return: the problem i have is somewhere in my code there's a memory leak. i realize return is supposed to unbind all the local variables, but since the memory leak is happening despite return, i thought it might help me track down the leak if i unbound everything explicitly that i had defined in local scope before i returned. or if anyone has recomm. on plugging leaks, would be thankful for any pointers there too. my understanding about locals() from the nutshell book was that i should treat that dictionary as read-only. is it safe to use it to delete entries? thanks again! From philippecmartin at sbcglobal.net Mon Jan 31 17:32:27 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 31 Jan 2005 16:32:27 -0600 Subject: serializing data structures Message-ID: <1107210747.8008.16.camel@localhost> Hi, I am trying to figure out the traps/issues about sending data structures through a TCP/IP socket under the following circumstances: 1) there could be a different O/S on both side of the socket 2) there could be a difference CPU architecure on both side of the socket 3) there could be a different major release of python (ex 2.3 and 2.4) on both side of the socket. I once wrote something in C to do that, but since python usually has a solution for me .... Any clue ? Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From cookedm+news at physics.mcmaster.ca Wed Jan 5 18:33:31 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 05 Jan 2005 18:33:31 -0500 Subject: date/time References: Message-ID: Thomas Guettler writes: > Am Wed, 05 Jan 2005 15:08:37 +0100 schrieb Nader Emami: > >> L.S., >> >> Could somebody help me how I can get the next format of date >> from the time module? > > I don't understand your question. Do you want to have the next day? > > 20041231 --> 20050101 ? > > You can do it like this: > - parse the string with time.strptime > - timetuple[2]+=1 > - mktime(timetuple) # --> secs > - strftime(localtime(secs)) Or using the datetime module: import time, datetime tt = time.strptime('20041231', '%Y%m%d') t = datetime.date.fromtimestamp(time.mktime(tt)) # now in a easier-to-handle form than the time tuple t += datetime.timedelta(days=1) print t.strftime('%Y%m%d') -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From http Sat Jan 22 20:16:04 2005 From: http (Paul Rubin) Date: 22 Jan 2005 17:16:04 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> Message-ID: <7xbrbhosh7.fsf@ruckus.brouhaha.com> "Fredrik Lundh" writes: > > You're not making any bloody sense. > > oh, I make perfect sense, and I think most people here understand > why I found your little "lecture" so funny. if you still don't get > it, maybe some- one can explain it to you. I would appreciate it if someone did. From bokr at oz.net Sun Jan 16 00:55:22 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 16 Jan 2005 05:55:22 GMT Subject: interpret 4 byte as 32-bit float (IEEE-754) References: <34t1p2F4foiplU1@individual.net> <41e952b9$1@nntp0.pdx.net> <41E96302.4020003@web.de> <41e964bc$1@nntp0.pdx.net> Message-ID: <41e9fae6.975536557@news.oz.net> On Sat, 15 Jan 2005 11:00:36 -0800, Scott David Daniels wrote: >G.Franzkowiak wrote: >> Scott David Daniels schrieb: >> >>> franzkowiak wrote: >>> >>>> I've read some bytes from a file and just now I can't interpret 4 >>>> bytes in this dates like a real value. An extract from my program: >>>> def l32(c): >>>> return ord(c[0]) + (ord(c[1])<<8) + (ord(c[2])<<16) + >>>> (ord(c[3])<<24) >>>> ... >>>> value = l32(f.read(4)) <--- 3F 8C CC CD should be 1.11 >>>> >>> OK, here's the skinny (I used blocks & views to get the answer): >>> >>> import struct >>> bytes = ''.join(chr(int(txt, 16)) for txt in '3F 8C CC CD'.split()) >>> struct.unpack('>f', bytes) >>> >>> I was suspicious of that first byte, thought it might be an exponent, >>> since it seemed to have too many on bits in a row to be part of 1.11. >>> >>> -Scott David Daniels >>> Scott.Daniels at Acm.Org >> >> >> Ok, I the string exist with "mystr = f.read(4)" and the solution for >> this case is in your line "struct.unpack('>f', bytes)" >> But what can I do when I want the interpret the content from the Integer >> myInt (*myInt = 0x3F8CCCCD) like 4-byte-real ? >> This was stored with an othes system in a binary file to >> CD CC 8C 3F and now is it in python in value. The conversion is not >> possible. It's right... one of this bytes is an exponent. >> I want copy the memory content from the "value address" to "myReal >> address" and use print "%f" %myReal. >> Is myReal then the right format ? >> What can I do with python, in FORTH is it simple >> ( >f f. ) >> >> gf >> >> >> >If you really want to do this kind of byte fiddling: > http://members.dsl-only.net/~daniels/block.html > >Then: > from block import Block, View > b = Block(4) # enough space for one float (more is fine) > iv = View('i', b) # getting to it as an integer > fv = View('f', b) # same memory as floating point > iv[0] = 0x3F8CCCCD # Here is a sample just using the integer > print fv[0] > >On an Intel/Amd/Generic "PC" machine, you should get 1.1 > Ok, for most bit patterns (except QNANs), you can do it in pure python: ----< i32as_single.py >------------------------------------ class NoQNAN(ValueError): pass # use to flag inability to return QNANs def i32as_single(i): """ (UIAM in my interpretation of a 1995 Pentium Processor Developer's Manual) This converts bits in a 32-bit integer as if they were bits of a single-precision IEEE 754 floating point number to python float +---+---+---+---+---+---+---+---+---+---+---+---+ ... +---+---+---+---+ | s | e e e e e e e eb| b b b ... b b b b0 | +---+---+---+---^---+---+---+---^---+---+---+---^ ... ^---+---+---+---+ 31 30 29 28 27 26 25 24 23 22 21 20 3 2 1 0 where s is the sign bit, and is the only thing that changes between + and - and e..eb is an 8-bit biased (by 127) exponent, and eb is the hidden unit 1 bit followed by 23 b..b0 significant "fraction" bits", normalized so that the most significant bit is always 1 and therefore doesn't have to be stored at eb, except that when all but the sign bit are zero, eb is ignored and the value is then a signed zero value. The binary fraction starting bit is after the hidden '1' bit eb at 23, so viewing bits 0..23 as an integer, we have to divide by 2**23 (or adjust the exponent) to get the 1.xxxx values when the official unbiased exponent is zero (offset value 127). Thus 0x3f800000 is zero unbiased exponent and no other bits, for a value of 1.0 A biased exponent of 255 signifies a NaN, and a biased exponent of zero signifies a denormal (which doesn't have a hidden bit, and whose unit bit is bit 22). Single precision denormals can be normalized in python (double) float format, which is done for the return value. """ signbit = i&0x80000000 if not i&0x7fffffff: return signbit and -0.0 or 0.0 # if -0.0 available biased_exp = (i>>23) & 0xff # bits 30-23 unitbit = biased_exp and 0x800000 or 0 # bit 23, or 0 for denormals significand = i & 0x7fffff # bits 22-0 if biased_exp == 255: if significand: raise NoQNAN, "Sorry, can't generate QNAN from %08x" % i return signbit and -1e9999 or 1e9999 # XXX s/b INF's for sure?? adjexp = (biased_exp or 1) - 127 - 23 # adjusted for denormal posvalue = (significand + unitbit)*2.0**adjexp return signbit and -posvalue or posvalue def test(): import struct num = 0 for sign in (0, 2*(-2**30)): for i3 in xrange(128): num3 = i3<<24 for i2 in xrange(256): print '\r%08x'%(num,), # show progress num2 = i2<<16 # skip mid byte of significand, make 0 # and twiddle only a few bits at the bottom for num0 in xrange(8): num = sign+num3+num2+num0 s = ''.join(map(chr,(num0, 0, i2,((sign and 0x80 or 0)+i3)))) try: ti32as = i32as_single(num) except NoQNAN: continue tstruct = struct.unpack('f', s)[0] # XXX ' no INF ?? if ti32as != tstruct: print '\n%x =>%r\n%r => %r' % (num, ti32as, s, tstruct) if __name__ == '__main__': test() ----------------------------------------------------------- [21:47] C:\pywk\clp>i32as_single.py C:\pywk\clp\i32as_single.py:31: FutureWarning: hex/oct constants > sys.maxint will return positi ve values in Python 2.4 and up signbit = i&0x80000000 7fff0007C:\pywk\clp\i32as_single.py:51: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up print '\r%08x'%(num,), # show progress ff7f0007C:\pywk\clp\i32as_single.py:38: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up raise NoQNAN, "Sorry, can't generate QNAN from %08x" % i fffe0007 Of course, the test() gives a clue how you might write the whole thing using struct by just summing the four chr-ed extracted bytes from the input i ;-) Anyway, a couple things (how to make a QNAN in python without calling struct, and '<' in struct): >>> from i32as_single import i32as_single as i32f >>> i32f(0x3f8ccccd) 1.1000000238418579 >>> i32f(0x00000000) 0.0 >>> i32f(0x7f800000) 1.#INF >>> i32f(0xff800000) -1.#INF But I don't know how to build QNaNs: >>> i32f(0x7f800001) Traceback (most recent call last): File "", line 1, in ? File "i32as_single.py", line 38, in i32as_single raise NoQNAN, "Sorry, can't generate QNAN from %08x" % i i32as_single.NoQNAN: Sorry, can't generate QNAN from 7f800001 Whereas struct does: >>> import struct >>> struct.unpack('f','\x00\x00\x80\x7f')[0] 1.#INF >>> struct.unpack('f','\x01\x00\x80\x7f')[0] 1.#QNAN BTW, your example: >>> struct.unpack('f','\xcd\xcc\x8c\x3f')[0] 1.1000000238418579 >>> i32f(0x3f8ccccd) 1.1000000238418579 But what does this mean? (I wanted to test with little endian unpacking, since that is what I knew I created, but that isn't what '<' means?? ...) >>> struct.unpack('f','\x00\x00\x80\x7f')[0] 1.#INF >>> struct.unpack('<41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <1105229619.776339.218900@c13g2000cwb.googlegroups.com> Message-ID: <41e09f53.362269896@news.oz.net> On 8 Jan 2005 16:13:39 -0800, "Carl Banks" wrote: > >Bengt Richter wrote: >> And, is the whole thing after the '=' an expression? E.g., >> >> x = ( foo(x) where: >> x = math.pi/4.0 >> ) where: >> def foo(x): print 'just for illustration', x > >How would that be any improvement over this? Not in any way except that the idea was not to show the best code, but to show an illustration of possible rules of parsing ;-) > >. x = foo(x) where: >. x = math.pi/4.0 >. def foo(x): print 'just for illustration', x > >Can anyone think of a use case for embedding "where" inside an >expression as opposed to making it part of a simple statement? And, if >so, is the benefit of it worth the massive hit in readability. I guess that might depend on the local-scope effects of 'where:' -- I think it is too early to jump to conclusions one way or the other. At this point I just wanted to clarify what the proposal really was, by asking questions about silly code snippets. > > >> or is this legal? >> >> for y in ([foo(x) for x in bar] where: >> bar = xrange(5) >> ): baz(y) where: >> def baz(arg): return arg*2 > >Here, I can only hope not. One reason I proposed a where...do syntax >is so that, if you wanted to localize a variable to a for loop or some >other compound statement, you could do it with a minimum of fuss. Just because something contorted is _possible_ is not a good reason for limiting a general capability IMO. Why not say instead, "I can only hope no one uses it that way."? > >. where: >. bar = xrange(5) >. def baz(arg): return arg*2 >. do: >. for y in [foo(x) for x in bar]: >. baz(y) > > >> Not trying to sabotage the idea, really, just looking for >clarification ;-) > >That's ok. For it fly, it's got to be able to withstand the flak. I actually like it quite a bit, in spite of the NIH ego thing ;-) Regards, Bengt Richter From nick at craig-wood.com Sun Jan 30 06:30:03 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 30 Jan 2005 11:30:03 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <7xzmysqmxk.fsf@ruckus.brouhaha.com> Message-ID: Skip Montanaro wrote: > Fine. Go build a sumo distribution and track the normal CPython. > The problem isn't all that new. (Take a look at scipy.org for one > take on that theme. Of course Linux distros have been doing their > take on this forever.) If I'm writing code just for fun. I'll be doing on Debian Linux, then I can do apt-get install python-crypto and I'm away. However if I'm writing code for work, it has to work on windows as well, which introduces a whole extra barrier to using 3rd party modules. Something else to compile. Something else to stick in the installer. Basically a whole heap of extra work. I think one of the special things about Python is its batteries included approach, and a crypto library would seem to be an obvious battery to install since it doesn't (or needn't) depend on any other library or application. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Mon Jan 10 18:06:57 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?utf-8?Q?Michel_Claveau_-_abstraction_m=C3=A9t?= =?utf-8?Q?a-galactique_non_triviale_en_fui?= =?utf-8?Q?te_perp=C3=A9tuelle.?=) Date: Tue, 11 Jan 2005 00:06:57 +0100 Subject: Python & unicode Message-ID: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> Hi ! If Python is Ok with Unicode, why the next script not run ? # -*- coding: utf-8 -*- def ?????(toto): return(toto*3) aret = ?????(4) @-salutations -- Michel Claveau -------------- next part -------------- An HTML attachment was scrubbed... URL: From apardon at forel.vub.ac.be Mon Jan 10 08:12:28 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Jan 2005 13:12:28 GMT Subject: tuples vs lists References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dfe2a6$0$22729$636a15ce@news.free.fr> Message-ID: Op 2005-01-08, Bruno Desthuilliers schreef : > worzel a ?crit : >> I get what the difference is between a tuple and a list, but why would I >> ever care about the tuple's immuutability? > > Because, from a purely pratical POV, only an immutable object can be > used as kay in a dict. This is not true. > So you can use tuples for 'composed key'. lists can be so used too. Just provide a hash. -- Antoon Pardon From inyeol.lee at siimage.com Tue Jan 11 18:37:29 2005 From: inyeol.lee at siimage.com (Inyeol Lee) Date: Tue, 11 Jan 2005 15:37:29 -0800 Subject: smtpd.py in python2.4/bin directory? Message-ID: <20050111233729.GA27685@siliconimage.com> After installing Python 2.4 from src tarball I found one new executable in python/bin directory - "smtpd.py". I also found the same file in python/lib/python2.4/. Is this intentional or just a minor bug in build script? Inyeol From fredrik at pythonware.com Mon Jan 24 18:05:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 Jan 2005 00:05:02 +0100 Subject: Looking for Form Feeds References: <41F5696D.9030100@novasyshealth.com> <200501241701.33232.hancock@anansispaceworks.com> Message-ID: Terry Hancock wrote: >> I also tried to create a ^M^L (typed in as Q M L) but that >> gives me a syntax error when I try to run the program (re does not like >> the control characters, I guess). Is it possible for me to pull out the >> formfeeds in a straightforward manner? > > I suspect you should convert that to hexadecimal codes: '\x0c\x0b' > (at least I *think* those are the characters you mean, I'm not really > familiar with the ^X notation). you're off by one: >>> hex(ord("M") - 64) '\0xd' >>> hex(ord("L") - 64) '\0xc' >>> chr(ord("M") - 64) '\r' >>> chr(ord("L") - 64) '\x0c' >>> "\f" '\x0c' From ncoghlan at iinet.net.au Thu Jan 27 04:54:32 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 27 Jan 2005 19:54:32 +1000 Subject: Inherting from object. Or not. In-Reply-To: <200501262214.40597.frans.englich@telia.com> References: <1106774681.501533.156220@f14g2000cwb.googlegroups.com> <200501262214.40597.frans.englich@telia.com> Message-ID: <41F8BA58.9060108@iinet.net.au> Frans Englich wrote: > On Wednesday 26 January 2005 21:24, M.E.Farmer wrote: > >>Hello Frans, >>What you are seeing is a step on the path to unification of types and >>classes. > > > I changed all base classes in my project to inherit object. There appears to > be no reason to not do it, AFAICT. Exactly. My advice is to use new-style classes unless you have a reason not to (if you're inheriting from a builtin type, then there is no need to inherit from object as well - the builtin types already have the correct basic type). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ola.natvig at infosense.no Tue Jan 18 09:01:42 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Tue, 18 Jan 2005 15:01:42 +0100 Subject: generator expressions: performance anomaly? In-Reply-To: <354h9gF4fgsqgU1@individual.net> References: <377Hd.77904$Jk5.30235@lakeread01> <354gj7F4etgn8U1@individual.net> <354h9gF4fgsqgU1@individual.net> Message-ID: Diez B. Roggisch wrote: >>Would it be a bad solution to make that a list or tuple of ten >>time.time() calls, you could also restrict what theese prebuilding >>sequenses could contain, or perhaps try to prebuild them, and then fail >>if it's impossible. > > > I don't fully understand what you mean. Restricting them would mean to add > static declarations that say "I return the same whenever you call me" - > which is even more than the already fragile "const" declaration of c++ > allows. > > And for your second suggestion - how exactly do you check for failing? > Generating 2 elements and checking if they are equal to the first two of > the old list? What about overloaded __cmp__/__eq__, or just the last > element differing? > > This problem is too complex to solve automatically - domain knowledge is > needed. As the code Antoon presented also suggests the simple solution: > > > lst = list(time.time() for i in xrange(10)) > tpl = tuple(lst) > > > I don't see why this is a desirable feature at all. Keep in mind that > putting statements or even stackframes between those two statements above > utterly complicates things. And we even didn't dig into the dynamic > features of python that for example make it possible to alter time.time > like this > > time.time = random.random() > > so that it behaves totally different - while the syntactically equivalence > still holds. No chance of catching that. My thoughts where to let the 'leftmost' section of the expression to be intact so that any of the dynamic things done to this part, i.e. replacing time.time with random.random are taken into consideration. What can be done is to extract the expression into a loopless structure lst = list(time.time() for i in xrange(10)) would be compiled to the bytecode version of: lst = [time.time(), time.time(), time.time(), time.time() ...] Then time.time can do whatever it wants to. It's the (x)range function that we need to enshure returns the same values in every execution. This *IS* a useless feature, but I think it's possible to make it work. ola From flamesrock at gmail.com Tue Jan 4 04:17:56 2005 From: flamesrock at gmail.com (flamesrock) Date: 4 Jan 2005 01:17:56 -0800 Subject: Python evolution: Unease In-Reply-To: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> Message-ID: <1104830276.579755.133870@f14g2000cwb.googlegroups.com> Well, I'm not a seasoned programmer like you but I have to say Python is the singlebest language I've worked with to date. In a matter of weeks I learned to do things that took me months in other languages and even found the process enjoyable. Maybe you are right. If so, couldn't Python be forked into something like you describe, while still remaining compatible at the core? (if anyones willing) Python++ anyone? From jacek.generowicz at cern.ch Thu Jan 13 11:41:01 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 13 Jan 2005 17:41:01 +0100 Subject: from __future__ import decorators References: Message-ID: Skip Montanaro writes: > Jacek> Crazy idea ... would it be possible to shadow 2.3's parser with > Jacek> one stolen from 2.4 ? > > If you're willing to go to that much trouble, why not just upgrade to 2.4? *I* upgraded to 2.4 sometime when it was in alpha. From fumanchu at amor.org Fri Jan 7 16:08:05 2005 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 7 Jan 2005 13:08:05 -0800 Subject: DOS problem (simple fix??) Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398131@exchange.hqamor.amorhq.net> Gavin Bauer wrote: > My DOS window (running in windows ME) closes the second it finishes > running my programs. As you can imagine, this makes it hard to see the > results. I've gotten in the habit of putting raw_input("Press enter to > exit") at the end of every program, and in addition to being pain in > the butt, it often fails to work. Being new to programming in general, > I make more mistakes than most people. My programs often have errors > before they get to my raw_input command. They then display the error > and immediately close. It is naturally a lot easier to fix an error > when you know what the error is. This makes debugging even more > annoying than it ordinarily would be, if you can imagine that. I've > heard that it should be a simple preference fix, but I've asked around > and no one seems to know how. > > Thank you, and please make all answers simple enough to be understood > by a highschool student and his father :) . Even after all the IPO hype, the map integration, and the Suggest beta, Google is STILL your friend: http://www.google.com/search?q=windows+console+remain+open In other words, use the /k switch to cmd.exe Robert Brewer MIS Amor Ministries fumanchu at amor.org From rkern at ucsd.edu Sun Jan 30 02:38:15 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 29 Jan 2005 23:38:15 -0800 Subject: Trouble installing numeric In-Reply-To: <20050129232540162-0800@news.claremont.edu> References: <20050129232540162-0800@news.claremont.edu> Message-ID: Chris Weisiger wrote: > I'm trying to install numeric on my MacOS X box using Darwin, with the > eventual goal of satisfying all of PyGame's dependencies so I can > finally start working on my semester project. I would be using MacPython, > except that I can't seem to get its Package Manager to work. Anyway, > when I try to install numeric, I get the following error: > > [HMC-58-125:~/proj/Numeric-23.7] chriswei% sudo ./setup.py install > Password: > running install > running build > running build_py > running build_ext > building 'lapack_lite' extension > gcc -Wl,-F. -Wl,-F. -bundle -framework Python build/temp.darwin-7.6.0- > Power_Macintosh-2.3/Src/lapack_litemodule.o build/temp.darwin-7.6.0- > Power_Macintosh-2.3/Src/blas_lite.o build/temp.darwin-7.6.0-Power_ > Macintosh-2.3/Src/f2c_lite.o build/temp.darwin-7.6.0-Power_Macintosh-2.3/ > Src/zlapack_lite.o build/temp.darwin-7.6.0-Power_Macintosh-2.3/Src/ > dlapack_lite.o -L/usr/lib/atlas -llapack -lcblas -lf77blas -latlas -lg2c - > o build/lib.darwin-7.6.0-Power_Macintosh-2.3/lapack_lite.so -framework > vecLib > ld: can't locate file for: -llapack > error: command 'gcc' failed with exit status 1 > > Previously it had been complaining about a missing directory '/usr/lib/ > atlas', but I just created that (without any idea what it wanted it for > or why it couldn't create it itself, natch). You can delete it. That is the directory specified by default to look for the ATLAS libraries which are a portable optimized LAPACK and BLAS. You don't need it on the Mac because you have vecLib, which is an Apple-provided version of ATLAS, pre-installed. > From what I've found online, > it's now having problems because a linear algebra module it needs ( > lapack) can't be found. However, isn't numeric supposed to have its own > "light" linear algebra code? Yes, however, the ATLAS or vecLib libraries will be much, much faster. > Looking in setup.py, I found the following > section: > > # delete all but the first one in this list if using your own LAPACK/ > BLAS > sourcelist = [os.path.join('Src', 'lapack_litemodule.c'), > # os.path.join('Src', 'blas_lite.c'), > # os.path.join('Src', 'f2c_lite.c'), > # os.path.join('Src', 'zlapack_lite.c'), > # os.path.join('Src', 'dlapack_lite.c') > ] ] > > I tried uncommenting the lines, but no dice. Also modify the library_dirs_list and libraries_list variables, but keep these *_lite.c files commented out. library_dirs_list = [] libraries_list = [] That way, Numeric will just pick up vecLib. This is fixed in CVS. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From rganesan at myrealbox.com Wed Jan 12 03:59:54 2005 From: rganesan at myrealbox.com (Ganesan R) Date: 12 Jan 2005 14:29:54 +0530 Subject: Help Optimizing Word Search References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> Message-ID: >>>>> "Case" == Case Nelson writes: > Hi there I've just been playing around with some python code and I've > got a fun little optimization problem I could use some help with. > Basically, the program needs to take in a random list of no more than > 10 letters, and find all possible mutations that match a word in my > dictionary (80k words). However a wildcard letter '?' is also an > acceptable character which increases the worst case time significantly. > So if the letters are ['a','b','c'] check a, b, c, ab, ac, ba, bc, ca, > cb, abc, acb, bac, bca, cab, cba where only a, ba and cab would be > added to the dict of words. If the letters are ['?','?'] check a-z, aa, > ab, ac, ad, ..., az, ba, bb, bc, bd, ..., zz You're trying to cheat at scrabble aren't you ;-). I once wrote a solution using regular expressions, which I brushed up and posted here. Can you check how it compares with your version? Call as "wordsearch abcd". You can also use wildcards. ===== .#!/usr/bin/python . .import sys .import os .import re . .wordlist = "/usr/share/dict/words" . .def get_freq(str): . """Create a hash of number of times a character occurs in string""" . freq = { } . for c in str: . freq[c] = freq.get(c, 0) + 1 . return freq . . .def main(argv = sys.argv): . chars = argv[1] . if argv[2]: . wordlist = argv[2] . wild = chars.count("?") . if wild: . chars = chars.replace("?", "") # remove the wild cards . if chars: . charpat = "[" + chars + "]*" . else: . charpat = "" . . # create a regexp suitable for matching . pattern = charpat . for w in xrange(wild): . pattern += ".?" + charpat . pattern = "^" + pattern + "$" . print >> sys.stderr, pattern . . # char count for our list of chars . charfreq = get_freq(chars) . . pattern_re = re.compile(pattern, re.IGNORECASE) . # for line in os.popen("zegrep -i '%s' %s" % (pattern, wordlist)): . for line in open(wordlist): . line = line.rstrip() . if not pattern_re.search(line): . continue . if not line or len(line) > len(chars) + wild: . continue . line = line.lower() . linefreq = get_freq(line) . . # check if chars occur fewer times than in the given string . extra = 0 . for c in linefreq.keys(): . if linefreq[c] > charfreq.get(c, 0): . extra += linefreq[c] - charfreq.get(c, 0) . if extra > wild: . break . else: . print line . .if __name__=='__main__': . main() ===== From a at b.c Tue Jan 11 13:51:19 2005 From: a at b.c (Doug Holton) Date: Tue, 11 Jan 2005 12:51:19 -0600 Subject: Game programming in Python In-Reply-To: References: Message-ID: Baza wrote: > I'm looking for any books or on-line resources on game programming using > Python. Does anyone have any advice? See http://pygame.org/ There is also a book called "Game Programming with Python". From chris.lasher at gmail.com Fri Jan 14 15:27:31 2005 From: chris.lasher at gmail.com (Chris Lasher) Date: 14 Jan 2005 12:27:31 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: <1105734450.961150.32980@z14g2000cwz.googlegroups.com> Forgive my ignorance, but what does using mmap do for the script? My guess is that it improves performance, but I'm not sure how. I read the module documentation and the module appears to be a way to read out information from memory (RAM maybe?). From fredrik at pythonware.com Mon Jan 31 12:02:14 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 31 Jan 2005 18:02:14 +0100 Subject: variable declaration References: <1107188359.375703.110590@f14g2000cwb.googlegroups.com> <1107190028.911373.158940@z14g2000cwz.googlegroups.com> Message-ID: Michael Tobis wrote: >> that's a nice theory, but since the decorator line is executed by the >> interpreter, it's a little weak. > > Well, uh, who else would process it? the compiler. from __future__ is a declaration. @expression is an executable statement. From jjcollins at cableone.net Sat Jan 1 22:31:56 2005 From: jjcollins at cableone.net (jcollins) Date: Sat, 1 Jan 2005 19:31:56 -0800 Subject: screen clear question Message-ID: <10teqpdvramua3@corp.supernews.com> Is there a command in Python to clear the screen? That is without writing multiple blank lines. Thanks. Jim C From decoder-x-mac-gujarati at mozilla.org Mon Jan 31 09:08:12 2005 From: decoder-x-mac-gujarati at mozilla.org (decoder-x-mac-gujarati at mozilla.org) Date: Mon, 31 Jan 2005 19:08:12 +0500 Subject: Report Message-ID: <20050131142033.6AAF31E4008@bag.python.org> The original message was received at Mon, 31 Jan 2005 19:08:12 +0500 from [140.253.248.170] ----- The following addresses had permanent fatal errors ----- python-list at python.org From golux at comcast.net Sat Jan 22 21:37:41 2005 From: golux at comcast.net (Stephen Waterbury) Date: Sat, 22 Jan 2005 21:37:41 -0500 Subject: [OT] XML design intent ... further musings In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> <41F2C840.2050304@comcast.net> Message-ID: <41F30DF5.6040002@comcast.net> Peter Hansen wrote: > If merely thinking about the purpose of XML doesn't make it > clear where Steve got that idea ... I meant no disparagement of Steve, and it is quite clear where he got that (correct!) idea ... It's also clear that the XML user community sees that as part of *their* purpose in applying XML. But here we are talking about intent of its designers, and "merely thinking about the purpose of XML" won't enable me to read their minds. ;) > read up a little bit more in > the spec [... in which it is stated rather explicitly!] > > I would ask what part of that, or of the simple phrase > "data object", or even of the basic concept of a markup language, > doesn't cry out "data interchange metalanguage" to you? It does indeed -- my apologies for not reading the annotations more carefully! I missed that one in particular. Okay, you've dragged me, kicking and screaming, to agree that the actual, published design intent of XML is to provide a "data interchange metalanguage". Thanks to Fredrik for the link he included (elsewhere in the "YAML" thread) to JavaScript Object Notation (JSON). JSON looks like a notable improvement over XML for data objects that are more fine-grained (higher ratio of markup to non-markup -- e.g., most relational data sets, RDF, etc.) than those at the more traditional "document" end of the spectrum (less markup, more text). The latter types of data objects are the ones I happen to believe are in the sweet spot of XML's design, regardless of its designers' more sweeping pronouncements (and hopes, no doubt). I should note that I have to deal with XML a lot, but always kicking and screaming (though much less now because of Fredrik's Elementtree package ;). Thanks, Fredrik and Peter, for the references. ;) Peace. Steve From stephen.thorne at gmail.com Mon Jan 31 18:24:57 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Tue, 1 Feb 2005 09:24:57 +1000 Subject: Want to meet any of these people? They are registered for PyCon In-Reply-To: References: Message-ID: <3e8ca5c80501311524614ab544@mail.gmail.com> On Mon, 31 Jan 2005 17:49:53 -0500, Steve Holden wrote: > Aahz wrote: > > In article , > > Steve Holden wrote: > > > >>Note that the sort order isn't perfect - I just sorted on the second > >>"word" in each name. PyCon is a *great* place to meet people and discuss > >>ideas. Hope to see you there. > > > > > > Good thing I'm not coming this year, eh? ;-) > > If you mean specifically for sorting purposes, it would have put the > null second name at the beginning just like you'd expect. Odd, the naive way I would have written such a script would have been: all_names = (line.split() for line in sys.stdin) sys.stdout.writelines(' '.join(x[1])+'\n' for x in sorted((name[1], name) for name in all_names)) which would not have worked correctly, it would have thrown an exception because "Aahz\n".split()[1] does not exist. I guess the second iteration would use name[1:] instead... unfortunately-not-going-to-pycon-ly y'rs. Stephen Thorne From onlyonemc at gmail.com Sun Jan 9 11:36:04 2005 From: onlyonemc at gmail.com (onlyonemc at gmail.com) Date: 9 Jan 2005 08:36:04 -0800 Subject: Long strings as function parameters Message-ID: <1105288564.441842.13060@c13g2000cwb.googlegroups.com> I would like to have functions that operate on long strings, 10-100 MB. In C I would of course pass a pointer to the string for a quick function call. What is an efficient way to do this in python? Cheers, -mark From leipoldw at ace-net.com Sun Jan 2 09:12:58 2005 From: leipoldw at ace-net.com (Walter S. Leipold) Date: Sun, 2 Jan 2005 09:12:58 -0500 Subject: Problems programming with Tkinter Message-ID: Svenglenn writes: > But, i want the program to open a new dialogue when i press > the button "Visa ruta" and in that dialogue will be a field > where you can enter a value directly in the program, but a > can't get it to work because is don't know how i shall do to > open a new dialogue window in the program? For simple data entry (and file choosing, too!), use the built-in Tk dialogs. For example: . import tkSimpleDialog . . answer = tkSimpleDialog.askString( . "Dialog title", . "Prompt", . parent=root, . initialvalue="Howdy!") . if answer is not None: . ...do something... -- Walt From miki.tebeka at zoran.com Tue Jan 11 03:30:56 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 11 Jan 2005 10:30:56 +0200 Subject: embedded scripts debugging In-Reply-To: <347dpqF45nskbU1@individual.net> References: <347dpqF45nskbU1@individual.net> Message-ID: <20050111083028.GE3808@zoran.com> Hello Andrey, > So the question is: Is there suitable library for simple python gui > debugger, or may be there are some other techniques for debugging > embedded scripts? What I usually do is add from pdb import set_trace in the embedded module somewhere and then add a call to set_trace (breakpoint) whenever I with. When the code reaches the call to set_trace, you'll have pdb prompt and you can debug as you like. Note that you can't add breakpoint dynamically this way. HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From http Fri Jan 21 01:24:22 2005 From: http (Paul Rubin) Date: 20 Jan 2005 22:24:22 -0800 Subject: What's the best python web-developer's editor References: Message-ID: <7xwtu7uwo9.fsf@ruckus.brouhaha.com> andy writes: > Anybody like to comment on which editor they use for python web app > development - Emacs For both discrete and mixed python and html code, and why? There's no reason to use anything else. From rnd at onego.ru Sun Jan 9 10:54:03 2005 From: rnd at onego.ru (Roman Suzi) Date: Sun, 9 Jan 2005 18:54:03 +0300 (MSK) Subject: Python3: on removing map, reduce, filter In-Reply-To: <7x4qhqr6cx.fsf@ruckus.brouhaha.com> References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> <7x4qhqr6cx.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 9 Jan 2005, Paul Rubin wrote: >Andrey Tatarinov writes: I hope there will be from __past__ import functional_paradigma in Python 3 ;-) And, also, what is the best way to replace reduce() ? Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From eurleif at ecritters.biz Tue Jan 11 16:05:44 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 11 Jan 2005 16:05:44 -0500 Subject: Python & unicode In-Reply-To: <1105451779.544442.204920@f14g2000cwb.googlegroups.com> References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> <1105451779.544442.204920@f14g2000cwb.googlegroups.com> Message-ID: <34itatF4d4i9kU1@individual.net> Serge.Orlov at gmail.com wrote: > So is the support of Unicode in virtually every computer language > because they don't support ... digits except 0..9. Hex digits aren't 0..9. Python 2.4 (#2, Dec 3 2004, 17:59:05) [GCC 3.3.5 (Debian 1:3.3.5-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 0xCF 207 >>> hex(123) '0x7b' From golux at comcast.net Mon Jan 3 15:16:20 2005 From: golux at comcast.net (Stephen Waterbury) Date: Mon, 03 Jan 2005 15:16:20 -0500 Subject: Developing Commercial Applications in Python In-Reply-To: References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: <41D9A814.7000502@comcast.net> It's me wrote: > Shaw-PTI (www.pti-us.com) uses Python in their software. ... but the "Python Powered" logo is conspicuous by its absence from their site. Too bad that some commercial exploiters of Python don't advertise that fact more often. Every little bit helps! Steve From skip at pobox.com Tue Jan 4 20:54:43 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 Jan 2005 19:54:43 -0600 Subject: Python evolution: Unease In-Reply-To: <7x652che6z.fsf@ruckus.brouhaha.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> Message-ID: <16859.18659.342325.317468@montanaro.dyndns.org> Paul> Skip Montanaro writes: >> Start writing (or reorganizing). Folks, this is open source. I'm >> sure by the traffic on the list most people here know how to write. Paul> Irrelevant, the issue isn't what docs can be written if someone Paul> wants to do it, it's what docs are actually already there. How do you think we got the docs we already have? Somebody wrote them. If there aren't enough docs or if they have mistakes, then somebody has to correct them. I'm just suggesting that more people put their money where they mouths are so-to-speak. >> This being the Internet and all, it's not clear that referencing >> external documentation is somehow worse than incorporating it >> directly into the distribution. Paul> The same thing could be said for software. So why not eliminate Paul> the Python library and let everyone download each module Paul> separately? Because it's bogus is why. Paul> It really does matter whether something is included or just Paul> referenced. Okay, then start doing the work necessary to incorporate that stuff into the core. Get Fredrik to say "okay" to including his Tkinter docs, then do what it takes to incorporate it. The fact that Fredrik can check those docs in himself but hasn't after several years suggests that he prefers the status quo for one or more reasons. I'm not saying references are perfect. I'm saying that given the time constraints of the existing developer crowd and the relative priority of various open tasks that folding in external documentation hasn't risen to the top of the queue yet. The best way to make that happen is for it to be your highest priority and then for you to make it happen. That's a longer-winded way to say what I meant with "this is open source". Paul> And that was just about Tkinter, for which good docs exist but Paul> just don't happen to be in the distro. How about something like Paul> SocketServer, for which no reasonable docs exist at all? I'm at a loss. Is there something about this quote taken directly from the section of the library reference manual entitled "Undocumented Modules" that is unclear? Here's a quick listing of modules that are currently undocumented, but that should be documented. Feel free to contribute documentation for them! (Send via email to docs at python.org.) The list there is itself incomplete. There is a reference manual section for SocketServer, btw: http://www.python.org/doc/current/lib/module-SocketServer.html If that needs examples or corrections or is incomplete, feel free to submit a patch to either SourceForge or by email to docs at python.org. Paul> I'm not trying to bash Python, which is excellent in many ways, or Paul> I wouldn't be using it. I just see various other free software Paul> projects as trying to live up to higher standards and I think Paul> Python should aspire to the same thing. I'm sorry, I don't know quite how to respond to that. Sure, I imagine there are other communities that do it better. I've seen PHP mentioned here recently, and have direct experience with CPAN (and actually like it pretty well). Look, I don't have much free time, and what free time I do have I mostly spend moonlighting on other software (much to my wife's chagrin). I imagine most of the other people who contribute to the Python distribution are similarly time-afflicted. Here are a couple ideas: 1. Do you have more money than time? Donate a few bucks to the PSF: http://www.python.org/psf/ Someone will probably do #2. 2. Do you have more time than money? Write a proposal to the PSF to implement/improve/polish off some aspect of the distribution: http://www.python.org/psf/ 3. Got some free time and don't care about a few extra bucks? Check out how to contribute to Python: http://www.python.org/dev/ >> As for stuff that exists in PEPs and release notes, they should >> already all have the necessary copyright (either they were placed in >> the public domain or they are already part of the Python >> distribution) to allow you do just check out a CVS tree, make the >> necessary edits and either check the files back in or submit a patch >> to SourceForge. Paul> And about that full featured Python web browser and native-code Paul> Python compiler, all you have to do is go write it. Come on. Where did I say to go write a browser or a native-code Python compiler? If that's your bag you can try resurrecting something Grail-like (browser) or contribute time top PyPy or Psyco. When I said "write", I literally meant write, as in English text. Paul> Having to piece together info from a dozen obscure and Paul> inconsistent PEP's and stuff in the CVS tree and source comments Paul> is not what most people think of as "documentation". Paul> Documentation means I can look in the manual and the info is right Paul> there, properly referenced in the table of contents and in the Paul> proper section for that type of language feature, unified with the Paul> rest of the docs. I was suggesting that maybe you might like to take the pieces and make them something coherent. If it was trivial it would have probably been done by now. >> In the documentation arena, I think more thought should probably be >> given to producing online docs that can be directly annotated, thus >> further reducing the barrier to more complete documentation (and more >> updates). Take a look at latex2html, propose or implement changes, >> or just rewrite the damn thing in Python. I think latex2html is >> probably a recurring nightmare for Fred Drake. Paul> I've personally been happy with Texinfo for other kinds of docs Paul> and would consider it easier to deal with than latex2html. It Paul> might even be feasible to edit it in a wiki, so anyone could Paul> improve it easily. Another idea is web-based doc comments like Paul> PHP and MySQL have, so the doc editors can incorporate the info Paul> from the comments in subsequent doc releases. I rather like reST (much of www.python.org is being reimplemented in reST), but that's just me. The key point I was trying to make is that an annotation capability would probably help. With such a feature you could add examples or links to the online Python Cookbook, whatever. Need some ideas? Look here: http://www.amk.ca/diary/archives/003336.html As Andrew indicated, it's a "half-hour hack", but it might give someone something to think about. Skip From ovazquez at gmail.SPAM.com Tue Jan 25 00:49:32 2005 From: ovazquez at gmail.SPAM.com (Orlando Vazquez) Date: Tue, 25 Jan 2005 05:49:32 GMT Subject: Another scripting language implemented into Python itself? In-Reply-To: <10vb8cve125v0b0@corp.supernews.com> References: <10vb8cve125v0b0@corp.supernews.com> Message-ID: Jeff Shannon wrote: snip > Because you cannot make Python secure against a malicious (or ignorant) > user -- there's too much flexibility to be able to guard against every > possible way in which user-code could harm the system. Parsing your own > (limited) scripting language allows much better control over what > user-code is capable of doing, and therefore allows (at least some > measure of) security against malicious code. I don't see how that would equate to something that the original programmer should be concerned about. You could include a bit in your licensing scheme that voids all support on code that has been modified in any way. You shouldn't be obligated and no one expects you to support something the end-user has mucked with. You could trivially enforce this by keeping checksums of all the system files. In any case, there's nothing you can really do to "secure" your code. This is true of any language, C, C++, and especially scripting languages like Python. Anyone who has the determination get at and modify the code probably will. The only time where I can see someone using another language in place of Python for a scripting language is just domain-specific factors, e.g. if you need the extension language to be easily used non-programmers. Just a thought. -- Orlando Vazquez From steven.bethard at gmail.com Wed Jan 26 15:23:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 13:23:17 -0700 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> Message-ID: Jack Diederich wrote: > On Wed, Jan 26, 2005 at 10:23:03AM -0700, Steven Bethard wrote: > >>Jack Diederich wrote: >> >>>Yes, this comes up every couple months and there is only one answer: >>>This is the job of the OS. >>>Java largely succeeds at doing sandboxy things because it was written that >>>way from the ground up (to behave both like a program interpreter and an >>>OS). >>>Python the language was not, and the CPython interpreter definitely was >>>not. >>> >>>Search groups.google.com for previous discussions of this on c.l.py >> >>Could you give some useful queries? Every time I do this search, I get >>a few results, but never anything that really goes into the security >>holes in any depth. (They're ususally something like -- "look, given >>object, I can get int" not "look, given object, I can get eval, >>__import__, etc.) > > > A search on "rexec bastion" will give you most of the threads, > search on "rexec bastion diederich" to see the other times I tried to > stop the threads by reccomending reading the older ones *wink*. > > Thread subjects: > Replacement for rexec/Bastion? > Creating a capabilities-based restricted execution system > Embedding Python in Python > killing thread ? Thanks for the keywords -- I hadn't tried anything like any of these. Unfortunately, they leave me with the same feeling as before... The closest example that I saw that actually showed a security hole made use of __builtins__. As you'll note from the beginning of this thread, I was considering the case where no builtins are provided and imports are disabled. I also read a number of messages that had the same problems I do -- too many threads just say "look at google groups", without saying what to search for. They also often spend most of their time talking about abstract problems, without showing code that illustrates how to break the "security". For example, I never found anything close to describing how to retrieve, say, 'eval' or '__import__' given only 'object'. What would be really nice is a wiki that had examples of how to derive "unsafe" functions from 'object'. I'd be glad to put one together, but so far, I can't find many examples... If you want to consider reading and writing of files as "unsafe", then I guess this might be one: file = object.__subclasses__()[16] If I could see how to go from 'object' (or 'int', 'str', 'file', etc.) to 'eval' or '__import__', that would help out a lot... Steve From nszabolcs at gmail.com Mon Jan 17 16:13:59 2005 From: nszabolcs at gmail.com (nszabolcs) Date: 17 Jan 2005 13:13:59 -0800 Subject: Py_Object* Py_BuildValue, Py_INCREF necessary? References: Message-ID: <1105996439.920021.284470@f14g2000cwb.googlegroups.com> no http://python.org/doc/2.4/api/refcountDetails.html nsz From brent.hughes at comcast.net Tue Jan 11 17:13:10 2005 From: brent.hughes at comcast.net (Brent W. Hughes) Date: Tue, 11 Jan 2005 15:13:10 -0700 Subject: Newbie: Pythonwin Message-ID: 1) I'm running a program within Pythonwin. It's taking too long and I want to stop/kill it. What do I do (other than ctrl-alt-del)? 2) I'm running a long program and I want to minimize it to let it continue to run in the background while I do something else in the foreground. I try clicking on Pythonwin's minimize box but it doesn't respond until the Python program finally quits Then it minimizes! Any way I can do what I want here? Brent From Noah.Richards at infineon.com Mon Jan 3 15:39:29 2005 From: Noah.Richards at infineon.com (Richards Noah (IFR LIT MET)) Date: Mon, 3 Jan 2005 15:39:29 -0500 Subject: Bad Interpreter References: <1104783849.754892.47560@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1104783849.754892.47560 at c13g2000cwb.googlegroups.com... > I have seen some previous messages about such a problem. I have this > problem but it is not clear what the solution really was. > > I am running FC2, python 2.3.3 > > the script i have sock.py runs if i say something like : > > python sock.py > > but ./sock.py results in a :bad interpreter error > how do i troubleshoot something like this? > > regards > What does the first line of your script look like? It needs to be pointing to the python interpreter binary, which you can locate with: which python (on the command line). Check and make sure it is. If it is and you are still getting this problem, post some code and the complete error. HTH. From reinhold-birkenfeld-nospam at wolke7.net Sun Jan 23 02:27:24 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 23 Jan 2005 08:27:24 +0100 Subject: default value in a list In-Reply-To: References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> <1gqs9gb.1mmtpcit05ruwN%aleaxit@yahoo.com> <35fordF4llio5U1@individual.net> Message-ID: <35h1uqF4kn2t2U1@individual.net> Nick Coghlan wrote: > Reinhold Birkenfeld wrote: >>>Why not put these together and put it in itertools, since the requirement seems >>>to crop up every other week? >>> >>> >>> line = "A:B:C".split(":") >>> ... >>> >>> def ipad(N,iterable, default = None): >>> ... return it.islice(it.chain(iterable, it.repeat(default)), N) >>> ... >>> >>> a,b,c,d = ipad(4,line) >>> >>> a,b,c,d >>>('A', 'B', 'C', None) >> >> >> Good idea! >> >> (+1 if this was posted on python-dev!) > > Please, please Google the python-dev archives before doing so ;) I have no intent of doing so, I would leave that to more experienced people... Reinhold ;) From jacek.generowicz at cern.ch Thu Jan 13 04:54:04 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 13 Jan 2005 10:54:04 +0100 Subject: from __future__ import decorators Message-ID: I have some code, which makes copious use of the @decorator syntax which was introduced in Python2.4. Now I find myself in a situation where I have to run the code under Python 2.3. However, I would like to keep developing the code with the new syntax. How could I best automate the process of making the syntax digestible by Python2.3 ? From ialbert at mailblocks.com Wed Jan 12 11:18:17 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Wed, 12 Jan 2005 11:18:17 -0500 Subject: java 5 could like python? In-Reply-To: References: Message-ID: <4MSdnSo5J_xU0HjcRVn-2g@giganews.com> vegetax wrote: > previus two python proyects where relatively big,and python didnt feel > well suited for the task. One typical problem that others might talk about in more detail is that you might be writing java code in python. That means using Java style class hierarchies, methods and overall organization. That does not work well in python. > -No naming convention. That is result of open source model that evolved over a long time. > getAttribute,GetAttribute,get_attribute, then i have to go and check the > doc, every time,which is a waste of time. Create a simple wrapper that does exactly what you want. For example it would take just a few minutes to create a URL class that you wanted. Then you have to figure it out only once. > -Is python library half object oriented? half functional oriented? Yes. As should most solutions be. Istvan. From br44114 at yahoo.com Tue Jan 18 10:40:12 2005 From: br44114 at yahoo.com (bogdan romocea) Date: Tue, 18 Jan 2005 07:40:12 -0800 (PST) Subject: script to automate GUI application (newbie) Message-ID: <20050118154012.91608.qmail@web50306.mail.yahoo.com> Dear Python experts, I have a GUI application (Windows; apparently written in Java) which I want to use through a script (without a mouse or keyboard). First, one of several buttons needs to be clicked (no keyboard shortcuts available, but I can measure the coordinates in pixels from the top left corner of the window to the center of the button to be clicked). Then, a window with a few drop-down lists pops up - I have to make some choices and click OK (it's possible to navigate from one drop-down to the next with Tab, and hit Enter for OK). I want to run the script above from code (if this then click "... and OK") and perhaps by means of several desktop shortcuts (one shortcut for each set of GUI inputs). Is such a script possible? If yes, how do I get there? I searched comp.lang.python but didn't find something directly applicable (or so it seemed to me - I'm a beginner). Directions (and sample code, if possible) will be warmly appreciated. Thank you, b. __________________________________ Do you Yahoo!? Yahoo! Mail - Easier than ever with enhanced search. Learn more. http://info.mail.yahoo.com/mail_250 From nelson at monkey.org Thu Jan 20 19:16:39 2005 From: nelson at monkey.org (Nelson Minar) Date: Fri, 21 Jan 2005 00:16:39 GMT Subject: Python and SOAP References: Message-ID: Peter Schaefer writes: > Is SOAPy still the way to go, or are there better methods? SOAPy hasn't been maintained in awhile. The two contemporary options are ZSI or SOAPpy, both at http://pywebsvcs.sourceforge.net/ ZSI seems to have more serious development now, but neither is perfect. You should consider doing a document/literal service instead of rpc/encoded, the old way. Unfortunately in my experience doc/lit doesn't work as well with Python, but it's a better way of doing things. The ZSI guys are working at it. From http Sun Jan 9 02:01:31 2005 From: http (Paul Rubin) Date: 08 Jan 2005 23:01:31 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> Message-ID: <7x7jmn84s4.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > x = (sqrt(a) where (a=2.0)) + (sqrt(b) where (a=3.0)) Hmm, I like that too. From merkosh at hadiko.de Fri Jan 21 19:54:17 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Sat, 22 Jan 2005 01:54:17 +0100 Subject: make install with python References: <35d4i9F4makucU1@individual.net> Message-ID: Friday 21 January 2005 20:47 pm Reinhold Birkenfeld wrote: [...] > The regular way is to use distutils and a setup.py file (google for > documentation). Ok, thanks. The document described just what I was looking for. Any suggestions how I handle uninstallation? This was provided by automake rather mechanically. I didn't find a section on that in the distutils documentation... :( Uwe From wittempj at hotmail.com Mon Jan 17 12:10:14 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 17 Jan 2005 09:10:14 -0800 Subject: List problems in C code ported to Python In-Reply-To: <41ebed38$0$87063$a1866201@visi.com> References: <41ebed38$0$87063$a1866201@visi.com> Message-ID: <1105981814.317402.192940@f14g2000cwb.googlegroups.com> >>> l = [] >>> for i in range(2): for j in range(2): l[i][j] = 'x' Traceback (most recent call last): File "", line 3, in -toplevel- l[i][j] = 'x' IndexError: list index out of range So you still have to dimension the list before you can use it , eg like >l = [] >for i in range(2): > l.append([]) > for j in range(2): > l[i].append(j) then you do not get the indexerror, but I feel a class is what you need here to make life easier and the program more readable From dave at pythonapocrypha.com Mon Jan 24 14:43:50 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Mon, 24 Jan 2005 12:43:50 -0700 Subject: how to call python code from C# In-Reply-To: <8LGdneLOysys1WjcRVn-1Q@powergate.ca> References: <8LGdneLOysys1WjcRVn-1Q@powergate.ca> Message-ID: <41F54FF6.30209@pythonapocrypha.com> Peter Hansen wrote: > paritosh mahana wrote: > >> How can I call python code from my C# code. [snip] > You could use ctypes or the pywin32 package to provide your > Python code with an ActiveX interface. Then you could just > use it via COM, like any other COM object. Lots of references > available via Google if you want to learn more about this > approach... Lemme add my two cents and say that this approach works well. We have a component that uses ctypes and runs as a COM local server (its own .exe) and we currently use it both from Internet Explorer and from a C# application. COM can be hairy initially, but if you have any experience with COM then this approach is pretty straightforward. -Dave From jimbo at cordiner.com Sun Jan 23 14:24:07 2005 From: jimbo at cordiner.com (jimbo at cordiner.com) Date: Sun, 23 Jan 2005 14:24:07 -0500 Subject: bdb Message-ID: <59B7644A-6D74-11D9-AF9A-000A95AC3812@cordiner.com> Hi, I am trying to sort how to best programmatically run the debugger on a program, and another way that I am trying to explore is by using the bdb module. There isn't any documentation for this and I have tried reading through the source, which includes an example/test at the end of bdb.py on Python 2.3/OS X. What I can't figure out is how this might work if you wanted to have the function 'step' through each line. I see various functions that suggest that they might be for this but I can not get anything to work. Has anyone any suggestions or point me in the direction of any other docs? Thank you! jms. From the bdb.py: def test(): t = Tdb() t.run('import bdb; bdb.foo(10)') where Tbd subclasses Bdp and overrides the user_ methods (see around line 533 of bdb.py. But what about set_step()? Or am I way off here? From beable+unsenet at beable.com.invalid Tue Jan 11 23:53:49 2005 From: beable+unsenet at beable.com.invalid (Brian Eable) Date: 12 Jan 2005 14:53:49 +1000 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: humblythegreatest at usa.com writes: > python.org = 194.109.137.226 > > 194 + 109 + 137 + 226 = 666 BUT! perl -e '$a="194.109.137.226"; @a = reverse split /\./, $a; for $i (0..3) { $sum += $a[$i]*(256**$i) } print "sum = $sum\n"' 226 + 35072 + 7143424 + 3254779904 = 3261958626 http://3261958626/ Which is NOT 666. -- a house-blowing wolfen sneezer / might be a porcine tortfeasor. -- plorkwort http://beable.com From beliavsky at aol.com Sun Jan 30 10:51:58 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 30 Jan 2005 07:51:58 -0800 Subject: Coding style article with interesting section on white space References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> <1gr74p3.1p45u1v182vecgN%aleaxit@yahoo.com> Message-ID: <1107100318.251828.86360@c13g2000cwb.googlegroups.com> Alex Martelli wrote: > > For scientific computation, consider the case of Numeric > > and Numarray. I don't think Numeric binaries are available for Python > > 2.4, > > ? Just > googled and visited the first hit -- I don't currently use Windows so I > don't know if it's still there, works well, etc. I should have Googled. I will investigate that link. At SourceForge, http://sourceforge.net/project/showfiles.php?group_id=1369 I see a Numarray but not a Numeric Windows binary for Python 2.4. The latest Numeric Windows binary there is for Python 2.3. > > > The recent "Pystone Benchmark" message says that Python is only 75% as > > fast on Linux as on Windows. Fortran programs do not suffer this > > performance hit and are in this respect more portable. In theory, as > > You're saying that using a different and better compiler cannot speed > the execution of your Fortran program by 25% when you move it from one > platform to another...?! This seems totally absurd to me, and yet I see > no other way to interpret this assertion about "Fortran programs not > suffering" -- you're looking at it as a performance _hit_ but of course > it might just as well be construed as a performance _boost_ depending on > the direction you're moving your programs. I had in mind the Polyhedron Fortran 90 benchmarks for Windows and Linux on Intel x86 at http://www.polyhedron.co.uk/compare/linux/f90bench_p4.html and http://www.polyhedron.co.uk/compare/win32/f90bench_p4.html . The speed differences of Absoft, Intel, and Lahey between Linux and Windows for individual programs, not to mention the average differential across all programs, is much less than 25%. The differences on a single OS between compilers can be much larger, but that has less bearing on portability across OS's. Thanks for your earlier informative comments on languages. Sparring with Alex Martelli is like boxing Mike Tyson, except that one experiences brain enhancement rather than brain damage :). From aleaxit at yahoo.com Sat Jan 1 12:41:25 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 1 Jan 2005 18:41:25 +0100 Subject: what is lambda used for in real code? References: Message-ID: <1gpq3nl.8f2klu80m2z0N%aleaxit@yahoo.com> Steve Holden wrote: > Adam DePrince wrote: > [...] > > > > In sort, we must preserve the ability to create an anonymous function > > simply because we can do so for every other object type, and functions > > are not special enough to permit this special case. > > > And you'd create an anonymous type how, exactly? >>> type('',(),{}) maybe...? Alex From steve at holdenweb.com Wed Jan 19 11:38:55 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Jan 2005 11:38:55 -0500 Subject: Accessing MDB files on Windows In-Reply-To: <4262806.PViGKJWPeZ@strongwill.g2ctech> References: <1635068.ZTfiooUzB4@strongwill.g2ctech> <4262806.PViGKJWPeZ@strongwill.g2ctech> Message-ID: <57wHd.80954$Jk5.41342@lakeread01> Jorge Luiz Godoy Filho wrote: > Larry Bates, Quarta 19 Janeiro 2005 14:01, wrote: > > >>I'm assuming the application will be run on Windows. > > > You're right. It will be run on Windows. I discarded some other platform > due to the difficulty of supporting this file format. > > >>You can use ODBC or DAO. >> >>An DAO solution that I wrote (and use) can be found >>at: >> >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303349 > > > Thanks! I'm looking at it. > > >>For ODBC you would just use the standard library module. > > > Thanks. I'll be trying the DAO first. > Note that DAO is a very old library, and nowadays ADO would probably be the preferred method in the Windows environment (can DAO even *use* oledb providers?). ADO libraries are available - see http://www.markcarter.me.uk/computing/python/ado.html for example, or Google for "python ado". Bottom line, there are many ways to skin this particular cat. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From donn at u.washington.edu Fri Jan 7 14:35:54 2005 From: donn at u.washington.edu (Donn Cave) Date: Fri, 07 Jan 2005 11:35:54 -0800 Subject: Securing a future for anonymous functions in Python References: <10trlbqnb86tbb0@corp.supernews.com> <7xvfaaaxky.fsf@ruckus.brouhaha.com> <10trupr9cmrtqd0@corp.supernews.com> Message-ID: In article <10trupr9cmrtqd0 at corp.supernews.com>, Jeff Shannon wrote: ... > Hm, I should have been more clear that I'm inferring this from things > that others have said about lambdas in other languages; I'm sadly > rather language-deficient (especially as regards *worthwhile* > languages) myself. This particular impression was formed from a > recent-ish thread about lambdas.... > > http://groups-beta.google.com/group/comp.lang.python/messages/1719ff05118c4a71 > ,7323f2271e54e62f,a77677a3b8ff554d,844e49bea4c53c0e,c126222f109b4a2d,b1c962739 > 0ee2506,0b40192c36da8117,e3b7401c3cc07939,6eaa8c242ab01870,cfeff300631bd9f2?th > read_id=3afee62f7ed7094b&mode=thread > > (line-wrap's gonna mangle that, but it's all one line...) > > Looking back, I see that I've mis-stated what I'd originally > concluded, and that my original conclusion was a bit questionable to > begin with. In the referenced thread, it was the O.P.'s assertion > that lambdas made higher-order and dynamic functions possible. From > this, I inferred (possibly incorrectly) a different relationship > between functions and lambdas in other (static) languages than exists > in Python. One could easily be led astray by that post. He may be right in some literal sense about "the true beauty of lambda function", inasmuch as beauty is in the eye of the beholder, but in practical terms, functions are functions. I took this up on comp.lang.functional some time back. I rewrote a well known piece of Haskell (State monad), moving functions from lambda expressions to named function declarations in a "where" clause and I think undisputably making it easier to understand, and I asserted that this is representative of the general case - lambda is a non-essential feature in Haskell. I don't know if anyone was persuaded, but I didn't see any counter-arguments either. But of course even if I'm right about that, it doesn't mean the feature should be stripped from Haskell, that would be an atrocity. It may not be essential, but it's eminently useful and natural. Is it useful and natural in Python? Is it worth breaking code over? Why do we even bother to discuss this here? There aren't good answers to those questions. Donn Cave, donn at u.washington.edu From swaroopch at gmail.com Tue Jan 25 16:03:29 2005 From: swaroopch at gmail.com (Swaroop C H) Date: Wed, 26 Jan 2005 02:33:29 +0530 Subject: MySQLdb In-Reply-To: <41F6B23E.6010904@bowettsolutions.com> References: <41F6AF8A.3040102@bowettsolutions.com> <351e8871050125125434eb6d2@mail.gmail.com> <41F6B23E.6010904@bowettsolutions.com> Message-ID: <351e887105012513031ff3cc94@mail.gmail.com> > >I think a better option is to have the rows in a text file and then > >use `mysqlimport` or 'load data infile' SQL[1] > > > >[1]: http://dev.mysql.com/doc/mysql/en/load-data.html > > > I remember using that a while ago when I dabbled with mysql so I think > thats a potential solution. With my current solution I get full error > logging with each row i try to insert. Will mysqlimport fail completeley > if one row fails? I've not yet encountered an error using mysqlimport. But the docs at that link say that it might fail completely depending on the type of error. Excerpt: " If you specify IGNORE, input rows that duplicate an existing row on a unique key value are skipped. If you don't specify either option, the behavior depends on whether or not the LOCAL keyword is specified. Without LOCAL, an error occurs when a duplicate key value is found, and the rest of the text file is ignored. With LOCAL, the default behavior is the same as if IGNORE is specified; this is because the server has no way to stop transmission of the file in the middle of the operation. " P.S. Its best to take this discussion off the list since its not directly related to Python. -- Swaroop C H Blog: http://www.swaroopch.info Book: http://www.byteofpython.info From flupke at nonexistingdomain.com Thu Jan 6 10:13:42 2005 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 06 Jan 2005 15:13:42 GMT Subject: 2 versions of python on 1 machine Message-ID: I searched with Google and on this newsgroups and i didn't find any info regarding this. If there is more info, please redirect me to that info. I have version 2.3.4 and 2.4 installed on windows and i thought that by switching the PYTHONPATH parameter to the dir of the 2.4 version that that would make python 2.4 active. However when i envoke python from the commandline, it still runs 2.3.4 Is it possible to have 2 versions installed and switching versions when you need to? How can i do that? Thanks, Benedict From fredrik at pythonware.com Mon Jan 24 06:26:55 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 12:26:55 +0100 Subject: compile python to binary References: <1d6cdae3050123080242bf8994@mail.gmail.com> <1d6cdae30501230826a7b468@mail.gmail.com> Message-ID: Daniel Bickett wrote: >> oh, you mean that "python compiler" didn't mean "the python compiler". >> [snip] > > I simply inferred that he was using the wrong terminology, being that > he said "binary" twice ;-) yeah, but PYC files (which is what the standard compiler produces) are binary files too, in all the usual senses of that word -- and it's not that uncommon that people ship Python programs as a bunch of EXEs/DLLs (or equivalents), and PYC files. From a at b.c Sun Jan 23 02:38:32 2005 From: a at b.c (Doug Holton) Date: Sun, 23 Jan 2005 01:38:32 -0600 Subject: What YAML engine do you use? In-Reply-To: <_cSdnRo1keDOzm7cRVn-ug@comcast.com> References: <35a6tpF4gmat2U1@individual.net> <35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fpq0F4mh1ffU1@individual.net> <_cSdnRo1keDOzm7cRVn-ug@comcast.com> Message-ID: > You might like programming in XML then: http://www.meta-language.net/ Actually, the samples are hard to find, they are here: http://www.meta-language.net/sample.html Programming in XML makes Perl and PHP look like the cleanest languages ever invented. From tanghaibao at gmail.com Wed Jan 26 15:43:19 2005 From: tanghaibao at gmail.com (Haibao Tang) Date: 26 Jan 2005 12:43:19 -0800 Subject: [perl-python] 20050126 find replace strings in file In-Reply-To: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> References: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> Message-ID: <1106772199.500554.117700@z14g2000cwz.googlegroups.com> OK. But please don't die throwing that string, or this post will lose its educational purpose as it was meant to be. From rm at rm.net Sat Jan 22 16:43:24 2005 From: rm at rm.net (rm) Date: Sat, 22 Jan 2005 22:43:24 +0100 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> Message-ID: <35fvroF4kngkmU1@individual.net> Doug Holton wrote: > rm wrote: > >> this implementation of their idea. But I'd love to see a generic, >> pythonic data format. > > > That's a good idea. But really Python is already close to that. A lot > of times it is easier to just write out a python dictionary than using a > DB or XML or whatever. Python is already close to YAML in some ways. > Maybe even better than YAML, especially if Fredrik's claims of YAML's > inherent unreliability are to be believed. Of course he develops a > competing XML product, so who knows. true, it's easy enough to separate the data from the functionality in python by putting the data in a dictionary/list/tuple, but it stays source code. rm From peter at somewhere.com Mon Jan 10 02:48:01 2005 From: peter at somewhere.com (Peter Maas) Date: Mon, 10 Jan 2005 08:48:01 +0100 Subject: SuSE 9.1: updating to python-2.4 In-Reply-To: References: Message-ID: Torsten Mohr schrieb: > along with my distribution SuSE 9.1 came python 2.3.3. > > I'd like to update to 2.4 now, is this an easy thing to do > or will lots of installed modules refuse to work then? > > Is there an easy way to find out what i need to update? I uninstalled 2.3.3 and compiled/installed 2.4 from source. Now there is a problem: each time I change my system, SuSE tries to reinstall 2.3.3 because of dependencies. I tried to mark SuSE-Python as tabu (taboo?) but this it isn't stored. Not sure if it is my fault or SuSE's. I'm too lazy to track it down. Perhaps you can do a regular upgrade via FTP. I didn't try that. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From peter at engcorp.com Thu Jan 20 21:02:09 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Jan 2005 21:02:09 -0500 Subject: Print a string in binary format In-Reply-To: <1106270502.219126.322790@f14g2000cwb.googlegroups.com> References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> <1106270502.219126.322790@f14g2000cwb.googlegroups.com> Message-ID: <7OidnfGojPU8_23cRVn-gg@powergate.ca> neutrino wrote: > Mmm, the output format that I want is like: > 0001110011111111000000001111111100000000.... > > I tried your code on Cygwin under Windows 2000, and on Linux, but it > prints out ASCII characters. Generally speaking, trying to work with binary like that will drive you mad. Most people find themselves far more productive learning to work with hexadecimal, which is nice in this case since you'll automatically get the hex representation of any non-printable character if you just print the string with repr() around it. -Peter From cpghost at cordula.ws Thu Jan 13 20:58:31 2005 From: cpghost at cordula.ws (Cordula's Web) Date: 13 Jan 2005 17:58:31 -0800 Subject: Gecko bindings for Python? References: <1105456257.275667.6260@f14g2000cwb.googlegroups.com> Message-ID: <1105667911.010343.275380@c13g2000cwb.googlegroups.com> Yes, that's exactly what I needed! Thanks alot! -cpghost. -- Cordula's Web. http://www.cordula.ws/ From http Thu Jan 6 17:53:19 2005 From: http (Paul Rubin) Date: 06 Jan 2005 14:53:19 -0800 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <10trej2fl8dip65@corp.supernews.com> Message-ID: <7xhdluuq3k.fsf@ruckus.brouhaha.com> Jeff Shannon writes: > Note that the so-called 'viral' nature of GPL code only applies to > *modifications you make* to the GPL software. Well, only under an unusually broad notion of "modification". The GPL applies to any program incorporating GPL'd components, e.g. if I distribute a Python compiler that incorporates some component from GCC, then my entire Python compiler must be GPL'd even though the GCC component is isolated inside the Python compiler and I wrote the rest of the Python compiler myself. If I don't like this, I have an obvious recourse, which is don't use GCC components in my Python compiler. The notion here is that the GCC components are attractive enough that being able to use them provides an incentive to GPL my Python compiler, which I might not do otherwise. > (Problems may come if someone licenses a library under the GPL; that's > what the LGPL was invented for. But the issue here is not that the > GPL is bad, it's that the author used the wrong form of it.) The "problem" is not a problem except that in the case of some libraries, simply being able to use a library module is often not enough incentive to GPL a large application if the library module's functionality is available some other way (including by reimplemntation). If the library does something really unique and difficult, there's more reason to GPL it instead of LGPL'ing it. > The 'infective' nature of the GPL *only* comes when you make use of > the *extra* privelidges that open source grants. So yes, those extra > privelidges come with a price (which is that you share what you've > done); but if you don't want to pay that price, you have the choice of > not using those privelidges. This does not, in any way, prevent you > from using GPL'ed software as a user. Well put. From davorss at gmail.com Wed Jan 26 22:28:45 2005 From: davorss at gmail.com (Davor) Date: Wed, 26 Jan 2005 22:28:45 -0500 Subject: python without OO In-Reply-To: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: I'd like to thank everyone for their replies. The main important lesson I got is: Python does not have that many issues with misuse of OO as compared to Java/C++ because it's *dynamically* typed language and extremely powerful *dictionary* data structure. I browsed docs a bit today, and they also confirm what I have believed - that OO is totally secondary in Python. In fact, object/classes/metaclasses are nothing but *dictionaries with identity* in python. Love this approach. In fact, you can very easily implement your own *OO model* completely separate of Python's OO model... Now I actually strongly believe that Python's author has introduced the whole OO model just to attract and make happy OO population... In fact, *Python's dynamic type checking mechanisms + dictionary is way more powerful than Java/C++'s static type checking mechanisms + their OO mechanisms* and you can definitely be more productive using Python's structured programming than Java/C++ OO programming :-)... and Python is probably the best example why we should have skipped OO all together.. --- second, instead of playing with OO plagued design principles do as follows: 1. separate data, functionality, and structure from each other as much as you can (in Python only valid structural element I've seen so far is module - ignore objects & classes!) 2. do not assume any have identity (even if the underlying language model provides and uses one) - so don't pass them around and crazy stuff... so you get a nice program with separate data structures and functions that operate on these data structures, with modules as containers for both (again ideally separated). Very simple to do and maintain no matter what OO preachers tell you... Davor From steven.bethard at gmail.com Fri Jan 28 20:37:49 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 28 Jan 2005 18:37:49 -0700 Subject: limited python virtual machine In-Reply-To: <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Steven Bethard wrote: > ... > >>If I could see how to go from 'object' (or 'int', 'str', 'file', etc.) >>to 'eval' or '__import__', that would help out a lot... > > >>>>object.__subclasses__() > > [, , , , > , , , 'module'>, , , > , , , 'site._Printer'>, , , ] > > Traipse through these, find one class that has an unbound method, get > that unbound method's func_globals, bingo. Thanks for the help! I'd played around with object.__subclasses__ for a while, but I hadn't realized that func_globals was what I should be looking for. Here's one route to __builtins__: py> string_Template = object.__subclasses__()[17] py> builtins = string_Template.substitute.func_globals['__builtins__'] py> builtins['eval'] py> builtins['__import__'] Steve From python at hope.cz Fri Jan 14 15:37:10 2005 From: python at hope.cz (python at hope.cz) Date: 14 Jan 2005 12:37:10 -0800 Subject: Index server Message-ID: <1105735030.574794.74400@z14g2000cwz.googlegroups.com> Is there an Index server available in Python? For example: I have large intranet with several servers and I would like to index documents like search engines do. Users then can search for a domument in ALL intranet servers like I do on Google. Thanks for answers L.A. From steve at holdenweb.com Sat Jan 8 15:00:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 08 Jan 2005 15:00:05 -0500 Subject: windows mem leak In-Reply-To: References: Message-ID: <41XDd.70234$Jk5.40626@lakeread01> Bob Smith wrote: > Does the Win32 port of Python have a memory leak? I have some code that > runs flawlessly on Linux, but bombs after a few hours on Windows. It's > threaded and uses a lot of memory. > > Thanks! Yes, that's a well-known problem. Code that runs with a few errors will port without any trouble at all to Windows, but once it runs flawlessly on Linux it starts to leak memory on Windows. The PSU suspects a plot in Redmond, the basic details of which ar -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From steven.bethard at gmail.com Tue Jan 25 18:50:28 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Jan 2005 16:50:28 -0700 Subject: string.atoi and string.atol broken? In-Reply-To: References: Message-ID: Mike Moum wrote: >>>>> s.atoi('4',3) >> >> Traceback (most recent call last): >> File "", line 1, in -toplevel- >> s.atoi('4',3) >> File "/usr/lib/python2.3/string.py", line 220, in atoi >> return _int(s, base) >> ValueError: invalid literal for int(): 4 What did you expect the value of '4' in base 3 to be? There is no '4' in base 3... only '0', '1' and '2'. >>>>> s.atoi('8',4) >> >> Traceback (most recent call last): >> File "", line 1, in -toplevel- >> s.atoi('8',4) >> File "/usr/lib/python2.3/string.py", line 220, in atoi >> return _int(s, base) >> ValueError: invalid literal for int(): 8 And no '8' in base 3 either. > Is this a bug, or am I missing something obvious? Well, first of all, unless you're using a Python before 2.0, you're missing that string.atoi is deprecated. You should be using int(), which can take the same parameters. I think secondly, you're missing that int(string, base) converts the given string to an int assuming that the string is in the given base. If the numbers you provide are out of the range of the digits that are valid for that base, you will get an error. Steve From jhefferon at smcvt.edu Tue Jan 11 08:45:26 2005 From: jhefferon at smcvt.edu (Jim) Date: 11 Jan 2005 05:45:26 -0800 Subject: Upgraded to python2.3 but httpd taking old version In-Reply-To: References: Message-ID: <1105451126.934903.142100@f14g2000cwb.googlegroups.com> Gurpreet Sachdeva wrote: > I upgraded my python to 2.3 from 2.2 but > [Tue Jan 11 16:18:45 2005] [error] [client 127.0.0.1] import cgi > [Tue Jan 11 16:18:45 2005] [error] [client 127.0.0.1] File > "/usr/lib/python2.2/cgi.py", line 38, in ? Does the first line of your file say #!/usr/bin/python2.3 (or whatever is appropriate for your system)? Jim From luisXX_lupe2XX at netvisaoXX.pt Thu Jan 20 08:05:59 2005 From: luisXX_lupe2XX at netvisaoXX.pt (Luis P. Mendes) Date: Thu, 20 Jan 2005 13:05:59 +0000 Subject: xml parsing escape characters In-Reply-To: <41eeda3a$0$27828$9b622d9e@news.freenet.de> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> Message-ID: <359o5cF4il48kU1@individual.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 this is the xml document: <DataSet> ~ <Order> ~ <Customer>439</Customer> (... others ...) ~ </Order> </DataSet> When I do: print xmldoc.toxml() it prints: <DataSet> ~ <Order> ~ <Customer>439</Customer> ~ </Order> </DataSet> __________________________________________________________ with: stringNode = xmldoc.childNodes[0] print stringNode.toxml() I get: <DataSet> ~ <Order> ~ <Customer>439</Customer> ~ </Order> </DataSet> ______________________________________________________________________ with: DataSetNode = stringNode.childNodes[0] print DataSetNode.toxml() I get: <DataSet> ~ <Order> ~ <Customer>439</Customer> ~ </Order> </DataSet> _______________________________________________________________- so far so good, but when I issue the command: print DataSetNode.childNodes[0] I get: IndexError: tuple index out of range Why the error, and why does it return a tuple? Why doesn't it return: <Order> <Customer>439</Customer> </Order> ?? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFB76y3Hn4UHCY8rB8RAvQsAKCFD/hps8ybQli8HAs3iSCvRjwqjACfS/12 5gctpB91S5cy299e/TVLGQk= =XR2a -----END PGP SIGNATURE----- From crap1234 at hotmail.com Sun Jan 2 10:02:28 2005 From: crap1234 at hotmail.com (Stefan Axelsson) Date: Sun, 02 Jan 2005 16:02:28 +0100 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> Message-ID: <33qgo5F42kl0bU1@individual.net> Roy Smith wrote: > In perl, I always use "use strict", but in Python, I just don't feel the > need. Between the exception mechanism and unit tests, the odds of a > typo going unnoticed for very long are pretty slim. I'll admit I don't > use Pychecker, but if I was doing production code, I would probably use > it as part of my QA process. Well, I don't have any experience with Python in the industrial setting (all my Python has been solo so far). I do have quite a bit of experience with Erlang (http://www.erlang.org) though, and while I agree that it's not quite as bad in practice as the most vocal static typing people would have it, it's not all roses either. The problem with unit tests is that they can be skipped (and frequently are) and you also have to be certain you exercise all code paths, even to detect a simple typo. It's not that these survive for 'very long' or (God forbid) to the final product, but many of them survive for long enough that they cost more than they should/would have. So *if* (substantial 'if' I realise that) my Erlang experiences generalises to this case, I'd say the benefits would outweigh the cost. Then again I'm seriously considering going back to Haskell, so I guess I'm at least a little biased. :-) :-) Stefan, -- Stefan Axelsson (email at http://www.cs.chalmers.se/~sax) From mritty at gmail.com Tue Jan 25 13:36:52 2005 From: mritty at gmail.com (Paul Lalli) Date: Tue, 25 Jan 2005 18:36:52 GMT Subject: [perl-python] 20050125 standard modules References: <1106669614.666772.17750@z14g2000cwz.googlegroups.com> Message-ID: <8lwJd.10520$Dz2.6624@trndny09> "Xah Lee" wrote in message news:1106669614.666772.17750 at z14g2000cwz.googlegroups.com... -------------------------- > in perl, i don't think there is one way to > list available modules. > I'm torn between knowing that I shouldn't feed trolls, and my hatred of leaving faulty information about Perl unchecked, where some unsuspecting newbie might stumble across it. So to those newbies, you should know that just because this clown doesn't think there's a way, does not in any way imply that there actually isn't a way. For a list of standard modules included in your distribution of Perl, run the following command in your shell: perldoc perlmodlib To get a list of non-standard modules that have already been installed, read the documentation for the ExtUtils::Installed module: perldoc ExtUtils::Installed To see what other modules are available to be downloaded, visit http://www.cpan.org Paul Lalli From warren_brown at csgsystems.com Tue Jan 11 17:24:54 2005 From: warren_brown at csgsystems.com (Brown, Warren R) Date: Tue, 11 Jan 2005 17:24:54 -0500 Subject: Python script produces "sem_trywait: Permission denied" Message-ID: <67C0A7BD9AAF714C8A33B986DF5738C40BB019@cmaexch01.csg.csgsystems.com> I've seen these messages too on AIX 5.2. It seems to come from doing an "import" on piped/fork processes with a python parent. (In particular import errno) I don't know the "proper" solution but I got rid of the messages (similar messages came up when I ran my app) by hacking Python/thread_pthread.h. There's a CHECK_STATUS macro the does a perror if any of the sem_* functions don't return an acceptable status. I just commented out the perror (didn't seem to hurt the python tests or my app) but I hope that someone more knowledgeable about Python internals might tell me if a more serious problem is looming. --- warren. -------------- next part -------------- An HTML attachment was scrubbed... URL: From spam-trap-095 at at-andros.demon.co.uk Sun Jan 30 11:11:36 2005 From: spam-trap-095 at at-andros.demon.co.uk (Andrew McLean) Date: Sun, 30 Jan 2005 16:11:36 +0000 Subject: Coding style article with interesting section on white space References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> <1gr74p3.1p45u1v182vecgN%aleaxit@yahoo.com> Message-ID: In article <1gr74p3.1p45u1v182vecgN%aleaxit at yahoo.com>, Alex Martelli writes >You're saying that using a different and better compiler cannot speed >the execution of your Fortran program by 25% when you move it from one >platform to another...?! This seems totally absurd to me, and yet I see >no other way to interpret this assertion about "Fortran programs not >suffering" -- you're looking at it as a performance _hit_ but of course >it might just as well be construed as a performance _boost_ depending on >the direction you're moving your programs. > >I think that upon mature consideration you will want to retract this >assertion, and admit that it IS perfectly possible for the same Fortran >program on the same hardware to have performance that differs by 25% or >more depending on how good the optimizers of different compilers happen >to be for that particular code, and therefore that, whatever point you >thought you were making here, it's in fact totally worthless. Look at the Fortran compiler benchmarks here: http://www.polyhedron.co.uk/compare/win32/f77bench_p4.html for some concrete evidence to support Alex's point. You will see that the average performance across different benchmarks of different Fortran compilers on the same platform can be as much a factor of two. Variation of individual benchmarks as much as a factor of three. Some of you might be surprised at how many different Fortran compilers are available! -- Andrew McLean From tim.golden at viacom-outdoor.co.uk Tue Jan 18 10:58:13 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 18 Jan 2005 15:58:13 -0000 Subject: script to automate GUI application (newbie) Message-ID: <9A28C052FF32734DACB0A288A35339910359CA@vogbs009.gb.vo.local> [bogdan romocea] | I have a GUI application (Windows; apparently written in Java) which I | want to use through a script (without a mouse or keyboard). First, one | of several buttons needs to be clicked (no keyboard shortcuts | available, but I can measure the coordinates in pixels from the top | left corner of the window to the center of the button to be clicked). | Then, a window with a few drop-down lists pops up - I have to | make some | choices and click OK (it's possible to navigate from one drop-down to | the next with Tab, and hit Enter for OK). | | I want to run the script above from code (if this then click "... and | OK") and perhaps by means of several desktop shortcuts (one shortcut | for each set of GUI inputs). | | Is such a script possible? If yes, how do I get there? I searched | comp.lang.python but didn't find something directly applicable (or so | it seemed to me - I'm a beginner). Directions (and sample code, if | possible) will be warmly appreciated. Have a look at WATSUP. I think it's the kind of thing you're after. http://www.tizmoi.net/watsup/intro.html TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From michele.simionato at gmail.com Mon Jan 3 09:40:04 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 3 Jan 2005 06:40:04 -0800 Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) In-Reply-To: References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <87u0py6elt.fsf@sme.intra.citec.fi> Message-ID: <1104763204.261322.59520@c13g2000cwb.googlegroups.com> Just wrote: > In article <87u0py6elt.fsf at sme.intra.citec.fi>, > Simo Melenius wrote: > > > I've sometimes replaced sys.stdout (and/or sys.stderr) to > > capture/redirect debugging information in existing code that has > > unwisely just "print"ed error and warning messages, instead of using > > sys.stderr or error logging modules. > > > > py> def with_output_to_string (func): > > ... try: > > ... sys.stdout = StringIO.StringIO () > > ... func () > > ... return sys.stdout.getvalue () > > ... finally: > > ... sys.stdout = sys.__stdout__ > > Aargh, I can't believe how widespread this idiom is :-(. See my other > reply in this thread: DON'T use sys.__stdout__. Ever. > > Just From tundra at tundraware.com Thu Jan 27 23:08:18 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 27 Jan 2005 23:08:18 EST Subject: tkinter: Can You Underline More Than 1 Char In A Menu Title In-Reply-To: References: Message-ID: Jeff Epler wrote: > On Thu, Jan 27, 2005 at 06:38:22AM -0500, Tim Daneliuk wrote: > >>Is it possible to underline more than a single character as I am doing >>with the 'underline=0' above. I tried 'underline=(0,2)' but that didn't >>work. > > > No. > > Jeff I love a clear answer ;) thanks... -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From dbickett at gmail.com Tue Jan 25 23:13:35 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Tue, 25 Jan 2005 23:13:35 -0500 Subject: Help! Host is reluctant to install Python In-Reply-To: References: Message-ID: <1d6cdae30501252013212d71fe@mail.gmail.com> On phr at localhost.localdomain wrote: > Daniel Bickett writes: > > I've been trying to convince my host to install python/mod_python on > > his server for a while now, however there are a number of reasons he > > is reluctant to do so, which I will outline here: > > I'm surprised that you're getting such detailed answers from him. > Usually, low-cost web hosts want to offer a one-size-fits-all package > that requires minimal interaction with customers. If you're paying > $10 a month for hosting and a host admin has to spend 1 hour sending > you email, that probably wipes out at least 6 months of profits from > you as a customer. If you want custom service you usually have to pay > a lo tmore. I know him personally, which is part of my reluctance to ditch him entirely as most of you have suggested ;-) Suffice it to say I was able to gain access to a 2.2 installation that was already on the server, however for my intents and purposes I need a minimum of 2.3. Now I'm working on getting him to upgrade to 2.4 and install mod_python :) New quick question: As for the former, on the download page it states that the RPM distribution is sufficient for Fedora Core 3 *and similar*, and I'm curious to know if that applies to Red Had Enterprise as well. Thank you all for your answers and your time. P.S. As for your pricing question, I only pay $20 a year. His services are very affordable. You can see them all at the following link: http://www.snorland.com/webhosting/ -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ From roy at panix.com Wed Jan 26 11:42:43 2005 From: roy at panix.com (Roy Smith) Date: 26 Jan 2005 11:42:43 -0500 Subject: Help With Python References: Message-ID: In article , Judi Keplar wrote: > >I am currently taking a course to learn Python and was looking for >some help. I need to write a Python statement to print a comma- >separated repetition of the word, "Spam", written 511 times ("Spam, >Spam, =85 Spam"). > >Can anybody help me get started? I am completely new to programming! Well, I'll point you in a couple of good directions. The first direction would be to approach this as a traditional procedural programming problem. You need some kind of loop that can exectute a print statement 511 times. In Python, that looks something like: for i in range(511): print "spam" Almost immediately, the question that comes to mind is where, exactly, does the loop start and stop? For example, you might expect that for i in range(5): print i would print the numbers 1 through 5, but it really prints 0 through 4. This kind of "off by one" thing is a very common common issue in writing loops in almost any programming language. It's a common enough issue that a whole class of bugs is named after it, known as "fencepost errors". So, left as an exercise for the reader (i.e. you), is to figure out if "for i in range(511)" really does the loop 511 times, or maybe 510 or 512? Next, you'll notice that the first loop I wrote prints one "spam" on each line. The way you described the problem, you want all the spams on one big long line, with commas between each one. The way you get Python to not advance to the next line is to end the print statement with a comma, like this: for i in range(511): print "spam", Notice that there's something tricky going on here; the comma doesn't get printed, it's just a way of telling the print statement, "don't go on to the next line". To really get it to print a comma, you need something like: for i in range(511): print "spam,", The first comma is inside the quoted string, so it gets printed. The second one is the one that says "don't go to the next line". You're still not quite done, but I've given you enough hints. Go play with that, see what you get, and see if you can figure out what problems you still need to fix. I said I'd point you in a couple of good directions, and the second one is to look up how the "join()" string method works. It's really cool, and solves your problem in a different way. But, first I think you should master the straight-forward way. Lastly, the really cool Pythonic way would be to get a bunch of Vikings into a restaurant and give them all breakfast menus. The only problem there is you'd have trouble handing all those Vikings in with your assignment. From kartic.krishnamurthy at gmail.com Fri Jan 21 12:27:56 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 21 Jan 2005 09:27:56 -0800 Subject: Tarfile module error In-Reply-To: References: Message-ID: <1106328476.921762.178630@c13g2000cwb.googlegroups.com> Your NewBackupFilename contains ":" which is not a valid character in a filename in Windows. You could do something like this: >>> NewBackupFilename = DirBackup + '\\' + '%s' % str(datetime.today()).replace(':', '-') + '.tar.bz2' >>> NewBackupFilename 'c:\\\\skpdc01\\\\Backups\\2005-01-21 12-26-21.373000.tar.bz2' >>> TarFileBackup = tarfile.open(NewBackupFilename, 'w:bz2') >>> # Works! I changed your DirBackup to 'C:\skpdc01\Backups' Thanks, --Kartic From wuwei23 at gmail.com Thu Jan 20 20:07:49 2005 From: wuwei23 at gmail.com (alex23) Date: 20 Jan 2005 17:07:49 -0800 Subject: iteritems() and enumerate() References: <1106206068.867004.195010@f14g2000cwb.googlegroups.com> <8bSdnaEf8cvk_XLcRVn-gg@speakeasy.net> Message-ID: <1106269669.338937.184220@c13g2000cwb.googlegroups.com> Erik Max Francis wrote: > You would be funnier if you weren't so incompetent. No, even if he was more competent, he'd still be a vicious, pointless asshole: "By the way, the pussy sex accuse us and hate us virile sex for undiscrimination and hunger for humping. But look at their ugliness, hogging with their arms and legs the moment a powerful dick or asshole walks by. If we males are assholes, they made us so. If male animals rape female animals, the females has a lot to do with it. Fuck them, and fuck them for their brainlessness." http://xahlee.org/Periodic_dosage_dir/t1/20040403_fem_fatale.html With an observational ability like that, who would *ever* listen to a word he'd say? From philippecmartin at sbcglobal.net Mon Jan 3 02:59:00 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 3 Jan 2005 08:59:00 +0100 Subject: Tkinter zoom box Message-ID: <200501030859.00110.philippecmartin@sbcglobal.net> Hi, I have the following convern: I have Tkinter applications that require a zoom box, and have had the following behavior without changing a line of code: 1) Mandrake 10.0/KDE 3.2/Python 2.3: no zoom box 2) Mandrake 10.0/KDE 3.2/Python 2.4: zoom box shows 3) Mandrake 10.1/KDE 3.3/Python 2.4: no zoom box 4) Mandrake 10.1/Gnome 2.6/Python 2.4: zoom box shows I know that sounds strange, but I am fairly certain this is what happened. Is there a way to _force_ that zoom box ? Regards, Philippe -- ********************* Philippe C. Martin SnakeCard LLC www.snakecard.com ********************* From benn at cenix-bioscience.com Thu Jan 13 07:45:29 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Thu, 13 Jan 2005 13:45:29 +0100 Subject: pyserial and com port interrupts In-Reply-To: References: Message-ID: <41E66D69.4050603@cenix-bioscience.com> engsol wrote: >Has anyone done a script that will rspond to the serial com port(s) >receive buffer interrupt, as opposed to polling and timeouts? >Win2000 is the main interest right now. >Thanks >Norm B > > Hello, I came across this problem as when I first used PySerial, I came from a java background which has the ability to register listeners to a serial comm instance and receive interrupts (although some implementations use polling behind the scenes anyway). I don't think that pyserial has this kind of thing so I used the following : def __checkSerial(self): self.__objLock.acquire() try: try: intNoChars = self.__objSerialPort.inWaiting() if (intNoChars > 0): strReceivedString = self.__objSerialPort.read(intNoChars) #or you could fire an event self.newMessage(strReceivedString) except: #put any clean up code in here. raise finally: self.__objLock.release() You can then wrap this in a thread which runs the method every x milliseconds (the code to ensure that I have all the information is elsewhere in a superclass which deals with this use case across communication implementations). However you will have to be aware that you will need to lock around groups of calls to ensure you are receiving the correct information (as above). Therefore, although threading in Python is 'easy' you would still have to think about this issue, it is unavoidable in communications I'm afraid. Even if you could receive interrupts then you will likely be receiving the interrupt on a different thread of execution than the main anyways so you'll still have threading problems and need to lock around calls. This is the problem which I usually express as '/RS232C is not really a standard, more of a rumour/'. Interestingly, if we take the 'python in threading is easy' discussion (partially due to the GIL), then for this use case we could also say that threading in VB6 is even easier than python - I'll leave you to guess why!!! Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From beliavsky at aol.com Sat Jan 1 19:02:05 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 1 Jan 2005 16:02:05 -0800 Subject: Approximating scattered data References: <41d72377$0$31717$a1866201@visi.com> Message-ID: <1104624125.552423.63000@z14g2000cwz.googlegroups.com> Grant Edwards wrote: >I've been looking for some way to approximate scattered 3D data >points in Python. The data doesn't seem to be amenable to >fitting functions like polymials, so I may have to use >something more like a spline surface. >However, I can't find anything usable from Python, and my >Fortram skills are pretty rusty. I tried SciPy, but it's spline >fitting module doesn't work at all for my data. I've found >mentions of a Python port NURBS toolbox, but all the links I >can find are broken. NURBS is available in Matlab and Scilab at http://www.aria.uklinux.net/nurbs.php3 , and translating to Python with Numeric/Numarray should not be too hard. If you are trying to fit z = f(x,y) without having a particular functional form in mind, you can apply a nonparametric regression technique. One of the easiest approaches to code is Nadaraya-Watson kernel regression -- see for example http://www.quantlet.com/mdstat/scripts/spm/html/spmhtmlnode24.html , equation 4.68, where a Gaussian kernel can be used for K. PyML at http://pyml.sourceforge.net/doc/tutorial/tutorial.html may implement this (I have not tried it). LIBSVM at http://www.csie.ntu.edu.tw/~cjlin/libsvm/ has a Python interface for Support Vector Machines, a fairly popular and recent flexible regression method. From spam at nospam.org Fri Jan 28 21:09:36 2005 From: spam at nospam.org (Erik Johnson) Date: Fri, 28 Jan 2005 19:09:36 -0700 Subject: SUCCESS! References: <41f6c3f7$1@nntp.zianet.com> <41f85dd8@nntp.zianet.com> <41f97058$1@nntp.zianet.com> Message-ID: <41faee43$1@nntp.zianet.com> ----- Original Message ----- From: "Peter Otten" <__peter__ at web.de> > According to http://cnswww.cns.cwru.edu/php/chet/readline/CHANGES the > features you missed were introduced in readline 4.0 and 4.2, so version 4.3 > should be sufficient. So let me ask you again, you have both the readline > and the readline-devel package installed? If yes, and configure still > complains, it may be time to look for something entirely different... Sorry! Sorry! I made a mistake - I went and checked whether readline was installed and not readline-devel. I installed readline-devel. (Thank you for re-asking that question.) Interestingly, configure *still* says... ej at sand:~/Python-2.3.4> ./configure | grep readline checking for rl_pre_input_hook in -lreadline... no checking for rl_completion_matches in -lreadline... no And the readline module is still not configured by default: #readline readline.c -lreadline -ltermcap But... if I change the line (in Modules/Setup) above to: readline readline.c -lreadline I get a clean compile and my up-arrow is now fixed! Thank you so much for your help, Peter! :) I don't know how to look at what is in a .so file, and I'm not clear on whether /usr/lib/libreadline.a and the /usr/include/readline headers existed prior to installing readline-devel or not (I would guess not), but it would seem that version 4.3 definitely *should* be sufficient (as you pointed out). ej at sand:/usr/lib> ls *readline* libguilereadline-v-12.a libguilereadline-v-12.so.12 libreadline.so libguilereadline-v-12.la libguilereadline-v-12.so.12.3.0 libguilereadline-v-12.so libreadline.a ej at sand:/usr/lib> nm libreadline.a | grep letion_match 000008d0 t gen_completion_matches 00001c60 T rl_completion_matches 00000070 T completion_matches U rl_completion_matches ej at sand:/usr/lib> nm libreadline.a | grep input_hook 00000030 B rl_pre_input_hook ej at sand:/usr/lib> cd /usr/include/readline/ ej at sand:/usr/include/readline> ls chardefs.h keymaps.h rlconf.h rltypedefs.h history.h readline.h rlstdc.h tilde.h ej at sand:/usr/include/readline> grep input_hook * readline.h:extern rl_hook_func_t *rl_pre_input_hook; ej at sand:/usr/include/readline> grep rl_completion_matches * readline.h:extern char **rl_completion_matches PARAMS((const char *, rl_compentry_func_t *)); So, there still seems to be a misbehaviour in the configure script. I'm sure there must be other people on similar systems that would like to just type: ./configure make make install and be done with it, running v2.3.4 (or other?) with command line editing working! Looks like a bug worth reporting, yeah? Thanks again for your help! :) From ncoghlan at iinet.net.au Mon Jan 10 06:54:45 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 10 Jan 2005 21:54:45 +1000 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: References: <34cieoF489ejfU1@individual.net> Message-ID: <41E26D05.5060408@iinet.net.au> Duncan Booth wrote: > Nick Coghlan wrote: > > >>Grammar Change >>-------------- >>Current:: >> statement ::= stmt_list NEWLINE | compound_stmt >> >>New:: >> statement ::= (stmt_list NEWLINE | compound_stmt) [local_namespace] >> local_namespace ::= "with" ":" suite >> >> >>Semantics >>--------- >>The code:: >> >> with: >> >> >>translates to:: >> >>def unique_name(): >> >> >>unique_name() >> > > > Your proposed grammar change says that you need a newline after the > statement: True, and not really what I intended. However, it does highlight the fact that statement lists haven't been considered in the discussion so far. If statement lists are permitted, getting the right targets bound in the containing scope is going to be fun for things like this: a = b = 2; c = 3; print a + b with: pass (Probably not impossible though - e.g. it may be feasible to figure out all the bindings that have to happen and return an appropriate tuple from the inner scope for binding in the outer scope) It might also be somewhat confusing as to exactly which statements are covered by the local scoping. (All of them would be, but you could be forgiven for assuming it was just the last one) I think the following would work as a version of the grammar which permits local namespaces for statement lists: statement ::= (stmt_list (NEWLINE | local_namespace)) | (compound_stmt [local_namespace]) local_namespace ::= "with" ":" suite Disallowing local namespaces for statement lists would suggest something like this: statement ::= (simple_stmt (NEWLINE | ";" stmt_list NEWLINE | local_namespace) ) | (compound_stmt [local_namespace]) local_namespace ::= "with" ":" suite I'm pretty sure the permissive version is legal for the CPython parser, and I think the somewhat baroque structure I've used for the restrictive version makes it legal, too. Disallowing local namespaces for statement lists might be a good place to start, since it gives an easier target for a first implementation. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From peter at engcorp.com Thu Jan 13 20:16:04 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 20:16:04 -0500 Subject: porting C code In-Reply-To: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> References: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> Message-ID: <0NidnetRONZTgHrcRVn-oQ@powergate.ca> Lucas Raab wrote: > I have the > statement: "typedef unsigned long int word32" and later on: "word32 > b[3]" referencing the third bit of the integer. If that's really exactly what you have, then you actually have something defining an array of three unsigned long integers named "b". And even if you didn't have precisely "word32 b[3]", but merely a "b[3]" reference somewhere, it would be referencing the third element of an array called "b", which is possibly a byte, maybe a long, but definitely not a bit. Maybe showing it as code rather than inline in your text would avoid the possibility of confusion. -Peter From david at graydragon.net Thu Jan 6 16:22:26 2005 From: david at graydragon.net (David Brown) Date: Thu, 6 Jan 2005 15:22:26 -0600 Subject: Python Operating System??? Message-ID: <10trb0mgiflcj4f@corp.supernews.com> Hello. I recently came across a free operating system called Unununium (or something like that) and it was developed in Python and Assembly. Now, I have been looking for a way to make an operating system for a long long time and the only possibilities I could find were C++ and assembly. I don't mind assembly so much if I don't have to use it very often. But C++ is so complicated and errors are pretty much impossible to find in the code for me. So, I was wondering if it would be possible to find a bootloader that loads a python file at startup or something... Is there an example somewhere of a Python OS? Thanks! From jjl at pobox.com Mon Jan 3 13:32:59 2005 From: jjl at pobox.com (John J. Lee) Date: 03 Jan 2005 18:32:59 +0000 Subject: What can I do with Python ?? References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> <1gpqhbl.125l3evz09uefN%aleaxit@yahoo.com> Message-ID: <1xd2fjms.fsf@pobox.com> Lee Harr writes: [...] > I think it looks pretty good. The only problem I see is section 5 > where it says: > > 5. Did we miss your concern? > > Please add a comment to this page. > > > but the page is immutable. Hopefully one of the site maintainers will read this and demonstrate that it's actually readonly rather than immutable, then make it appendable ;-) John From a at a.invalid Thu Jan 6 05:08:13 2005 From: a at a.invalid (Timo Virkkala) Date: Thu, 06 Jan 2005 10:08:13 GMT Subject: Other notes In-Reply-To: <1104972047.050366.211670@f14g2000cwb.googlegroups.com> References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Andrew Dalke: >>(BTW, it needs to be 1 .. 12 not 1..12 because 1. will be interpreted >> as the floating point value "1.0".)< > Uhm, I have to fix my ignorance about parsers. > Cannot a second "." after the first tell that the first "." isn't in > the middle of a floating point number? Python uses an LL(1) parser. From Wikipedia: """ LL(1) grammars, although fairly restrictive, are very popular because the corresponding LL parsers only need to look at the next token to make their parsing decisions.""" >>>This may allow: assert 5 interval 9 == interval(5,9) >>Maybe you could give an example of when you need this in real life?< > Every time you have a function with 2 parameters, you can choose to use > it infix. But why would you want to? What advantage does this give over the standard syntax? Remember, in Python philosophy, there should be one obvious way to do it, and preferably only one. Adding a whole another way of calling functions complicates things without adding much advantage. Especially so because you suggest it is only used for binary, i.e. two-parameter functions. From hwlgw at hotmail.com Mon Jan 24 05:17:25 2005 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 24 Jan 2005 02:17:25 -0800 Subject: delay and force in Python References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> Message-ID: <1106561845.160088.278420@f14g2000cwb.googlegroups.com> Just for the record, an implementation without using generators, somewhat like in Sect. 3.5 of the Wizard book, and without recursion limit problems. . . def stream_hd(s): # the head of the stream . return s[0] . . def stream_tl(s): # the tail of the stream . return s[1]() . . ## . # The low argument is required: the first element of the stream. . # You either use high= or stop_f= to define the end of the . # stream. Omit both for an infinite stream. stop_f is a function . # that takes low as argument and returns True or False. . # The next_f function takes one argument (an element of the stream, . # same type as the low argument has) . # The stop_f function takes one argument (same type as low) . # @param low object . # @param high object . # @param next_f function . # @param stop_f function . # @return list, a stream . def make_stream(low, high=None, next_f=None, stop_f=None): . if next_f is None: next_f = lambda x: x + 1 . if high is not None: # using high . if low > high: . return None . else: . return [low, lambda: make_stream( . next_f(low), high=high, next_f=next_f)] . elif stop_f is not None: # using stop_f . if low > stop_f(low): . return None . else: . return [low, lambda: make_stream( . next_f(low), next_f=next_f, stop_f=stop_f)] . else: # infinite stream . return [low, lambda: make_stream( . next_f(low), next_f=next_f)] . . ## . # iterative version of filter . # @param pred function, (stream-element) -> bool . # @param s list, a stream . # @return list, a stream . def stream_filter(pred, s): . if s is None: return [] . while True: . elem = stream_hd(s) . if pred(elem): . return [elem, lambda: stream_filter(pred, stream_tl(s))] . else: . s = stream_tl(s) . if s is None: return [] . . . if __name__ == '__main__': . . def is100some(x): return x % 100 == 0 . assert(stream_hd(stream_tl(stream_tl(stream_filter( . is100some, . make_stream(1, 11111111111111))))) == 300) . . def add_33(x): return x + 33 . assert(stream_hd(stream_tl(stream_filter( . is100some, . # stream 1,34,67,100,... . make_stream(1,999999999, next_f = add_33)))) == 3400) . . assert(stream_hd(stream_tl(stream_filter( . is100some, . # infinite stream 1,2,... . make_stream(1)))) == 200) . . def mod_20000(x): return x % 20000 == 0 . # this will need more evaluations than the recursion limit count . infinite_filter = stream_filter(mod_20000, make_stream(1)) . assert( stream_hd(stream_tl(infinite_filter)) == 40000 ) . From esj at harvee.org Tue Jan 18 17:33:26 2005 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 18 Jan 2005 17:33:26 -0500 Subject: simultaneous multiple requests to very simple database In-Reply-To: References: Message-ID: <41ED8EB6.503@harvee.org> Thomas Bartkus wrote: > "Eric S. Johansson" wrote in message > news:mailman.859.1106065617.22381.python-list at python.org... > > >>at this point, I know they will be some kind souls suggesting various >>SQL solutions. While I appreciate the idea, unfortunately I do not have >>time to puzzle out yet another component. Someday I will figure it out >>because I really liked what I see with SQL lite but unfortunately, today >>is not that day (unless they will give me their work, home and cell >>phone numbers so I can call when I am stuck. ;-) > > > > Forgive me if this reply sounds a bit glib. But I do mean it without malice. understood and taken in that spirit. > Do you seriously expect to write your own (database) solution and that this > will save you time and effort over learning an existing (SQL) solution? > > Because - > If you are seeking to "save time" on "puzzles", you are certainly going > about it the wrong way. one thing I learned a long time ago was to respect the nagging voice in the back of my head that says "there is something wrong". Right now with databases, that voice is not nagging but screaming. So I made my query to try and prove that intuition wrong. So far, that has not happened. When I look at databases, I see a bunch of very good solutions that are either overly complex or heavyweight on one hand and very nice and simple but unable to deal with concurrency on the other. two sets of point solutions that try to stretch themselves and the developers to fit other application contexts. 99.9 percent of what I do (and I suspect this could be true for others) could be satisfied by a slightly enhanced super dictionary with a record level locking. but, the database world does not fit this model. It has a great deal more complication then what is frequently necessary. If I ever find the time, I will try to build such a beast probably around Metakit. The only reason for reluctance is that I have spent too many hours tracking down concurrency problems at the OS level way to many years ago and so I do not create multithreaded applications lightly. so in conclusion, my only reason for querying was to see if I was missing a solution. So far, I have not found any work using because they add orders of magnitude more complexity than simple dbm with file locking. Obviously, the simple solution has horrible performance right now I need simplicity implementation. thanks for your commentary. ---eric From aleaxit at yahoo.com Sat Jan 22 07:00:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 13:00:36 +0100 Subject: circular iteration References: Message-ID: <1gqsjq8.11240q817nwks2N%aleaxit@yahoo.com> Simon Brunning wrote: ... > > is there a faster way to build a circular iterator in python that by doing this: > > > > c=['r','g','b','c','m','y','k'] > > > > for i in range(30): > > print c[i%len(c)] > > I don''t know if it's faster, but: > > >>> import itertools > >>> c=['r','g','b','c','m','y','k'] > >>> for i in itertools.islice(itertools.cycle(c), 30): > ... print i Whenever you're using itertools, the smart money's on "yes, it's faster";-). E.g., on a slow, old iBook...: kallisti:~ alex$ python -mtimeit -s'c="rgbcmyk"' 'for i in range(30): c[i%len(c)]' 10000 loops, best of 3: 47 usec per loop kallisti:~ alex$ python -mtimeit -s'c="rgbcmyk"; import itertools as it' 'for i in it.islice(it.cycle(c),30): i' 10000 loops, best of 3: 26.4 usec per loop Of course, if you do add back the print statements they'll take orders of magnitude more time than the cyclic access, so /F's point on premature optimization may well be appropriate. But, if you're doing something VERY speedy with each item you access, maybe roughly halving the overhead for the cyclic access itself MIGHT be measurable (maybe not; it IS but a few microseconds, after all). I like itertools' approach because it's higher-abstraction and more direct. Its blazing speed is just a trick to sell it to conservative curmudgeons who don't see abstraction as an intrinsic good -- some of those are swayed by microseconds;-) Alex From nav+posts at bandersnatch.org Thu Jan 6 10:16:05 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: Thu, 06 Jan 2005 10:16:05 -0500 Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: <87pt0iegga.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> eeykay at gmail.com writes: > Can somebody there to point me any good commercial applications > developed using python ? Python is used in several games, including Temple of Elemental Evil and the forthcoming Civilization 4. Humungous Games, which makes software for children, is also using Python. Sorry if games would give your boss the wrong impression... Most commercial software houses don't advertise details of their development platforms. Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From jzgoda at gazeta.usun.pl Thu Jan 6 15:54:19 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Thu, 06 Jan 2005 21:54:19 +0100 Subject: Python evolution: Unease In-Reply-To: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> Message-ID: Iwan van der Kleyn wrote: > But I see little to no efforts from the core python team to address my > needs as listed above. They seem mainly to focus on the core attributes > and syntax of the language. Very little or no efforts are taken to > improve the infrastructure around the language. > > And then I read the following sentence by Van Rossum: > > "In order to make type inferencing a little more useful, I'd like to > restrict certain forms of extreme dynamic behavior in Python" > > In the end, it's mindset which counts. And I think that mindset is going > to be determine the way foreward for Python: more features, increased > complexity, less dynamism. Lots of syntax crud, without addressing the > need to improve the infrastructure around the language. I saw this once somewhere: http://groups.google.com/groups?selm=cf38ph%242f8%241%40namru.matavnet.hu -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From jussij at zeusedit.com Sun Jan 9 01:51:45 2005 From: jussij at zeusedit.com (Jussi Jumppanen) Date: Sun, 09 Jan 2005 17:51:45 +1100 Subject: Ranting about the state of Python IDEs for Windows References: <1105222350.906941.83130@c13g2000cwb.googlegroups.com> Message-ID: <41E0D481.1C0F@zeusedit.com> Carlos Ribeiro wrote: > Oh well. A mailing list is not the most appropriate place for > rants (a blog is better), but it's still better than keeping > it for myself. > > I'm frustrated. My search for a good IDE to support my activities Take a look at Zeus: http://www.zeusedit.com/lookmain.html > doing development for Python in the Windows environment Zeus only runs on Windows. > But it's all that I have -- a 500MHz PC with 64MB and Win98 SE. Zeus should run fine on this machine. If you added another stick of 64MB it would run better :) Jussi Jumppanen Author of: Zeus for Windows (New version 3.93 out now) "The C/C++, Cobol, Java, HTML, Python, PHP, Perl programmer's editor" Home Page: http://www.zeusedit.com From aahz at pythoncraft.com Sat Jan 29 06:31:45 2005 From: aahz at pythoncraft.com (Aahz) Date: 29 Jan 2005 06:31:45 -0500 Subject: limited python virtual machine References: <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> Message-ID: In article <1gr3mwj.1mhbjao122j7fxN%aleaxit at yahoo.com>, Alex Martelli wrote: >Steven Bethard wrote: >> >> If I could see how to go from 'object' (or 'int', 'str', 'file', etc.) >> to 'eval' or '__import__', that would help out a lot... > >>>> object.__subclasses__() >[, , , , >, , , 'module'>, , , >, , , 'site._Printer'>, , , ] > >Traipse through these, find one class that has an unbound method, get >that unbound method's func_globals, bingo. One thing my company has done is written a ``safe_eval()`` that uses a regex to disable double-underscore access. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From jjreavis at gmail.com Mon Jan 10 10:15:27 2005 From: jjreavis at gmail.com (Jeff Reavis) Date: 10 Jan 2005 07:15:27 -0800 Subject: Powerful CGI libraries for Python? In-Reply-To: References: Message-ID: <1105370127.829355.120290@c13g2000cwb.googlegroups.com> You may want to check out Spyce http://spyce.sourceforge.net/index.html It will work as cgi (or using fast cgi or mod python) and has templating, session support, active tags, etc. -jjr From danperl at rogers.com Fri Jan 28 08:22:57 2005 From: danperl at rogers.com (Dan Perl) Date: Fri, 28 Jan 2005 08:22:57 -0500 Subject: How to test that an exception is raised ? References: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> Message-ID: "StepH" wrote in message news:41fa0da9$0$2018$6c56d894 at feed0.news.be.easynet.net... > But i've prob with the 1st test : test_badFile. > When I run the test, unittest say that no error is Raised. > But when I run the mps2xml module with a bad file as arg., the exception > is > well Raised. I assume you don't actually see the exception (you don't see the stack traceback printed as an output) but you just see your own message "FileError". That means that the exception was raised and caught by your try-except statement. > What i'm doing wrong ? > > It is because the exception in catched in the mps2xml module ? With the above mentioned assumption, that must be it. Once the exception is caught, it is caught and no other code invoking mps2xml.mps2xml (including the assertRaises in your test) will see the exception. Your mps2xml.mps2xml function should return a value indicating success or failure or should re-raise the exception. You need a mechanism to let invoking code know that it was successful or it failed. With a return code, you should test that and not the exception. The assert you use should work if you re-raise the exception. And BTW, it is a bad idea to use a generic "except" statement like you do. That catches ALL the exceptions and you will never know if a different exception than IOError was raised. You should catch only IOError specifically or any other exception that you may expect. You can add then an extra "except" statement catching all the other exceptions, but only if it is essential for your application to handle all exceptions gracefully instead of just exiting with a stack traceback. > Thanks for your helps. > > StepH. > > From aleaxit at yahoo.com Fri Jan 7 06:15:29 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 12:15:29 +0100 Subject: Tkinter Puzzler References: Message-ID: <1gq0pqa.1bvpnoehc2zs3N%aleaxit@yahoo.com> Tim Daneliuk wrote: > I am trying to initialize a menu in the following manner: > > for entry in [("Up", KeyUpDir), ("Back", KeyBackDir), ("Home", > KeyHomeDir), ("Startdir", KeyStartDir), ("Root", KeyRootDir)]: > > func = entry[1] > UI.ShortBtn.menu.add_command(label=entry[0], command=lambda: func(None)) > > However, at runtime, each of the menu options binds to the *last* function > named in the list (KeyStartDir). > > Explicitly loading each entry on its own line works fine: > > UI........command=lambda:KeyWHATEVERDir(None) > > Any ideas why the first form does not fly? One word: late binding. Well, two, pedantically speaking;-). The lambda you're passing as the value for 'command' is a closure: it knows it will have to look up name 'func' in the environment in which it's embedded -- but also that it's meant to do that lookup as late as possible, each time it's called. If you wanted to do the lookup just once, at the time lambda executes and created an anonymous function rather than each time said anonymous function is called, you could have expressed that...: command=lambda func=func: func(None) Here, func is a local variable (argument) of the anonymous function, and its "default value" is set ONCE, when the anon function is created. Back to your code, when your anon function is called, it looks up name 'func' in the surrounding environment... and there it finds it bound to whatever it was RE-bound to the LAST time... Point to remember: a closure looks up free-variable names in its surrounding environment *as late as possible*, i.e., when the function object is called; while default argument values are evaluated *at function creation time* (when lambda or def executes, not when the resulting function object gets called). Alex From john at grulic.org.ar Mon Jan 17 01:42:16 2005 From: john at grulic.org.ar (John Lenton) Date: Mon, 17 Jan 2005 03:42:16 -0300 Subject: fefinining % of c'm'y and k In-Reply-To: <1105941466.596034.166370@f14g2000cwb.googlegroups.com> References: <1105941466.596034.166370@f14g2000cwb.googlegroups.com> Message-ID: <20050117064216.GA28935@grulic.org.ar> On Sun, Jan 16, 2005 at 09:57:46PM -0800, moshebg at shamaut.co.il wrote: > hello > i need a program (and pleas shoe me the modol in the softwar) that : > if i have a scaned photo > i want to define out of each poligon color ,as it seems in the photo, > the cmyk > in % (percets) of the color/ > 4 exampl from poligon color orang defin the cmyk in % > like that: (example) > c: 30% > m:56% > y:78% > k: 10% > moshe > thanks if I understand you correctly, then what you want to do is to determine the amounts of each color an image has. I can think of two ways of doing this, both using PIL; one faster, img = Image.open('foo.png') dot = img.resize((1,1),1) avg = dot.getpixel((0,0)) for i in zip(dot.getbands(), avg): print "%s: %s" % i and the other, thorougher img = Image.open('foo.png') width, height = img.size numdots = width*height avg = [sum(i)/numdots for i in zip(*[img.getpixel((x,y)) for x in xrange(width) for y in xrange(height)])] for i in zip(dot.getbands(), avg): print "%s: %s" % i the first is usually pretty close to the second, but YMMV. Converting from these image-specific average values to CMYK is a non-trivial problem (impossible in the general casew); see for example http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2d0c54513c4970f7 where this issue was discussed. -- John Lenton (john at grulic.org.ar) -- Random fortune: Excellent day to have a rotten day. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From simon.brunning at gmail.com Wed Jan 26 09:48:16 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 26 Jan 2005 14:48:16 +0000 Subject: fast list lookup In-Reply-To: <3e96ebd7.0501260641.159e007f@posting.google.com> References: <3e96ebd7.0501260641.159e007f@posting.google.com> Message-ID: <8c7f10c60501260648c4a7c9a@mail.gmail.com> On Wed, 26 Jan 2005 06:45:29 -0800 (PST), Klaus Neuner wrote: > what is the fastest way to determine whether list l (with > len(l)>30000) contains a certain element? If the list isn't sorted, I doubt you'll do better than if an_element in my_list: # do whatever If the list is sorted, have a look at the bisect module. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From skip at pobox.com Sat Jan 29 08:23:54 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 29 Jan 2005 07:23:54 -0600 Subject: Who should security issues be reported to? In-Reply-To: <41FB080E.1070308@iinet.net.au> References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <41FB080E.1070308@iinet.net.au> Message-ID: <16891.36458.766674.340161@montanaro.dyndns.org> Nick> Upgrading your Python interpreter (even to a new maintenance Nick> branch release) in a production environment is usually a fairly Nick> involved exercise requiring a significant amount of testing, and Nick> the fact of the matter is, you're unlikely to do so unless there Nick> is some feature or bug-fix in a new version that you really Nick> need. (I'm still using Python 2.2.2 at work - it's entirely Nick> adequate for our needs, so there's no real pressure to upgrade on Nick> the current project. For a new project, I'd probably start with Nick> 2.4, planning to go to 2.4.1 in a couple of months time, but there Nick> aren't really any post-2.2 additions to Python that I can't handle Nick> living without). Still, if a security bug was serious enough, my guess is that someone would step up to supply patches (or Windows installers) for any of a number of versions that were affected by the bug, even 2.1 or 1.5.2. That someone might or might not be part of the core development team. That nothing like that has been done before doesn't preclude it being done in the future. Skip From steve at holdenweb.com Wed Jan 19 09:01:08 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Jan 2005 09:01:08 -0500 Subject: generator expressions: performance anomaly? In-Reply-To: References: <354esdF4fouh0U1@individual.net> Message-ID: <5PtHd.80946$Jk5.119@lakeread01> Antoon Pardon wrote: > Op 2005-01-18, Steve Holden schreef : [...] > > But you do have a point that I have a tendency to put salt on > any snail. I'll try to restrain myself a bit more in the future. > Finally! :-) I find I like you much better after this reflective response. Thanks for taking the time to read my snarking and respond to it. "A tendency to put salt on any snail" is a nice phrase I've never come across before. Is it specifically Belgian? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From esj at harvee.org Thu Jan 13 22:23:49 2005 From: esj at harvee.org (Eric S. Johansson) Date: Thu, 13 Jan 2005 22:23:49 -0500 Subject: a ConfigParser wtf moment Message-ID: I'm not sure if this is a real problem or if I have been staring at code too long. given this code #!/usr/bin/python from ConfigParser import * configuration_file = "test.conf" substitution = {"xyzzy":"maze"} configuration = SafeConfigParser() configuration.readfp(file(configuration_file)) list = configuration.items("core") print list list = configuration.items("core",0, substitution) print list --------------- and this configuration file ----------- [core] xyzzy=little bird dwarf = greasy smoke %(xyzzy)s plugh ------------ why do I get the following results? ------------- trial backup # python test.py [('dwarf', 'greasy smoke little bird plugh'), ('xyzzy', 'little bird')] [('dwarf', 'greasy smoke maze plugh'), ('xyzzy', 'maze')] trial backup # ------------- if you're having a hard time seeing it, before the substitution, xyzzy is set to the value in the configuration file, afterwards, it is set to the value of the substitution in the code. It seems to me that substitutions should not affect any configuration file symbols of the same name. anyway to fix this problem without python diving? ---eric From ncoghlan at iinet.net.au Sun Jan 9 00:54:08 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 15:54:08 +1000 Subject: python3: 'where' keyword In-Reply-To: <7xhdlsw6ov.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <7xhdlsw6ov.fsf@ruckus.brouhaha.com> Message-ID: <41E0C700.8080604@iinet.net.au> Paul Rubin wrote: > AdSR writes: > >>>Killer app for this keyword: >>>class C(object): >>> x = property(get, set) where: >>> def get(self): >>> return "Silly property" >>> def set(self, val): >>> self.x = "Told you it was silly" >> >>Hey, this is super-elegant! > > > Heh, even further: > > z = C() where: > class C(object): > ... > > Lets you make anonymous classes and singleton objects. Here's another nice one if 'where' is added to compound statements as well: @dbc(pre, post) def foo(): pass where: def pre(): pass def post(): pass Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jimmy at retzlaff.com Tue Jan 25 03:32:16 2005 From: jimmy at retzlaff.com (Jimmy Retzlaff) Date: Tue, 25 Jan 2005 00:32:16 -0800 Subject: Open Folder in Desktop Message-ID: Kamilche wrote: > Is there a command you can execute in Python that will open a window on > the desktop, such as 'My Documents'? Kind of like 'system', but for > folder names, not just programs. I'm running on Windows 2000. There are two issues here. The first is how to open a folder and the second is how to resolve "special" folders. Folders are "documents" typically associated with the explorer.exe application. To open a document with its default app (e.g., a folder), use os.startfile which is included in Python. For example: import os os.startfile(r'c:\windows') Folders like My Documents, My Pictures, etc. are special and you need to determine their actual path before you can open them. The pywin32 extensions (https://sourceforge.net/project/showfiles.php?group_id=78018) include a way to get at this: from win32com.shell import shellcon, shell path = shell.SHGetFolderPath(0, shellcon.CSIDL_MYPICTURES, 0, 0) os.startfile(path) Google for CSIDL to find the constants to use for other special folders. Jimmy From kartic.krishnamurthy at gmail.com Wed Jan 5 11:30:42 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 5 Jan 2005 08:30:42 -0800 Subject: get the IP address of a host In-Reply-To: <1104941334.814311.198610@z14g2000cwz.googlegroups.com> References: <1104941334.814311.198610@z14g2000cwz.googlegroups.com> Message-ID: <1104942642.925891.43120@f14g2000cwb.googlegroups.com> or socket.gethostbyname(socket.gethostname()) From lbates at syscononline.com Fri Jan 28 09:49:49 2005 From: lbates at syscononline.com (Larry Bates) Date: Fri, 28 Jan 2005 08:49:49 -0600 Subject: is extending an object considered acceptable usage? In-Reply-To: References: Message-ID: When I want to do what I think you are asking, I create an iterator in that returns a category item each time the .next method is called. That way you can write. ITEM=item() . . . for CATEGORY in ITEM: in my item class: class item: def __init__(self, ): self.CATEGORIES=[] self.next_index=0 # Index point for next method def __iter__(self): return self def next(self): # # Try to get the next route # try: CATEGORY=self.CATEGORIES[self.next_index] except: self.next_index=0 raise StopIteration # # Increment the index pointer for the next call # self.next_index+=1 return CATEGORY I had one project where these were nested 5-6 deep and the resultant code reads beautifully. Larry Bates mike wrote: > > i have an Item which belongs to a Category, so Item has: > > - item.categoryId, the database primary key of its Category > > - item.category, a reference to its Category. this null unless i need a > reference from item to its Category object, in which case i call > setCategory(category) > > sometimes i want a list of categories, and from each i want to be able > to access a list of its items. in this case is it considered acceptable > to just create a list of those items and assign it as a property of > their category? eg: > > category.items = listOfItems > > this packages everything up into a hierarchy and is more convenient to > use, especially in Cheetah templates, but requries modifying the > structure of the object, which bothers me (probably for some > subconscious java-related reason). > > the alternative might be to create a dictionary that keys the lists of > items on their category: > > items = {} > items[category.id] = listOfItems > > this feels less "controversial" to me, but requires extra objects and > house-keeping. > > > thanks - just curious if there were arguments one way or the other. From baoqiu at gmail.com Mon Jan 31 01:46:51 2005 From: baoqiu at gmail.com (Baoqiu Cui) Date: 30 Jan 2005 22:46:51 -0800 Subject: a Python bug in processing __del__ method ?? Message-ID: <1107154011.859866.23480@z14g2000cwz.googlegroups.com> Today I was playing with a small Python program using Python 2.4 on Cygwin (up-to-date version, on Windows XP), but ran into a strange error on the following small program (named bug.py): ------------------------------- #!/usr/bin/python class Person: population = 0 def __del__(self): Person.population -= 1 peter = Person() ------------------------------- The error returned is this: $ python bug.py Exception exceptions.AttributeError: "'NoneType' object has no attribute 'population'" in > ignored However, if I rename variable name 'peter' to something like 'peter1' or 'david', the error is gone. Looks to me the error only happens to variable name 'peter'. Does anyone know what is wrong? Is this a bug only on Cygwin? - Baoqiu From peter at engcorp.com Mon Jan 24 10:55:26 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jan 2005 10:55:26 -0500 Subject: Memory Usage In-Reply-To: References: Message-ID: <9-adnWKPTqfwh2jcRVn-uA@powergate.ca> rbt wrote: > Peter Hansen wrote: >> I would expect to see such behaviour, given how difficult it is >> to measure *actual* memory usage. How are you measuring it? >> Just by looking at the Mem Usage column in the Task Manager? > > That's right. I look at that column. Should I measue mem usage in some > other way? Probably, but for a start, have you noticed that even just switching to another window can drastically affect the memory apparently used by an application? For example, running the wxPython demo, clicking on a few controls and getting memory usage up to 27MB, then minimizing the window will drop it down aboiut 2MB. Restoring the window will bring the amount back to only about 4MB, at least until you click on stuff. Even then, it might climb to only about 14MB or so. This particular phenomenon might not be affecting your application, but it's an indication of how bad this measurement technique can be. Inside the Control Panel, you will find "Administrative Tools". In there is a "Performance" gadget. It's not trivial to use, and I can't give a tutorial here, but if you can manage to display the Working Set for the specific Process in which you are interested, that's probably a better way to view the information. (To be honest, I think it's actually this particular value which the "Mem Usage" field shows in the Task Manager, but at least this way you get a real-time graph and more precision, and a record of the usage.) There are also dozens of other parameters you can examine to help you track down the actual usage, or to help find out what is going if it turns out that you really are using such different amounts on the two machines. More important than any of this, however, might be making sure you have similar conditions on the two machines. Are you terminating as many other processes as you can? Making sure there is ample Physical Memory Available (see the Performance tab of Task Manager, for example)? If you have one of the machines running out of memory because of other applications running, it is quite possible that the OS will steal memory from the Python process to feed the other apps, and that can show up in the working set size. As I said, this stuff isn't exactly straightforward, so it's not necessarily surprising you are seeing this behaviour. There's probably a relatively simple explanation, however, but it might come only after a bit of exploration. -Peter From Mark.English at liffe.com Fri Jan 21 05:39:31 2005 From: Mark.English at liffe.com (Mark English) Date: Fri, 21 Jan 2005 10:39:31 -0000 Subject: Class introspection and dynamically determining function arguments Message-ID: <40E605146701DE428FAF21286A97D30917450F@wphexa02.corp.lh.int> > From: "Mark English" > > I'd like to write a Tkinter app which, given a class, pops up a > window(s) with fields for each "attribute" of that class. The > user could enter values for the attributes and on closing the > window would be returned an instance of the class. The actual > application I'm interested in writing would either have > simple type attributes (int, string, etc.), or attributes > using types already defined in a c-extension, although I'd > prefer not to restrict the functionality to these requirements. <------------------------> From: "Diez B. Roggisch" > whatfor is it planned? <------------------------> From: Nick Coghlan If this only has to work for classes created for the purpose > (rather than for an arbitrary class): <------------------------> Although I'm writing it for a specific need with a specific set of classes, I was asking here to find a more general, robust approach. So handling an arbitrary class would be preferable. > This is the only way to go, as python has no attribute declarations as static compiled languages have The classes I'm dealing with do have attributes since they're C-Extension types with attributes provided in the "tp_getset" slot. So this is one case where I can query the class for attributes without having to create an instance. Thanks for making me think of that, since looking in the class's __dict__ pretty much gives me what I want. I'm not sure that that's something I can rely on though which is exactly the sort of issue where I'd like to know if there's a right way (e.g. an existing module) to ask a class for its attributes, without poking around in __dict__ directly and doing some type checking. I guess in a way I'm asking for introspection with a greater degree of granularity than "dir". ----------------------------------------------------------------------- The information contained in this e-mail is confidential and solely for the intended addressee(s). Unauthorised reproduction, disclosure, modification, and/or distribution of this email may be unlawful. If you have received this email in error, please notify the sender immediately and delete it from your system. The views expressed in this message do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary companies. ----------------------------------------------------------------------- From jaco.smuts at clover.co.za Sat Jan 15 08:37:05 2005 From: jaco.smuts at clover.co.za (Jaco Smuts) Date: Sat, 15 Jan 2005 15:37:05 +0200 Subject: How can I get the names of the files in a directory? In-Reply-To: <20050115131023.36656.qmail@web50501.mail.yahoo.com> Message-ID: have a look at the glob module Sara Fwd Sent by: python-list-bounces+jsmuts=clover.co.za at python.org 01/15/2005 03:10 PM To python-list at python.org cc Subject How can I get the names of the files in a directory? Can you guys also help me find a module that looks in a directory and print out the names of the files in there? __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From kbk at shore.net Sat Jan 8 14:15:36 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Sat, 8 Jan 2005 14:15:36 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200501081915.j08JFaqo021328@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 267 open ( +6) / 2727 closed ( +9) / 2994 total (+15) Bugs : 798 open ( -3) / 4748 closed (+15) / 5546 total (+12) RFE : 165 open ( +0) / 140 closed ( +1) / 305 total ( +1) New / Reopened Patches ______________________ Remove witty comment in pydoc.py (2005-01-01) CLOSED http://python.org/sf/1094007 opened by Reinhold Birkenfeld Docs for file() vs open() (2005-01-01) CLOSED http://python.org/sf/1094011 opened by Reinhold Birkenfeld Improvements for shutil.copytree() (2005-01-01) CLOSED http://python.org/sf/1094015 opened by Reinhold Birkenfeld xml.dom.minidom.Node.replaceChild(obj, x, x) removes child x (2005-01-01) http://python.org/sf/1094164 opened by Felix Rabe os.py: base class _Environ on dict instead of UserDict (2005-01-02) http://python.org/sf/1094387 opened by Matthias Klose add Bunch type to collections module (2005-01-02) http://python.org/sf/1094542 opened by Steven Bethard self.button.pack() in tkinter.tex example (2005-01-03) http://python.org/sf/1094815 opened by [N/A] fixes urllib2 digest to allow arbitrary methods (2005-01-03) http://python.org/sf/1095362 opened by John Reese Argument passing from /usr/bin/idle2.3 to idle.py (2003-11-30) http://python.org/sf/851459 reopened by jafo fix for trivial flatten bug in astgen (2005-01-04) http://python.org/sf/1095541 opened by DSM exclude CVS conflict files in sdist command (2005-01-04) http://python.org/sf/1095784 opened by Wummel Fix for wm_iconbitmap to allow .ico files under Windows. (2005-01-05) http://python.org/sf/1096231 opened by John Fouhy Info Associated with Merge to AST (2005-01-07) http://python.org/sf/1097671 opened by Kurt B. Kaiser Direct framework linking for MACOSX_DEPLOYMENT_TARGET < 10.3 (2005-01-07) http://python.org/sf/1097739 opened by Bob Ippolito Encoding for Code Page 273 used by EBCDIC Germany Austria (2005-01-07) http://python.org/sf/1097797 opened by Michael Bierenfeld Patches Closed ______________ locale.getdefaultlocale does not return tuple in some OS (2004-10-21) http://python.org/sf/1051395 closed by rhettinger imghdr -- identify JPEGs in EXIF format (2003-06-08) http://python.org/sf/751031 closed by rhettinger Remove witty comment in pydoc.py (2005-01-01) http://python.org/sf/1094007 closed by rhettinger Docs for file() vs open() (2005-01-01) http://python.org/sf/1094011 closed by rhettinger Improvements for shutil.copytree() (2005-01-01) http://python.org/sf/1094015 closed by jlgijsbers a new subprocess.call which raises an error on non-zero rc (2004-11-23) http://python.org/sf/1071764 closed by astrand Argument passing from /usr/bin/idle2.3 to idle.py (2003-11-30) http://python.org/sf/851459 closed by jafo @decorators, including classes (2004-08-12) http://python.org/sf/1007991 closed by jackdied Convert glob.glob to generator-based DFS (2004-04-27) http://python.org/sf/943206 closed by jlgijsbers Make cgi.py use email instead of rfc822 or mimetools (2004-12-06) http://python.org/sf/1079734 closed by jlgijsbers New / Reopened Bugs ___________________ marshal.dumps('hello',0) "Access violation" (2005-01-03) CLOSED http://python.org/sf/1094960 opened by Mark Brophy General FAW - incorrect "most stable version" (2005-01-03) http://python.org/sf/1095328 opened by Tim Delaney Python FAQ: list.sort() out of date (2005-01-03) CLOSED http://python.org/sf/1095342 opened by Tim Delaney Bug In Python (2005-01-04) CLOSED http://python.org/sf/1095789 opened by JastheAce "Macintosh" references in the docs need to be checked. (2005-01-04) http://python.org/sf/1095802 opened by Jack Jansen The doc for DictProxy is missing (2005-01-04) http://python.org/sf/1095821 opened by Colin J. Williams Apple-installed Python fails to build extensions (2005-01-04) http://python.org/sf/1095822 opened by Jack Jansen time.tzset() not built on Solaris (2005-01-05) http://python.org/sf/1096244 opened by Gregory Bond sys.__stdout__ doco isn't discouraging enough (2005-01-05) http://python.org/sf/1096310 opened by Just van Rossum _DummyThread() objects not freed from threading._active map (2004-12-22) http://python.org/sf/1089632 reopened by saravanand Example needed in os.stat() (2005-01-06) CLOSED http://python.org/sf/1097229 opened by Facundo Batista SimpleHTTPServer sends wrong Content-Length header (2005-01-06) http://python.org/sf/1097597 opened by David Schachter urllib2 doesn't handle urls without a scheme (2005-01-07) http://python.org/sf/1097834 opened by Jack Jansen getsource and getsourcelines in the inspect module (2005-01-07) CLOSED http://python.org/sf/1098134 opened by Bj?rn Lindqvist mailbox should use email not rfc822 (2003-06-19) http://python.org/sf/756982 reopened by jlgijsbers typo in "Python Tutorial": 1. Whetting your appetite (2005-01-08) http://python.org/sf/1098497 opened by Ludootje Bugs Closed ___________ Don't define _SGAPI on IRIX (2003-04-27) http://python.org/sf/728330 closed by loewis python24.msi install error (2004-12-01) http://python.org/sf/1076500 closed by loewis garbage collector still documented as optional (2004-12-27) http://python.org/sf/1091740 closed by rhettinger marshal.dumps('hello',0) "Access violation" (2005-01-03) http://python.org/sf/1094960 closed by rhettinger General FAQ: list.sort() out of date (2005-01-04) http://python.org/sf/1095342 closed by jlgijsbers Bug In Python (2005-01-04) http://python.org/sf/1095789 closed by rhettinger test_macostools fails when running from source (2004-07-16) http://python.org/sf/992185 closed by jackjansen Sate/Save typo in Mac/scripts/BuildApplication.py (2004-12-01) http://python.org/sf/1076490 closed by jackjansen _DummyThread() objects not freed from threading._active map (2004-12-22) http://python.org/sf/1089632 closed by bcannon Example needed in os.stat() (2005-01-06) http://python.org/sf/1097229 closed by facundobatista gethostbyaddr on redhat for multiple hostnames (2004-12-14) http://python.org/sf/1085069 closed by loewis Unable to see Python binary (2004-12-10) http://python.org/sf/1082874 closed by loewis Change in signal function in the signal module (2004-12-10) http://python.org/sf/1083177 closed by akuchling test_descr fails on win2k (2004-07-12) http://python.org/sf/989337 closed by rhettinger test_imp failure (2004-07-15) http://python.org/sf/991708 closed by rhettinger getsource and getsourcelines in the inspect module (2005-01-07) http://python.org/sf/1098134 closed by jlgijsbers crash (SEGV) in Py_EndInterpreter() (2002-11-17) http://python.org/sf/639611 closed by jlgijsbers shutil.copytree copies stat of files, but not of dirs (2004-10-18) http://python.org/sf/1048878 closed by jlgijsbers shutil.copytree uses os.mkdir instead of os.mkdirs (2004-06-19) http://python.org/sf/975763 closed by jlgijsbers RFE Closed __________ optparse .error() should print options list (2004-12-22) http://python.org/sf/1089955 closed by gward From pushlinque at hotmail.com Thu Jan 13 09:43:11 2005 From: pushlinque at hotmail.com (Jane) Date: Thu, 13 Jan 2005 09:43:11 -0500 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: "Lucas Raab" wrote in message news:UsuFd.5434$KJ2.1253 at newsread3.news.atl.earthlink.net... > Jane wrote: > > wrote in message > > news:1105495569.479185.166340 at z14g2000cwz.googlegroups.com... > > > >>python.org = 194.109.137.226 > >> > >>194 + 109 + 137 + 226 = 666 > >> > >>What is this website with such a demonic name and IP address? What > >>evils are the programmers who use this language up to? > >> > > > > Some people have too much time on their hands... > > > > Jane > > > > > > Better get some ointment for that burn!! Huh??? Jane From erdewit at d-e-l-e-t-e.zonnet.nl Mon Jan 17 12:10:40 2005 From: erdewit at d-e-l-e-t-e.zonnet.nl (Ewald R. de Wit) Date: Mon, 17 Jan 2005 11:10:40 -0600 Subject: directory bug on linux; workaround? References: Message-ID: Russell E. Owen wrote: > It seems that the path was to a "fat" file partition and included a > directory name that was all uppercase. The directory was created, but > using lowercase. I'm not yet sure the version of python. > > The workaround for now is to not use fat file partitions. But I was > wondering if anyone had a better option? You can mount the FAT partition with the 'shortname' argument, i.e. put something like /dev/sda1 /usbkey auto umask=0,user,iocharset=iso8859-1,sync,kudzu,codepage=850,noauto,exec,users,shortname=winnt,check=s 0 0 in your /etc/fstab Btw, this is a general Linux problem and is not really related to Python (it also happens when working with shells or filemanagers). -- -- Ewald From lbates at syscononline.com Wed Jan 5 19:18:00 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 05 Jan 2005 18:18:00 -0600 Subject: PIL and ReportsLab error In-Reply-To: References: Message-ID: PIL doesn't support compressed TIF files. You must uncompress them prior to trying to place them. I use tiffcp utility via os.system call to uncompress TIF files, then place them into my .PDF file. Larry Bates Syscon, Inc. Jason Koch wrote: > Hello, > I am trying to produce pdf files from tiffs and I keep getting this > error. Does anyone > have any tips on this one. I am using the ReportLab package with the PIL. > > File "C:\Python23\Lib\site-packages\PIL\Image.py", line 309, in > _getdecoder > raise IOError("decoder %s not available" % decoder_name) > IOError: decoder group4 not available > > Thanks, > From remi at cherrypy.org Mon Jan 3 13:14:29 2005 From: remi at cherrypy.org (remi at cherrypy.org) Date: 3 Jan 2005 10:14:29 -0800 Subject: Frameworks for "Non-Content Oriented Web Apps" References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <1104776069.637218.113610@f14g2000cwb.googlegroups.com> Have a look a the new CherryPy (http://www.cherrypy.org). It allows developers to build web applications in much the same way they would build any other object-oriented Python program. This might corespond to what you're looking for. Remi. From donn at drizzle.com Sun Jan 9 01:06:07 2005 From: donn at drizzle.com (Donn Cave) Date: 9 Jan 2005 00:06:07 -0600 Subject: python3: accessing the result of 'if' References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> <1105236383.521393.40680@c13g2000cwb.googlegroups.com> Message-ID: <41e0c9cf$1_2@127.0.0.1> Quoth "Carl Banks" : ... | As a compromise, howabout: | | . if m > 20 where m=something(): | . do_something_with(m) | | In this case, the m=something() is NOT an assignment statement, but | merely a syntax resembling it. The "where m=something()" is part of | the if-statement, not the if-expression. It causes m to be visisble in | the if-expression and the if-block. If m=something() binds the function return to a name "m" for use in other expressions, it sure IS an assignment. If it isn't an assignment statement, it's only inasmuch as assignment has become something other than a statement. Over whose dead body, I wonder. In case it's of any interest, here's how "where" looks with "if" in Haskell. It would take longer than you might imagine to explain what that "return" is doing there, but part of it is that every "if" must have an "else", and there is no such thing as "elif". Haskell's layout (indent) structure is more flexible than Python's, there are other ways this could look. if a > 10 then putStrLn (show a) else return () where a = 5 + 6 FYI, I suppose the closest it comes to anything like "assignment as an expression" is pattern matching - case (regexp_group "^([^:]*): (.*)" line) of Nothing -> f1 line Just [a, v] -> f2 a v -- This "unwraps" the return value of regexp_group, an imaginary -- function of type (String -> String -> Maybe [String]). The -- Maybe type has two values, Maybe a = Nothing | Just a. | It (or your suggestion) could work with a while-loop too. | | . while line where line=f.readline(): | . do_something_with(line) | | The main problem here (as some would see it) is that you can't do | something this: | | . if m > 20 where (def m(): a(); b()): The way it made sense to me, "where" introduces a block. The whole point is a private scope block. Actually kind of like the reverse of a function, where instead of binding names to input parameters, you in effect bind names to the scope for a sort of return-by-reference effect. But never mind, the point is that you get a private block, with one or more names exported to the surrounding scope in the left hand side of the where clause. What you're trying to do here seems to have almost nothing to do with that. If Python 3 is going to get assignment-as-expression, it will be because GvR accepts that as a reasonable idea. You won't bootleg it in by trying to hide it behind this "where" notion, and you're not doing "where" any good in trying to twist it this way either. Donn Cave, donn at drizzle.com From grahamd at dscpl.com.au Fri Jan 28 06:17:41 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 28 Jan 2005 03:17:41 -0800 Subject: Who should security issues be reported to? In-Reply-To: References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> Message-ID: <1106911061.429966.303510@f14g2000cwb.googlegroups.com> Aahz wrote: > In article <1106863164.745581.11920 at f14g2000cwb.googlegroups.com>, > wrote: > > > >Who are the appropriate people to report security problems to in > >respect of a module included with the Python distribution? I don't > >feel it appropriate to be reporting it on general mailing lists. > > There is no generally appropriate non-public mechanism for reporting > security issues. If you really think this needs to be handled > privately, do some research to find out which core developer is most > likely to be familiar with it. Even before you do that, check > SourceForge to find out whether anyone else has reported it as a bug. I find this response a bit dissappointing frankly. Open Source people make such a big deal about having lots of people being able to look at source code and from that discover security problems, thus making it somehow making it better than proprietary source code. From what I can see, if an Open Source project is quite large with lots of people involved, it makes it very hard to try and identify who you should report something to when there is no clearly identifiable single point of contact for security related issues. Why should I have to go through hoops to try and track down who is appropriate to send it to? All you need is a single advertised email address for security issues which is forwarded onto a small group of developers who can then evaluate the issue and forward it on to the appropriate person. Such developers could probably do such evaluation in minutes, yet I have to spend a lot longer trying to research who to send it to and then potentially wait days for some obscure person mentioned in the source code who has not touched it in years to respond, if at all. Meanwhile you have a potentially severe security hole sitting there wating for someone to expliot, with the only saving grace being the low relative numbers of users who may be using it in the insecure manner and that it would be hard to identify the actual web sites which suffer the problem. I'm sorry, but this isn't really good enough. If Open Source wants to say that they are better than these proprietary companies, they need to deal with these sorts of things more professionally and establish decent channels of communications for dealing with it. And yes I have tried mailing the only people mentioned in the module in question and am still waiting for a response. From spam-trap-095 at at-andros.demon.co.uk Mon Jan 17 19:02:07 2005 From: spam-trap-095 at at-andros.demon.co.uk (Andrew McLean) Date: Tue, 18 Jan 2005 00:02:07 +0000 Subject: Fuzzy matching of postal addresses Message-ID: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> I have a problem that is suspect isn't unusual and I'm looking to see if there is any code available to help. I've Googled without success. Basically, I have two databases containing lists of postal addresses and need to look for matching addresses in the two databases. More precisely, for each address in database A I want to find a single matching address in database B. I'm 90% of the way there, in the sense that I have a simplistic approach that matches 90% of the addresses in database A. But the extra cases could be a pain to deal with! It's probably not relevant, but I'm using ZODB to store the databases. The current approach is to loop over addresses in database A. I then identify all addresses in database B that share the same postal code (typically less than 50). The database has a mapping that lets me do this efficiently. Then I look for 'good' matches. If there is exactly one I declare a success. This isn't as efficient as it could be, it's O(n^2) for each postcode, because I end up comparing all possible pairs. But it's fast enough for my application. The problem is looking for good matches. I currently normalise the addresses to ignore some irrelevant issues like case and punctuation, but there are other issues. Here are just some examples where the software didn't declare a match: 1 Brantwood, BEAMINSTER, DORSET, DT8 3SS THE BEECHES 1, BRANTWOOD, BEAMINSTER, DORSET DT8 3SS Flat 2, Bethany House, Broadwindsor Road, BEAMINSTER, DORSET, DT8 3PP 2, BETHANY HOUSE, BEAMINSTER, DORSET DT8 3PP Penthouse,Old Vicarage, 1 Clay Lane, BEAMINSTER, DORSET, DT8 3BU PENTHOUSE FLAT THE OLD VICARAGE 1, CLAY LANE, BEAMINSTER, DORSET DT8 3BU St John's Presbytery, Shortmoor, BEAMINSTER, DORSET, DT8 3EL THE PRESBYTERY, SHORTMOOR, BEAMINSTER, DORSET DT8 3EL The Pinnacles, White Sheet Hill, BEAMINSTER, DORSET, DT8 3SF PINNACLES, WHITESHEET HILL, BEAMINSTER, DORSET DT8 3SF The challenge is to fix some of the false negatives above without introducing false positives! Any pointers gratefully received. -- Andrew McLean From ptmcg at austin.rr._bogus_.com Wed Jan 12 11:04:28 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 12 Jan 2005 16:04:28 GMT Subject: Iteration over two sequences References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> Message-ID: "Henrik Holm" wrote in message news:1gq9qs9.3snutr1s4mcn2N%news+0409 at henrikholm.com... > I am just starting to learn Python, mostly by going through the examples > in Dive Into Python and by playing around. > > Quite frequently, I find the need to iterate over two sequences at the > same time, and I have a bit of a hard time finding a way to do this in a > "pythonic" fashion. One example is a dot product. The straight-ahead > C-like way of doing it would be: > > def dotproduct(a, b): > psum = 0 > for i in range(len(a)): > psum += a[i]*b[i] > return psum > > However, the range(len(a)) term is awfully un-pythonic :) > The built-in function map() gives me a way of "transposing" the a list > and the b list, and now I can handle it with a list comprehension: > > def dotproduct(a, b): > return sum([x*y for x, y in map(None, a, b)]) > > My concern is one of efficiency: it seems to me that I have two loops > there: first one implied with map(...) and then the for loop -- which > seems like a waste since I feel I should be able to do the > multiplication via an argument to map. So far I have come up with an > alternative via defining a separate function: > > def dotproduct(a, b): > def prod(x,y): return x*y > return sum(map(prod, a, b)) > > I suppose I could also use a lambda here -- but is there a different, > efficient, and obvious solution that I'm overlooking? > > > Thanks, > Henrik > > -- > "On some great and glorious day the plain folks of the land will reach > in their heart's desire at last and the White House will be adorned by > a downright moron." > -H.L. Mencken (1880-1956) American Writer zip maybe? def dotproduct(a,b): return sum([x*y for x,y in zip(a,b)]) -- Paul From fredrik at pythonware.com Thu Jan 27 11:43:15 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 27 Jan 2005 17:43:15 +0100 Subject: On benchmarks, heaps, priority queues References: <1106835562.598569.211370@c13g2000cwb.googlegroups.com><1106842754.010427.74630@c13g2000cwb.googlegroups.com> <1106843673.755688.244160@f14g2000cwb.googlegroups.com> Message-ID: aaronwmail-usenet at yahoo.com wrote: > Hypothetical performance improvements are the root of all evil. > -- Bill Tutt (paraphrased) well, after this week, I'd say that Hypothetical performance limitations are the root of all evil. From howardrh at westerncom.net Wed Jan 19 18:58:37 2005 From: howardrh at westerncom.net (howardrh at westerncom.net) Date: 19 Jan 2005 15:58:37 -0800 Subject: Python and Excel References: Message-ID: <1106179117.094466.305960@f14g2000cwb.googlegroups.com> Please consider this reply as one vote for posting your python Excel interface/software on the Vaults of Pamassus Web Site. Located at http://www.vex.net/parnassus/ From grante at visi.com Sat Jan 1 15:26:13 2005 From: grante at visi.com (Grant Edwards) Date: 01 Jan 2005 20:26:13 GMT Subject: Python equivalent of script(1) References: <1104607982.132310.181560@c13g2000cwb.googlegroups.com> Message-ID: <41d70765$0$31695$a1866201@visi.com> On 2005-01-01, cepl at surfbest.net wrote: > Is there anything like script(1) for python interactive sessions. $ script transcript.txt Script started, file is transcript.txt $ python ... Not sure if there's a way to shut off readline... -- Grant Edwards grante Yow! But was he mature at enough last night at the visi.com lesbian masquerade? From jeremy+plusnews at jeremysanders.net Wed Jan 19 12:07:44 2005 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Wed, 19 Jan 2005 17:07:44 +0000 Subject: simultaneous multiple requests to very simple database References: Message-ID: On Tue, 18 Jan 2005 11:26:46 -0500, Eric S. Johansson wrote: > So the solutions that come to mind are some form of dictionary in shared > memory with locking semaphore scoreboard or a multithreaded process > containing a single database (Python native dictionary, metakit, gdbm??) > and have all of my processes speak to it using xmlrpc which leaves me > with the question of how to make a multithreaded server using stock > xmlrpc. Another solution might be to store the records as files in a directory, and use file locking to control access to the files (careful over NFS!). You might also consider berkeley db, which is a simple database to add to an application, (and which I believe supports locks), but I must admit I'm not a fan of the library. I assume that the bottleneck is processing the records, otherwise this all seems a bit academic. Jeremy From tbolands at yahoo.com Fri Jan 21 18:14:23 2005 From: tbolands at yahoo.com (TB) Date: 21 Jan 2005 15:14:23 -0800 Subject: default value in a list Message-ID: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Hi, Is there an elegant way to assign to a list from a list of unknown size? For example, how could you do something like: >>> a, b, c = (line.split(':')) if line could have less than three fields? Thanks, TB From godoy at ieee.org Sat Jan 15 11:32:28 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Sat, 15 Jan 2005 14:32:28 -0200 Subject: python mode indentation problem References: <1105802644.939051.229990@f14g2000cwb.googlegroups.com> Message-ID: <1489909.b1Lq4kxVjM@strongwill.g2ctech> Xah Lee, S?bado 15 Janeiro 2005 13:24, wrote: > does anyone know why the Python mode in emacs uses spaces for first > level indentation but one tab for second level? > > i'm using emacs 21.3.50.1. > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html It doesn't. It uses spaces for everything, unless told otherwise. -- Godoy. From http Sun Jan 9 23:23:02 2005 From: http (Paul Rubin) Date: 09 Jan 2005 20:23:02 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> Message-ID: <7xvfa53obd.fsf@ruckus.brouhaha.com> Arich Chanachai writes: > >Yes, compiled Lisp. There are Python compilers too.\ > > > ??? You mean like Pyrex or some such? I wouldn't exactly call these > "Python" compilers, as that kind of obscures some underlying > (critical) facts. Also psyco. And I think Pypy is currently set up to compile Python into Pyrex and then run the Pyrex results through GCC. From apardon at forel.vub.ac.be Tue Jan 18 07:42:39 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Jan 2005 12:42:39 GMT Subject: generator expressions: performance anomaly? References: <377Hd.77904$Jk5.30235@lakeread01> Message-ID: Op 2005-01-18, Steve Holden schreef : > Antoon Pardon wrote: > >> Op 2005-01-18, Nick Coghlan schreef : >> >>>Raymond Hettinger wrote: >>> >>>>[Delaney, Timothy C] >>>> >>>> >>>>>Nick's other suggestion - that genexps propagate __len__ - might >>>>>still be interesting. Of course, it would only be applicable for >>>>>unconditional genexps(i.e. no if clause). >>>> >>>>Length transparency for iterators is not as general as one would expect. I once >>>>spent a good deal of effort exploring where it made sense, and I was surprised >>>>to find that it only rarely works out. Length transparency is an unexpectedly >>>>thorny subject with many dead-ends which precludes a fully general solution such >>>>as that proposed by Nick. >>>> >>>>For a recap of my research, see the docstring for Lib/test/test_iterlen.py . >>> >>>"""The situation slightly more involved whenever an object allows length >>>mutation during iteration. """ >>> >>>Ouch. Nice understatement. >>> >>>It's rather unfortunate that we can't make use of the length information even >>>when the source *doesn't* mutate, though. I'll have to think some more to see if >>>I can come up with any concrete ideas for you to shoot down :) >> >> >> Something else I was thinking about. I think it would be nice if the >> python compilor could figure out whether a genexp in a list or tuple >> expression always generates the same list or tuple and then instead >> of generating code would generate the list or tuple in place. >> > Since it doesn't yet optimize 2+5 to a constant-folded 7 you should > realize that you are suggesting a large increase in the compiler's > analytical powers. Well I can dream, cant I? > I agree it would be nice under certain circumstances, but don't forget > that unlike list comprehensions (for which it would be even nicer) the > whole point of generator expressions is often to defer the generation of > the individual items until they are required and thereby relieve stress > on memory. > > As an edge case to demonstrate the point, what about a constant but > infinite sequence? Maybe I was not clear enough. I meant to limit it to cases such as lst = list(genexp) tpl = tuple(genexp) Since in such cases the object is build in memory any way, I don't think it would be a problem of having them prebuilt in memory, or am I missing something? -- Antoon Pardon From a at b.c Tue Jan 11 13:55:42 2005 From: a at b.c (Doug Holton) Date: Tue, 11 Jan 2005 12:55:42 -0600 Subject: Windows GUIs from Python In-Reply-To: References: Message-ID: Bob Swerdlow wrote: > Anyone have opinions about whether we will be better off using PythonNet or > wxPython for the GUI layer of our application on Windows? Our code is all > Python and is now running on Mac OS X with PyObjC and Cocoa, which works > very well. Our goal is not necessarily to move to a cross-platform > solution, but rather to create a solid Windows version that looks and feels > like a native application. All the code that interacts with the user is > factored out of our business logic, so it is a matter of find a good > view/controller library and writing a thin glue layer. And, of course, we > want to build it as efficiently and robustly as we can. I would also recommend wxPython. It runs on Macs, too, so you can at least see how it compares to your PyObjC interface and keep primarily developing on your Mac. You might also be interested in PyGUI although it doesn't have a native Windows implementation yet: http://nz.cosc.canterbury.ac.nz/~greg/python_gui/ From abpillai at gmail.com Thu Jan 6 05:21:56 2005 From: abpillai at gmail.com (Anand) Date: 6 Jan 2005 02:21:56 -0800 Subject: Contributor's List In-Reply-To: <1105006211.527899.318740@c13g2000cwb.googlegroups.com> References: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> <1105006211.527899.318740@c13g2000cwb.googlegroups.com> Message-ID: <1105006916.810877.38170@c13g2000cwb.googlegroups.com> Please direct all queries to the Cookbook editors...! Thanks -Anand From philippecmartin at sbcglobal.net Mon Jan 24 13:17:13 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 24 Jan 2005 12:17:13 -0600 Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) Message-ID: <1106590633.15475.3.camel@localhost> I use "__"for private variables because I must have read on net it was the way to do so - yet this seems to have changed - thanks: http://www.network-theory.co.uk/docs/pytut/tut_77.html As far as the specific stderr reroute example - I just grabbed some of my code and forgot to get rid of that stuff Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From ola.natvig at infosense.no Mon Jan 31 10:16:19 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Mon, 31 Jan 2005 16:16:19 +0100 Subject: import directory error In-Reply-To: <41fe49b5$0$2168$8fcfb975@news.wanadoo.fr> References: <41fe49b5$0$2168$8fcfb975@news.wanadoo.fr> Message-ID: <4nu1d2-hjh.ln1@pluto.i.infosense.no> Olivier Noblanc ATOUSOFT wrote: > Hello, > > > When i want to import a .py fire from another subdirectory i make > > import inc/setupxml > > > but that make me an error message. > > A man tell me to put a dot but that doesn't work. > > Can you help me ? > > Thanks. > > > You should write import inc.setupxml this imports the module located at inc/setupxml.py It's said that it imports the setupxml *module* from the inc *package* All packages should include a __init__.py file. The import may not work unless. You will get the __init__.py file if you type import inc -- -------------------------------------- Ola Natvig infoSense AS / development From http Thu Jan 20 00:23:03 2005 From: http (Paul Rubin) Date: 19 Jan 2005 21:23:03 -0800 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> Message-ID: <7xekggbrns.fsf@ruckus.brouhaha.com> Tim Peters writes: > > Huh? [1,2,[3,4,5],[6,[[[[7]],8]]]] is a perfectly valid Python list. > > You're claiming not to know any relevant difference between Python > lists and Lisp lists? Heh. Python doesn't provide syntactic sugar for [1,[2,[3,[4,[]]]]] if that's what you mean. In Lisp you'd say (1 2 3 4). It's still a perfectly valid list in Python. Python by convention uses multi-element arrays instead of lists of conses. > > And you can break out of a containing loop from a nested loop > > with try/raise. > > Heh heh. Yes, you can. I've never seen a real Python program that > did, but there's nothing to stop you. I do that on a fairly routine basis. I won't say "often", but it's a standard technique that finds a use now and then. > What did you think the "direct" in "direct way" might have been > intended to mean? I guess you meant there's no syntax sugar for a multi-level break or a break with a label. It hasn't been that big a problem. C doesn't have it either. The need for it comes up infrequently enough that try/except is a satisfactory way to handle it. > > More troublesome is not being able to see a variable in a > > containing scope from a nested scope, unless the containing > > scope is the global one. Why bother debating lexical scope for > > years before deciding to add it, only to stop halfway? > > I'd call it 80% of the way, but suit yourself. The debates are all > easily found, if you really want to know. Well, I'd say whatever the percentage is, it started at near zero and has been slowly increasing and continues to increase. For example, [x*x for x in range(5)] doesn't create a temporary scope but (x*x for x in range(5)) does, and [x*x for x in range(5)] will apparently do so in a future version. There's a technique in numerical analysis called Richardson extrapolation, where you compute an integral by evaluating the function at n=k points, then at n=2k points, then at n=4k points, etc. and fit a curve through these approximations to estimate the limit at n=infinity. This turns out to be a good way to compute integrals. Basically by making a few better and better approximations at the answer, you can make a good estimate of the final result you'd get if you kept approximating forever. I see the same thing happening in Python. It's going through successively better approximations to get closer to a limit. Python has it harder than some other languages, because it tries to serve the needs of both throwaway scripts and large-scale development projects. The result is that feature after feature starts out with an implementation sufficient for small scripts, and then edges towards the needs of large-scale projects. But it's often predictable at the beginning what the final destination is going to be. So once we can see where it's going, why not proceed to the finish line immediately instead of bothering with the intermediate steps? From FBatista at uniFON.com.ar Thu Jan 6 10:32:45 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 6 Jan 2005 12:32:45 -0300 Subject: File Handling Problems Python I/O Message-ID: [Josh] #- able to do so without a problem, but here's the catch: The open #- statement is only working on certain files. I open a simple text file #- say file1.txt without any issues, but I change the open statement to #- another text file and it error's out stating the file #- doesn't exist. I #- know the code is correct because it worked for the other file. I have #- tried both binary and ascii modes to no avail. Any idea why this is #- happening? I am running Python 2.3.4 wxPython 2.5.3.1 and SPE as the #- IDE on Win2k. Thanks Could you please post the actual code? Also, post the result to the following: "os.listdir('.')". . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at grulic.org.ar Mon Jan 17 10:15:56 2005 From: john at grulic.org.ar (John Lenton) Date: Mon, 17 Jan 2005 12:15:56 -0300 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: <20050117151556.GD3811@grulic.org.ar> On Mon, Jan 17, 2005 at 11:41:20AM +0000, Antoon Pardon wrote: > Op 2005-01-17, Steve Holden schreef : > > Antoon Pardon wrote: > > [...] > >>>"A foolish consistency is the hobgoblin of little minds". Rules are made > >>>to be broken. > >> > >> > >> Like only use immutables as dictionary keys. > >> > > Fair enough, but don;t go advising newbies to do this. > > How about something like this. > > Because of the extra precautions one has to take when > using mutables as hash keys, we advise newbies > to stick with immutable keys until they have gathered > enough knowledge and experience to adequatly weight > the pro and cons of a mutable key solution against > an immutable key solution. knowledgeable and experienced users know when to ignore the rules. -- John Lenton (john at grulic.org.ar) -- Random fortune: Una buena gran parte del arte del bien hablar consiste en saber mentir con gracia. -- Erasmo de Rotterdam. (1469-1536). -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From rootshell at gazeta.pl Thu Jan 13 08:03:44 2005 From: rootshell at gazeta.pl (rootshell at gazeta.pl) Date: Thu, 13 Jan 2005 14:03:44 +0100 Subject: Free python server. Message-ID: <001b01c4f970$5247d830$208e1d53@unqku4k1fl8nea7> Hi there. What I need is web sever, where I could put just one python script. Greetings. Rootshell. From tjreedy at udel.edu Thu Jan 6 20:09:08 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Jan 2005 20:09:08 -0500 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com><7x652che6z.fsf@ruckus.brouhaha.com><7x4qhw859p.fsf@ruckus.brouhaha.com><7xk6qrnbum.fsf@ruckus.brouhaha.com><41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7x652bnhx0.fsf at ruckus.brouhaha.com... > If I have a 400 gig hard drive, I don't see why I need 99.99% of it > empty instead of 99.0% after I do my OS install. Even though I currently only have 80 megs (about the minimum one can currently buy), I've about decided you are right. Having just installed a 3 CD game last night, I realize that my stinginess with disk space for more serious stuff is obsolete. (My first hard disk was 5 or 10 megs.) A gigabyte would cover Python + Wxpython + numarray + scipy + pygame + a lot of other stuff. Would it be possible, at least for Windows, to write a Python script implementing a 'virtual distribution'? IE, download Python, install it, download next package, install it, etc. -- prefereably table driven? Terry J. Reedy From peter at engcorp.com Thu Jan 20 16:10:26 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Jan 2005 16:10:26 -0500 Subject: Print to Windows default Printer In-Reply-To: References: Message-ID: <8cOdnW3_BMHfg23cRVn-3w@powergate.ca> Tim Golden wrote: > [Samantha] > | The printer is on LPT1, but I sure can't get the temp file to > | print for some > | reason. > | I am using Windows XP SP2. > | S > > i'm afraid I have to step out here (metaphorically speaking): > I'm using Win2K and have no access to XP boxes. The technique > works fine here; it may be that either they've removed the > functionality under XP, or that there's some security > context which is preventing you from accessing the port. > > Can anyone else try a "PRINT blah" or a "COPY blah LPT1:" > on XP SP2? Works fine here. That is, without having my printer on, I can see the job go into the printer control window as just another job. One does, of course, have to have the printer set up to *be* LPT1, however, and that doesn't happen by default unless you select something about "print from MSDOS programs" when you set it up, or you go into the Properties and make sure you configure it properly on the Ports tab... -Peter From ncoghlan at iinet.net.au Thu Jan 20 04:13:51 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 20 Jan 2005 19:13:51 +1000 Subject: Dictionary keys (again) (was Re: lambda) In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: <41EF764F.3000101@iinet.net.au> David Eppstein wrote: > Yes, and what should the following do? > > lst1 = [1] > lst2 = [2] > dct = {lst1: "1", lst2: "2"} > lst2[0]=1 > lst1[0]=2 > print dct[[1]] > print dct[[2]] > Provide yet another example for why mutable keys are almost guaranteed to result in suprising semantics :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From hikenboots at yahoo.com Sun Jan 2 11:36:16 2005 From: hikenboots at yahoo.com (John French) Date: Sun, 2 Jan 2005 10:36:16 -0600 Subject: Advice request for project Message-ID: I've been interested in Python for a while now but haven't had an opportunity to use / learn it. I'm tasked now with a project at work that might be my first opportunity. I have to write a ~75 concurrent user document storage app. that allows users to scan documents from locally attached scanners and save to a database for retrieval. I also need to be able to call MS Word with templates and allow the user to save the file to the database. I think I understand that I can interface MS COM for these, correct? My interest is in using FreeBSD/Postgresql/Python as a back end and a Python GUI app on the XP workstations. I'm going to end up adding some non-database functionality to the project in the future that precludes only using odbc to the database. I'll likely end up with some form of inter-user messaging being incorporated before it's over. Is it better to write one server side socket app to handle everything or start via odbc and necessary server side apps later? If anyone can tell me if this project seems appropriate to Python and offer suggestions as to an initial architecture, I'd appreciate it. I'm quite interested in the RAD aspect of the language but quite lost at the moment. (I did just sign up for the Tutor mailing list). Thanks in Advance From tjreedy at udel.edu Wed Jan 12 19:19:21 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Jan 2005 19:19:21 -0500 Subject: What strategy for random accession of records in massive FASTA file? References: Message-ID: RE: What strategy for random accession of records in massive FASTA file? "Batista, Facundo" wrote in message news:A128D751272CD411BC9200508BC2194D053C7E95 at escpl.tcp.com.ar... [If you want to keep the memory usage low, you can parse the file once and store in a list the byte position where the record starts and ends. Then access the list randomly and read each record with seek() and read(). ---------- Or if you want to access by sequence name rather than number, use a dict instead. tjr From jerf at jerf.org Mon Jan 31 22:09:37 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 31 Jan 2005 22:09:37 -0500 Subject: set, dict and other structures References: <1107214762.198058.55680@f14g2000cwb.googlegroups.com> Message-ID: On Tue, 01 Feb 2005 00:43:21 +0000, Raymond Hettinger wrote: > My guess is that there will be two issues. One is that no one > implementation of graphs seems to satisfy all users. The second is that > only a small fraction of Python users need for graph support (there is > probably a much greater demand for combinatorics, numeric/numarray, or > financial modules). If the appeal is not broad, it has little chance of > making it into the standard library. This reminded me of a group of people that were supposed to have started in on this: http://www.python.org/moin/PythonGraphApi It's too soon to call it dead, but I don't see a success pattern for it; I'd say they foundered on trying to shoot for the moon in advance, instead of starting to write code and incrementally improving it. (Hint, hint, if any of you are reading this.) Trying to create a graph library that meets any significant percentage of the needs of the people who would use it is quite non-trivial. It's not impossible, but it's a lot lot lot lot lot of work. I remember counting at least 48 distinct types of graphs when I enumerated my concerns to that project and I'm sure there are a few more dimensions that didn't make it into that list (the Wiki talks about "hierachial" graphs which adds another dimension I didn't count, for instance, and I'm sure there are more...). From xah at xahlee.org Sat Jan 22 06:57:40 2005 From: xah at xahlee.org (Xah Lee) Date: 22 Jan 2005 03:57:40 -0800 Subject: [perl-python] 20050121 file reading & writing Message-ID: <1106395060.211314.54530@f14g2000cwb.googlegroups.com> # -*- coding: utf-8 -*- # Python # to open a file and write to file # do f=open('xfile.txt','w') # this creates a file "object" and name it f. # the second argument of open can be # 'w' for write (overwrite exsiting file) # 'a' for append (ditto) # 'r' or read only # to actually print to file or read from # file, one uses methods of file # objects. e.g. # reading entire file # text = f.read() # reading the one line # line = f.realine() # reading entire file as a list, of lines # mylist = f.readlines() # to write to file, do f.write('yay, first line!\n') # when you are done, close the file f.close() # closing files saves memory and is # proper in large programs. # see # http://python.org/doc/2.3.4/tut/node9.html # or in Python terminal, # type help() then topic FILES # try to write a program that read in a # file and print it to a new file. ------------------------ # in perl, similar functionality exists. # their construct is quite varied. # example of reading in file # and print it out # (first, save this file as x.pl) open(f,") {print $line} close(f) or die "error: $!"; print "am printing myself\n"; # the above is a so called "idiom" # meaning that it is the way such is # done in a particular language, as in # English. # note, the f really should be F in Perl # by some references, but can also be # lower case f or even "f". All are not # uncommon. There is no clear reason for # why or what should be or what # is the difference. Usually it's # not worthwhile to question in # Perl. ">x.pl" would be for write to # file. The tells perl the file # object, and when Perl sees t=<> it # reads a line. (usually, but technically # depending on some predefined # variables...) The f they call "file handle". # ... see # perldoc -tf open # to begin understanding. ------------ Note: this post is from the Perl-Python a-day mailing list at http://groups.yahoo.com/group/perl-python/ to subscribe, send an email to perl-python-subscribe at yahoogroups.com if you are reading it on a web page, program examples may not run because html conversion often breaks the code. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From cybermanxu at hotmail.com Fri Jan 21 17:03:51 2005 From: cybermanxu at hotmail.com (Jinming Xu) Date: Fri, 21 Jan 2005 16:03:51 -0600 Subject: Tuple size and memory allocation for embedded Python Message-ID: Hi Folks, Python seems unstable, when allocating big memory. For example, the following C++ code creates a tuple of tuples: PyObject* arCoord = PyTuple_New(n); double d = 1.5; for(int i=0; i Message-ID: Nelson Minar writes: > Could someone help me get started using XPath or XQuery in Python? I figured this out. Thanks for the help, John! Examples below. I used this exercise as an opportunity to get something off my chest about XML and Python - it's kind of a mess! More here: http://www.nelson.monkey.org/~nelson/weblog/tech/python/xpath.html Here are my samples, in three libraries: # PyXML from xml.dom.ext.reader import Sax2 from xml import xpath doc = Sax2.FromXmlFile('foo.opml').documentElement for url in xpath.Evaluate('//@xmlUrl', doc): print url.value # libxml2 import libxml2 doc = libxml2.parseFile('foo.opml') for url in doc.xpathEval('//@xmlUrl'): print url.content # ElementTree from elementtree import ElementTree tree = ElementTree.parse("foo.opml") for outline in tree.findall("//outline"): print outline.get('xmlUrl') Please see my blog entry for more commentary http://www.nelson.monkey.org/~nelson/weblog/tech/python/xpath.html From reinhold-birkenfeld-nospam at wolke7.net Fri Jan 14 14:32:15 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 14 Jan 2005 20:32:15 +0100 Subject: Why would I get a TypeEror? In-Reply-To: References: Message-ID: <34ql1vF4dqd9pU1@individual.net> It's me wrote: > Sorry if my question was a little "lazy" and yes, I was asking about the > "lazy evaluation". :=) > > I am surprised about this (and this can be dangerous, I guess). > > If this is true, I would run into trouble real quick if I do a: > > (1/x,1.0e99)[x==0] > > and that's not good. > > Something to keep in mind. :-( Lazy evaluation: use the (x==0 and 1e99 or 1/x) form! Reinhold From kartic.krishnamurthy at gmail.com Mon Jan 24 12:19:05 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 24 Jan 2005 09:19:05 -0800 Subject: Import from database In-Reply-To: References: Message-ID: <1106587145.067483.14710@z14g2000cwz.googlegroups.com> Steve, I believe you have to put ntpath, macpath and posixpath in the module database for os.path to work. I tried it with zipimporter builtin and I got the same traceback till I added ntpath.py to my zip file. (Of course, I renamed the original ntpath to _ntpath so that the original did not get imported) Thanks, --Kartic From steven.bethard at gmail.com Sat Jan 29 18:31:06 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 29 Jan 2005 16:31:06 -0700 Subject: bound vs unbound functions In-Reply-To: <1107040729.535936.42230@c13g2000cwb.googlegroups.com> References: <1107040729.535936.42230@c13g2000cwb.googlegroups.com> Message-ID: Michael Tobis wrote: > Anyway, I'd like to dynamically add a method to an instance at > instantiation time. Something like Nearly identical question from yesterday and a series of answers: http://mail.python.org/pipermail/python-list/2005-January/263024.html Steve From cr999 at ir.hit.edu.cn Sat Jan 8 22:55:30 2005 From: cr999 at ir.hit.edu.cn (cr999) Date: Sun, 9 Jan 2005 11:55:30 +0800 Subject: Are there some resources about Python's VM and Python's implementation? Message-ID: <003701c4f5ff$283f5000$1d02a8c0@cr> I am very interested in Python's VM and also Python's implementation. I want to read the Phton's source code but i think it is very helpful if there are some resources and docuemnts about this topic. Anybody knows about this? Thanks :) Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From ncoghlan at iinet.net.au Thu Jan 27 05:15:22 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 27 Jan 2005 20:15:22 +1000 Subject: python without OO In-Reply-To: <1106798140.896125.187850@f14g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> <1106798140.896125.187850@f14g2000cwb.googlegroups.com> Message-ID: <41F8BF3A.8050402@iinet.net.au> beliavsky at aol.com wrote: > Furthermore, if in Python the algorithm for the reverse function > applies to many kinds of objects, it just needs to be coded once, > whereas a reverse method would have to provided for each class that > uses it (perhaps through inheritance). Indeed, this is why Python not only provides the list.reverse() method to reverse a list in place, but also provides the reversed() function to reverse any sequence: Py> lst = list("ABCDEFGHIJ") Py> lst.reverse() Py> print "".join(lst) JIHGFEDCBA Py> print "".join(reversed(lst)) ABCDEFGHIJ Ditto list.sort() and sorted(). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jfj at freemail.gr Thu Jan 27 21:01:29 2005 From: jfj at freemail.gr (jfj) Date: Thu, 27 Jan 2005 18:01:29 -0800 Subject: Tuple slices In-Reply-To: References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> <1106669254.838248.317170@z14g2000cwz.googlegroups.com> <10vdj4s9ib19fe3@corp.supernews.com> <41F7F5CF.5040902@freemail.gr> Message-ID: <41F99CF9.2020201@freemail.gr> Nick Coghlan wrote: > > 1. Applies only if you are making large slices, or a lot of slices with > each containing at least 3 elements. > A view can also *cost* memory, when it looks at a small piece of a > large item. The view will keep the entire item alive, even though it > needs only a small piece. That is correct. > > 2. Hell no. The *elements* aren't copied, pointers to the elements are. > If you *don't* copy the pointers, then every item access through the > view involves an indirection as the index into the original sequence > gets calculated. If you have x=(1,2,...100001) y=x[:-1] then you copy 100000 pointers AND you INCREF them AND you DECREF them when y dies. The unfortunate case by (1) would be: x=(1,2,...100001) x=x[:1] > > So views *may* save memory in some applications, but are unlikely to > save time in any application (except any saving resulting from the > memory saving). > They do. If tp_dealloc of a tuple view doesn't decref the pointers. We should look for what is the most common case. Gerald -PS: the PEP for the removal ought to have a ":)" at the end. From python-url at phaseit.net Sun Jan 9 13:08:03 2005 From: python-url at phaseit.net (Josiah Carlson) Date: Sun, 09 Jan 2005 18:08:03 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 9) Message-ID: QOTW: Jim Fulton: "[What's] duck typing?" Andrew Koenig: "That's the Australian pronunciation of 'duct taping'." "I'm thinking that the I-Ching is a vast untapped resource for programming wisdom, plus it makes it funny." -- Mark Carter Nick Coghlan brings up the 'lambdas are going away in 3.0' topic, which has been discussed before: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/81e17b1d3ccba538 A user asks about a non-generator-based method for iteration using class __iter__ and next() methods: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/6336a00ad217888a Daniel Bickett asks about getting Twisted and wxPython working together, and receives both a threaded and non-threaded version: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/73f1e7758225afc3 A question about iterating over floats...be careful! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1278866159ac4429 A Boogieman asks whether Python is easily learned and what can be done with it. Quick answer: yes, and anything you are capable of doing: This Boogieman later asks about GUI toolkits: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e67b776df72eb336 http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d502698b4adacd01 Erik Bethke writes Majong game after using Python for a month. Ahh, will the wonders of Python never cease? http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/6d710e35007f0f32 Kamilche asks about getting warnings when not calling a function, and gets pointed to pychecker, something more of us should be using: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/dff810b7dacd247c Are people allowed to build commercial applications in Python? YES! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/aa953388db68b196 Questions about asyncore brings up a web server in asyncore from _Python Web Programming_, and a pointer to Twisted. Alternatively, one could look at the asynchat or smtpd modules in the standard library as sources of inspiration: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/81360ec06013e36d ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. deli.cio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From jepler at unpythonic.net Sun Jan 23 17:27:44 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Sun, 23 Jan 2005 16:27:44 -0600 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <200501232255.08496.francis.girard@free.fr> References: <63b5e209.0501210558.686f5c10@posting.google.com> <200501221106.49241.francis.girard@free.fr> <200501232255.08496.francis.girard@free.fr> Message-ID: <20050123222743.GA32583@unpythonic.net> Your formulation in Python is recursive (hamming calls hamming()) and I think that's why your program gives up fairly early. Instead, use itertools.tee() [new in Python 2.4, or search the internet for an implementation that works in 2.3] to give a copy of the output sequence to each "multiply by N" function as well as one to be the return value. Here's my implementation, which matched your list early on but effortlessly reached larger values. One large value it printed was 6412351813189632 (a Python long) which indeed has only the distinct prime factors 2 and 3. (2**43 * 3**6) Jeff from itertools import tee import sys def imerge(xs, ys): x = xs.next() y = ys.next() while True: if x == y: yield x x = xs.next() y = ys.next() elif x < y: yield x x = xs.next() else: yield y y = ys.next() def hamming(): def _hamming(j, k): yield 1 hamming = generators[j] for i in hamming: yield i * k generators = [] generator = imerge(imerge(_hamming(0, 2), _hamming(1, 3)), _hamming(2, 5)) generators[:] = tee(generator, 4) return generators[3] for i in hamming(): print i, sys.stdout.flush() -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From bob.ducharme at gmail.com Wed Jan 26 17:06:24 2005 From: bob.ducharme at gmail.com (bobdc) Date: 26 Jan 2005 14:06:24 -0800 Subject: short programming projects for kids In-Reply-To: <1106332638.595750.150590@c13g2000cwb.googlegroups.com> References: <1106332638.595750.150590@c13g2000cwb.googlegroups.com> Message-ID: <1106777184.137556.17280@f14g2000cwb.googlegroups.com> Thanks Andr?, Adrian, Steve, Duncan, and zombiehunter for the excellent suggestions. Bob From daniel at bowettsolutions.com Wed Jan 5 14:48:52 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Wed, 05 Jan 2005 19:48:52 +0000 Subject: Python evolution: Unease In-Reply-To: References: Message-ID: <41DC44A4.8080406@bowettsolutions.com> Batista, Facundo wrote: > [John Roth] > > #- I would like to contribute some documentation to Python. > #- I've got the time, I write quite a bit, etc. I've got fairly > #- strong opinions about some things that need to be documented, > #- (such as all the new style class descriptor stuff from 2.2) > #- and I have relatively little difficulty matching the existing style. > #- > #- However, I don't > #- know TEX, Latex, CVS or Sourceforge. (The latter two are > #- on my "learn sometime soon so I can put PyFIT where it belongs" > #- list.) > > The easiest way to contribute with documentation is the following: > > 1. You found something badly documented. > 2. You write/correct the docs as you think they should be. > 3. Open a bug in SF and attach your text (just plain text if you don't > want to produce something more elaborate). > > Of course, for step 3 you need a SF account: that's only five minutes. > > . Facundo > > Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog > PyAr - Python Argentina: http://pyar.decode.com.ar/** > Contribute to where on Sourceforge??? Which domentation are we talking about in general? From martin at v.loewis.de Thu Jan 20 13:37:31 2005 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 20 Jan 2005 19:37:31 +0100 Subject: xml parsing escape characters In-Reply-To: <41eff4cf$0$6209$e4fe514c@news.xs4all.nl> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efb72d$1_2@newspeer2.tds.net> <41efe52f$0$6220$e4fe514c@news.xs4all.nl> <41efee5d$0$11622$9b622d9e@news.freenet.de> <41eff4cf$0$6209$e4fe514c@news.xs4all.nl> Message-ID: <41effa64$0$3366$9b622d9e@news.freenet.de> Irmen de Jong wrote: >> Usually, but not in this case. If you have a text that looks like >> XML, and you want to put it into an XML element, the XML file uses >> < and >. The XML parser unescapes that as < and >. However, it >> does not then consider the < and > as markup, and it shouldn't. > > > That's also what I said? You said it in response to >>> All the behaviour you are seeing is a consequence of this. You need >>> to unescape the contents of the tag to be able to treat it >>> as structured XML. In that context, I interpreted >> The unescaping is usually done for you by the xml parser that you >> use. as "The parser should have done what you want; if the parser didn't, that is is bug in the parser". > The OP probably wants to feed that to a new xml parser instance > to process it as markup. > Or perhaps the way the original XML document is constructed is > flawed. Either of these, indeed - probably the latter. Regards, Martin From mercuryprey at gmail.com Sun Jan 30 13:55:08 2005 From: mercuryprey at gmail.com (mercuryprey at gmail.com) Date: 30 Jan 2005 10:55:08 -0800 Subject: Disassembling strings and turning them into function parameters In-Reply-To: References: <1107107283.694377.286360@c13g2000cwb.googlegroups.com> Message-ID: <1107111308.052945.263600@c13g2000cwb.googlegroups.com> Hey, that's exactly what I need! Thanks for your help, the others too of course :) Didn't expect to get answers so quickly.. From rasdj at frontiernet.net Sun Jan 30 23:21:49 2005 From: rasdj at frontiernet.net (rasdj at frontiernet.net) Date: 30 Jan 2005 20:21:49 -0800 Subject: next line, new line In-Reply-To: References: <1107142942.626773.131980@c13g2000cwb.googlegroups.com> Message-ID: <1107145309.922093.295360@c13g2000cwb.googlegroups.com> Thanks Jeremy, something like this would work: try: lines = [ line.replace(",\n;", ")\n;") for line in input ] If I could figgure out how to: IF ':' in line READ next line in lines = [ line.replace(",\n;", ")\n;") for line in input ] output.write(str.join('', lines)) because there are lots of "comma newline" but the only ones I want are the ones that follow the semicolon. RasDJ From aleaxit at yahoo.com Thu Jan 27 13:29:57 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 27 Jan 2005 19:29:57 +0100 Subject: String Fomat Conversion References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> Message-ID: <1gr2aln.1a15eud1xil75nN%aleaxit@yahoo.com> Steven Bethard wrote: ... > Beware of mixing iterator methods and readline: _mixing_, yes. But -- starting the iteration after some other kind of reading (readline, or read(N), etc) -- is OK... > http://docs.python.org/lib/bltin-file-objects.html > > next( ) > ...In order to make a for loop the most efficient way of looping > over the lines of a file (a very common operation), the next() method > uses a hidden read-ahead buffer. As a consequence of using a read-ahead > buffer, combining next() with other file methods (like readline()) does > not work right. > > I haven't tested your code in particular, but this warning was enough to > make me generally avoid mixing iter methods and other methods. Yeah, I know... it's hard to explain exactly what IS a problem and what isn't -- not to mention that this IS to some extent a matter of the file object's implementation and the docs can't/don't want to constrain the implementer's future freedom, should it turn out to matter. Sigh. In the Nutshell (2nd ed), which is not normative and thus gives me a tad more freedom, I have tried to be a tiny bit more specific, taking advantage, also, of the fact that I'm now addressing the 2.3 and 2.4 implementations, only. Quoting from my current draft (pardon the XML markup...): """ interrupting such a loop prematurely (e.g., with break), or calling f.next() instead of f.readline(), leaves the file's current position at an arbitrary value. If you want to switch from using f as an iterator to calling other reading methods on f, be sure to set the file's current position to a known value by appropriately calling f.seek. """ I hope this concisely indicates that the problem (in today's current implementations) is only with switching FROM iteration TO other approaches to reading, and (if the file is seekable) there's nothing so problematic here that a good old 'seek' won't cure... Alex From tim.peters at gmail.com Fri Jan 14 19:13:13 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 14 Jan 2005 19:13:13 -0500 Subject: Why 'r' mode anyway? In-Reply-To: <41e827df$0$6219$e4fe514c@news.xs4all.nl> References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> <41e80785$0$6203$e4fe514c@news.xs4all.nl> <41e827df$0$6219$e4fe514c@news.xs4all.nl> Message-ID: <1f7befae0501141613545a30cd@mail.gmail.com> [Tim Peters] >> That differences may exist is reflected in the C >> standard, and the rules for text-mode files are more restrictive >> than most people would believe. [Irmen de Jong] > Apparently. Because I know only about the Unix <-> Windows > difference (windows converts \r\n <--> \n when using 'r' mode, > right). So it's in the line endings. That's one difference. The worse difference is that, in text mode on Windows, the first instance of chr(26) in a file is taken as meaning "that's the end of the file", no matter how many bytes may follow it. That's fine by the C standard, because everything about a text-mode file containing a chr(26) character is undefined. > Is there more obscure stuff going on on the other systems you > mentioned (Mac OS, VAX) ? I think on Mac Classic it was *just* line end differences. Native VAX has many file formats. "Record-based" file formats used to be very popular. There the OS saves meta-information in the file, such as each record contains an offset to the start of the next record, and may even contain an index structure to support random access to records quickly (for example, "a line" may be a record, and "read the last line" may go quickly). Read that in binary mode, and you'll be reading up the bits in the index and offsets too, etc. IIRC, Unix was actually quite novel at the time in insisting that all files were just raw byte streams to the OS. > (That means that the bug in Simplehttpserver that my patch > 839496 addressed, also occured on those systems? Or that > the patch may be incorrect after all??) Don't know, and (sorry) no time to dig. > While your argument about why Python doesn't use its own > platform- independent file format is sound of course, I find it often > a nuisance that platform specific things tricle trough into Python > itself and ultimately in the programs you write. I sometimes feel > that some parts of Python expose the underlying C/os > implementation a bit too much. Python never claimed write once > run anywhere (as that other language does) but it would have > been nice nevertheless ;-) > In practice it's just not possible I guess. It would be difficult at best. Python hides a lot of platform crap, but generally where it's reasonably easy to hide. It's not easy to hide native file conventions, partly because Python wouldn't play well with *other* platform software if it did. Remember that Guido worked on ABC before Python, and Python is in (small) part a reaction against the extremes of ABC. ABC was 100% platform-independent. You could read and write files from ABC. However, the only files you could read from ABC were files that were written by ABC -- and files written by ABC were essentially unusable by other software. Socket semantics were also 100% portable in ABC: it didn't have sockets, nor any way to extend the language to add them. Etc -- ABC was a self-contained universe. "Plays well with others" was a strong motivator for Python's design, and that often means playing by others' rules. From jjl at pobox.com Sat Jan 1 11:44:23 2005 From: jjl at pobox.com (John J. Lee) Date: 01 Jan 2005 16:44:23 +0000 Subject: PyQT installation References: <1104370062.562575.88620@f14g2000cwb.googlegroups.com> <1104417268.153983.71970@z14g2000cwz.googlegroups.com> <8SVAd.64014$Jk5.26087@lakeread01> <1gpo9ow.7zqmxi1rwc564N%aleaxit@yahoo.com> Message-ID: <871xd5hzfc.fsf@pobox.com> aleaxit at yahoo.com (Alex Martelli) writes: [...] > Basically: if you want it on Windows for free, forget Qt Correct. > (I hear the > cygwin people are trying to make a GPL Qt available for Win+cyg+XFree, > but I suspect trolltech ain't happy about that -- anyway, I don't think > it would be "native", X11 being still required). [...] Not correct. It's driven by KDE, and it's more ambitious than that: http://kde-cygwin.sourceforge.net/qt3-win32/roadmap.php IIRC, people have already run some KDE apps under Windows (though still needing X, so far). I wonder how TrollTech will react as (and if) it progresses. John From fredrik at pythonware.com Wed Jan 26 12:48:28 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Jan 2005 18:48:28 +0100 Subject: Subclassed dict as globals References: Message-ID: Evan Simpson wrote: > In Python 2.4 the following works: > > >>> class G(dict): > ... def __getitem__(self, k): > ... return 'K' + k > ... > >>> g = G() > >>> exec 'print x, y, z' in g > Kx Ky Kz > >>> > > ...while in Python 2.3 it fails with NameError: name 'x' is not defined. Is this an "accidental > feature", or can I count on this working in future versions of Python? it's an official addition, and it's at least to safe for it to be in all future versions of CPython 2.X. http://www.python.org/doc/2.4/whatsnew/node12.html The eval(expr, globals, locals) and execfile(filename, globals, locals) functions and the exec statement now accept any mapping type for the locals parameter. Previously this had to be a regular Python dictionary. (Contributed by Raymond Hettinger.) I don't think he added this purely by accident, but it might have been a side effect of some other optimization. ;-) > For that matter, is there a way to do this (intercept global variable accesses) > in Python 2.3? not that I'm aware of... From levub137 at wi.rr.com Sun Jan 2 15:10:39 2005 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sun, 02 Jan 2005 14:10:39 -0600 Subject: [ANN] rpncalc-1.2 RPN Calculator For Python Message-ID: The rpncalc package adds an interactive Reverse Polish Notation (RPN) interpreter to Python. This interpreter allows the use of Python as an RPN calculator. You can easily switch between the RPN interpreter and the standard Python interpreter. Home page: http://calcrpnpy.sourceforge.net/ Changes in 1.2 * Added ratfun module that provides polynomial and rational function classes. These classes support mixed arithmetic where numbers, polynomials, and rational functions can be combined in a Python expression. * Incorporate a syntax that allows entering polynomials and rational functions from the RPN interpreter. From steve at holdenweb.com Sat Jan 8 13:44:55 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 08 Jan 2005 13:44:55 -0500 Subject: The limitation of the Photon Hypothesis In-Reply-To: References: Message-ID: Steve Horsley wrote: > bill wrote: > >> Please reply to hdgbyi at public.guangzhou.gd.cn, thank you ! > > > No - I'll reply to the newsgroup, if you don't mind. > >> The limitation of the Photon Hypothesis > > > >> THE UNCERTAINTY PRINCIPLE IS UNTENABLE > > > > You cannot use classical theory to disprove quantum theory that easily. > The uncertainty is quantum in origin, and not just an artifact of > classical mechanics applied to clumsy measurement. > > You don't convince me. > > Also, I think you probably accidentally posted to the wrong newsgroup. > > Steve > > No, he deliberately posted to the wrong newsgroup. But that's because there isn't a right newsgroup for this kind of twaddle (except possibly alt.rubbish.alternate.universe). You have just marked yourself as a noob, since this hoary old favorite seems to appear about ten times a year. Welcome to Usenet! regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From ncoghlan at iinet.net.au Mon Jan 10 05:11:29 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 10 Jan 2005 20:11:29 +1000 Subject: Long strings as function parameters In-Reply-To: References: <1105288564.441842.13060@c13g2000cwb.googlegroups.com> Message-ID: <41E254D1.7010305@iinet.net.au> Jeremy Bowers wrote: > I had thought there was an obvious class in the standard library to assist > with this, but I must have been wrong. buffer is the closest current contender, but I believe it's on the outer due to some problems with its implementation. I think the intention is to eventually have a 'bytes' type, but I don't recall if that was going to be mutable or immutable. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steve at holdenweb.com Mon Jan 3 14:47:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Jan 2005 14:47:05 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xacrs230c.fsf@ruckus.brouhaha.com> Message-ID: Aahz wrote: > In article , > Steve Holden wrote: > >>Aahz wrote: >> >>>In article <7xacrs230c.fsf at ruckus.brouhaha.com>, >>>Paul Rubin wrote: >>> >>>>I was pretty skeptical of Java's checked exceptions when I first used >>>>them but have been coming around about them. There's just been too >>>>many times when I wrote something in Python that crashed because some >>>>lower-level function raised an exception that the upper level hadn't >>>>been expecting, after the program had been in use for a while. I'd >>>>sure rather find out about that at compile time. >>> >>>That's funny -- Bruce Eckel talks about how he used to love checked >>>exceptions but has come to regard them as the horror that they are. >>>I've learned to just write "throws Exception" at the declaration of >>>every method. >> >>Pretty sloppy, though, no? And surely the important thing is to have a >>broad handler, not a broad specification of raisable exceptions? > > > Yes, it's sloppy, but I Don't Care. I'm trying to write usable code > while learning a damnably under-documented Java library -- and I'm *not* > a Java programmer in the first place, so I'm also fighting with the Java > environment. Eventually I'll add in some better code. The road to hell is paved with good intentions. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From absom at myrealbox.com Thu Jan 6 09:02:33 2005 From: absom at myrealbox.com (Abhijit Soman) Date: Thu, 06 Jan 2005 19:32:33 +0530 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> References: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> Message-ID: <344u90F473li5U1@individual.net> wordsender at gmail.com wrote: > Hey guys, > > I can't figure this one out, why is this simple script giving me > problems? > > logfile=file(r'test.txt','w') > logfile.write('datetime') > test=logfile.readlines() > > When I run it I get the error message: > Traceback (most recent call last): > File "C:\Documents and Settings\Gregory\My Documents\Get New Great > Job\testfile.py", line 3, in ? > test=logfile.readlines() > IOError: [Errno 9] Bad file descriptor > > I'm running Windows XP, Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC > v.1200 32 bit (Intel)] on win32 > Any help would be greatly appricated. > > Thanks, > > Greg > As logfile is opened in write mode you cannot read it. You've to open it in read mode for reading. Greetings, Abhijit -- Everybody wants to go to heaven but nobody wants to die From klachemin at comcast.net Tue Jan 18 15:42:21 2005 From: klachemin at comcast.net (Kamilche) Date: 18 Jan 2005 12:42:21 -0800 Subject: Tkinter in thread hangs on windows but not on Linux References: Message-ID: <1106080941.235008.296640@c13g2000cwb.googlegroups.com> This example worked for me on Windows 2000, after inserting import threading from Tkinter import * import ScrolledText at the top. From cam.ac.uk at mh391.invalid Sun Jan 16 20:39:58 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 17 Jan 2005 01:39:58 +0000 Subject: List problems in C code ported to Python In-Reply-To: References: <3SDGd.22010$Z%.6947@fe1.texas.rr.com> Message-ID: Michael Hoffman wrote: > Paul McGuire wrote: >> So "A" == 'a' is true in Python, not true in C. > I think you meant: > > >>> "A" == "A" > True Er, "A" == 'A' -- Michael Hoffman From mikeb at mitre.org Tue Jan 4 13:48:47 2005 From: mikeb at mitre.org (Mike Brenner) Date: Tue, 04 Jan 2005 13:48:47 -0500 Subject: lies about OOP Message-ID: <41DAE50F.414152C8@mitre.org> > ... C++ *appears* to increase the cost of fixing defects ... Some additional points: Some languages allow direct pointer manipulation which favors certain classes of bugs. This is independent of whether the language is OO, and these are probably the most costly defects to find (hanging pointers, buffer overflows, array index busting, memory leakages, etc.). Some languages have strong type checking, which reduces some classes of bugs. This is independent of whether the language is OO. Some people like to think they are OO if they wrap every incoming piece of data in get/put methods in classes. This reduces some categories of errors at the cost of flexibility. When the input format changes, the code needs serious modification everywhere. This is also independent of whether the language is OO, and is a matter of style. While python classes permit you to wrap everything, python classes are so "thin" a wrapper that it is as if they almost aren't wrapped. A trend for style would be to use OO for the methods on stable objects (a continually decreasing breed over time) and use data-driven methods to permit handling data of very flexible input formats. This trend will permit more use of techniques like XSLT, where data structures define the transformations instead of classical code, and techniques like semantical analysis using ontologies, taxonomies, thesaurii, dictionaries, and mappings of semantics into real-world contexts. In other words, data-driven software is not top-down (problem-oriented). It is also not bottom-up (object-oriented). It is simply data-oriented, and totally driven by the input data. This trend will result in the number of lines of code going down, the cost of software going down, and the consciousness of data relationships going up. We will then see Python-D, the python Data language. While Python said: "indentation of code is everything", Python-D will say: all the relational arrows in your dataflow diagram (which IS your code) must be pointing upwards. While Python said: "simplify, reduce coupling, increase cohesion of the software, and do tricks with lambda", Python-D will say: "simplify, reduce coupling, and increase cohesion of the data, and do tricks with metadata." Mike Brenner From jtauber at jtauber.com Sat Jan 8 16:24:00 2005 From: jtauber at jtauber.com (jtauber) Date: 8 Jan 2005 13:24:00 -0800 Subject: Python Operating System??? In-Reply-To: <10trb0mgiflcj4f@corp.supernews.com> References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: <1105219440.064891.199690@c13g2000cwb.googlegroups.com> My experiment, Cleese, was making progress before I got distracted by other things. The approach was a micro-kernel in C made up of the CPython bytecode interpreter with the file-related calls to libc ripped out and some bare-metal port read/writes and memory operations exposed to Python as built-in functions. Everything else could then be written in pure Python. Dave Long was able to write a VGA driver in Python and an implementation of Sokoban that used it. You could then boot your machine to Sokoban :-) I should probably get back to it at some stage. see http://cleese.sourceforge.net/ James Tauber http://jtauber.com/blog/ From tjreedy at udel.edu Sun Jan 2 17:41:32 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Jan 2005 17:41:32 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com><7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com><33q4plF410bo2U1@individual.net> <1104689464.828070.309990@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1104689464.828070.309990 at c13g2000cwb.googlegroups.com... >> 2004-I: "xundef.f", line 2: 'y' is set but never used. > 2005-W: "xundef.f", line 4: 'x' is used but never set. > 2153-W: "xundef.f", line 5, column 1: Subscript out of range. None of these are syntax errors. The first two of these would be caught by lint or pychecker (I am presuming). > One reason interpreted languages like Python are recommended to > beginners is to avoid the edit/compile/debug cycle. But I think it is > faster and less frustrating to have many errors caught in one shot. True syntax errors often result in such a cascade of bogus errors that it may often be best to fix the first reported error and then recompile. Of course, compilers vary in their recovery efforts. Terry J. Reedy From BOOGIEMANPN at YAHOO.COM Mon Jan 3 15:50:46 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Mon, 3 Jan 2005 21:50:46 +0100 Subject: How do I make Windows Application with Python ? Message-ID: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> Well that's it, how do I make Windows Application with Python ??? Is there simple way that works 100% ? How can I rework visual design done in VS 2003 to use it for my python program ? From martin at v.loewis.de Fri Jan 21 19:49:45 2005 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sat, 22 Jan 2005 01:49:45 +0100 Subject: xml parsing escape characters In-Reply-To: <41F1420E.9090706@netvisaoXX.pt> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efedf2$0$11622$9b622d9e@news.freenet.de> <35adg4F4jgvpnU1@individual.net> <41F01A86.2040805@v.loewis.de> <41F1420E.9090706@netvisaoXX.pt> Message-ID: <41F1A329.4050908@v.loewis.de> Luis P. Mendes wrote: > From your experience, do you think that if this wrong XML code could be > meant to be read only by somekind of Microsoft parser, the error will > not occur? This is very unlikely. MSXML would never do this incorrectly. Regards, Martin From mahs at telcopartners.com Fri Jan 21 23:11:59 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Fri, 21 Jan 2005 20:11:59 -0800 Subject: pure python code to do modular-arithmetic unit conversions? In-Reply-To: References: Message-ID: Dan Stromberg wrote: > Is there already a pure python module that can do modular-arithmetic unit > conversions, like converting a huge number of seconds into months, > weeks... or a bandwidth measure into megabits/s or gigabits/s or > megabytes/s or gigabytes/s, whatever's the most useful (ala df -h)? > > Thanks! > Take a look at: http://home.tiscali.be/be052320/Unum_tutorial.html From the intro: "Unum stands for 'unit-numbers'. It is a Python module that allows to define and manipulate true quantities, i.e. numbers with units such as 60 seconds, 500 watts, 42 miles-per-hour, 100 kg per square meter, 14400 bits per second, 30 dollars etc. The module validates unit consistency in arithmetic expressions; it provides also automatic conversion and output formatting." Michael From roy at panix.com Sun Jan 2 13:09:27 2005 From: roy at panix.com (Roy Smith) Date: Sun, 02 Jan 2005 13:09:27 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: claird at lairds.us (Cameron Laird) wrote: > Let me add a cautionary note, though: Big Companies, > including Oracle, Software AG, IBM, Cisco, and so on, have > adopted Tcl over and over. All of them still rely on Tcl > for crucial products. All of them also have employees who > sincerely wonder, "Tcl? Isn't that dead?" A lot of people laugh at Tcl, but it's really a very useful tool. In my last job, we did a major component of our product (SNMP-based network management package) in Tcl, probably on the order of 10 kloc. It has its limitations, but it's very easy to learn, very easy to embed and extend, and reasonably fast. It certainly blows away shell scripting. Around here, AOL/Moviephone has been trolling for years for Tcl people; I guess that counts as a big company. From fredrik at pythonware.com Wed Jan 26 12:07:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Jan 2005 18:07:39 +0100 Subject: string.atoi and string.atol broken? References: <0ttev01qgb9k6a9f34g185lhohkn2p3evq@4ax.com> <4mffv0dqtj0dpjtsqn7lcf46ndc4ei9bc5@4ax.com> Message-ID: Christos TZOTZIOY Georgiou wrote: > You're messing with the time machine again, right? no, it was a subversion pilot error, this time. but now that you remind me, I have to say that this http://mail.python.org/pipermail/python-list/2005-February/030720.html is a bit scary. I wonder from where I was posting that? > [1] Ska vi dela femtio-femtio? Jag kan t?nka mig 60-40 om du st?r f?r det praktiska. From rNOSPAMon at flownet.com Sun Jan 2 15:15:46 2005 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 02 Jan 2005 12:15:46 -0800 Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > In article , > Roy Smith wrote: > >In article , > > Ron Garret wrote: > >> In article <1104657461.868175.252380 at c13g2000cwb.googlegroups.com>, > >> "Erik Bethke" wrote: > >>> > >>> I have NEVER experienced this kind of programming joy. > >> > >> Just wait until you discover Lisp! > > Taking this more seriously than it deserves, I've tried poking at Lisp a > couple of times -- each time, I walk away shaking my head in disgust. > Lisp just ain't as *READABLE* as Python. Readability is in the eye of the beholder, but this is not the place to argue this. But this topic does bring up a legitimate question: I have a bunch of code that generates HTML using PRINT statements. I need to convert all this code to return strings rather than actually printing them (so I can use the results to populate templates). In Lisp I could do this: (with-output-to-string (s) (let ( (*standard-output* s) ) (call-html-generating-code) s)) Is there an equivalent Python trick to capture a function call's output as a string? Thanks, rg From fuzzyman at gmail.com Tue Jan 25 07:58:52 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Jan 2005 04:58:52 -0800 Subject: snakespell and myspell Message-ID: <1106657932.301181.150050@z14g2000cwz.googlegroups.com> I'm looking to implement a plugin spell checker. I'm probably going to go with PyEnchant, as it looks to be the most promising currently maintained spell checker. I just wondered if anyone knew what happened to snakespell and myspell. Both seem to have dissapeared from the net. People have reported good results from both - and it seems a shame to lose them. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From claird at lairds.us Sun Jan 2 13:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Sun, 02 Jan 2005 18:08:04 GMT Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: In article <41d7def6$0$74273$ed2619ec at ptn-nntp-reader03.plus.net>, Mark Carter wrote: . [tale of *very* typical experience with non-software engineers] . . >use something like Python. I didn't get a reaction from that at the >time, but no doubt they'll be telling me that I'll have to make Excel >work through the internet, or something. I do that, by the way--work with Excel through the 'Net. I use Python, of course. From http Thu Jan 13 13:49:12 2005 From: http (Paul Rubin) Date: 13 Jan 2005 10:49:12 -0800 Subject: sorted (WAS: lambda) References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <7x7jmh1eek.fsf@ruckus.brouhaha.com> Message-ID: <7xpt09xizb.fsf@ruckus.brouhaha.com> Steven Bethard writes: > Note that sorted is a builtin function, not a method of a list > object. Oh, same difference. I thought it was a method because I'm not using 2.4 yet. The result is the same, other than that having it as a function instead of a method is another inconsistency to remember. From mahs at telcopartners.com Tue Jan 25 14:06:56 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 25 Jan 2005 11:06:56 -0800 Subject: Classical FP problem in python : Hamming problem In-Reply-To: References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> Message-ID: Nick Craig-Wood wrote: > Steven Bethard wrote: > >> Nick Craig-Wood wrote: >> >>>Thinking about this some more leads me to believe a general purpose >>>imerge taking any number of arguments will look neater, eg >>> >>>def imerge(*generators): >>> values = [ g.next() for g in generators ] >>> while True: >>> x = min(values) >>> yield x >>> for i in range(len(values)): >>> if values[i] == x: >>> values[i] = generators[i].next() >>> >> >> This kinda looks like it dies after the first generator is exhausted, >> but I'm not certain. > > > Yes it will stop iterating then (rather like zip() on lists of unequal > size). Not sure what the specification should be! It works for the > hamming problem though. > > >>>>list(imerge(iter([1, 2]), iter([1, 2, 3]), iter([1, 2, 3, 4]))) > > [1, 2] > > >>An alternate version that doesn't search for 'i': >> >> py> def imerge(*iterables): >> ... iters = [iter(i) for i in iterables] >> ... values = [i.next() for i in iters] >> ... while iters: >> ... x, i = min((val, i) for i, val in enumerate(values)) >> ... yield x >> ... try: >> ... values[i] = iters[i].next() >> ... except StopIteration: >> ... del iters[i] >> ... del values[i] >> ... >> py> list(imerge([1, 4, 7], [2, 5, 8], [3, 6, 9])) >> [1, 2, 3, 4, 5, 6, 7, 8, 9] >> py> list(imerge([3, 6, 9], [1, 4, 7], [2, 5, 8])) >> [1, 2, 3, 4, 5, 6, 7, 8, 9] >> py> list(imerge([1, 4, 7], [3, 6, 9], [2, 5, 8])) >> [1, 2, 3, 4, 5, 6, 7, 8, 9] > > > This isn't quite right... > > >>>>list(imerge([1, 2, 3], [1, 2, 3], [1, 2, 3])) > > [1, 1, 1, 2, 2, 2, 3, 3, 3] > > This should produce > [1, 2, 3] > > So I'm afraid the searching *is* necessary - you've got to find all > the generators with the min value and move them on. > Here's a dict-based implementation: cute, but slow, at least for a small number of iterators >>> def imerge(*iterables): ... cache = {} ... iterators = map(iter,iterables) ... number = len(iterables) ... exhausted = 0 ... while 1: ... for it in iterators: ... try: ... cache.setdefault(it.next(),[]).append(it) ... except StopIteration: ... exhausted += 1 ... if exhausted == number: ... raise StopIteration ... val = min(cache) ... iterators = cache.pop(val) ... yield val >>> list(imerge([1, 2, 3, 6], [1, 2, 3, 7], [1, 2, 3, 4, 5])) [1, 2, 3, 4, 5, 6, 7] >>> Michael From drjonfox at gmail.com Tue Jan 18 07:19:04 2005 From: drjonfox at gmail.com (drjonfox at gmail.com) Date: 18 Jan 2005 04:19:04 -0800 Subject: Central New Jersey PIG Meeting -- Python Interest Group In Princeton PIG/IP In-Reply-To: References: <1105976215.038859.72730@z14g2000cwz.googlegroups.com> Message-ID: <1106050744.772501.178230@f14g2000cwb.googlegroups.com> Yes Jay. PIG/IP meetings are publicly open with no RSVP necessary. Most of the folks coming are LUG/IP members, as I am and the location is the same as LUG/IP meetings. We haven't formalized the group's affiliation yet. -- Jon From aleaxit at yahoo.com Tue Jan 18 16:21:40 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 18 Jan 2005 22:21:40 +0100 Subject: what would you like to see in a 2nd edition Nutshell? References: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> <1gpkxzx.fu7ild1r7602uN%aleaxit@yahoo.com> <200412301319.10987.drlinux@columbus.rr.com> <1105952686.436008.132990@z14g2000cwz.googlegroups.com> Message-ID: <1gqlus1.18qfs1r1r467xeN%aleaxit@yahoo.com> Steven Chan wrote: > I completely agree. I'm also waiting for an advanced Python/project > management book that helps folks out with large-scale projects. I won't schedule that project until the Nutshell 2nd ed is substantially done... and I'm not _promising_ I'll schedule it right afterwards;-). > And, for the 2nd edition, may I suggest: > - coverage of OptionParser module, which is more advanced than the > getopt module that you discuss on page 141. I assume you mean optparse -- that's the module; OptionParser is a class within that module. Yep, covering that is in the plan. > - better Mac OS X application building coverage. Tell us how to build > double-clickable applications. Python in a Nutshell is a book about *cross-platform* Python. There is practically no *WINDOWS*-specific coverage -- 80% of the market or whatever -- it would be absurd if there was platform-specific coverage for a (wonderful) system that has less than 1/10th as much volume (and much as I may be rooting for the mac mini to revolutionize the market, I suspect it will only make a relatively small, incremental difference). I *WISH* I could write a book about Python on the Mac -- ever since I got my iBook, over a year ago, it's been my love and joy, and as soon as I had to change a desktop machine I got myself a dual processor G5 PowerMac too. However, when I proposed that idea to O'Reilly, their reaction was a firm no -- it's too narrow a market, they think (and, being the premier publisher for both the Mac AND Python, they should know, if anybody does). I don't know if this perception of O'Reilly can be changed. If it ever does change, I sure hope they'll call me first, to do that book...!!! > I wish I could ask for wxPython coverage (the whole chapter on tkinter > is useless to me), but I won't start a flame war here. As long as Tkinter is distributed with standard Python and not deprecated, it's unlikely that a reference work about Python can just quietly ignore it. If standard Python changed in this respect, I would of course take that into account in the next following edition!-) Alex From nick at craig-wood.com Thu Jan 13 11:30:03 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 13 Jan 2005 16:30:03 GMT Subject: Debian says "Warning! you are running an untested version of Python." on 2.3 References: Message-ID: Gerhard Haering wrote: > ROFL. Are you using testing, sid or experimental? I expect overzealous > patching from Debian developers, but this is the worst I've heard > of. I would have thought that is unlikely given the way packages move (unmodified) from unstable -> testing (and eventually) -> stable. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From fredrik at pythonware.com Mon Jan 24 07:34:07 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 13:34:07 +0100 Subject: finding name of instances created References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> <1106397218.724722.172660@c13g2000cwb.googlegroups.com> <41F4DEDE.6070003@iinet.net.au> Message-ID: Nick Coghlan wrote: > Incidentally, this discussion made me realise the real reason why using a lambda to create a named > function is evil: > > Py> def f(): pass > ... > Py> f.func_name > 'f' > Py> f = lambda: None > Py> f.func_name > '' > > I think I've heard that explanation before, but it never really clicked. that's nothing you cannot fix, though: >>> f = lambda: None >>> f.func_name = "f" >>> f.func_name 'f' (only works in 2.4 and later, from what I can tell) From siona at chiark.greenend.org.uk Mon Jan 24 10:05:16 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 24 Jan 2005 15:05:16 +0000 (GMT) Subject: What is print? A function? References: Message-ID: <48h*RouFq@news.chiark.greenend.org.uk> Michael Hoffman wrote: >Frans Englich wrote: >> Nah, I don't think it's a function, but rather a builtin "statement". But it's >> possible to invoke it as an function; print( "test" ) works fine. >That is not invoking it as a function. The parentheses are only for >ordering the expression on the right > >You can do this too: > > >>> print("abc"),("def"),("ghi") >abc def ghi And for further enlightenment: .>>> print("abc", "def", "ghi") ('abc', 'def', 'ghi') -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From duncan-news at grisby.org Wed Jan 5 06:05:49 2005 From: duncan-news at grisby.org (Duncan Grisby) Date: Wed, 05 Jan 2005 12:05:49 +0100 Subject: Looking for CORBA (omniORB) examples References: <1104875968.342963.181970@z14g2000cwz.googlegroups.com> Message-ID: <35964$41dbca0d$5160480d$13218@nf1.news-service.com> In article <1104875968.342963.181970 at z14g2000cwz.googlegroups.com>, wrote: >can we script CORBA objects/events with python. my search for simple >examples has not yielded any results. any help appreciated. There are some simple examples in the omniORBpy distribution. There are a few more examples in this presentation I gave: http://www.grisby.org/presentations/py10code.html Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From stewart.midwinter at gmail.com Wed Jan 26 16:36:11 2005 From: stewart.midwinter at gmail.com (stewart.midwinter at gmail.com) Date: 26 Jan 2005 13:36:11 -0800 Subject: subprocess.Popen() redirecting to TKinter or WXPython textwidget??? In-Reply-To: <41f80b1b$0$148$3a628fcd@reader1.nntp.hccnet.nl> References: <41f80b1b$0$148$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <1106775371.049857.36360@z14g2000cwz.googlegroups.com> Ivo, my initial thought would be, you need to know how much text you will get back from popen. My Python reference has the following example: import os dir = os.popen('ls -al', 'r') while (1): line = dir.readline() if line: print line, else: break that example shows how to capture the process output in a file-type object, then bring it into a string with readline(). in your app, you could create a Tkinter stringVar, say myOutput, for the process output. In your Tkinter widget, you could then set a textvariable=myOutput. also use the wait_variable and watch options (hope I recall these correctly, don't have my Tkinter ref. at hand) to detect when there's been a change to the contents of the StringVar and update the contents of the label. Hope this helps, if not, write back. cheers S From simon.brunning at gmail.com Mon Jan 24 11:22:11 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon, 24 Jan 2005 16:22:11 +0000 Subject: Python 2.1 - 2.4 differences In-Reply-To: References: Message-ID: <8c7f10c605012408222153e13d@mail.gmail.com> On Mon, 24 Jan 2005 17:13:44 +0100, BOOGIEMAN wrote: > I found some e-book about Python 2.1, I want to print it but just to check > first if sintax of Python 2.1 is same as 2.4 ? Pretty musch the same, but naturally, some things have changed. See these documents for the major changes, by release: * http://www.python.org/doc/2.2.3/whatsnew/ * http://www.python.org/doc/2.3/whatsnew/ * http://www.python.org/doc/2.4/whatsnew/ -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From xah at xahlee.org Mon Jan 24 09:54:16 2005 From: xah at xahlee.org (Xah Lee) Date: 24 Jan 2005 06:54:16 -0800 Subject: [perl-python] 20050124 classes & objects Message-ID: <1106578456.705117.74220@c13g2000cwb.googlegroups.com> ? # -*- coding: utf-8 -*- ? # Python ? ? # in Python, one can define a boxed set ? # of data and functions, which are ? # traditionally known as "class". ? ? # in the following, we define a set of data ? # and functions as a class, and name it xxx ? class xxx: ? "a class extempore! (^_^)" ? i=1 # i'm a piece of data ? def okaydokey(self): return "okaydokey" ? def square(self,a): return a**a ? ? # in the following, ? # we create an object, of the class xxx. ? # also known as "instantiate a class". ? x = xxx() ? ? # data or functions defined in a class ? # are called the class's attributes or ? # methods. ? # to use them, append a dot and ? # their name after the object's name. ? print 'value of attribute i is:', x.i ? print "3 squared is:", x.square(3) ? print "okaydokey called:", x.okaydokey() ? ? # in the definition of function inside a ? # class, the first parameter "self" is ? # necessary. (you'll know why when you need to) ? ? # the first line in the class definition ? # is the class's documentation. It can ? # be accessed thru the __doc__ ? # attribute. ? print "xxx's doc string is:", x.__doc__ ? ? # one can change data inside the class ? x.i = 400 ? ? # one can also add new data to the class ? x.j=4 ? print x.j ? ? # or even override a method ? x.square = 333 ? # (the following line will no longer work) ? # print "3 squared is:", x.square(3) ? ? # in Python, one must be careful not to ? # overwrite data or methods defined in a ? # class. ---------------------- for a obfuscated treatment with a few extra info, see http://python.org/doc/2.3.4/tut/node11.html in Python terminal, type help() then topic CLASSES to read about existing datatypes as classes, and classes in Python try to write a class with one data of integer and two functions, one increases it by 1, one decreases it by 1. note: inside a class definition, to refer to data inside itself use self. e.g. self.i ------------------------------------------ Perl does not support classes or objects in the so-called "Object Oriented" programing. However, a complete set of emulations of OO style of programing have been done, resulting in modules and books and many documentations and tutorials. here is a quote from perldoc perlobj First you need to understand what references are in Perl. See perlref for that. Second, if you still find the following reference work too complicated, a tutorial on object-oriented programming in Perl can be found in perltoot and perltooc. it goes on and sayz: If you're still with us, then here are three very simple definitions that you should find reassuring. 1. An object is simply a reference that happens to know which class it belongs to. 2. A class is simply a package that happens to provide methods to deal with object references. 3. A method is simply a subroutine that expects an object reference (or a package name, for class methods) as the first argument. Good luck. Note: this post is from the Perl-Python a-day mailing list at http://groups.yahoo.com/group/perl-python/ to subscribe, send an email to perl-python-subscribe @ yahoogroups.com if you are reading it on a web page, program examples may not run because html conversion often breaks the code. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From merkosh at hadiko.de Fri Jan 28 17:39:45 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Fri, 28 Jan 2005 23:39:45 +0100 Subject: example needed: sip + Qt References: <39688.82.68.80.137.1106920041.squirrel@82.68.80.137> Message-ID: Friday 28 January 2005 23:18 pm Uwe Mayer wrote: > Traceback (most recent call last): > File "", line 1, in ? > ImportError: ./hello.so: undefined symbol: _ZTV5Hello > > $ c++filt _ZTV5Hello > vtable for Hello > > The compilation did not give any warnings or error messages. Any ideas? $ ldd -d hello.so libqt-mt.so.3 => /usr/lib/libqt-mt.so.3 (0x40057000) libXext.so.6 => /usr/X11R6/lib/libXext.so.6 (0x4190c000) libX11.so.6 => /usr/X11R6/lib/libX11.so.6 (0x4154e000) libpthread.so.0 => /lib/tls/libpthread.so.0 (0x41173000) libstdc++.so.5 => /usr/lib/libstdc++.so.5 (0x40743000) libm.so.6 => /lib/tls/libm.so.6 (0x4114f000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x407fd000) libc.so.6 => /lib/tls/libc.so.6 (0x41019000) libfontconfig.so.1 => /usr/lib/libfontconfig.so.1 (0x418d8000) libaudio.so.2 => /usr/lib/libaudio.so.2 (0x40807000) libXt.so.6 => /usr/X11R6/lib/libXt.so.6 (0x4191c000) libpng12.so.0 => /usr/lib/libpng12.so.0 (0x4081c000) libz.so.1 => /usr/lib/libz.so.1 (0x41856000) libXrender.so.1 => /usr/lib/libXrender.so.1 (0x41749000) libXrandr.so.2 => /usr/X11R6/lib/libXrandr.so.2 (0x40842000) libXcursor.so.1 => /usr/lib/libXcursor.so.1 (0x41734000) libXft.so.2 => /usr/lib/libXft.so.2 (0x416e1000) libfreetype.so.6 => /usr/lib/libfreetype.so.6 (0x42487000) libSM.so.6 => /usr/X11R6/lib/libSM.so.6 (0x42583000) libICE.so.6 => /usr/X11R6/lib/libICE.so.6 (0x4256a000) libdl.so.2 => /lib/tls/libdl.so.2 (0x41184000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x80000000) libexpat.so.1 => /usr/lib/libexpat.so.1 (0x40847000) undefined symbol: _ZTV5Hello (./hello.so) undefined symbol: _ZNK5Hello9classNameEv (./hello.so) undefined symbol: _ZN5Hello7qt_castEPKc (./hello.so) undefined symbol: _ZN5Hello9qt_invokeEiP8QUObject (./hello.so) undefined symbol: _ZN5Hello7qt_emitEiP8QUObject (./hello.so) undefined symbol: _ZN5Hello11qt_propertyEiiP8QVariant (./hello.so) undefined symbol: _ZTI5Hello (./hello.so) undefined symbol: _Py_NoneStruct (./hello.so) undefined symbol: PyCObject_Type (./hello.so) Uwe From xah at xahlee.org Thu Jan 20 02:50:12 2005 From: xah at xahlee.org (Xah Lee) Date: 19 Jan 2005 23:50:12 -0800 Subject: [perl-python] 20050120 find functions in modules Message-ID: <1106207412.251279.279670@f14g2000cwb.googlegroups.com> ? # -*- coding: utf-8 -*- ? # Python ? ? # once a module is loaded ? # import mymodule ? # one can find all the names it ? # export with dir() ? ? import sys ? print dir(sys) ? ? # without argument it gives the names ? # you've defined ? print dir() ? ? # to find a list of built-in names ? # import the module __builtin__ ? # and use dir on it. ? import __builtin__ ? print dir(__builtin__) ? ? # see ? # http://python.org/doc/2.3.4/tut/node8.html ? ? ---------------- ? # in Perl, Perl experts can achieve ? # similar functionality by, for example: ? ? use Data::Dumper ('Dumper'); ? print Dumper \%Data::Dumper::; ? ? # it has to do with understanding the inner ? # mechanisms of Perl's module system. ? ? --------------- ? ? Note: this post is from the Perl-Python ? a-day mailing list at ? http://groups.yahoo.com/group/perl-python/ ? to subscribe, send an email to ? perl-python-subscribe @ yahoogroups.com if ? you are reading it on a web page, ? program examples may not run because ? html conversion often breaks the code. ? ? Xah ? xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html From samantha7395 at hotmail.com Thu Jan 20 11:59:45 2005 From: samantha7395 at hotmail.com (Samantha) Date: Thu, 20 Jan 2005 08:59:45 -0800 Subject: Print to Windows default Printer References: Message-ID: Thanks Tim, That is exactly what I want to do. How do I map the printer to LPT1? S "Tim Golden" wrote in message news:mailman.931.1106211699.22381.python-list at python.org... > [Samantha] > | Thanks Tim. I didn't realize it would be so difficult. > | S > > Strictly, if all you want to do is print text and you > have mapped LPTx: to some printer (local or network) > then the venerable "PRINT " or "COPY LPTx:" > may well be what you want. You can issue these via > an os.system call from within Python, and if that serves > the purpose, well... > > > > import os > > f = open ("temp.txt", "w") > f.write ("""I must go down to the sea again, > To the lonely sea and the sky. > And all I ask is a tall ship > And a star to steer her by. > """) > f.close () > > os.system ("print temp.txt") > > > > TJG > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ From Sonny.Baillargeon at bmonb.com Tue Jan 4 13:16:51 2005 From: Sonny.Baillargeon at bmonb.com (Baillargeon, Sonny) Date: Tue, 4 Jan 2005 13:16:51 -0500 Subject: Pexpect getting a defuct process Message-ID: <453D335C35136F4B8163C281D58BBD884D0E75@NBNUNYCEXCH1.nesbittburns.ca> Nothing...I know that's the default answer but considering I control the environment, I can assure you that nothing changed. -----Original Message----- From: Jorge Luiz Godoy Filho [mailto:godoy at ieee.org] Sent: Tuesday, January 04, 2005 12:06 PM To: python-list at python.org Subject: Re: Pexpect getting a defuct process Baillargeon, Sonny, Ter?a 04 Janeiro 2005 14:42, wrote: > This used to work before but now I get a defunct process after it runs. > Any ideas? "before" what? What has changed in your environment to make it stop working? -- Godoy. **************************************************************************** This e-mail and any attachments may contain confidential and privileged information. If you are not the intended recipient, please notify the sender immediately by return e-mail, delete this e-mail and destroy any copies. Any dissemination or use of this information by a person other than the intended recipient is unauthorized and may be illegal. Unless otherwise stated, opinions expressed in this e-mail are those of the author and are not endorsed by the author's employer. From claird at lairds.us Sat Jan 15 09:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Sat, 15 Jan 2005 14:08:03 GMT Subject: Why 'r' mode anyway? References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> <41e827df$0$6219$e4fe514c@news.xs4all.nl> Message-ID: In article , Tim Peters wrote: . . . >reading up the bits in the index and offsets too, etc. IIRC, Unix was >actually quite novel at the time in insisting that all files were just >raw byte streams to the OS. Not just "novel", but "puzzling" and even "controversial". It was far from clear that the Unix way could be successful. . . . >but generally where it's reasonably easy to hide. It's not easy to >hide native file conventions, partly because Python wouldn't play well >with *other* platform software if it did. > >Remember that Guido worked on ABC before Python, and Python is in >(small) part a reaction against the extremes of ABC. ABC was 100% >platform-independent. You could read and write files from ABC. >However, the only files you could read from ABC were files that were >written by ABC -- and files written by ABC were essentially unusable >by other software. Socket semantics were also 100% portable in ABC: >it didn't have sockets, nor any way to extend the language to add >them. Etc -- ABC was a self-contained universe. "Plays well with >others" was a strong motivator for Python's design, and that often >means playing by others' rules. At a slightly different level, that--not playing well enough with others--is what held Smalltalk back. Again, a lot of this stuff wasn't obvious at the time, even as late as 1990. I think we understand better now that languages are secondary, in that good developers can be productive with all sorts of syntaxes and semantics; as a practical matter, daily struggles have to do with the libraries or how the languages access what is outside themselves. From ncoghlan at iinet.net.au Mon Jan 31 06:38:34 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 31 Jan 2005 21:38:34 +1000 Subject: Nested scopes and class variables In-Reply-To: <1107161922.285810.8510@f14g2000cwb.googlegroups.com> References: <1107161922.285810.8510@f14g2000cwb.googlegroups.com> Message-ID: <41FE18BA.2010506@iinet.net.au> wittempj at hotmail.com wrote: > To me it seems you should do it something like this: > -def f(x): > - class C(object): > - def __init__(self, x): > - self.x = x # here you set the attribute for class C > - c = C(x) # instantiate a C object > - print c.x > > -f(5) > That does something different - in this case, x is an instance variable, not a class variable. You do raise an interesting questions though: Py> def f(x): ... class C(object): ... x = None ... def __init__(self): ... if C.x is None: ... C.x = x ... C() ... print C.x ... Py> x = 5 Py> f(6) 6 So, the real problem here is the interaction between the ability to write " = " in a class definition with the reference on the RHS being resolved in the global namespace and nested scopes (since that first lookup does NOT respect nested scopes). Functions don't have the problem, since they don't allow that initial lookup to be made from the outer scope. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From rittersporn at gmail.com Sat Jan 8 08:13:51 2005 From: rittersporn at gmail.com (rittersporn at gmail.com) Date: 8 Jan 2005 05:13:51 -0800 Subject: Pre/Postconditions with decorators References: <1105094828.619317.315340@z14g2000cwz.googlegroups.com> <34814fF43bm4cU1@individual.net> Message-ID: <1105190031.287227.319360@c13g2000cwb.googlegroups.com> Thank you very much. It is really a very elegant piece of code :-) Eiffel (language) has both type checking and design by contract. Python lacks both. Your module tackles type checking, I tried to execute arbitrary code before and after function execution to realize runtime assertions. I wonder if this should be separated in a Python "checker"-module. Both are part of the interface "contract". Ciao From golux at comcast.net Sat Jan 8 02:33:18 2005 From: golux at comcast.net (Stephen Waterbury) Date: Sat, 08 Jan 2005 02:33:18 -0500 Subject: Software archeology (was Re: Developing Commercial Applications in Python) In-Reply-To: References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: <41DF8CBE.8080506@comcast.net> Aahz wrote: > In article , > Stephen Waterbury wrote: > >>Aahz wrote: >> >>>In article , >>>Stephen Waterbury wrote: >>> >>>>Also see Python Success Stories: http://pythonology.org/success >>>> >>>>A notable example is Verity's search engine -- see >>>>http://python.oreilly.com/news/PythonSS.pdf >>> >>>Actually, your statement is slightly inaccurate. The Verity search >>>engine is more than fifteen years old in its core technology; it was >>>started as a LISP project at IIRC MIT. (At one point I was much amused >>>to look at the C source code and find car() and cdr() functions.) As of >>>my last information, Python isn't used at all in or with the Verity >>>search engine. What you're referring to is the Verity Ultraseek engine, >>>originally written and owned by Infoseek before getting transferred to >>>Verity through a series of dot-bomb transactions. The Ultraseek engine >>>doesn't use Python, but Python is used to control the engine, and I think >>>much of the spider is written in Python. >> >>Actually, Aahz didn't add anything useful that wasn't explained better >>in the article itself, pointing to which was the purpose of my post, >>but he is correct: Python was *not* used to write the Verity search >>engine ... how the hell do these stupid rumors get started anyhow?? ;). >>Just read the article, dammit! :) > > You're quite correct that I added little useful information, but seeing > as I used to work at Verity, I couldn't resist adding some hopefully > interesting and/or amusing trivia. Especially the LISP bit. Well GEEZ, you should've mentioned that you used to work there! All the trivia *were* amusing ... sorry if I harshed! :) Cheers, Steve From steve at holdenweb.com Wed Jan 19 15:21:52 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Jan 2005 15:21:52 -0500 Subject: a question In-Reply-To: <1106165238.353672.272980@f14g2000cwb.googlegroups.com> References: <3YvHd.80953$Jk5.28602@lakeread01> <6kwHd.48934$w62.45338@bgtnsc05-news.ops.worldnet.att.net> <1106165238.353672.272980@f14g2000cwb.googlegroups.com> Message-ID: <7ozHd.80963$Jk5.43195@lakeread01> Will Stuyvesant wrote: > Andrew Koenig wrote: > >>how about writing this instead? >> >> ('this is a ' >> 'long string') > > > Yes, nice. And to make that possible we have to write > ('one-string-item',) instead of ('one-string-item') if we want a tuple > with one string inside. Sometimes that feels like a wart to me, but > now I know it, sometimes not. > That has very little to do with tuples. You could just as easily write 'this is a '\ 'long string' It's the dangling comma that's required to specify a tuple: >>> 1, (1,) >>> regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From marklists at mceahern.com Sat Jan 1 15:21:42 2005 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 01 Jan 2005 14:21:42 -0600 Subject: Looping using iterators with fractional values In-Reply-To: <1104609929.888351.8870@c13g2000cwb.googlegroups.com> References: <1104609929.888351.8870@c13g2000cwb.googlegroups.com> Message-ID: <41D70656.6000505@mceahern.com> drife wrote: > Hello, > > Making the transition from Perl to Python, and have a > question about constructing a loop that uses an iterator > of type float. How does one do this in Python? > > Use a generator: >>> def iterfloat(start, stop, inc): ... f = start ... while f <= stop: ... yield f ... f += inc ... >>> for x in iterfloat(0.25, 2.25, 0.25): ... print '%9.2f' % x ... 0.25 0.50 0.75 1.00 1.25 1.50 1.75 2.00 2.25 >>> From bulba at bulba.com Tue Jan 4 12:54:40 2005 From: bulba at bulba.com (Bulba!) Date: Tue, 04 Jan 2005 18:54:40 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> Message-ID: On Mon, 3 Jan 2005 00:08:25 +0100, aleaxit at yahoo.com (Alex Martelli) wrote: >> True. I have a bit of interest in economics, so I've seen e.g. >> this example - why is it that foreign branches of companies >> tend to cluster themselves in one city or country (e.g. >It's not just _foreign_ companies -- regional clustering of all kinds of >business activities is a much more widespread phenomenon. First, even though I disagree with you in places, thanks for this reply - it enhanced my knowledge of the topic in some places. Re the foreign/domestic companies: I have observed this what I call "irrational clustering" esp. re foreign companies here. >Exogenous is fine if you're looking at the decision a single firm, the >N+1 - th to set up shop in (say) a city, faces, given decisions already >taken by other N firms in the same sector. >The firm's production processes have inputs and outputs, coming from >other firms and (generally, with the exception of the last "layer" of >retailers etc) going to other firms. Say that the main potential buyers >for your firm's products are firms X, Y and Z, whose locations all >"happen to be" (that's the "exogenous" part) in the Q quarter of town. >So, all your competitors have their locations in or near Q, too. Where >are you going to set up your location? Rents are higher in Q than >somewhere out in the boondocks -- but being in Q has obvious advantages: >your salespeople will be very well-placed to shuttle between X, Y, Z and >your offices, often with your designers along so they can impress the >buyers or get their specs for competitive bidding, etc, etc. What you wrote regards especially strong the industries you pointed at: fashion, jewellery, esp. I think in those industries those factors may be decisive. When this street is renown in the city to have "good jewellers" located there, the choice for a new jeweller in this city is almost like this: get located there or die. However, I'd argue that industries with those kinds of dependencies are actually pretty rare. >At some >points, the competition for rents in quarter Q will start driving some >experimenters elsewhere, but they may not necessarily thrive in those >other locations. If, whatever industry you're in, you can strongly >benefit from working closely with customers, then quarter Q will be >where many firms making the same products end up (supply-side >clustering). >Now consider a new company Z set up to compete with X, Y and Z. Where >will THEY set up shop? Quarter Q has the strong advantage of offering >many experienced suppliers nearby -- and in many industries there are >benefits in working closely with suppliers, too (even just to easily >have them compete hard for your business...). I grant that this model is neat and intuitive - but I'd argue it is not very adequate to real world. Read on. >So, there are easily >appreciated exogenous models to explain demand-side clustering, too. >That's how you end up with a Holliwood, a Silicon Valley, a Milan (for >high-quality fashion and industrial design), even, say, on a lesser >scale, a Valenza Po or an Arezzo for jewelry. Ancient European cities >offer a zillion examples, with streets and quarters named after the >trades or professions that were most clustered there -- of course, there >are many other auxiliary factors related to the fact that people often >_like_ to associate with others of the same trade (according to Adam >Smith, generally to plot some damage to the general public;-), but >supply-side and demand-side, at least for a simpler exogenous model, are >plenty. >Say that it's the 18th century (after the corporations' power to stop >"foreign" competition from nearby towns had basically waned), you're a >hat-maker from Firenze, and for whatever reason you need to move >yourself and your business to Bologna. If all the best hat-makers' >workshops and shops are clustered around Piazza dell'Orologio, where are >YOU going to set up shop? Rents in that piazza are high, BUT - that's >where people who want to buy new hats will come strolling to look at the >displays, compare prices, and generally shop. That will only be true if the hats from Piazza dell'Orologio are much better than elsewhere. If the quality and prices of products converged, the gain for the customers to go there isn't high. And the prices for customers have to be higher, as the high rents drive some suppliers out, so the supply of hats is lower, ergo customer prices are higher. >That's close to where >felt-makers are, since they sell to other hat-makers. Should your >business soon flourish, so you'll need to hire a worker, that's where >you can soon meet all the local workers, relaxing with a glass of wine >at the local osteria after work, and start getting acquainted with >everybody, etc, etc... That is true in the model. However, I don't find it very true in practice in a lot of industries: - "physical proximity" in this city very often means navigating through jammed roads, so the transportation costs in terms of time and money may very well increase rather than decrease by locating "in a cluster", even though physical distance may be smaller. physical distance != temporal distance & a cost of getting there. - since everything is more expensive, so is labor; even if you pay this worker a little bit less elsewhere, he might find it more attractive to commute shortly to work and have lower costs of living in a different area, so this very well may work as a motivation to relocate - few large businesses nowadays have customers neatly clustered in one location, they tend to sell countrywide or worldwide; so the premium for getting into this expensive place is low and the costs are high - production nowadays tends to be geographically distributed as well - communication costs and transportation costs are DRAMATICALLY lower nowadays than they used to be (today it costs 1/80 [one eightieth] to transport a kg of mass using an aircraft in comparison to what it cost in 1930s; ditto for telecommunication). Consider real world examples: Microsoft in Redmond or Boeing in Seattle. Microsoft needs quite a lot of programmers. It would be rather hard to find enough programmers born and educated in Redmond, wouldn't it? Boeing: Seattle?! Why Seattle? Doesn't Boeing sell most of its new aircrafts in Washington? AFAIK, in Europe Boeing does much of its production in cooperation with Alena in Italy. From this viewpoint it really doesn't matter much if Boeing is located in Seattle or anywhere else in America really, does it? Right here (Poland), most of the foreign corporations set up their call centers in Warsaw, which is totally ridiculous given how expensive that city is. Oh I can understand setting up a warehouse by HP there because it's close to its biggest customers. But I really see no good reason behind HP call center being located in Warsaw, too, AFAIK (or at least that's the city code when I have to call them sometimes). Most of the successful domestic companies I have observed here have started and still operate in some God-forgotten provincial towns, where land and labor is cheap and when it comes to highly skilled professionals, you have to "import" some or all of them from elsewhere anyway, because not even a big city is likely to have precisely all the kinds of ultra-specialized professionals that you may need. And there's less crime, and shuttling kids to school isn't a nightmare, and the costs of living are lower. Plus there's less of other things to do, so your workers tend to focus more on work. :-) >Risk avoidance is quite a secondary issue here (except if you introduce >in your model an aspect of imperfect-information, in which case, >following on the decisions made by locals who may be presumed to have >better information than you is an excellent strategy). Nor is there any >"agency problem" (managers acting for their interests and against the >interest of owners), not a _hint_ of it, in fact -- the hatmaker acting >on his own behalf is perfectly rational and obviously has no agency >problem!). I find no justification in most of foreign companies setting up their call centers in a ridiculously overpriced capital city - so from my viewpoint the risk avoidance is the only explanation that is left. Not all corporations do that: in this country Coca-Cola has made their big "green field" investment almost in the middle of nowhere in this country. GM, Volkswagen, FIAT, and most of other carmakers have made similar decisions. Doesn't seem like those were bad business decisions for them. The cluster I've seen - an IT "corporate area" in Dublin, Ireland - was specifically created not due to "natural clustering", but due to govt policy of tax breaks and preparing good infrastructure in this place rather than some inter-business and inter-customer dependencies, since e.g. Microsoft (where the company sent me for training) neither is able to get all the workers it needs just from this city, nor it sells mostly to local customers, but it sells all over Europe. To me, the issue of manager having to face their superiors asking him a question - "why on Earth have you decided to locate our branch in the middle of nowhere in this country? Why not in capital city? Can't you look at the map? Read some stats how many inhabitants this city has and what is the income level there?" is overwhelming: it would take long time to explain for this manager who e.g. may have already got his hands dirty in this industry in that country to know that say, there's little revenue increase to be gained in locating the facility in capital city, the needed workers are actually hard to find there, etc. To me, this is much like decision whether do much of development in Python or MS VS / VB. "But everybody's using VisualStudio / VB" is a simple and compelling argument: "so many people can't be wrong", while explanations that going Python may actually be better decision in this context requires long and complex explanations and managers oft can not even be bothered to read executive summaries. I feel econ models frequently are elegantly designed abstractions of elegantly designed problems; the problem is how close those are to the real-world problems. At the end of the day, it's "human action" that gets all of that implemented. I've seen too much resources going down the drain in completely idiotic projects and decisions to believe managers are rational beings. ;o) -- Real world is perfectly indifferent to lies that are the foundation of leftist "thinking". From ncoghlan at iinet.net.au Tue Jan 25 22:49:51 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 13:49:51 +1000 Subject: Can't load bytecode with execfile ? In-Reply-To: References: Message-ID: <41F7135F.3000000@iinet.net.au> Bo Jacobsen wrote: > I have a number of files compiled to bytecode using py_compile.compile(). > The .pyc files can be invoked by python directly ($python file.pyc), but > "loading" them by execfile just throws an exception ? Py> help(execfile) Help on built-in function execfile in module __builtin__: execfile(...) execfile(filename[, globals[, locals]]) Read and execute a Python _SCRIPT_ from a file. The globals and locals are dictionaries, defaulting to the current globals and locals. If only globals is given, locals defaults to it. (Emphasis Added) Execfile doesn't go through the "is it bytecode?" check that the import machinery or the -m command line switch use. It tries to interpret anything you give it as Python source code - which is why you get a syntax error when you try to use it on compiled bytecode. Allowing it to handle compiled bytecode might make a reasonable feature request, though. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From erikbethke at gmail.com Wed Jan 19 10:54:21 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 19 Jan 2005 07:54:21 -0800 Subject: ElementTree cannot parse UTF-8 Unicode? Message-ID: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> Hello All, I am getting an error of not well-formed at the beginning of the Korean text in the second example. I am doing something wrong with how I am encoding my Korean? Do I need more of a wrapper about it than simple quotes? Is there some sort of XML syntax for indicating a Unicode string, or does the Elementree library just not support reading of Unicode? here is my test snippet: from elementtree import ElementTree vocabXML = ElementTree.parse('test2.xml').getroot() where I have two data files: this one works: this one fails: From bj_666 at gmx.net Sat Jan 8 15:48:25 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 08 Jan 2005 21:48:25 +0100 Subject: escape string for command line References: Message-ID: In , Ksenia Marasanova wrote: > I have a simple ecard creation script on a website, where user can add > text to a graphic. I use ImageMagick for it: > > # template_file => path to image template file > # new_file => path to generated file > # text => user input > command = '''convert %s -font OfficinaSanITC-BookOS -pointsize 12 > -fill "#8C2F48" -draw "gravity north text 0,26 '%s'" %s''' % ( > template_file, text, new_file) > system(command) > > I was wondering, is there a general way to escape the string entered > by the user, to prevent code injection into command line? Take a look at the "string-escape" encoding: >>> evil = "'; rm -rf /;" >>> command = "echo '%s'" >>> print command % evil.encode('string-escape') echo '\'; rm -rf /;' > Will it > always be safe, even when binary data is submitted through POST? Don't know if it's always safe. Unprintable bytes like 0x00 will be escaped as '\x00'. Ciao, Marc 'BlackJack' Rintsch From roy at panix.com Mon Jan 3 15:38:15 2005 From: roy at panix.com (Roy Smith) Date: 3 Jan 2005 15:38:15 -0500 Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: Stephen Waterbury wrote: >> Shaw-PTI (www.pti-us.com) uses Python in their software. > >... but the "Python Powered" logo is conspicuous by its >absence from their site. Too bad that some commercial >exploiters of Python don't advertise that fact more often. Companies use all sorts of technologies to produce their products. I have no idea who Shaw-PTI is or what they do, but I'm sure they also use other languages, and web servers, and operating systems, and telephones and office furniture and pencil sharpeners. They're all just tools. You don't expect a company to waste space on their web site advertising which brand of pencil sharpener they use, so why would you expect they would do so for a programming language? Sometimes you see web sites with "Powered by IBM" or "Powered by Sun" or whatever. I'm sure behind every one of those is a deal cut with the supplier to promote their name in return for some favorable terms on a contract. From ptmcg at austin.rr._bogus_.com Mon Jan 10 12:00:18 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 10 Jan 2005 17:00:18 GMT Subject: Writing huge Sets() to disk References: Message-ID: "Martin MOKREJ?" wrote in message news:mailman.448.1105373471.22381.python-list at python.org... > Hi, > I have sets.Set() objects having up to 20E20 items, > each is composed of up to 20 characters. Keeping > them in memory on !GB machine put's me quickly into swap. > I don't want to use dictionary approach, as I don't see a sense > to store None as a value. The items in a set are unique. > > How can I write them efficiently to disk? To be more exact, > I have 20 sets. _set1 has 1E20 keys of size 1 character. > > alphabet = ('G', 'A', 'V', 'L', 'I', 'P', 'S', 'T', 'C', 'M', 'A', 'Q', 'F', 'Y', 'W', 'K', 'R', 'H', 'D', 'E') > for aa1 in alphabet: > # l = [aa1] > #_set1.add(aa1) > for aa2 in alphabet: > # l.append(aa2) > #_set2.add(''.join(l)) > [cut] > > The reason I went for sets instead of lists is the speed, > availability of unique, common and other methods. > What would you propose as an elegant solution? > Actually, even those nested for loops take ages. :( > M. _set1 only has 19 keys of size 1 character - 'A' is duplicated. Assuming you replace 'A' with another character (say 'Z'), then here is what you get: _set1 - 20 elements (20**1) _set2 - 400 elements (20**2) _set3 - 8000 elements (20**3) ... _set20 - 20**20 ~ 10 ^ (1.301*20) or 1E26 If you have no duplicates in your alphabet, then you wont need to use sets, every combination will be unique. In this case, just use a generator. Here's a recursive generator approach that may save you a bunch of nested editing (set maxDepth as high as you dare): alphabet = ('G', 'A', 'V', 'L', 'I', 'P', 'S', 'T', 'C', 'M', 'Z', 'Q', 'F', 'Y', 'W', 'K', 'R', 'H', 'D', 'E') maxDepth = 3 def genNextCombo(root=list(),depth=1): for a in alphabet: thisRoot = root + [a] yield "".join( thisRoot ) if depth < maxDepth: for c in genNextCombo(thisRoot, depth+1): yield c for c in genNextCombo(): print c # or write to file, or whatever -- Paul From jeff at ccvcorp.com Tue Jan 25 20:08:17 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 25 Jan 2005 17:08:17 -0800 Subject: Help! Host is reluctant to install Python In-Reply-To: References: Message-ID: <10vdr0kksufnp7c@corp.supernews.com> Daniel Bickett wrote: > I've been trying to convince my host to install python/mod_python on > his server for a while now, however there are a number of reasons he > is reluctant to do so, which I will outline here: > > 1. His major reason is optimization. He uses Zend's optimization of > PHP as an example, and he has stated that python is rather resource > consuming. This depends, as all things, on what's being done with it -- it's certainly possible to write resource-hogging Python apps, but it's possible to do that in any language. And I'm not aware of Python being particularly worse in this regard than any other web-scripting language. I suspect this translates to "I'm avoiding anything that I don't already know". > And, in light of point #1, I suggested that if there wasn't any > optimization immediately available, he could just enable it for my > account (thus lessening potential resource consumption at any given > time), to which he retorted "Do /you/ know how to do that?", and I > must say, he has me cornered ;-) I don't know how to do that offhand... but then, I don't expect people to pay me for web-hosting expertise. I would expect, from the little that I *do* know of Apache configuration, that it wouldn't be too difficult to allow Python CGIs to run out of only one specific directory, that being within your webspace. If you're paying for this service, then I'd agree with everyone else that you should be paying for a different service. There's plenty of webhosts around who *will* do Python. If this is a friend, then point him to the Python Success Stories (http://www.pythonology.com/success) and suggest that if there's that many Python web apps around, it can't be too horrible on resources/management, and that he shouldn't be so afraid to try something new... Jeff Shannon Technician/Programmer Credit International From fumanchu at amor.org Mon Jan 31 12:21:10 2005 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 31 Jan 2005 09:21:10 -0800 Subject: variable declaration Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33982FA@exchange.hqamor.amorhq.net> Alex Martelli wrote: > > Robert Brewer wrote: > > > Bah. Nothing teaches you a new language like having your > job depend upon > > it. People who study languages merely for "personal growth" > learn 50% of > > the syntax and 1% of the concepts, and then fritter that > learning away > > on inconsequential newsgroups the world over. > > I disagree. I studied Python, even though it had nothing to > do with my > job, just with the idea of using it on hobby projects; yet I believe I > can reasonably claim to have learned more than 50% of the > syntax and 1% > of the concepts, even though you might claim that, whatever percentage > it may be, it's "frittered away on inconsequential newsgroups". You are an exceptional person, Alex. ;) Robert Brewer MIS Amor Ministries fumanchu at amor.org From tzot at sil-tec.gr Wed Jan 26 11:45:19 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 26 Jan 2005 18:45:19 +0200 Subject: string.atoi and string.atol broken? References: <0ttev01qgb9k6a9f34g185lhohkn2p3evq@4ax.com> Message-ID: <4mffv0dqtj0dpjtsqn7lcf46ndc4ei9bc5@4ax.com> On Wed, 26 Jan 2005 13:23:42 +0100, rumours say that "Fredrik Lundh" might have written: >Christos TZOTZIOY Georgiou wrote: > >>>the function's named "atoi", not "atoitoa". >> >> [Fredrik] [0] >cool. can I have a copy of your script? I hereby declare my script in perpetual alpha-testing stage, and therefore won't be making it public, since I intend to make money out of this [1] collecting all translations in a book called "The effbot's guide to pythonology" [2]. >reminds me that I have a few patches in the inqueue. I wonder >what this one does? ;-) >hmm ;-) guess I can tune that later ;-) and what about that other >patch? ;-) let's see ;-) patch, checkout, reload File "effbot.py", line 29238 > <<<<<<< .mine > ^ >IndentationError: expected an indented block You're messing with the time machine again, right? Your patch is probably for nightly build 20071202032501 . At the moment, most of the script logic (and bugs :) is concentrated in line 2: what_to_print = raw_input("Translation of /F's single line reply? ") [0] got it right this time [1] Ska vi dela femtio-femtio? [2] which book will help you improve your own python use, hopefully :) -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From danb_83 at yahoo.com Sun Jan 16 12:33:59 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 16 Jan 2005 09:33:59 -0800 Subject: why are some types immutable? In-Reply-To: References: Message-ID: <1105896839.966379.220890@z14g2000cwz.googlegroups.com> Roy Smith wrote: > Torsten Mohr wrote: > > reading the documentation (and also from a hint from this NG) > > i know now that there are some types that are not mutable. > > > > But why is it this way? > > > > From an overhead point of view i think it is not optimal, > > for example for a large string it could be much faster to > > have it changed in place, not generating a new one for > > every step in a change. > > There has been a huge amount written about immutable types recently. A > search of the Google news archives should turn up tons of articles. > > But, in a nutshell, the biggest reason for immutable types (tuples and > strings) is that this lets they be dictionary keys. If you want to know > why dictionary keys have to be immutable, More precisely, dictionary keys can't be mutable in any way that affects the result of the hash function or the == or != operators. From PPNTWIMBXFFC at spammotel.com Fri Jan 7 03:48:11 2005 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Fri, 07 Jan 2005 09:48:11 +0100 Subject: Apple creator on Python Message-ID: One of the "creators" of Apple has written a book and mentions Python in the interview: http://www.macdevcenter.com/pub/a/mac/2005/01/04/hertzfeld.html After writing around 20 stories, I shifted gears and worked on the web software to publish them, writing a simple authoring system in Python, which I love to program in. From aahz at pythoncraft.com Mon Jan 31 19:08:30 2005 From: aahz at pythoncraft.com (Aahz) Date: 31 Jan 2005 19:08:30 -0500 Subject: Want to meet any of these people? They are registered for PyCon References: Message-ID: In article , Steve Holden wrote: > >Sorry you can't make it to Python. My even-naiver way of approaching the >problem was to use the sort utility built into Cygwin, thereby avoiding >writing any code at all. That's cheating! ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger." --Roy Smith, c.l.py, 2004.05.23 From steven.bethard at gmail.com Fri Jan 7 18:49:01 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Jan 2005 16:49:01 -0700 Subject: switching an instance variable between a property and a normal value In-Reply-To: References: Message-ID: Robert Brewer wrote: > Steven Bethard wrote: > >>I'm playing around with a mapping type that uses setdefault >>as suggested >>in http://www.python.org/moin/Python3_2e0Suggestions. The >>default value >>for a missing key is either a simple value, or a value >>generated from a >>function. If it's generated from the function, it should be >>generated >>new each time so that, for example, if the default is an empty list, >>d[1] and d[2] don't access the same list. This is why 'c.x is c.x' >>should be False if I'm using the function. >> >>The best option I guess is to rewrite this with a >>_getdefault() function instead of a property: >> >>But I was hoping to avoid having two separate attributes (self._value >>and self._func) when only one should have a value at any given time. > > > It seems to me like you were using the property as a glorified flag. > Just use a flag. > > ftypes = ('BuiltinFunctionType', 'BuiltinMethodType', > 'FunctionType', 'GeneratorType', 'LambdaType', > 'MethodType', 'UnboundMethodType',) > > class D(dict): > def __init__(self): > self._default = None > self._call_default = False > def __getitem__(self, key): > if not key in self: > if self._call_default: > self[key] = self._default() > else: > self[key] = self._default > return dict.__getitem__(self, key) > def setdefaultvalue(self, value): > self._default = value > self._call_default = isinstance(value, ftypes) > > ...or: > > def setdefaultvalue(self, value, call_callables=True): > self._default = value > self._call_default = callable(value) and call_callables Well, the right solution using a flag for the particular behavior I was looking for would have to look something like: class D(dict): def __init__(self): self._default = None self._call = False def __getitem__(self, key): if not key in self: if self._call: func, args, kwds = self._default self[key] = func(*args, **kwds) else: self[key] = self._default return dict.__getitem__(self, key) def setdefault(self, value, call=False, *args, **kwds): if call: self._default = value, args, kwds else: self._default = value self._call = call where I also accept *args and **kwds when the default value is to be called. It's certainly doable with a flag, but note that I have to check the flag every time in both __getitem__ and setdefault. It'd minimize redundancy a bit if I only had to check it in one place. Guess I could do something like: class D(dict): def __init__(self): self._default = None self._call_default = False def __getitem__(self, key): if not key in self: self[key] = self._default() return dict.__getitem__(self, key) def setdefault(self, value, call=False, *args, **kwds): if call: def caller(): return value(*args, **kwds) else: def caller(): return value self._default = caller Then I only have to test call when setdefault is called. Not sure I like this any better though... Steve P.S. The reason I had two functions, setdefaultvalue and setdefaultfunction has to do with argument parsing for setdefaultfunction. Note that def setdefault(self, value, call=False, *args, **kwds): ... means that you can't call functions with keyword arguments 'value' or 'call'. That means I have to rewrite this function as something like def setdefault(*args, **kwds): self = args[0] value = args[1] call = ??? ... The problem is, if 'call' is a keyword argument, I don't know whether it was intended as one of the function arguments or as an argument to setdefault. If setdefaultvalue and setdefaultfunction are two separate methods, I don't run into this problem. From martin at v.loewis.de Sun Jan 16 06:46:06 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 16 Jan 2005 12:46:06 +0100 Subject: mutable string? In-Reply-To: References: Message-ID: <41ea53ff$0$25939$9b622d9e@news.freenet.de> Torsten Mohr wrote: > is there some string class that i can change in place, > like perls strings? array.array is mutable. You can use the 'c' code if you want an array of characters. > Is it possible to do some regex replacement functions > that would even change its length? You can't use re.sub array, but you can use re.search, and you can perform slice assigment. > Can i append to this string? Yes. > Is there some wrapper for C++ STL string class (if that > would make sense)? It would be possible, but I cannot see why one would want to do that. Regards, Martin From macrocosm at fastmail.fm Sat Jan 8 13:27:48 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Sat, 08 Jan 2005 13:27:48 -0500 Subject: Python Operating System??? In-Reply-To: References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> Message-ID: <41E02624.90602@fastmail.fm> Peter Hansen wrote: > Paul Rubin wrote: > >> When Unix was first written, people thought implementing an OS in C >> was ludicrous. Everyone knew OS's had to be written in assembler. > > > Actually, when Unix was first written that belief was entirely > correct, and OSes *did* have to be written in assembler. *nods* > > That is, pure C did not have the capability to handle all > that was required. I recall it taking a good decade before it > became *common* to find C compilers with, for example, @interrupt > support to let the compiler generate code that properly saved > all registers and used RTI instead of RTS (or whatever it might > have been called one one's particular flavour of CPU). If my memory serves me, you are entirely correct. > > Now, once you added a few tiny interrupt handlers, and some context > switching (stack manipulation) routines, pretty much everything else > *could* be done in C, but that doesn't invalidate the point. *nods* > > I think it's safe to say that none of pure C, pure Lisp, or pure Python > are really capable of being used as the *sole* language to build > an operating system. *nods* > > It's also safe to say that this is a largely irrelevant point. > It would probably only be of academic interest to try to do > something like that. Any practical attempt would not think more > than twice of resorting to a little "glue" in assembler or in > the form of "canned" byte sequences built by hand and stuck > into the appropriate places in memory... > > -Peter Indeed indeed. Once must remain focused and ask oneself what he/she is attempting to achieve. In all likelihood, a little asm/c/python glue work won't hurt the objective, especially given that doing otherwise would entail a very _low level_ reworking of Python that would take as much and likely more effort and skill than to resort to asm/c when Python falls incapable. One could do a Python-Lisp OS w/ Lisp used for the Python incapable areas, but you would near entirely loose the benefits of Lisp in that respect--- it would have to be so low-level, could you call it Lisp? (A question someone else here posed in this thread.) - Arich From rkern at ucsd.edu Thu Jan 6 21:12:23 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 06 Jan 2005 18:12:23 -0800 Subject: Python evolution: Unease In-Reply-To: References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <16859.16548.249527.30210@montanaro.dyndns.org> <864d37090501050117761a32e6@mail.gmail.com> Message-ID: Bulba! wrote: > On Wed, 05 Jan 2005 17:25:08 -0800, Robert Kern > wrote: >>I still think numarray is a good start for this. It handles more than >>just numbers. And RecArray (an array that has different types in each >>column, as you seem to require) can be subclassed to add these methods >>to it. > > > I have downloaded it, playing with it and like it. I esp. like things > like: > > >>>>print a + a > > [2 4 6] > > or > > >>>>b.getshape() > > (4,3) > > Very Pythonic. :-) > > However, not all things are generic enough like I meant. That > is not to criticize, but merely to point out that the library is for > obvious reasons slanted towards numerical work, so e.g. while the > following works: > > .>>> from numarray import transpose > .>>> transpose([[1,2],[3,4]]) > array([[1, 3], > [2, 4]]) > > ...this doesn't: > > >>>>transpose([('phone1', 12345), ('phone2', 67890)]) > > Traceback (most recent call last): > File "", line 1, in ? > [....] > TypeError: Expecting a python numeric type, got something else. > > Why would someone want to do such a thing: suppose he > wants 'phone1' and 'phone2' and number records sequenced > horizontally instead vertically, while when he read that from > a file, such was the file structure. It's a boneheaded example, > but you get the idea. http://stsdas.stsci.edu/numarray/numarray-1.1.html/module-numarray.objects.html In [1]: from numarray import objects, transpose In [2]: a = objects.array([['phone1', 12345], ['phone2', 67890]]) In [3]: a Out[3]: ObjectArray([['phone1', 12345], ['phone2', 67890]]) In [4]: transpose(a) Out[4]: ObjectArray([['phone1', 'phone2'], [12345, 67890]]) Note the use of lists. Using tuples makes the constructor think you want a vector of tuple objects. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tim.peters at gmail.com Sun Jan 30 17:57:37 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 30 Jan 2005 17:57:37 -0500 Subject: pickle, cPickle, & HIGHEST_PROTOCOL In-Reply-To: <1107124050.160083.129630@f14g2000cwb.googlegroups.com> References: <1107124050.160083.129630@f14g2000cwb.googlegroups.com> Message-ID: <1f7befae0501301457b8e7216@mail.gmail.com> [A.B., Khalid] > I wonder if someone can explain what is wrong here. I am pickling a > list of dictionaries (see code attached) and unpickling it back using > the HIGHEST_PROTOCOL of pickle and cPickle. ... > ... on Win98. Pickles are binary data. Therefore you should open pickle files in binary mode on all platforms, and must open them in binary mode on Windows. That is, replace your lines: f = file('pkl_' + fn, 'w') f = file('pkl_' + fn, 'r') with: f = file('pkl_' + fn, 'wb') f = file('pkl_' + fn, 'rb') It's true that you can get away with opening pickle files in text mode on Windows if you stick to the default pickle protocol (0), although in that case your pickle files won't be portable across platforms. For that reason, don't try to be clever: always use binary-mode files to store pickles, regardless of pickle protocol in use. From cookedm+news at physics.mcmaster.ca Mon Jan 10 22:53:05 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 10 Jan 2005 22:53:05 -0500 Subject: why not datetime.strptime() ? References: Message-ID: Joshua Spoerri writes: > Skip Montanaro pobox.com> writes: >> josh> Shouldn't datetime have strptime? >> If someone wants to get their feet wet with extension module >> programming >> this might be a good place to start. Mostly, I think nobody who has >> needed/wanted it so far has the round tuits available to spend on the >> task. > > OK, it was pretty straightforward. Thanks for the direction. > > To whom should I send the patch (attached)? Submit it to the patch tracker on sourceforge. But first, some constructive criticism: > --- Modules/datetimemodule.c.orig 2003-10-20 10:34:46.000000000 -0400 > +++ Modules/datetimemodule.c 2005-01-10 20:58:38.884823296 -0500 > @@ -3774,6 +3774,32 @@ > return result; > } > > +/* Return new datetime from time.strptime(). */ > +static PyObject * > +datetime_strptime(PyObject *cls, PyObject *args) > +{ > + PyObject *result = NULL, *obj, *module; > + const char *string, *format; > + > + if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format)) > + return NULL; > + if ((module = PyImport_ImportModule("time")) == NULL) > + return NULL; > + obj = PyObject_CallMethod(module, "strptime", "ss", string, format); > + Py_DECREF(module); You don't check for errors: an exception being thrown by PyObject_CallMethod will return obj == NULL. If there's a module in sys.path called time that overrides the stdlib time, things will fail, and you should be able to catch that. > + result = PyObject_CallFunction(cls, "iiiiiii", > + PyInt_AsLong(PySequence_GetItem(obj, 0)), > + PyInt_AsLong(PySequence_GetItem(obj, 1)), > + PyInt_AsLong(PySequence_GetItem(obj, 2)), > + PyInt_AsLong(PySequence_GetItem(obj, 3)), > + PyInt_AsLong(PySequence_GetItem(obj, 4)), > + PyInt_AsLong(PySequence_GetItem(obj, 5)), > + PyInt_AsLong(PySequence_GetItem(obj, 6))); Are you positive those PySequence_GetItem calls will succeed? That they will return Python integers? > + Py_DECREF(obj); > + return result; > +} > + > /* Return new datetime from date/datetime and time arguments. */ > static PyObject * > datetime_combine(PyObject *cls, PyObject *args, PyObject *kw) > @@ -4385,6 +4411,11 @@ > PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp " > "(like time.time()).")}, > > + {"strptime", (PyCFunction)datetime_strptime, > + METH_VARARGS | METH_CLASS, > + PyDoc_STR("strptime -> new datetime parsed from a string" > + "(like time.strptime()).")}, > + > {"combine", (PyCFunction)datetime_combine, > METH_VARARGS | METH_KEYWORDS | METH_CLASS, > PyDoc_STR("date, time -> datetime with same date and time fields")}, It probably would help to add some documentation to add to the datetime module documentation. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From mark at freelance-developer.com Sat Jan 1 16:03:08 2005 From: mark at freelance-developer.com (Mark Nenadov) Date: Sat, 01 Jan 2005 16:03:08 -0500 Subject: What can I do with Python ?? References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> Message-ID: What can you do with Python? Just about anything your heart desires. How hard is Python to learn? I'd say it is near the top of the barrel when it comes to being easy to learn. I'd certainly say that for the most part, you will learn Python much faster than you would learn C#. Can you make a full-screen game with it? Yes, most certainly--providing you have the skill/knowledge to program a full-screen game. But then again that is rarely a matter of having the right programming language, but rather a matter of having the right libraries. -- ~Mark Nenadov On Sat, 01 Jan 2005 21:57:32 +0100, BOOGIEMAN wrote: > Beginners question, but really what can you do with it ? > How hard is Python to learn compared with other languages > (let's say C#). Can you make fullscreen game with it (for example) ? > I've looked at http://www.python.org but nothing concrete there From danperl at rogers.com Fri Jan 28 16:50:39 2005 From: danperl at rogers.com (Dan Perl) Date: Fri, 28 Jan 2005 16:50:39 -0500 Subject: How to test that an exception is raised ? References: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> <41fa400b$0$2029$6c56d894@feed0.news.be.easynet.net> <41faa68f$0$17406$4d4efb8e@read.news.be.uu.net> Message-ID: "StepH" wrote in message news:41faa68f$0$17406$4d4efb8e at read.news.be.uu.net... > So why the assertRaises function in unittest ? My goal is to test if an > exception is well raised when a bad filename is passed to the mps2xml > function. It is for functions in which the exception is raised and not caught. You can use the exception mechanism to let the code invoking your function know that something "exceptional" has happened. It means that you "throw" that exception to the invoking code which has to catch it. Maybe the terminology is poorly chosen, but assertRaises does not check whether an exception is raised inside the function but only that an exception is raised (or "thrown", as described by other languages) from inside the function to outside. A function does not "throw" an exception if the exception is caught inside the function. Is that clearer now? In java for instance, functions are actually declared to "throw" an exception if any operation inside the function may throw that exception and the exception is not caught inside the function. If you implement a function A that invokes another function B and B throws an exception of type C, then you must catch the exception C in A or you have to declare A that it "throws C". Hope this helps. Dan From cwilbur at mithril.chromatico.net Sun Jan 9 22:49:30 2005 From: cwilbur at mithril.chromatico.net (Charlton Wilbur) Date: Mon, 10 Jan 2005 03:49:30 GMT Subject: a new Perl/Python a day References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: <87r7ku3pwq.fsf@mithril.chromatico.net> >>>>> "XL" == Xah Lee writes: XL> i'll cross post to comp.lang.perl.misc and comp.lang.python. XL> If you spot mistakes, feel free to correct or discourse here. Error #1: crossposting to those two groups. (Error #2 is implying that you're a Perl expert, but someone else already pointed that out.) Charlton -- cwilbur at chromatico dot net cwilbur at mac dot com From macrocosm at fastmail.fm Thu Jan 6 21:08:06 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Thu, 06 Jan 2005 21:08:06 -0500 Subject: Python Operating System??? In-Reply-To: <0WlDd.8830$5R.1182@newssvr21.news.prodigy.com> References: <10trb0mgiflcj4f@corp.supernews.com> <0WlDd.8830$5R.1182@newssvr21.news.prodigy.com> Message-ID: <41DDEF06.8020506@fastmail.fm> Roose wrote: >What exactly do you mean by an operating system? > >If you don't want to program in C/C++ then you're going to have a hard time. >I don't want to be too discouraging, but with that attitude I doubt you >would get very far. > > Indeed, this is very true. >It sounds like you want to make more of an OS shell -- no? You can >implement a shell on top of any OS and probably do it in a language like >Python. > > He should just build around a linux core or use OS kit (if he is serious/determined). >But if it is going to be a complete OS in pure Python, uh, it won't be! >You'll have to do a lot of stuff in C, at the least interface with the >hardware. > > > > He could use something like O' caml or Oz no? I might be confused, but I understood them to be C/C++ comparable in terms of power and in that they both compile vs. VMs and interpreters (for O' caml this is optional I think). Or what about D? From max at alcyone.com Sun Jan 23 18:46:02 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 23 Jan 2005 15:46:02 -0800 Subject: [perl-python] 20050121 file reading & writing In-Reply-To: References: <1106395060.211314.54530@f14g2000cwb.googlegroups.com> Message-ID: Bob Smith wrote: > To do this efficiently on a large file (dozens or hundreds of megs), you > should use the 'sizehint' parameter so as not to use too much memory: > > sizehint = 0 > mylist = f.readlines(sizehint) It doesn't make any difference. .readlines reads the entire file into memory at once. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Can I lay with you / As your wife -- India Arie From daniel at bowettsolutions.com Wed Jan 26 17:16:57 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Wed, 26 Jan 2005 22:16:57 +0000 Subject: MySQLdb executemany In-Reply-To: References: Message-ID: Daniel Bowett wrote: > I seem to have found a bug/limitation of executemany in MySQLdb. > > I am inserting 3100 records into a database. It works fine and adds them > in about 1 second. > > I went back to the program today and realised i'd missed a field so > added it to the insert statement. This seems to break it if I try to add > all the records in one go. Through trial and error I have realised the > limit is 2786 records in one go. Any more than that I get two different > errors on the executemany statement: > > "MySQL server has gone away" - This occurs if I try to add all 3100 > records in one go. > > "Lost Connection to MySQL server during query" - This happens if I am > near the 2786 threshold. > > Is there a known limit with this function??? > UPDATE ------ The maximum packet size in mysql by default is 1MB. Hence why I was hitting ths problem. http://dev.mysql.com/doc/mysql/en/packet-too-large.html From rkern at ucsd.edu Thu Jan 13 19:41:45 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 13 Jan 2005 16:41:45 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <10ue4s49jl8s6d7@corp.supernews.com> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <41e5ebee.709560864@news.oz.net> <1105632841.461042.68310@c13g2000cwb.googlegroups.com> <10udfj4c4rgkvcc@corp.supernews.com> <1105651353.769879.229690@f14g2000cwb.googlegroups.com> <10ue4s49jl8s6d7@corp.supernews.com> Message-ID: Jeff Shannon wrote: > (Plus, if this format might be used for RNA sequences as well as DNA > sequences, you've got at least a fifth base to represent, which means > you need at least three bits per base, which means only two bases per > byte (or else base-encodings split across byte-boundaries).... That gets > ugly real fast.) Not to mention all the IUPAC symbols for incompletely specified bases (e.g. R = A or G). http://www.chem.qmul.ac.uk/iubmb/misc/naseq.html -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From ola.natvig at infosense.no Tue Jan 4 05:44:04 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Tue, 04 Jan 2005 11:44:04 +0100 Subject: How do I make Windows Application with Python ? In-Reply-To: <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> Message-ID: BOOGIEMAN wrote: > On Mon, 03 Jan 2005 17:19:22 -0500, Peter Hansen wrote: > > >>What do you mean by "Windows Applications"? I'm running >>Python on Windows XP, so every program I write with >>Python is a "Windows application" by my definition. Obviously >>you are using a different one. >> >>(And if you just mean "it has a GUI", then my answer is >>"I use wxPython with Python". There is also Tkinter, and >>other options. Please ask a more specific, detailed question >>to get useful answers.) > > > Well, I programmed a little in MS Visual Studio 2003, and there you have > Console apllication and Windows application (among others). Windows one is > with buttons and other gadgets. So, I want to make applications that > doesn't open console to display result, I want to display it into the > message box. Also, I want to use that application on the computers where > Python isn't installed if you are familliar with the .NET framework you can use the beta release og Python.NET to create your GUI. It gives you access to the Windows Forms controlls in the .NET framework -- -------------------------------------- Ola Natvig infoSense AS / development From asda at sdarta.com Wed Jan 5 23:55:36 2005 From: asda at sdarta.com (worzel) Date: Thu, 6 Jan 2005 12:55:36 +0800 Subject: is python more popular than coldfusion? References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dca575$0$14347$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <1104985449.245498.215940@z14g2000cwz.googlegroups.com> Message-ID: <41dcc4c7$0$14331$5a62ac22@per-qv1-newsreader-01.iinet.net.au> re: YOU'LL SEE IT'S ADDICTIVE Yes, I know! I am hooked already! Its such a breeze after doing so much Java programming. I just download Jython - the possibilities with this seem incredible. Unlike you, I learned Coldfusion after learning Java first (about 1996). For the sake of a couple of jobs I got on and then some training work as a Macromedia Instructor, it was okay for a while. But, the work dried up, and then the training became in very low demand, so I find myself looking for a new 'second language' - Python is it! (Its in danger of becoming my 'first language' as I am enjoying it so much!) "Luis M. Gonzalez" wrote in message news:1104985449.245498.215940 at z14g2000cwz.googlegroups.com... >> by the way, does anybody want to buy any coldfusion books :) > > I have Sam's Teach Yourself Coldfusion by Charles Mohnike, which I > bought in 2001. > By this time I used to think that I was learning rocket science the > easy way, and thinking about learning php or asp was really scary... > these codes looked very complex for my uninitiated eyes. > However, It was good for grasping the logic of interacting with a > database through sql and making my website dynamic. > Soon I realized that finding a cheap CF hosting wasn't easy at all, and > I started to read about php. > Php is also for web development, but it gave me the basic knowledge to > understand programming. > However, I wanted to learn a more general purpose language and I don't > remember how, I landed in pythonland. > > Let me tell you that I could learn python basics in just a few hours. > Once I got the interpreter running, I couldn't stop! > Just get one of the many tutorial available on the web and start > playing. YOU'LL SEE IT'S ADDICTIVE. > > If you want to start from zero, I suggest Josh Cogliati's beginner > tutorial. > Another good introduction is A Byte of Python (google this), or any of > the ones quoted in Python's web site. > > Learning Python is a good book too (especially the second edition). > Enjoy! > From km at mrna.tn.nic.in Thu Jan 20 05:10:06 2005 From: km at mrna.tn.nic.in (km) Date: Thu, 20 Jan 2005 15:40:06 +0530 Subject: inbuilt function buffer() Message-ID: <20050120101006.GA1496@mrna.tn.nic.in> Hi all, I which context is the inbuilt function buffer() used ? regards, KM From bokr at oz.net Tue Jan 11 05:25:59 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 11 Jan 2005 10:25:59 GMT Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <1105381339.922714.23200@c13g2000cwb.googlegroups.com> <1oFEd.71967$Jk5.45632@lakeread01> Message-ID: <41e39978.557378407@news.oz.net> On Mon, 10 Jan 2005 21:15:50 -0500, Tim Peters wrote: >... > >[Anna] >>> BTW - I am *quite* happy with the proposal for "where:" syntax - I >>> think it handles the problems I have with lambda quite handily. > >[Steve Holden] >> Whereas I find it to be an excrescence, proving (I suppose) that one >> man's meat is another person's poison, or something. > >I've been waiting for someone to mention this, but looks like nobody >will, so I'm elected. Modern functional languages generally have two >forms of local-name definition, following common mathematical >conventions. "where" was discussed here. The other is "let/in", and Well, I did say it reminded me of some kind of weird let ;-) http://groups-beta.google.com/groups?q=%20Reminds%20me%20of%20some%20kind%20of%20weird%20let&hl=en&lr=&sa=N&tab=wg >seems a more natural fit to Python's spelling of block structure: > > let: > suite > in: > suite > >There's no restriction to expressions here. I suppose that, like the >body of a class, the `let` suite is executed starting with a >conceptually empty local namespace, and whatever the suite binds to a >local name becomes a temporary binding in the `in` suite (like >whatever a class body binds to local names becomes the initial value >of the class __dict__). So, e.g., > > i = i1 = 3 > let: > i1 = i+1 > from math import sqrt > in: > print i1, sqrt(i1) > print i1, > print sqrt(i1) > >would print > > 4 2 > 3 > >and then blow up with a NameError. > >LIke it or not, it doesn't seem as strained as trying to pile more >gimmicks on Python expressions. I could get to like it ;-) Hm, a little extension to this could provide a new way to populate closure variables, and also (never mind, one thing at a time ;-) #1: If you gave your 'let' above a list of 'externs' that can be rebound from within the let. E.g., let(sqrt): the effect in your example would be to eliminate the NameError you mention. The compiler would make an entry for sqrt in the enclosing namespace, and generate code to bind/rebind if assigned from within the let. This would be an interesting way to create closure bindings: let(foo): preset = 'another way to make closure vairables' in: def foo(): return preset ... print foo() #2: Making the in: suite callable as a light weight function with no arguments. An optional binding name after in would bind like def and create a persistent named callable instead of just an implicitly called anonymous suite. Then you could define the same effective foo by let: preset = 'another way to make closure vairables' in foo: return preset # return now legal ... print foo() The combination would work like: let(rebindable): factor = 10 in bar: rebindable *= factor rebindable = 2 bar() print rebindable # => 20 rebindable += 5 bar() print rebindable # => 250 You can see this could be used nicely in case functionality, with a dict of named in-functions. What do you think? Regards, Bengt Richter From http Fri Jan 7 07:39:44 2005 From: http (Paul Rubin) Date: 07 Jan 2005 04:39:44 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41dcf582.122188317@news.oz.net> <7xd5wh7qdf.fsf@ruckus.brouhaha.com> <1gq0odo.1x1uyr2kgdgiyN%aleaxit@yahoo.com> Message-ID: <7xu0ptjtv3.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > Paul Rubin wrote: > > Really, I just want to buy a new > > computer, turn it on, and have everything there. That's generally > > impossible without running satanware from Redmond > > The princes of insufficient light from Cupertino will in fact be very > happy to sell you such computers, I actually do sometimes advise nontechnical people to buy those things and run the installed software since GNU/Linux is really not there yet with a number of types of apps, and is more of a maintenance headache. But if I bought one myself, I'd feel oblige to reformat the hard drive to get rid of the darkware (= no source) just like I do with a PC. I've played with that notion at different times since the hardware is actually rather nice. > and _their_ definition of "everything" > includes a bit more than the Redmonders' (e.g., Python is there, perl is > there, gcc is there, so is Apache, a good development GUI-based IDE, Oh cool, you mean emacs/gud/gdb. > emacs, a solid firewall, a _usable_ Terminal/commandline program to run > bash or tcsh on, ...), Yes, shell mode in Emacs works fine, I haven't had much need to use anything else. Xterm also works. > though it's no doubt still missing many pieces > that you or I might want as parts of *our* "everything" (gvim rather > than just vim, I'm not sure what the difference is supposed to be... I remember someone explaining "you can't spell vile without vi". > GUI/IDEs for Python, I remember there was a gud interface for Python but it didn't work pretty well. There's also IDLE which is pretty crude and flaky. I think I'll just wait for Pypy deployment before worrying about this situation too much. Is there something else I can download? > Python add-ons such as numarray, > gmpy, ctypes, ...) -- all of those you still have to download and > install, just as you would for the satanware. That's unfortunate, that stuff should be included with Python. From ncoghlan at iinet.net.au Tue Jan 25 08:53:26 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 25 Jan 2005 23:53:26 +1000 Subject: delay and force in Python In-Reply-To: References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> <41EE6658.8000409@iinet.net.au> Message-ID: <41F64F56.3080107@iinet.net.au> Peter Otten wrote: > Nick Coghlan wrote: > > >>>Py> print islice((x for x in xrange(1, 996) if x % 2 == 0), 1, 2).next() >>>4 >> >>Wouldn't it be nice if this could be spelt: >> >>print (x for x in xrange(1, 996) if x % 2 == 0)[2] >> >>Well, I just put a patch on SF to enable exactly that: >>http://www.python.org/sf/1108272 > > > I like it. Of course you always have to bear in mind that one giant leap for > a list could be _many_ small steps for an iterator. Indeed. The main cases I am thinking of involve picking off the first few items of an iterator (either to use them, or to throw them away before using the rest). And if an app actually *needs* random access, there's a reason lists still exist ;) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steven.bethard at gmail.com Wed Jan 19 12:17:00 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 19 Jan 2005 10:17:00 -0700 Subject: Dictionary keys (again) (was Re: lambda) In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Nick Coghlan wrote: > For a 'mutable key' to make sense, the following: > > lst = [] > dct = {l: "Hi!"} > print dct[[]] > print dct[lst] > lst.append(1) > print dct[[1]] > print dct[lst] > > Should print: > Hi > Hi > Hi > Hi And here's an implementation that does so: py> class sillydict(dict): ... def __getitem__(self, key): ... items = self.items() ... self.clear() ... self.update(items) ... return super(sillydict, self).__getitem__(key) ... py> class sillylist(list): ... def __hash__(self): ... return hash(tuple(self)) ... py> lst = sillylist([]) py> dct = sillydict({lst: "Hi!"}) py> print dct[sillylist([])] Hi! py> print dct[lst] Hi! py> lst.append(1) py> print dct[sillylist([1])] Hi! py> print dct[lst] Hi! Of course, as noted by the classes themselves, they're silly. ;) But as long as you don't mind rehashing the dict each time the dict is accessed ;) you can get sane behavior even in the presence of mutable keys. Steve From spamerom at niet.com Sat Jan 8 10:06:30 2005 From: spamerom at niet.com (JZ) Date: Sat, 8 Jan 2005 16:06:30 +0100 Subject: The best way to do web apps with Python? References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <12tz3aez24pv4.i8nqbs9uqlg1$.dlg@40tude.net> Dnia Sat, 8 Jan 2005 21:11:49 +0800, worzel napisa?(a): > What is the best way to web developemnt with Python? Hmm. :) I prefer http://cherrypy.org + http://cheetahtemplate.org/. Very easy to learn and develop, yet powerfull. > Is there anything close to PHP style in-page script > placement that can create and use other Python objects? Check http://spyce.sourceforge.net or http://nick.borko.org/pse -- JZ ICQ: 6712522 http://zabiello.om From premshree.pillai at gmail.com Sat Jan 22 02:43:49 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Sat, 22 Jan 2005 13:13:49 +0530 Subject: Event details changed: Bangalore Python January Meetup In-Reply-To: <20050121171306.16111.qmail@web40729.mail.yahoo.com> References: <8548c5f3050121084976c0ac8a@mail.gmail.com> <20050121171306.16111.qmail@web40729.mail.yahoo.com> Message-ID: On Fri, 21 Jan 2005 09:13:06 -0800 (PST), Swaroop C H wrote: > > Read Anand's email!! Especially the part about 'well-known Python community > members' ... ha ha, I can't stop laughing ;) :) Hey, in case I forget (I have a terrible memory), message me! :) > > --- Anand Pillai wrote: > > > Yes. I am quite happy with the response that we received. I also noted that > > four members joined the group today which is quite an achievement :-). > > The membership has reached 20 in less than a month, 21 days to be > > exact, i.e about one member joining every day on an average. That is > > quite a tremendous response which I did not expect to get initially > > :-). I guess that the timing was somehow spot on perhaps. > > > > It is encouraging for the group that two well-known Python community > > members namely yourself and Premshree are part of it. I got Prem's > > RSVP > > a few hours back. Bernhardt, the german guy called me up and said he > > is not coming since he has to attend Mysore LUG meeting in the > > weekend. Also I don't see Pradeep (btbytes) saying yes. Is he going to > > come? > > > > That makes about 8 confirmed attendees. Let us hope that we get some > > more unexpected turn out tomorrow. > > > > See ya at Ebony. > > > > -Anand > > > > On Fri, 21 Jan 2005 08:09:34 -0800 (PST), Swaroop C H > > wrote: > > > Hello Anand, > > > > > > Looks like around 10 people are coming. Good response :) > > > > > > http://www.swaroopch.info/archives/2005/01/21/python-meetup-in-bangalore-tomorrow/ > > > > > > See you tomorrow evening. > > > > > > Regards, > > > Swaroop > > > > > > --- Anand Pillai wrote: > > > > > > > As you requested, below is a copy of the email you just sent. > > > > Had you *not* requested a copy, based on the audience of the > > > > email you selected, you *still* would have received the email. > > > > ----------------------------------------------------------------- > > > > > > > > Your Organizer, Anand Pillai, sent the following message to > > > > some members of Bangalore Python Meetup Group: > > > > > > > > I have booked a table for 8 at the Ebony Restaurant, Barton > > > > Center tomorrow at 7:30 pm. This requires a small change in the > > > > meeting timing. Please arrive by 7:15 - 7:30 pm at Barton > > > > Center and go directly to Ebony on the top floor. > > > > > > > > Barton Center is a prominent building on M.G Road a few yards > > > > after Higgin Bothams & Indian Coffee House, when you walk from > > > > the Brigade road end towards Cubbon Park end. It has a fast > > > > food joint at the entrance , which is busy most of the time. In > > > > case you come early, please wait there. However do remember to > > > > walk up towards Ebony by about 7:15 - 7:30 pm. Ask the hotel > > > > staff for the tables reserved by Anand Pillai. > > > > > > > > In case you get stuck or confused, call the number 9886483821 > > > > for directions. > > > > > > > > If less than five people turn out by 8:00 pm the meeting will > > > > be cancelled. > > > > > > > > Hope to see all of you at Ebony tomorrow! > > > > > > > > -Anand > > > > > > > > P.S: The "official" mail is below. > > > > -==============================================- > > > > > > > > I've updated this event. For more details, see the full listing: > > > > http://python.meetup.com/158/events/3974233/" > > > > > > > > If the change affects your plans to attend, please take a > > > > moment to update your RSVP. (You can RSVP 'No' or 'Maybe' as > > > > well as 'Yes'.)" > > > > > > > > You can always get in touch with me through the 'Contact > > > > Organizer' feature on the Meetup.com website: > > > > http://python.meetup.com/158/suggestion/" > > > > ----------------------------------------------------------------- > > > > > > > > To visit Bangalore Python Meetup Group, go here: > > > > http://python.meetup.com/158/ > > > > > > > > Did this email end up in your spam/junk/bulk folder? Add > > > > info at meetup.com to your address book to ensure that you receive > > > > all future messages in your Inbox. > > > > > > > > ----------------------------------------------------------------- > > > > HOW TO UNSUBSCRIBE > > > > You received this message because you registered this email > > > > address at Meetup.com. > > > > > > > > To remove yourself from individual Meetup Groups and their > > > > related emails, click the link below and select 'Remove > > > > yourself' under the name of the appropriate Group: > > > > http://www.meetup.com/account/ > > > > > > > > To unsubscribe from ALL your Meetup Groups and the Meetup.com > > > > service as a whole, click here: > > > > http://www.meetup.com/account/remove/ > > > > ----------------------------------------------------------------- > > > > > > > > > > > > > > > > > ===== > > > Swaroop C H > > > Blog: http://www.swaroopch.info > > > Book: http://www.byteofpython.info > > > > > > > > > -- > > Anand B Pillai, > > Techical Specialist, > > SETLabs, INFOSYS Technologies, > > Electronics City, > > Hosur Road, Bangalore - 560100. > > > > > ===== > Swaroop C H > Blog: http://www.swaroopch.info > Book: http://www.byteofpython.info > -- Premshree Pillai http://www.livejournal.com/~premshree From craig at postnewspapers.com.au Fri Jan 28 08:24:48 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 28 Jan 2005 21:24:48 +0800 Subject: example needed: sip + Qt In-Reply-To: References: Message-ID: <1106918688.3941.51.camel@albert.localnet> On Fri, 2005-01-28 at 13:30 +0100, Uwe Mayer wrote: > Hi, > > can someone provide me with a running example for subclassing QWidget (or > something similarly simple) in C++ and then creating SIP (4.x+) bindings > for in for Python (2.3+)? Out of curiosity, would this be for an extension module used in an embedded Python interpreter, or for plain extension module for use with a standalone interpreter? I'm afraid I can't help you with your specific problem, though I'll be interested to hear if anybody here does know. If you don't have any luck here, try the PyQt/PyKDE list (and search its archives first). -- Craig Ringer From sp1d3rx at gmail.com Wed Jan 26 18:16:36 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 26 Jan 2005 15:16:36 -0800 Subject: exclude binary files from os.walk In-Reply-To: References: <41f8167b$0$8648$a1866201@visi.com> Message-ID: <1106781396.336126.319540@f14g2000cwb.googlegroups.com> you might want to look up the 'isascii' function... i.e. - can be represented using just 7-bits. From http Sat Jan 22 23:08:56 2005 From: http (Paul Rubin) Date: 22 Jan 2005 20:08:56 -0800 Subject: [OT] XML design intent ... further musings References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> <41F2C840.2050304@comcast.net> Message-ID: <7xhdl8pz1j.fsf@ruckus.brouhaha.com> Stephen Waterbury writes: > I should note that I have to deal with XML a lot, but always > kicking and screaming (though much less now because of Fredrik's > Elementtree package ;). Thanks, Fredrik and Peter, for the > references. ;) I love this old rant about XML: http://groups-beta.google.com/group/comp.lang.lisp/msg/9a30c508201627ee From jeff at ccvcorp.com Tue Jan 25 19:46:54 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 25 Jan 2005 16:46:54 -0800 Subject: Browsing text ; Python the right tool? In-Reply-To: References: Message-ID: <10vdpohm549g44a@corp.supernews.com> Paul Kooistra wrote: > 1. Does anybody now of a generic tool (not necessarily Python based) > that does the job I've outlined? > 2. If not, is there some framework or widget in Python I can adapt to > do what I want? Not that I know of, but... > 3. If not, should I consider building all this just from scratch in > Python - which would probably mean not only learning Python, but some > other GUI related modules? This should be pretty easy. If each record is CRLF terminated, then you can get one record at a time simply by iterating over the file ("for line in open('myfile.dat'): ..."). You can have a dictionary of classes or factory functions, one for each record type, keyed off of the 2-character identifier. Each class/factory would know the layout of that record type, and return a(n) instance/dictionary with fields separated out into attributes/items. The trickiest part would be in displaying the data; you could potentially use COM to insert it into a Word or Excel document, or code your own GUI in Python. The former would be pretty easy if you're happy with fairly simple formatting; the latter would require a bit more effort, but if you used one of Python's RAD tools (Boa Constructor, or maybe PythonCard, as examples) you'd be able to get very nice results. Jeff Shannon Technician/Programmer Credit International From aahz at pythoncraft.com Fri Jan 28 16:24:30 2005 From: aahz at pythoncraft.com (Aahz) Date: 28 Jan 2005 16:24:30 -0500 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> Message-ID: In article , Tim Peters wrote: >[grahamd at dscpl.com.au] >> >> Who are the appropriate people to report security problems to >> in respect of a module included with the Python distribution? >> I don't feel it appropriate to be reporting it on general mailing >> lists. > >The Python project has no non-public resources for this. Filing a bug >report on SourceForge is the usual approach. If you must, you could >send email directly to Guido . He may or may >not have time to follow up on it; public disclosure is the norm in >this project. Be forewarned that despite that he currently works for >a security startup, his threshold for "security panic" is very high. You mean s/despite/because/ don't you? ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From rm at rm.net Sat Jan 22 14:31:34 2005 From: rm at rm.net (rm) Date: Sat, 22 Jan 2005 20:31:34 +0100 Subject: What YAML engine do you use? In-Reply-To: <46ednYMe9-q4Om_cRVn-tQ@comcast.com> References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> Message-ID: <35fo4iF4maov2U1@individual.net> Doug Holton wrote: > What do you expect? YAML is designed for humans to use, XML is not. > YAML also hasn't had the backing and huge community behind it like XML. > XML sucks for people to have to write in, but is straightforward to > parse. The consequence is hordes of invalid XML files, leading to > necessary hacks like the mark pilgrim's universal rss parser. YAML > flips the problem around, making it harder perhaps to implement a > universal parser, but better for the end-user who has to actually use > it. More people need to work on improving the YAML spec and > implementing better YAML parsers. We've got too many XML parsers as it is. 100% right on, stuff (like this)? should be easy on the users, and if possible, on the developers, not the other way around. But developers come second. Now, I didn't check the specs, they might be difficult, they might be incorrect, maybe their stated goal is not reached with this implementation of their idea. But I'd love to see a generic, pythonic data format. bye, rm From mmokrejs at ribosome.natur.cuni.cz Mon Jan 17 08:14:24 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?ISO-8859-2?Q?Martin_MOKREJ=A9?=) Date: Mon, 17 Jan 2005 14:14:24 +0100 Subject: Writing huge Sets() to disk In-Reply-To: References: Message-ID: <41EBBA30.10303@ribosome.natur.cuni.cz> Steve Holden wrote: > Martin MOKREJ? wrote: > >> Hi, >> could someone tell me what all does and what all doesn't copy >> references in python. I have found my script after reaching some >> state and taking say 600MB, pushes it's internal dictionaries >> to hard disk. The for loop consumes another 300MB (as gathered >> by vmstat) to push the data to dictionaries, then releases >> little bit less than 300MB and the program start to fill-up >> again it's internal dictionaries, when "full" will do the >> flush again ... >> >> The point here is, that this code takes a lot of extra memory. >> I believe it's the references problem, and I remeber complains >> of frineds facing same problem. I'm a newbie, yes, but don't >> have this problem with Perl. OK, I want to improve my Pyhton >> knowledge ... :-)) >> > Right ho! In fact I suspect you are still quite new to programming as a > whole, for reasons that may become clear as we proceed. > >> >> >> >> def push_to_disk(self): >> _dict_on_disk_tuple = (None, self._dict_on_disk1, >> self._dict_on_disk2, self._dict_on_disk3, self._dict_on_disk4, >> self._dict_on_disk5, self._dict_on_disk6, self._dict_on_disk7, >> self._dict_on_disk8, self._dict_on_disk9, self._dict_on_disk10, >> self._dict_on_disk11, self._dict_on_disk12, self._dict_on_disk13, >> self._dict_on_disk14, self._dict_on_disk15, self._dict_on_disk16, >> self._dict_on_disk17, self._dict_on_disk18, self._dict_on_disk19, >> self._dict_on_disk20) The None above is there just as I didn't want to evaluate all the time something like "x+1": for x in _dict_on_disk_tuple: key = .... newdict[x+1][key] = ... This None doesn't hurt me, then x contains exactly the value I need several times in the loop ... > > > It's a bit unfortunate that all those instance variables are global to > the method, as it means we can't clearly see what you intend them to do. > However ... > > Whenever I see such code, it makes me suspect that the approach to the > problem could be more subtle. It appears you have decided to partition > your data into twenty chunks somehow. The algorithm is clearly not coded > in a way that would make it easy to modify the number of chunks. No, it's not, but that's not the speed problem, really. ;) > > [Hint: by "easy" I mean modifying a statement that reads > > chunks = 20 > > to read > > chunks = 40 > > for example]. To avoid this, we might use (say) a list of temp edicts, > for example (the length of this could easily then be parameterized as > mentioned. So where (my psychic powers tell me) your __init__() method > currently contains > > self._dict_on_disk1 = something() > self._dict_on_disk2 = something() > ... > self._dict_on_disk20 = something() Almost. They are bsddb dictionary files. > > I would have written > > self._disk_dicts = [] > for i in range(20): > self._disk_dicts.append(something) > > Than again, I probably have an advantage over you. I'm such a crappy > typist I can guarantee I'd make at least six mistakes doing it your way :-) Originally I had this, I just to get of one small list. ;) > >> _size = 0 > > > What with all these leading underscores I presume it must be VERY > important to keep these object's instance variables private. Do you have > a particular reason for that, or just general Perl-induced paranoia? :-) See below. ;) > >> # >> # sizes of these tmpdicts range from 10-10000 entries for each! >> for _tmpdict in (self._tmpdict1, self._tmpdict2, >> self._tmpdict3, self._tmpdict4, self._tmpdict5, self._tmpdict6, >> self._tmpdict7, self._tmpdict8, self._tmpdict9, self._tmpdict10, >> self._tmpdict11, self._tmpdict12, self._tmpdict13, self._tmpdict14, >> self._tmpdict15, self._tmpdict16, self._tmpdict17, self._tmpdict18, >> self._tmpdict19, self._tmpdict20): >> _size += 1 >> if _tmpdict: >> _dict_on_disk = _dict_on_disk_tuple[_size] >> for _word, _value in _tmpdict.iteritems(): >> try: >> _string = _dict_on_disk[_word] >> # I discard _a and _b, maybe _string.find(' ') >> combined with slice would do better? >> _abs_count, _a, _b, _expected_freq = >> _string.split() >> _abs_count = int(_abs_count).__add__(_value) >> _t = (str(_abs_count), '0', '0', '0') >> except KeyError: >> _t = (str(_value), '0', '0', '0') >> >> # this writes a copy to the dict, right? >> _dict_on_disk[_word] = ' '.join(_t) >> >> # >> # clear the temporary dictionaries in ourself >> # I think this works as expected and really does release memory >> # >> for _tmpdict in (self._tmpdict1, self._tmpdict2, >> self._tmpdict3, self._tmpdict4, self._tmpdict5, self._tmpdict6, >> self._tmpdict7, self._tmpdict8, self._tmpdict9, self._tmpdict10, >> self._tmpdict11, self._tmpdict12, self._tmpdict13, self._tmpdict14, >> self._tmpdict15, self._tmpdict16, self._tmpdict17, self._tmpdict18, >> self._tmpdict19, self._tmpdict20): >> _tmpdict.clear() >> > There you go again with that huge tuple. You just like typing, don't > you? You already wrote that one out just above. Couldn't you have > assigned it to a local variable? Well, in this case I was looking what's slow, and wanted to avoid one slice on a referenced tuple. ;) > > By the way, remind me again of the reason for the leading None in the > _dict_on_disk_tuple, would you? I was told to code this way - to make it clear that they are internal/local to the function/method. Is it wrong or just too long? ;-) > > The crucial misunderstanding here might be the meaning of "release > memory". While clearing the dictionary will indeed remove references to > the objects formerly contained therein, and thus (possibly) render those > items subject to garbage collection, that *won't* make the working set > (i.e. virtual memory pages allocated to your process's data storage) any > smaller. The garbage collector doesn't return memory to the operating > system, it merely aggregates it for use in storing new Python objects. Well, it would be fine, but I thought python returns that immediately. >> The above routine doesn't release of the memory back when it >> exits. >> > And your evidence for this assertion is ...? Well, the swapspace reserved grows during that posted loop. Tell me, there were about 5 local variable in that loop. Their contents while the loop iterates get constantly updated, so they shouldn't need more and more space, right? But they do! It's 300MB. it seems to me like the variable always points to a new value, but the old value still persists in the memory not only the the source tmpdictionary, but also somewhere else as it used to be referenced by that local variable. I'd say those 300MB account for those references. Most of the space is returned to the system (really, swap get's freed) when the loop get to the point where the dictionaries are cleared. More or less same behaviour I see of course even without swap, it just happened to me to be easily visible with the swap problem. > >> >> See, the loop takes 25 minutes already, and it's prolonging >> as the program is in about 1/3 or 1/4 of the total input. >> The rest of my code is fast in contrast to this (below 1 minute). >> >> -rw------- 1 mmokrejs users 257376256 Jan 17 11:38 diskdict12.db >> -rw------- 1 mmokrejs users 267157504 Jan 17 11:35 diskdict11.db >> -rw------- 1 mmokrejs users 266534912 Jan 17 11:28 diskdict10.db >> -rw------- 1 mmokrejs users 253149184 Jan 17 11:21 diskdict9.db >> -rw------- 1 mmokrejs users 250232832 Jan 17 11:14 diskdict8.db >> -rw------- 1 mmokrejs users 246349824 Jan 17 11:07 diskdict7.db >> -rw------- 1 mmokrejs users 199999488 Jan 17 11:02 diskdict6.db >> -rw------- 1 mmokrejs users 66584576 Jan 17 10:59 diskdict5.db >> -rw------- 1 mmokrejs users 5750784 Jan 17 10:57 diskdict4.db >> -rw------- 1 mmokrejs users 311296 Jan 17 10:57 diskdict3.db >> -rw------- 1 mmokrejs users 295895040 Jan 17 10:56 diskdict20.db >> -rw------- 1 mmokrejs users 293634048 Jan 17 10:49 diskdict19.db >> -rw------- 1 mmokrejs users 299892736 Jan 17 10:43 diskdict18.db >> -rw------- 1 mmokrejs users 272334848 Jan 17 10:36 diskdict17.db >> -rw------- 1 mmokrejs users 274825216 Jan 17 10:30 diskdict16.db >> -rw------- 1 mmokrejs users 273104896 Jan 17 10:23 diskdict15.db >> -rw------- 1 mmokrejs users 272678912 Jan 17 10:18 diskdict14.db >> -rw------- 1 mmokrejs users 260407296 Jan 17 10:13 diskdict13.db >> >> Some spoke about mmaped files. Could I take advantage of that >> with bsddb module or bsddb? >> > No. I'll ask in a different way? How do you update huge files, when it has to happen say thousand times? > >> Is gdbm better in some ways? Recently you have said dictionary >> operations are fast ... Once more. I want to turn of locking support. >> I can make the values as strings of fixed size, if mmap() would be >> available. The number of keys doesn't grow much in time, mostly >> there are only updates. >> > Also (possibly because I come late to this thread) I don't really > understand your caching strategy. I presume at some stage you look in > one of the twenty temp dicts, and if you don;t find something you read > it back in form disk? I parse some input file, get one list containing mixed-in words of sizes 1 to 20. The *cache* here means once it get's some amount of data in the list, the list is converted to dictionary in memory, as there are many repeated items in th list. Then, I copy the contents of that temporary dictionary to those dictionaries located on disk (the code moving the contents of temporary dictionaries to those on disk is the one posted). > > This whole thing seems a little disorganized. Perhaps if you started > with a small dataset your testing and development work would proceed > more quickly, and you'd be less intimidated by the clear need to > refactor your code. I did and the bottlenecks where in the code. Now the bottleneck is constantly re-writing almost 20 files of filesizes about 200MB and up. OK. I think I'll do it another way. I'll just generate words of one size per each loop, flush the results to disk, and loop back. With this scenario, I'll read 20 times the input, which seems to be less expensive then having 20 huge dictionaries on disk constantly updated. Possibly I won't be able to keep the dictionary in memory and flush it just once to disk, as the size might be about gigabyte ...? Don't know, probably will have to keep the *cache* method mentioned above, and update the files several times. This is the part I can refactor, but I'll overwrite those huge files maybe only 20x or 200x instead of 20000 times. Still, I'll search for a way to update them efficiently. Maybe even mmaped plaintextfiles would be updated more efficiently than this .db file. Hmm, will probably have to keep in memory position of the fixed-sized value in such a file. Thanks for help! Martin From invalidemail at aerojockey.com Tue Jan 11 06:06:48 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 11 Jan 2005 03:06:48 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <1105381339.922714.23200@c13g2000cwb.googlegroups.com> <1oFEd.71967$Jk5.45632@lakeread01> Message-ID: <1105441608.304627.271340@f14g2000cwb.googlegroups.com> Tim Peters wrote: > ... > > [Anna] > >> BTW - I am *quite* happy with the proposal for "where:" syntax - I > >> think it handles the problems I have with lambda quite handily. > > [Steve Holden] > > Whereas I find it to be an excrescence, proving (I suppose) that one > > man's meat is another person's poison, or something. > > I've been waiting for someone to mention this, but looks like nobody > will, so I'm elected. Modern functional languages generally have two > forms of local-name definition, following common mathematical > conventions. "where" was discussed here. The other is "let/in", and > seems a more natural fit to Python's spelling of block structure: > > let: > suite > in: > suite Ah. During that discussion, I did kind of suggest this (spelling it where...do) as an alternative to where (thinking I was clever). Only no one seemed to take notice, probably because I suggested something more poignant at the same time. Now I see why I liked the idea so much; it was exactly like let forms. > There's no restriction to expressions here. I suppose that, like the > body of a class, the `let` suite is executed starting with a > conceptually empty local namespace, and whatever the suite binds to a > local name becomes a temporary binding in the `in` suite (like > whatever a class body binds to local names becomes the initial value > of the class __dict__). So, e.g., > > i = i1 = 3 > let: > i1 = i+1 > from math import sqrt > in: > print i1, sqrt(i1) > print i1, > print sqrt(i1) > > would print > > 4 2 > 3 > > and then blow up with a NameError. > > LIke it or not, it doesn't seem as strained as trying to pile more > gimmicks on Python expressions. Indeed. -- CARL BANKS From apardon at forel.vub.ac.be Tue Jan 18 08:28:00 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Jan 2005 13:28:00 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-18, Nick Coghlan schreef : > Antoon Pardon wrote: >> More specific the Decimal class is mutable and usable as dict key. > > It's *meant* to be immutable though. The fact that we used __slots__ instead of > __setattr__ to implement the immutability, so you *can* overwrite the slot > variables if you really want to is merely an artifact of the current Python > implementation. > > The limited mutability bug will disappear in Python 2.5, so it's not a good > example of a 'mutable' dict key (especially given that the only way to mutate it > is to modify private variables directly). > > And, as I've stated previously, if the issue of sane mutable keys in > dictionaries and sets really bugs you so much - implement identity_dict and > identity_set in C and lobby for their inclusion in the collections module. I'm not bugged by its absence in Python. I'm bugged by the attitude about them. But anyway I'm thinking about implementing a safe dictionary that will copy whenever it would otherwise allow the risk of mutating a key. > On the more general point of "don't use mutable objects with non-identity based > comparisons as dictionary keys", try teaching students for a while (or listen to > those who have): What kind of students? I have implemented a hash table when I was a student and its implementation allowed the use of 'mutable' objects as a key without a problem. It simply always made copies when appropiate and didn't allow external access to the keys. So although the key objects were 'mutable' there was no way a user could accidently mutate a key. So don't use a mutable as a dictionary key isn't so much a dictionary limitation in general but a specific limitation of the python implementation. And yes I understand, the current implenatation is the result of the fact that the same dictionaries are used internally for variables in scopes and attributes in objects and the fact that no copies are involved gives a boost to performance. But it could be argued that providing these same dictionaries with those semantics to the users was a premature optimisation. > When stating useful general principles, it is never, ever worth it to get into > the quibbly little details about exceptions to the principle. If students ask, > admit that they exist, but point out that the exceptions are rare, and not worth > worrying about at that point in their learning. But don't use mutable keys is not a general principle. It is a principle introduced by the limitations of the python implementations. I don't like it when a good rule of thumb because of implementation limitations is sold as a general principle. -- Antoon Pardon From fredrik at pythonware.com Fri Jan 14 05:35:07 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 14 Jan 2005 11:35:07 +0100 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com><7xmzvfn096.fsf@ruckus.brouhaha.com><7xsm559heo.fsf@ruckus.brouhaha.com><7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: Antoon Pardon wrote: >> no, expressions CAN BE USED as statements. that doesn't mean >> that they ARE statements, unless you're applying belgian logic. > > No I am applying set logic. Any string that is in the set of > valid expressions is also in the set of valid statements. since you're arguing that one concept is identical to another concept, that operation has to work in both directions. > Like any animal that is in the set of dogs is also in the > set of mamals. and all mammals are dogs? it this a language problem? do you have problems parsing the statements you reply to? even when someone explictly says "Given that we are having this discussion in the context of", you chose to ignore that context. what's wrong with you? From flamesrock at gmail.com Sat Jan 1 20:24:39 2005 From: flamesrock at gmail.com (flamesrock) Date: 1 Jan 2005 17:24:39 -0800 Subject: Confusion About Classes In-Reply-To: References: <1104194131.792545.140560@z14g2000cwz.googlegroups.com> <1104213408.450534.205270@z14g2000cwz.googlegroups.com> <1104370779.827348.205400@c13g2000cwb.googlegroups.com> <1104388925.645630.168900@c13g2000cwb.googlegroups.com> Message-ID: <1104629079.456741.116020@z14g2000cwz.googlegroups.com> Well, I took a short excursion into xml for a different part of the program, but the class is now finished!! (source below) I have a few more questions for you guys. 1)If I set self.serverConfig = file(os.path.join('configuration','score.conf'), 'w') and then go self.serverConfig.close(), is there a way to open it in read mode without calling the filename directly? Like self.serverConfig.open('r') -which doesn't work BTW- instead of open(os.path.join('configuration','score.conf'), 'r')? Using open(self.ServerConfig, 'r') doesn't seem to work either. 2) A problem arose when converting the encoded file back into a string for decoding; the \n's seemed to have dissapeared so it returned an error when I tried to decode. Is there a way to stop python from disposing of those those characters before writing to file? 3) Is there way to retrieve the timestamp of a file via ftp? >>There are NAMES, thats why there are NAMESPACES. >>A name is just a reference or 'handle' to an object, because..... >>everything in python is an OBJECT,(except for names, they are just >>names). And >>That being said, understanding this part of Python can aid enormously in >>working with the language. If you'd like to think of it in C terms, >>basically every 'name' in Python is a pointer to a PyObject, and 'names' >>(as pointers) are always passed by value -- that is, you get a copy of >>the pointer, but not a copy of the object. Ahhhhh...now *that* makes sense. So dynamically typed variables aren't variables at all...but just another term for pointers? cool, I like that. And thanks for the examples, guys. Its coming together and I'm starting to actually 'get it' :) So name mangling basically follows the rules of private and public in Java? (I have limited experience in java so don't quote me on that.) (Google groups isn't displaying the spaces correctly, so I added four *'s = 1 four space indentation..) import ftplib, ezPyCrypto, ConfigParser import traceback, sys, os #------------------------------------------------------------------------------- class create_server: ****'''Create a create_server object whenever a new server is to be added to ****the SCORE network.''' ****def __init__(self, absCFGpath, domain, servername, master_ftpUSER, ****master_ftpPASS, score_ftpUSER='anonymous', score_ftpPASS='anonymous', ****scorecontact='admin at simcitysphere.com', maxusers='unlimited', httpport='80', ****ftpport='21', passivemode=True): ********self.domain = domain ********self.httpport = httpport ********self.ftpport = ftpport ********self.servername = servername ********self.maxusers = maxusers ********self.scorecontact = scorecontact ********try: ************self.serverConfig = file(os.path.join('configuration','score.conf'), 'w') ********except: ************os.mkdir('configuration') ************self.serverConfig = file(os.path.join('configuration','score.conf'), 'w') ********self.absCFGpath = absCFGpath ********self.master_ftpUSER = master_ftpUSER ********self.master_ftpPASS = master_ftpPASS ********self.score_ftpUSER = score_ftpUSER ********self.score_ftpPASS = score_ftpPASS ********self.passivemode = passivemode ********self.parser = ConfigParser.ConfigParser() #------------------------------------------------------------------------------- ****def createUniversalConfig(self): ********'''Creates the SCORE servers main configuration file.''' ********self.parser.add_section('score') ********self.parser.set('score', 'domain', self.domain) ********self.parser.set('score', 'servername', self.servername) ********self.parser.set('score', 'httpport', self.httpport) ********self.parser.set('score', 'ftpport', self.ftpport) ********self.parser.set('score', 'maxusers', self.maxusers) ********self.parser.set('score', 'scorecontact', self.scorecontact) ********self.parser.write(self.serverConfig) ********self.serverConfig.close() ********return open(os.path.join('configuration','score.conf'), 'r') #------------------------------------------------------------------------------- ****def editUniversalConfig(self, section, key, value): ********'''edit the SCORE servers main configuration file.''' ********self.serverConfig = open(os.path.join('configuration','score.conf'), 'w') ********self.parser.set(section, key, value) ********self.serverConfig.close #------------------------------------------------------------------------------- ****def createUSERfile(self): ********'''Creates an encrypted ascii public ftp password file that clients use ********to decode after logging in''' ********crypt = ezPyCrypto.key() ********userFile = file(os.path.join('configuration','uFile.enc'), 'w') ********userFile.write(crypt.encStringToAscii(self.score_ftpUSER)) ********userFile.close() ********userFile = open(os.path.join('configuration','uFile.enc'), 'r') ********return userFile #------------------------------------------------------------------------------- ****def createPASSfile(self): ********'''Creates an encrypted ascii public ftp password file that clients use ********to decode after logging in''' ********crypt = ezPyCrypto.key() ********passFile = file(os.path.join('configuration','pFile.enc'), 'w') ********passFile.write(crypt.encStringToAscii(self.score_ftpPASS)) ********passFile.close() ********passFile = open(os.path.join('configuration','pFile.enc'), 'r') ********return passFile #------------------------------------------------------------------------------- ****def uploadConfigs(self): ********'''Uploads the universal config/ftpuser/pass files to the correct directories on the site''' ********##print "Files:", sys.argv[1:] relic.. ********print "Logging in..." ********ftp = ftplib.FTP() ********ftp.set_pasv(self.passivemode) #true if passive, false if active ********ftp.connect(self.domain, self.ftpport) ********print ftp.getwelcome() ********try: ************try: ****************ftp.login(self.master_ftpUSER, self.master_ftpPASS) ****************ftp.cwd(self.absCFGpath) #*the SCORE root directory ****************print "Currently in:", ftp.pwd() ****************print "Uploading..." ****************sConfig = self.createUniversalConfig() ****************uFile = self.createUSERfile() ****************pFile = self.createPASSfile() ****************ftp.storlines('STOR score.conf', sConfig) ****************try: ********************ftp.cwd(self.absCFGpath + '/files') ****************except ftplib.error_perm: #*if dir doesn't exist ********************ftp.mkd('files') ********************ftp.cwd(self.absCFGpath + '/files') #change to config directory ****************ftp.storlines('STOR uFile.enc', uFile) ****************ftp.storlines('STOR pFile.enc', pFile) ****************sConfig.close() ****************uFile.close() ****************pFile.close() ****************print "OK" ****************print "Files:" ****************print ftp.retrlines('LIST') ************finally: ****************print "Quitting..." ************ftp.quit() ********except: ************traceback.print_exc() #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- -thanks, flamesrock From vze4rx4y at verizon.net Mon Jan 17 07:56:39 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Mon, 17 Jan 2005 12:56:39 GMT Subject: generator expressions: performance anomaly? References: Message-ID: [Delaney, Timothy C] > Nick's other suggestion - that genexps propagate __len__ - might > still be interesting. Of course, it would only be applicable for > unconditional genexps(i.e. no if clause). Length transparency for iterators is not as general as one would expect. I once spent a good deal of effort exploring where it made sense, and I was surprised to find that it only rarely works out. Length transparency is an unexpectedly thorny subject with many dead-ends which precludes a fully general solution such as that proposed by Nick. For a recap of my research, see the docstring for Lib/test/test_iterlen.py . Raymond Hettinger From gsakkis at rutgers.edu Tue Jan 25 10:14:11 2005 From: gsakkis at rutgers.edu (gsakkis at rutgers.edu) Date: 25 Jan 2005 07:14:11 -0800 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net><35lbvdF4k3ss4U1@individual.net> Message-ID: <1106666051.334641.70740@z14g2000cwz.googlegroups.com> Terry Reedy wrote: > "George Sakkis" wrote in message > news:35lbvdF4k3ss4U1 at individual.net... > > Actually my initial motivation was not a huge tuple I had to slice many > > times. It was something much > > less extraordinarily unlikely, a recursive function with a sequence > > parameter: > > > > def foo(sequence): > > # base_case > > # do_stuff() > > combine(foo(sequence[:n]), > > foo(sequence[n:])) > > > > Having each slice be a view of the original sequence instead of a fresh > > copy would be a Good Thing > > Why? To save time? memory? Either would require more that a few bytes per > slice. If they are, you can probably use virtual slices as follows. > > def foo(sequence): > def _foo(seq, start, stop) > # base_case > # do_stuff() > combine(_foo(seq, start, n), _foo(seq, n, stop)) > _foo(sequence, 0, len(sequence) > > In other words, if you don't really want slices copied out of the sequence, > then don't slice! Just use 2 ints to indicate the working region or view. > Both this and using a nested function with additional params are standard > techniques. This also works when the seq is mutable and you want changes > to the 'slice' to change the original, as in quicksort. > > Terry J. Reedy I would say these are standard *C/C++* techniques; slicing simplifies things and thus seems more 'pythonic' to me. George From sharidas at zeomega.com Sat Jan 15 08:23:26 2005 From: sharidas at zeomega.com (Satchidanand Haridas) Date: Sat, 15 Jan 2005 18:53:26 +0530 Subject: How can I get the names of the files in a directory? In-Reply-To: <20050115131023.36656.qmail@web50501.mail.yahoo.com> References: <20050115131023.36656.qmail@web50501.mail.yahoo.com> Message-ID: <41E9194E.7080803@zeomega.com> Hi, try the 'listdir' function in the 'os' module. Also check the 'walk' function. regards, Satchit ---- Satchidanand Haridas (sharidas at zeomega dot com) ZeOmega (www.zeomega.com) Open Minds' Open Solutions #20,Rajalakshmi Plaza, South End Road, Basavanagudi, Bangalore-560 004, India Sara Fwd wrote: >Can you guys also help me find a module that looks in >a directory and print out the names of the files in there? > > > >__________________________________ >Do you Yahoo!? >Yahoo! Mail - Helps protect you from nasty viruses. >http://promotions.yahoo.com/new_mail > > From jdhunter at ace.bsd.uchicago.edu Fri Jan 21 16:00:08 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 21 Jan 2005 15:00:08 -0600 Subject: Graph and Table implementation In-Reply-To: (Jan Rienyer Gadil's message of "Fri, 21 Jan 2005 17:26:25 +0800") References: Message-ID: >>>>> "Jan" == Jan Rienyer Gadil writes: Jan> could anyone please help me! what and how is the best Jan> implementation of creating a table based on data coming from Jan> the serial port ? and also how would i be able to create Jan> graphs (2D) based on these data? Jan> opinions and suggestion are most highly welcome. thanks. matplotlib can handle most kinds of 2D plots -- it even has a table command for including simple tabular data in your graph http://matplotlib.sourceforge.net/screenshots.html#table_demo so for heavy duty tables you'll probably want to use a GUI widget. JDH From bulba at bulba.com Sun Jan 9 13:58:22 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 09 Jan 2005 19:58:22 +0100 Subject: Speed revisited References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> Message-ID: On Sat, 08 Jan 2005 17:57:30 -0700, Steven Bethard wrote: >Note that Python lists are implemented basically as arrays, which means >that deleting an item from anywhere but the end of the list is O(n) >because all items in the list must be moved down to fill the hole. Ouch... -- I have come to kick ass, chew bubble gum and do the following: from __future__ import py3k And it doesn't work. From davorss at gmail.com Wed Jan 26 00:22:31 2005 From: davorss at gmail.com (Davor) Date: 25 Jan 2005 21:22:31 -0800 Subject: python without OO In-Reply-To: <1106710590.312881.222520@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> Message-ID: <1106716951.060290.253010@z14g2000cwz.googlegroups.com> M.E.Farmer, first to clarify few things - I'm neither manager nor professionally involved in code development - I'm just embarking on a small project that I would like to attract some programmers to later on and make it a nice open-source system. Based on my previous experience with few SMALL projects, I would like to avoid object orientation as much as possible. The reason is that I always ended up working with people who were without much experience, same as me, but they were all so influenced by OO propaganda that it was impossible to reason with them and to go with as simple solution as possible (not saying that OO solution is necessarily more complex than a structured one IN ALL CASES - but in any single case I've seen so far it was). So every single time I was wasting time trying to explain why not to go with cool OO way as opposed to simple un-cool structured solution. So, if the application was feasible to develop in C or C++, the solution would be easy - just choose C and avoid all OO mess - of course would have slightly more problems with C's looser type-checking but in my experience it's far less problem then troubles that happen when one starts going crazy with C++ generic classes, multiple inheritance, deep inheritance trees, etc.. The nature of the application that I'm planning on is perfectly suited to a good high-level scripting language, and python looked very attractive so I decided to take look at it, but then i realized it has all this OO stuff that I got scared off immediately :-) - luckily some of these other guys including yourself mentioned that there are not that many issues with Python's OO stuff as there is with Java's of C++ (seems I'm not the only one with Java&C++ OO traumas :-)) - so I'm encouraged to proceed with Python. > It seems you are telling me that : > 1) You do not understand most programming concepts not really - I rather want to prevent incorporation of anything that is not really needed in the code... > 2) You are not willing to learn. more that I like to reject anything that is not obviously substantiated and that many people seem to have problems with... > 3) You might not have the skill set to manage developers maybe not good management approach but I would always opt for "not giving them the tools I don't want them to use" over "giving them tools I don't want them to use and then forbidding them to use these tools" - especially if they are not getting paid for what they are building :-) > Stop telling your programmers how to program! Seriously NOW. > If you managed a group of doctors would you tell them that they could > only use techniques that *YOU* understood, even if the were STANDARD > and well known by others? This sounds like one of those ideas preached by agile community - I say set up the rules and conventions as much as you can (in a *non-intrusive* way) if you are a manager... Exactly the group of professionals you mentioned in your example is support for what I am claiming. In fact in that profession everything is exactly about the rules, precise techniques, and exact processes that have to be done and when they have to be used. If anything gets done outside of recommended practices they are legally responsible for. For example, if a person has to undergo sinus surgery and the endoscopic version is sufficient (simple, non-intrusive, internal incision) and a doctor decides to do the traditional surgery with external cutting - I guess everyone would be pissed off - especially the patient :-).. Also, yes, I have read GOF book... but I never found it a big deal - no one ever had to document structured patterns - which definitely exist - but seem to be obvious enough that there is no need to write a book about them... Thanks for your feedback! Davor From merkosh at hadiko.de Fri Jan 21 14:44:02 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Fri, 21 Jan 2005 20:44:02 +0100 Subject: make install with python Message-ID: Hi, I am writing a Python application and use the GNU auto-tools to compile what needs compilation (i.e. Qt's .ui files). However, I don't know how to write an automake file that installs the main file (lmc.py) and some library files (i.e. ClassA.py, ClassB.py) into the appropriate directories. Any tips there? Thanks Uwe From ewanon at gmail.com Thu Jan 6 23:24:24 2005 From: ewanon at gmail.com (EW) Date: 6 Jan 2005 20:24:24 -0800 Subject: Problem remotely shutting down a windows computer with python In-Reply-To: <1104848654.965978.63000@z14g2000cwz.googlegroups.com> References: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> <1104848654.965978.63000@z14g2000cwz.googlegroups.com> Message-ID: <1105071864.183918.72410@f14g2000cwb.googlegroups.com> This does exactly what I needed! Thanks! Not sure what Windows Management Instrumentation is, but I'll look into it now. Eric From __peter__ at web.de Fri Jan 21 10:36:28 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Jan 2005 16:36:28 +0100 Subject: need help on generator... References: <63b5e209.0501210558.686f5c10@posting.google.com> Message-ID: Joh wrote: > i'm trying to understand how i could build following consecutive sets > from a root one using generator : > > l = [1,2,3,4] > > would like to produce : > > [1,2], [2,3], [3,4], [1,2,3], [2,3,4] > > but unfortunately can not, i guess i can do it by using sub generator > and maybe enumerate, please if you help could you explain a bit the > trick ? looks like this sub generator thing mess me up. Here is an (untested) variant that accepts any iterable while trying to remain memory-efficient. This makes it necessary to shuffle the order of the output a bit. from itertools import tee, islice def gen(iterable, start, end): it = iter(iterable) while True: it, a = tee(it) a = tuple(islice(a, end-1)) for sz in xrange(start, len(a)+1): yield a[:sz] it.next() if __name__ == "__main__": print list(gen(range(1, 5), 2, 4)) # prints: # [(1, 2), (1, 2, 3), (2, 3), (2, 3, 4), (3, 4)] Peter From skip at pobox.com Tue Jan 4 20:19:32 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 Jan 2005 19:19:32 -0600 Subject: Python evolution: Unease In-Reply-To: References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> Message-ID: <16859.16548.249527.30210@montanaro.dyndns.org> Terry> Numarray has a record array type. If there is not one publicly Terry> available, perhaps you could write a CSV file to record-array Terry> slurper and contribute it to the Recipes site or maybe even the Terry> CSV module. -1 on putting such a beast into the CSV module, especially if, as it seems, it would rely on something outside the core. Skip From segphault at sbcglobal.net Mon Jan 24 08:19:45 2005 From: segphault at sbcglobal.net (Ryan Paul) Date: Mon, 24 Jan 2005 13:19:45 GMT Subject: finding name of instances created References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> Message-ID: On Fri, 21 Jan 2005 16:13:19 -0800, Andr? wrote: > Short version of what I am looking for: > > Given a class "public_class" which is instantiated a few times e.g. > > a = public_class() > b = public_class() > c = public_class() > > I would like to find out the name of the instances so that I could > create a list of them e.g. > ['a', 'b', 'c'] > A working solution: class A: pass a = A() b = A() c = A() [x for x,y in locals().items() if hasattr(y,"__class__") and y.__class__ == A] That said, you probably dont want to do it. I doubt that it will work consistently. BTW, based on my understanding of the other stuff you said, this is probably not the best way to do whatever it is you are trying to do. --SegPhault From erikbethke at gmail.com Wed Jan 19 06:45:41 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 19 Jan 2005 03:45:41 -0800 Subject: wxPython and PyGame - do they play well together? In-Reply-To: <1106039039.627729.62990@f14g2000cwb.googlegroups.com> References: <1106026599.092269.292170@c13g2000cwb.googlegroups.com> <1106039039.627729.62990@f14g2000cwb.googlegroups.com> Message-ID: <1106135141.121584.327370@c13g2000cwb.googlegroups.com> After a touch more of exploration... actually from the wxPython demo's startup tips lead me over to the wxPython Wiki.... Here I found this gem: http://wiki.wxpython.org./index.cgi/IntegratingPyGame Awesome. There is in fact some very tricky timing of the import statement for pygame -Erik From ncoghlan at iinet.net.au Fri Jan 7 11:00:50 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 02:00:50 +1000 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> Message-ID: <41DEB232.1000007@iinet.net.au> Jacek Generowicz wrote: > [*] Funnily enough, getting them to understand that "lambda x: fn(x)" > is just a very silly way of writing "fn", can be quite a struggle > at times ... but that's probably a consequence of the context in > which lambda is introduced. If you genuinely taught them that, you may have done them a disservice: Py> def f(x): ... print x ... Py> f1 = f Py> f2 = lambda x: f(x) Py> f1("hi") hi Py> f2("hi") hi Py> def f(x): ... print x * 2 ... Py> f1("hi") hi Py> f2("hi") hihi Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From davorss at gmail.com Tue Jan 25 18:33:11 2005 From: davorss at gmail.com (Davor) Date: Tue, 25 Jan 2005 18:33:11 -0500 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: > On the other hand, this does beggar for a reason to bother with Python at > all. It seems you could be happy doing BASH scripts for Linux or DOS batch > files for Windows. Both are "nice&simple" scripting languages free of > object oriented contamination. not really, what I need that Python has and bash&dos don't is: 1. portability (interpreter runs quite a bit architectures) 2. good basic library (already there) 3. modules for structuring the application (objects unnecessary) 4. high-level data structures (dictionaries & lists) 5. no strong static type checking 6. very nice syntax so initially I was hoping this is all what Python is about, but when I started looking into it it has a huge amount of additional (mainly OO) stuff which makes it in my view quite bloated now... anyhow, I guess I'll have to constrain what can be included in the code through different policies rather than language limitations... Thanks Davor From jjl at pobox.com Mon Jan 3 13:11:06 2005 From: jjl at pobox.com (John J. Lee) Date: 03 Jan 2005 18:11:06 +0000 Subject: using HTTP Digest auth with arbitrary HTTP methods? References: Message-ID: John Reese writes: > In comp.lang.python, [I] wrote: [...] > I instead copied it (to urllib3.py) and made the following changes: > a. in AbstractDigestAuthHandler.get_authorization, call > req.get_method() instead of req.has_data() and 'POST' or 'GET' > (python has a ternary operator, who knew) (Re ternary operator: Everybody who read this list at certain times in the past is painfully aware of that fact, and of precisely why it's not quite true, and of all the syntax alternatives for real ternary conditionals that will never be part of Python ;-) > b. in AbstractHTTPHandler.do_open, call req.get_method instead of the > hard-coded if-logic which is the same as that in req.get_method > > Both of these seem like bugs in urllib2. Yup, bugs both. > Then I overrode urllib2.Request and made it possibly to set the method, > and then passed an instance of my custom Request class (the one that > shouldn't have to exist, since Request should allow method to be set > explicitly) to OpenerDirector.open(). > > I'd like to see these changes make it into the standard library -- after > being vetted by whoever's in charge of urllib2. Anybody know who I > should talk to? Nobody is really in charge: just go ahead and submit a patch. Drop me an email when you do, and I'll try to review it. The only reason urllib2 doesn't already do arbitrary HTTP methods is that nobody has spent the time to think carefully if a .set_method() really is the right way to do it, then followed through with the work needed to get a patch applied. As always, a precondition for change is that somebody thinks something through carefully, writes tests, documentation, patch and submits all three to the SF patch tracker with a brief explanation like the one you give above. BTW, Greg Stein started work on adding the stuff you need at the httplib level (as module httpx). He seems too busy to finish it, but see modules httpx and davlib (one or both are in the Python CVS sandbox). He thinks httplib is a better place for DAV than urllib2, and he should know. But go ahead and fix urllib2 anyway... :-) John From snail at objmedia.demon.co.uk Wed Jan 26 08:59:24 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Wed, 26 Jan 2005 13:59:24 +0000 Subject: is there better 32 clock() timing? References: <41f61372.1768192005@news.oz.net> <41f63d79.1778950866@news.oz.net> <41f746c3.1846865602@news.oz.net> Message-ID: In message <41f746c3.1846865602 at news.oz.net>, Bengt Richter writes >>QueryPerformanceCounter is 47 times slower to call than clock() on my >>1Ghz Athlon. >That really makes me wonder. Perhaps the Athlon handles RDTSC by way of >an illegal instruction trap and faking the pentium instruction? No. Athlon implements it correctly- if it didn't you'd end up in the debugger with an illegal instruction trap - you don't. Also my stats below show that Athlon's RDTSC is faster than Pentium's which I doubt you'd get if you were faking things. Taking it further - the test to see if a processor supports RDTSC is to wrap it in an exception handler and execute the instruction - if it doesn't you end up in the __except part of the SEH handler. QueryPerformanceCounter and RDTSC are not the same thing. QueryPerformanceCounter talks to hardware to get its results. I imagine that differences in performance for QueryPerformanceCounter are down to how the HAL talks to the hardware and can't be blamed on the processor or manufacturer. clock() gets its info from the OS at (I imagine) the same granularity as the NT scheduler. Some systems schedule at 10ms/11ms others at about 6ms or 7ms. I think this is to do with single/dual processors - unsure as I don't have a dual processor box. If you call GetThreadTimes() you will find values returned that match the approx clock() values - which is why I think they are related. I've just run some tests using the same old program. QPC is QueryPerformanceCounter. QPF is QueryPerformanceFrequency. I've included the QPC/QPF column to show the timings in seconds. 1Ghz Athlon, Windows XP, SP2 1,000,000 iterations QPC QPC/QPF (seconds) QueryPerformanceCounter 7156984 5.998233 GetThreadTimes 503277 0.421794 RDTSC 103430 0.086684 clock() 148909 0.124800 QPC QPC/QPF (seconds) 850Mhz Pentium III, W2K. 1,000,000 iterations QueryPerformanceCounter 5652161 1.579017 GetThreadTimes 3608976 1.008222 RDTSC 842950 0.235491 clock() 699840 0.195511 The results surprise me - Pentium III clock() takes less time to execute than Pentium III RDTSC! It surprises me that the 850Mhz Pentium III QPC is faster than the 1Ghz Athlon QPC, but whichever way you slice it, QPC is massively slower than RDTSC or clock(). Also surprising is the W2K GetThreadTimes is so slow compared to the Athlon GetThreadTimes(). >of the timer chip that drives the old 55ms clock that came from IBM >using cheap TV crystal based oscillators instead of defining an >OS-implementer-friendly time base, I think. The frequency was nominally >1193182 hz I believe. Obviously the OS didn't get interrupted that often, >but if you divide by 2**16, you get the traditional OS tick of ~55ms: I though that was the Windows 9x way of doing things. You get the 49 day wrap around with this one I think. >you can't expect to control ignition of a racing engine reliably with >an ordinary windows based program ;-) ...and Schumacher is in the lead, oh look! The Ferrari has blue screened. The new regulations to reduce speeds in F1 are working, that has really slowed him down... Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From kosh at aesaeion.com Wed Jan 26 21:32:38 2005 From: kosh at aesaeion.com (kosh) Date: Wed, 26 Jan 2005 19:32:38 -0700 Subject: 20050126 find replace strings in file In-Reply-To: References: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> Message-ID: <200501261932.38770.kosh@aesaeion.com> On Wednesday 26 January 2005 7:13 pm, Tad McClellan wrote: > [ Followup set ] > > Dan Perl wrote: > > I can't imagine why or how, but there are > > actually 26 members in the perl-python Yahoo! group who have registered > > to get these bogus lessons sent to them daily! > > There is one born every minute. > Nah it is daily humor. Just think of it like a joke list. :) From snail at objmedia.demon.co.uk Fri Jan 7 08:47:18 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Fri, 7 Jan 2005 13:47:18 +0000 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <1105056774.393244.199250@f14g2000cwb.googlegroups.com> Message-ID: In message , Christopher Koppler writes >Still, Java feels like C++ done right, while being more wrong >:-[ Couldn't disagree more. Just about anything you want to do that is low-level, is impossible in Java. Anyway this is off-topic. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From steven.bethard at gmail.com Wed Jan 12 19:49:43 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 17:49:43 -0700 Subject: dict.updated In-Reply-To: <5GiFd.8571$Vj3.3354@newssvr17.news.prodigy.com> References: <5GiFd.8571$Vj3.3354@newssvr17.news.prodigy.com> Message-ID: Rick Morrison wrote: > I could live with creating a new dict, sure (although it seems wasteful). I > realize that something like this probably doesn't stand a chance of ever > making it into the std library for what might be called "philosophical" > reasons. I just want it for me (my personal philosophy runs more to the > pragmatic -- well at least for coding). > > I suppose the in-place version would be more along the lines of: > > >>>>def updated(d, updates): > > ... d.update(updates) > ... return d > ... > >>>>[updated(d, {'c':3}) for d in [{'a':1, 'b':2}, {'x':10, 'y':'11'}]] > > [{'a': 1, 'c': 3, 'b': 2}, {'y': '11', 'x': 10, 'c': 3}] > > But I'd like to put the "updated" method on the "dict" object, which is what > I can't seem to figure out. > Yeah I know that's "bad", but to my mind so is polluting the global > namespace with the "updated" function. You could do something like: py> class dict(dict): ... def updated(self, *args, **kwds): ... self.update(*args, **kwds) ... return self ... py> [d.updated(c=3) for d in [dict(a=1, b=2), dict(x=10, y=11)]] [{'a': 1, 'c': 3, 'b': 2}, {'y': 11, 'x': 10, 'c': 3}] It'd mean you'd have to create all your dicts with the dict constructor instead of {} though. Steve From marc.poulhies at NO-SP4Mepfl.ch Mon Jan 31 11:41:30 2005 From: marc.poulhies at NO-SP4Mepfl.ch (=?iso-8859-1?Q?Marc_Poulhi=E8s?=) Date: Mon, 31 Jan 2005 17:41:30 +0100 Subject: Using HTTPSConnection and verifying server's CRT References: <41fe5357@epflnews.epfl.ch> Message-ID: <41fe5fb7@epflnews.epfl.ch> ngps at netmemetic.com (Ng Pheng Siong) writes: Hi, > According to Marc Poulhi?s : >> I tried to see if the M2Crypto has this possibility, but from my tests >> and from what I can find on the website, it seems not :/ > > How did you test and where on the website does it say not? I did things like this: con = M2Crypto.httpslib.HTTPSConnection("some_secure_server") con.request("GET" , "/") I tried to play with optional parameters (strict, debuglevel, etc) to see if it was saying that it will not check server's CRT or some other debug message dealing with server's certificate, but it is always returning the webpage without saying anything :) I did not say that M2C's doc stated clearly that this was not possible (that's why I wrote "seems"), but I couldn't find something stating it was possible (I tried google, API docs). >> Can someone confirm me this is not possible or point me to something >> that could help me? > > M2Crypto does server cert verification. With M2Crypto's httpslib, you pass > in an SSL.Context instance to the HTTPSConnection constructor to configure > the SSL; one of the config knobs is cert verification. So, redo your test, > satisfy yourself that this is doable, and send me your code to include as > an example in the distribution. ;-) Ok, sorry for that. Maybe that with more readings I could have spotted this. I'll try that tomorrow and give my code if I have something working! > M2Crypto even does client certs. Since Apr 2000, according to the very last > blog entry on the ZServerSSL page. Yes, I did try this and have my client authenticated to the server. Thanks for this quick and clear answer ;) Marc From binux.lists at gmail.com Mon Jan 10 00:55:32 2005 From: binux.lists at gmail.com (Binu K S) Date: Mon, 10 Jan 2005 11:25:32 +0530 Subject: Datetime module In-Reply-To: <1105335972.454019.46450@c13g2000cwb.googlegroups.com> References: <1105335972.454019.46450@c13g2000cwb.googlegroups.com> Message-ID: <2b7d8b42050109215523001bc0@mail.gmail.com> The time module will do. >>> import time >>> time.ctime() 'Mon Jan 10 11:17:54 2005' Use strftime if you need to format the time differently. >>> time.strftime("%Y-%m-%d %H:%m:%S",time.localtime()) '2005-01-10 11:01:45' On 9 Jan 2005 21:46:12 -0800, rublind at gmail.com wrote: > I am writing a script that acts as an AIM bot [using twisted.IM's base > scripts] and I want to add a logging feature. I got it to log who sends > what to whom, but what I want to add is the date and time that the > message was sent (or recieved by the bot), I tried to look at datetime > on my own, and I couldn't get anything to work. > Anyone know a simple way to get the current date and/or time? > > Thanks! > > -- > http://mail.python.org/mailman/listinfo/python-list > From http Sun Jan 9 10:04:46 2005 From: http (Paul Rubin) Date: 09 Jan 2005 07:04:46 -0800 Subject: Python3: on removing map, reduce, filter References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> Message-ID: <7x4qhqr6cx.fsf@ruckus.brouhaha.com> Andrey Tatarinov writes: > anyway list comprehensions are just syntaxic sugar for > >>> for var in list: > >>> smth = ... > >>> res.append(smth) > > (is that correct?) I would expect lc's to work more like map does. From steven.bethard at gmail.com Sun Jan 23 15:46:04 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 23 Jan 2005 13:46:04 -0700 Subject: What is print? A function? In-Reply-To: References: Message-ID: Frans Englich wrote: > The reason I thinks about this is I need to implement a debug print for my > program; very simple, a function/print statement that conditionally prints > its message whether a bool is true. Not overly complex. Sounds like you want to override sys.stdout: py> class ConditionalWriter(object): ... def __init__(self, outfile, cond=True): ... self.outfile = outfile ... self.cond = cond ... def write(self, text): ... if self.cond: ... self.outfile.write(text) ... ... py> import sys py> writer = ConditionalWriter(sys.stdout) py> sys.stdout = writer py> print "hi!" hi! py> writer.cond = False py> print "hi!" py> writer.cond = True py> print "hi!" hi! You probably want to restore sys.stdout when you're done too: py> sys.stdout = writer.outfile py> writer.cond = False py> print "hi!" hi! That said, you probably _really_ want the logging module: http://docs.python.org/lib/module-logging.html Steve From apardon at forel.vub.ac.be Wed Jan 12 03:07:52 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 Jan 2005 08:07:52 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: Op 2005-01-12, It's me schreef : > > "Robert Kern" wrote in message > news:cs1mp9$sg9$1 at news1.ucsd.edu... >> >> That's *it*. > > So, how would you overload an operator to do: > > With native complex support: > > def twice(a): > return 2*a > > print twice(3+4j), twice(2), twice("abc") > > Let's presume for a moment that complex is *not* a native data type in > Python. How would we implement the above - cleanly? I suppose in the same way as (graphic) points and vectors can be implemented cleanly. A few years back I had written a Vector class in python, just to get an understanding of how things worked. It worked without a problem with your twice function. >>> Vec(1.0,2.0) Vector[1.0, 2.0] >>> def twice(a): ... return 2 * a ... >>> twice(Vec(1.0,2.0)) Vector[2.0, 4.0] >>> I suppose what can be done with a vector class could have been done with a complex class should complex numbers not have been native to python. -- Antoon Pardon From jeff at ccvcorp.com Fri Jan 21 20:04:11 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 21 Jan 2005 17:04:11 -0800 Subject: default value in a list In-Reply-To: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: <10v39ald6em3u6f@corp.supernews.com> TB wrote: > Hi, > > Is there an elegant way to assign to a list from a list of unknown > size? For example, how could you do something like: > > >>>> a, b, c = (line.split(':')) > > if line could have less than three fields? (Note that you're actually assigning to a group of local variables, via tuple unpacking, not assigning to a list...) One could also do something like this: >>> l = "a:b:c".split(':') >>> a, b, c, d, e = l + ([None] * (5 - len(l))) >>> print (a, b, c, d, e) ('a', 'b', 'c', None, None) >>> Personally, though, I can't help but think that, if you're not certain how many fields are in a string, then splitting it into independent variables (rather than, say, a list or dict) *cannot* be an elegant solution. If the fields deserve independent names, then they must have a definite (and distinct) meaning; if they have a distinct meaning (as opposed to being a series of similar items, in which case you should keep them in a list), then which field is it that's missing? Are you sure it's *always* the last fields? This feels to me like the wrong solution to any problem. Hm, speaking of fields makes me think of classes. >>> class LineObj: ... def __init__(self, a=None, b=None, c=None, d=None, e=None): ... self.a = a ... self.b = b ... self.c = c ... self.d = d ... self.e = e ... >>> l = "a:b:c".split(':') >>> o = LineObj(*l) >>> o.__dict__ {'a': 'a', 'c': 'c', 'b': 'b', 'e': None, 'd': None} >>> This is a bit more likely to be meaningful, in that there's almost certainly some logical connection between the fields of the line you're splitting and keeping them as a class demonstrates that connection, but it still seems a bit smelly to me. Jeff Shannon Technician/Programmer Credit International From claudio.grondi at freenet.de Fri Jan 21 03:11:36 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 21 Jan 2005 08:11:36 -0000 Subject: DevX: "Processing EDI Documents into XML with Python" Message-ID: <35c0hcF4jnr7pU1@individual.net> "You don't have to rely on expensive and proprietary EDI conversion software to parse, validate, and translate EDI X12 data to and from XML; you can build your own translator with any modern programming language, such as Python." by Jeremy Jones http://www.devx.com/enterprise/Article/26854 Excerpt: "Python is an object-oriented, byte-compiled language with a clean syntax, clear and consistent philosophy, and a strong user community. These attributes (both of the language and the community) make it possible to quickly write working, maintainable code, which in turn makes Python an excellent choice for nearly any programming task. Processing any "flavor" of EDI is no exception." Hi, just wanted to share with you, that the last issue of the DevX newsletter comes with a Python related article as first item in the list of subjects. Claudio From harold.fellermann at upf.edu Mon Jan 10 11:45:28 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Mon, 10 Jan 2005 17:45:28 +0100 Subject: syntax error in eval() Message-ID: <08965366-6327-11D9-B3E0-003065FB7B26@upf.edu> Hi all, I am trying to dynamically add class attributes at runtime using the function eval(), i.e. I want to do something like >>> class X : pass ... >>> X.attr = 5 but without knowing either the attributes name nor its value. However, I encounter a syntax error I cannot understand: Python 2.4 (#1, Dec 30 2004, 08:00:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> class X : pass ... >>> attrname = "attr" >>> eval("X.%s = val" % attrname , {"X":X, "val":5}) Traceback (most recent call last): File "", line 1, in ? File "", line 1 X.attr = val ^ SyntaxError: invalid syntax Does anyone have a clue what might be wrong? Thanks in advance. - harold - -- "I know what I believe. I will continue to articulate what I believe and what I believe - I believe what I believe is right." -- George W. Bushman From apardon at forel.vub.ac.be Tue Jan 18 02:57:18 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Jan 2005 07:57:18 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-17, Steve Holden schreef : > Antoon Pardon wrote: > > Mostly, though, I was trying to say that I found your nitpicking > insistence on terminological exactitude, even when giving advice to > those new to the language, both inappropriate and tedious in the extreme. I think it is appropiate because not all new to the language are new to programming and even newbees have a right to know how it really is. Otherwise after some time you get experienced users who don't know the fact. In this case for example there are a number of people who flat out assert that muatble dict keys in pyhthon is impossible. -- Antoon Pardon From steve at holdenweb.com Sun Jan 2 09:20:36 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 02 Jan 2005 09:20:36 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xacrs230c.fsf@ruckus.brouhaha.com> Message-ID: Aahz wrote: > In article <7xacrs230c.fsf at ruckus.brouhaha.com>, > Paul Rubin wrote: > >>I was pretty skeptical of Java's checked exceptions when I first used >>them but have been coming around about them. There's just been too >>many times when I wrote something in Python that crashed because some >>lower-level function raised an exception that the upper level hadn't >>been expecting, after the program had been in use for a while. I'd >>sure rather find out about that at compile time. > > > That's funny -- Bruce Eckel talks about how he used to love checked > exceptions but has come to regard them as the horror that they are. > I've learned to just write "throws Exception" at the declaration of > every method. Pretty sloppy, though, no? And surely the important thing is to have a broad handler, not a broad specification of raisable exceptions? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From michael at stroeder.com Fri Jan 14 04:19:33 2005 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 14 Jan 2005 10:19:33 +0100 Subject: python connect to db2 In-Reply-To: References: <1105689253.3167.0.camel@linux.tister.com> Message-ID: <5efkb2-co4.ln1@nb2.stroeder.com> yuzx wrote: > > i try to connect to db2 use python,i find it on > python-db2 doc: > > $ python > >>> import DB2 > >>> conn = DB2.connect(dsn='sample', uid='db2inst1', pwd='ibmdb2') > >>> curs = conn.cursor() > > but i don't know about dsn, It's the host name. In a former project (using module DB2 together with 'IBM DB2 Connect' to access OS/390 database via TCP/IP) I had to invoke a special catalog db2 script before being able to use the host name. Ciao, Michael. From Scott.Daniels at Acm.Org Sat Jan 15 16:47:55 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 15 Jan 2005 13:47:55 -0800 Subject: interpret 4 byte as 32-bit float (IEEE-754) In-Reply-To: <41E97907.9070709@web.de> References: <34t1p2F4foiplU1@individual.net> <41e952b9$1@nntp0.pdx.net> <41E96302.4020003@web.de> <41e964bc$1@nntp0.pdx.net> <41E97907.9070709@web.de> Message-ID: <41e98c50$1@nntp0.pdx.net> G.Franzkowiak wrote: > Scott David Daniels schrieb: >> If you really want to do this kind of byte fiddling: >> http://members.dsl-only.net/~daniels/block.html >> Then: >> from block import Block, View >> b = Block(4) # enough space for one float (more is fine) >> iv = View('i', b) # getting to it as an integer >> fv = View('f', b) # same memory as floating point >> iv[0] = 0x3F8CCCCD # Here is a sample just using the integer >> print fv[0] >> On an Intel/Amd/Generic "PC" machine, you should get 1.1 > > That's good :-)) > I'm missing the makefile ;-) > I'm using the other world... right There's a lot more than one other world. distlib is your friend. There is no makefile. If you are not on a windows box, get the source, extract the files from the zip, and run: python setup.py install -Scott David Daniels Scott.Daniels at Acm.Org From ng01.spamguard at icewater.org Mon Jan 24 22:44:04 2005 From: ng01.spamguard at icewater.org (mike) Date: Mon, 24 Jan 2005 22:44:04 -0500 Subject: is extending an object considered acceptable usage? Message-ID: i have an Item which belongs to a Category, so Item has: - item.categoryId, the database primary key of its Category - item.category, a reference to its Category. this null unless i need a reference from item to its Category object, in which case i call setCategory(category) sometimes i want a list of categories, and from each i want to be able to access a list of its items. in this case is it considered acceptable to just create a list of those items and assign it as a property of their category? eg: category.items = listOfItems this packages everything up into a hierarchy and is more convenient to use, especially in Cheetah templates, but requries modifying the structure of the object, which bothers me (probably for some subconscious java-related reason). the alternative might be to create a dictionary that keys the lists of items on their category: items = {} items[category.id] = listOfItems this feels less "controversial" to me, but requires extra objects and house-keeping. thanks - just curious if there were arguments one way or the other. From uche at ogbuji.net Thu Jan 27 22:19:25 2005 From: uche at ogbuji.net (Uche Ogbuji) Date: 27 Jan 2005 19:19:25 -0800 Subject: Clarification on XML parsing & namespaces (xml.dom.minidom) In-Reply-To: <41f5eb4b$0$10526$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41f5eb4b$0$10526$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1106882365.827371.59940@f14g2000cwb.googlegroups.com> Greg Wogan-Browne wrote: > I am having some trouble figuring out what is going on here - is this a > bug, or correct behaviour? Basically, when I create an XML document with > a namespace using xml.dom.minidom.parse() or parseString(), the > namespace exists as an xmlns attribute in the DOM (fair enough, as it's > in the original source document). However, if I use the DOM > implementation to create an identical document with a namespace, the > xmlns attribute is not present. > > This mainly affects me when I go to print out the document again using > Document.toxml(), as the xmlns attribute is not printed for documents I > create dynamically, and therefore XSLT does not kick in (I'm using an > external processor). > > Any thoughts on this would be appreciated. Should I file a bug on pyxml? It's odd behavior, but I think it's a stretch to call it a bug. You problem is that you're mixing namespaced documents with the non-namespace DOM API. That means trouble and such odd quirks every time. Use getAttributeNS, createElementNS, setAttributeNS, etc. rather than getAttribute, createElement, setAttribute, etc. -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://4Suite.org http://fourthought.com Use CSS to display XML - http://www.ibm.com/developerworks/edu/x-dw-x-xmlcss-i.html Introducing the Amara XML Toolkit - http://www.xml.com/pub/a/2005/01/19/amara.html Be humble, not imperial (in design) - http://www.adtmag.com/article.asp?id=10286UBL 1.0 - http://www-106.ibm.com/developerworks/xml/library/x-think28.html Manage XML collections with XAPI - http://www-106.ibm.com/developerworks/xml/library/x-xapi.html Default and error handling in XSLT lookup tables - http://www.ibm.com/developerworks/xml/library/x-tiplook.html Packaging XSLT lookup tables as EXSLT functions - http://www.ibm.com/developerworks/xml/library/x-tiplook2.html From jeff at ccvcorp.com Tue Jan 4 19:10:22 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 04 Jan 2005 16:10:22 -0800 Subject: Lambda as declarative idiom In-Reply-To: References: Message-ID: <10tmbqt2u4hmg91@corp.supernews.com> Robert Brewer wrote: > Michael Spencer wrote: > >>I believe that this "possibility to postpone" divides into >>two related but separate concepts: controlling the moment >>of evaluation, and assembling the arguments required at >>that moment. They are both species of 'eval', but >>managing arguments is more specialized, because it includes >>possibly renaming parameters, assigning default values, >>processing positional and keyword arguments, and, perhaps >>in the future dealing with argument types. > > Yes, but the "moment of evaluation" is more complex than just > "postponing". In a declarative construct, you probably also want global > variables to be bound early, so that the expression does not depend upon > *any* free variables. Ditto for closures. A more realistic example: > > term = input("Enter the amount to add") > e = expr(x): x + term > > ...MUCH code passes, maybe even a new process or thread... > > d = a + e(3) I see this as simply a combination of both of the aforementioned concepts -- argument control plus moment-of-evaluation control. Jeff Shannon Technician/Programmer Credit International From dial#####$#$#NOSPAM####$$##$tone at gmail.com Thu Jan 6 10:25:23 2005 From: dial#####$#$#NOSPAM####$$##$tone at gmail.com (Valentino Volonghi aka) Date: Thu, 6 Jan 2005 16:25:23 +0100 Subject: Nevow Tutorial and sample app References: <1105016703.493588.308570@z14g2000cwz.googlegroups.com> Message-ID: <1gpz6lc.i8e84x16qg22N%dial#####$#$#NOSPAM####$$##$tone@gmail.com> wrote: > Can any one redirect me to a good nevow tutorial and/or a an appliction > that is niether too big nor too small and can be help in learning > nevow. Nevow tutorial with the distrubution is too simple and it You should probably look at all the examples in the latest svn release. I've made some changes on the way examples directory work and now you can run all the examples by just running: twistd -noy examples.tac It will create a local webserver at http://localhost:8080/ with an index of all the examples (in difficulty order) with colored browseable source code and the live example. Plus you can access each sample application's (like the blog engine or the interactive chat server, or the pastebin) source code. Examples should scale well from very simple and basic hello world to very sophisticated ones like the blog engine which uses also xmlrpc and smtp protocols, or live pages like chatola. -- Valentino Volonghi aka Dialtone Now Running MacOSX 10.3.7 Blog: http://vvolonghi.blogspot.com http://weever.berlios.de From qvx3000 at yahoo.com Fri Jan 28 18:03:34 2005 From: qvx3000 at yahoo.com (Qvx) Date: 28 Jan 2005 15:03:34 -0800 Subject: Daylight savings and getmtime Message-ID: <8b2d5523.0501281503.253269@posting.google.com> Hello, I'we written a simple web deployment program which scans for the changes made to local copy of web site. Changed files are than packaged into a zip file and deployed to web server. Now here's the catch. Changes are computed using (1) log file from the last deployment and (2) local file system. Log file contains datestamps (integers) returned from os.path.getmtime(f) function at the time of last deployment. So i'm comparing two getmtime() values. The problem is when Daylight saving kicks in: suddenly all local files are reported as older than they were at the time of deployment. How do I compensate for this? Thanks, Tvrtko For those curious, here is the script. I apologize for Croatian comments and literals and missing private libraries, but I think the code is self-explanatory. ______________ # -*- coding: windows-1250 -*- from os.path import getmtime, join from os import walk, rename from zipfile import ZipFile, ZIP_DEFLATED from sets import Set from StringIO import StringIO from ftplib import FTP from qvx.io import adapt_stdout, unadapt_stdout from qvx.composite import Dot from qvx.compositeutil import read_composite import sys import time class DeploymentError(Exception): pass class Deployer: def __init__ (self, cfg_file): self.reset(cfg_file) def reset (self, cfg_file): self.read_cfg(cfg_file) self.local_files = [] self.remote_files = [] self.new_files = [] self.deleted_files = [] self.newer_files = [] self.older_files = [] self.www_all_time = None self.old_deployed = False def read_cfg (self, cfg_file): tree = read_composite(cfg_file) self.cfg = Dot(tree).DEPLOYMENT def prepare_file_lists (self): # Sastavi popis _datoteka_ u DIR direktoriju. # Izostavi datoteke iz _notes direktorija self.local_files = [] for root, dirs, files in walk(self.cfg.DIR): filtered = [join(root, f).replace('\\', '/') for f in files if f not in self.cfg.SKIP_FILES] self.local_files.extend(filtered) for skip_dir in self.cfg.SKIP_DIRS.split(','): if skip_dir.strip() in dirs: dirs.remove(skip_dir) # Sastavi popis datoteka na serveru # Koristi se sa informacijama od zadnjeg deploymenta # Popis se nalazi u www_all.txt datoteci self.remote_files = [] remote_stamps = {} zip = ZipFile(self.cfg.FILE, 'r') for line in zip.read('www_all.txt').split('\n'): name, stamp = line.split('\t') remote_stamps[name] = int(stamp) self.remote_files.append(name) self.www_all_time = zip.getinfo('www_all.txt').date_time # Deployment nije obavljen ako nije zapisan log self.old_deployed = 'deployment.log' in zip.namelist() zip.close() # Rastavi datoteke u tri kategorije: nove, obrisane i iste lset = Set(self.local_files) rset = Set(self.remote_files) self.new_files = list(lset - rset) self.deleted_files = list(rset - lset) common_files = list(lset & rset) # Pogledaj ?to se promijenilo u zajedničkim datotekama self.newer_files = [] self.older_files = [] for name in common_files: remotetime = remote_stamps[name] localtime = getmtime(name) #+ 3600 # Ako je razlika unutar sekunde, zanemari if abs(remotetime-localtime) > int(self.cfg.IGNORE_SEC): if remotetime > localtime: self.older_files.append(name) elif localtime > remotetime: self.newer_files.append(name) def need_redeployment (self): return not self.old_deployed def check_changes (self): # Ne bi trebalo biti starijih if self.older_files: raise DeploymentError('Ne smije biti starijih datoteka!') if not (self.new_files or self.deleted_files or self.newer_files): raise DeploymentError('Nema promjena!') def make_deployment_file (self): # Uključi potrebne datoteke deployment = ZipFile('new_'+self.cfg.FILE, 'w', ZIP_DEFLATED) for name in self.new_files + self.newer_files: deployment.write(name) # Uključi popis svih datoteka all_files = '\n'.join([f+'\t'+str(getmtime(f)) for f in self.local_files]) deployment.writestr('www_all.txt', all_files) # Uključi popis datoteka za obrisati for_delete = '\n'.join(self.deleted_files) if for_delete: deployment.writestr('www_delete.txt', for_delete) deployment.close() print '\nNapravljena je nova deployment datoteka.' # Preimenuj deployment datoteke timestr = '%04d-%02d-%02d_%02d-%02d-%02d' % self.www_all_time old_deployment = self.cfg.FILE.replace('.zip', '_'+timestr+'.zip') rename(self.cfg.FILE, old_deployment) rename('new_'+self.cfg.FILE, self.cfg.FILE) print 'Stara deployment datoteka se sada zove', old_deployment def exec_ftp (self, silent, logtext, func, *arg): try: self.ftp_log = self.ftp_log + '\n\n' + logtext self.ftp_log = self.ftp_log + '\n' + func(*arg) return 'OK' except Exception, e: self.ftp_log = self.ftp_log + '\n' + str(e) if not silent: raise DeploymentError(str(e)) return 'ERROR' def deploy_ftp (self): self.ftp_log = '' # Spoji se na FTP server print '\nSpajam se na ftp server %s ...' % (self.cfg.SERVER,), try: ftp = FTP(self.cfg.SERVER) print 'OK' except Exception, e: print 'ERROR' raise DeploymentError('Ne mogu se spojiti na FTP server: '+str(e)) # Logiraj se print 'Logiram se kao %s ... ' % (self.cfg.USER,), print self.exec_ftp(False, 'LOGIN', ftp.login, self.cfg.USER, self.cfg.PASSWORD) # Kopiraj datoteke deployment = ZipFile(self.cfg.FILE, 'r') deployment_files = [n for n in deployment.namelist() if n not in ['www_all.txt', 'www_delete.txt', 'deployment.log']] if deployment_files: print '?aljem datoteke:' for name in deployment_files: bytes = deployment.read(name) fp = StringIO(bytes) print ' ', name, len(bytes), ' bytes ...', print self.exec_ftp(True, 'STORBIN '+name, ftp.storbinary, 'STOR '+name, fp) fp.close() # Obri?i datoteke if 'www_delete.txt' in deployment.namelist(): deleted_files = deployment.read('www_delete.txt').split('\n') print 'Bri?em datoteke:' for name in deleted_files: print ' ', name, '...', print self.exec_ftp(True, 'DEL '+name, ftp.delete, name) deployment.close() # Bye bye print 'Zavr?avam s radom ...', print self.exec_ftp(True, 'BYE', ftp.quit) # Ispi?i FTP log print '\nFTP log:' print '-'*20, print self.ftp_log def write_log (self, text): # Zapi?i deployment log deployment = ZipFile(self.cfg.FILE, 'a', ZIP_DEFLATED) deployment.writestr('deployment.log', text) deployment.close() def run_interactively (self): # Adaptiraj stdout: mijenja kodnu stranicu u cp852 radi ispisa # hrvatskih grafema, također logira sve poruke ofa = adapt_stdout('cp852', True) try: try: # Analiziraj datoteke self.prepare_file_lists() print '*'*5, 'Obrisani', '*'*5, self.deleted_files print '*'*5, 'Novi ', '*'*5, self.new_files print '*'*5, 'Noviji ', '*'*5, self.newer_files print '*'*5, 'Stariji ', '*'*5, self.older_files if self.need_redeployment(): # Pitaj korisnika da li ?eli poslati od prije pripremljeni deployment na server yn = raw_input('\nOd prije pripremljeni deployment nije obavljen.\n>>> Da li ?elite taj deployment poslati na server? [y/N]: ') if yn.lower().strip() == 'y': self.deploy_ftp() self.write_log(''.join(ofa._log)) else: self.check_changes() # Pitaj korisnika da li ?eli napraviti deployment datoteku yn = raw_input('\n>>> Da li ?elite pripremiti deployment? [y/N]: ') if yn.lower().strip() == 'y': desc = raw_input('\n>>> Upi?ite kratki opis: ') print '\nOpis:', desc self.make_deployment_file() # Pitaj korisnika da li ?eli poslati deployment na server yn = raw_input('\n>>> Da li ?elite poslati deployment na server? [y/N]: ') if yn.lower().strip() == 'y': self.deploy_ftp() self.write_log(''.join(ofa._log)) except DeploymentError, e: print str(e) finally: # Vrati stari stdout unadapt_stdout(ofa) if __name__ == '__main__': deployer = Deployer('hpk.ini') deployer.run_interactively() x = raw_input('\n[Pritisnite Enter ...] ') sys.exit(0) From mt at 3planes.com Mon Jan 31 18:23:55 2005 From: mt at 3planes.com (Michael Tobis) Date: 31 Jan 2005 15:23:55 -0800 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1107188359.375703.110590@f14g2000cwb.googlegroups.com> <1gr9lyc.1rrm543162uefN%aleaxit@yahoo.com> Message-ID: <1107213835.138613.117620@c13g2000cwb.googlegroups.com> This is definitely a wart: ... z = 42.3 ... ... def f(): ... if False: ... global z ... z = -666 ... ... f() ... print z From http Tue Jan 11 11:49:52 2005 From: http (Paul Rubin) Date: 11 Jan 2005 08:49:52 -0800 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> Message-ID: <7xu0pndi6n.fsf@ruckus.brouhaha.com> Alexander Schremmer <2004b at usenet.alexanderweb.de> writes: > > I need to set up a wiki for a small group. I've played with MoinMoin > > a little bit and it's reasonably straightforward to set up, but > > limited in capabilities and uses BogusMarkupConventions. > > At which point do you see limitations? It doesn't have features that MW has, like user pages, lists of incoming links to wiki pages, automatic discussion links for every wiki page, automatic update notification for specific pages of your choice, support for managing image uploads and embedding them into wiki pages, etc. etc. > And what of the markup don't you like? The BogusMixedCaseLinkNames. I'd rather have ordinary words with spaces between them, like we use in ordinary writing. > > In the larger world, though, there's currently One True wiki package, > > namely Mediawiki (used by Wikipedia). > > It is just very famous because of Wikipedia IMHO. Well, it's gotten a lot more development attention because of that same Wikipedia. > Having a DBMS backend is good in your opinion? It has some severe > disadvantages like not easy to scale (you would need to setup DBMS > replication), two potential points of failure, more complex setup, bigger > memory requirements, etc. I didn't say that it was good, in fact I was listing it as a disadvantage there. I think for a small wiki like I was discussing, it's just an extra administrative hassle. For a large wiki though, MoinMoin's approach is completely unworkable and MoinMoin's documentation actually says so. First of all MoinMoin uses a separate subdirectory for every page, and all those subdirs are in a flat top level directory, so if you have 100,000 wiki pages, the top level directory has that many subdirs. Most file systems are not built to handle such large directories with any reasonable speed. (Also, every revision has its own file in the subdir. Lots of Wikipedia pages have thousands of revisions). Second, DBMS's have indexes and transactions, that make it simple to have features like "what links here". Yes you could do something like that in MoinMoin with additional files, but then you'd have to update multiple files when you commit a change, which can leave stuff inconsistent if there's a crash partway through the update (I wonder just how crash-resilient MoinMoin is right now, even). The DBMS can also handle stuff like replication automatically. > If you really want to use the wiki for content, you have to agree on > a markup style. You could use an independent one (like > RestructuredText) and hope that MediaWiki supports it (MoinMoin > does). Or you end up writing complex migration scripts just for the > markup. I looked at RestructuredText once and hated it. WikiMedia's markup language has bogosities just like anything else, but for the most part it's not too bad. Anyway, lots more people are used to it than any other Wiki markup language, just because of Wikipedia's popularity. > > Is anyone here actually running Mediawiki who can say just how > > big a hassle it is? > > A few months I tried to install it. I got it running. But I did not like > the necessary complex administration tasks. I'm not too surprised. That's why MoinMoin was the first one I tried. > > The other one will be public and is planned grow to medium size (a few > > thousand active users) > > There are even MoinMoin sites that are as big as that. Maybe you should > rethink your kind of prejudice and re-evaluate MoinMoin. I don't doubt there are MoinMoin sites that size, but with that large a user base, I want something nicer looking than those StupidMixedCasePageNames. From itsme at yahoo.com Mon Jan 3 14:53:59 2005 From: itsme at yahoo.com (It's me) Date: Mon, 03 Jan 2005 19:53:59 GMT Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: Well, now that they are API based, they can easily add any script language they so wish through SWIG (www.swig.org). Maybe not LISP. SNOBOL would be the right thing to do. (*NOT*) "Richards Noah (IFR LIT MET)" wrote in message news:crc699$l24$1 at athen03.muc.infineon.com... > > > > It was actually developed in Fortran some 35 years ago. Then migrated to > > F77. Then added a C/C++ layer to sit ontop. Then converted to API > based. > > Then added a Python layer on top. > > > > The only thing unfortunate is that they went with MFC on the newest > version. > > Yuck! > > > > Hahaha, sounds like a party to me. And they didn't even throw in a layer of > Lisp for good effort? Too bad, if you ask me :) > > From daranrife at yahoo.com Fri Jan 28 19:16:00 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 16:16:00 -0800 Subject: LinearAlgebra incredibly slow for eigenvalue problems In-Reply-To: <1106957598.136667.45430@z14g2000cwz.googlegroups.com> References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> <1106952951.834888.65430@f14g2000cwb.googlegroups.com> <1106957598.136667.45430@z14g2000cwz.googlegroups.com> Message-ID: <1106957760.485860.104760@f14g2000cwb.googlegroups.com> David, One more thing. I checked to see if the SciPy libraries had dependencies on ATLAS. They do not, however, the eigenvector calculation is still much faster than Numeric? This is very strange. Daran From fu.limin.tao at gmail.com Thu Jan 27 17:42:51 2005 From: fu.limin.tao at gmail.com (Limin Fu) Date: Thu, 27 Jan 2005 23:42:51 +0100 Subject: ANN: Tao Scripting Language 0.8.5 beta released! In-Reply-To: <397cc8578b5e9adf0e31f18ffa556593@gmail.com> References: <397cc8578b5e9adf0e31f18ffa556593@gmail.com> Message-ID: I only looked at languages which are more often used in bioinformatics, at that time I didn't heard about Lua. I knew it about 2 or 3 months after I began to implement Tao. For Io, this is my first time to hear about it :) Cheers, Limin On Thu, 27 Jan 2005 23:02:45 +0100, PA wrote: > > On Jan 27, 2005, at 22:54, Limin Fu wrote: > > > I found that, a language with simple syntax, convenient text > > processing functionality, powerful numeric computation capability, and > > simple C/C++ interfaces would be very useful > > You bet. > > Have you looked at Lua? > > http://www.lua.org/about.html > > Or perhaps Io? > > http://www.iolanguage.com/About/ > > Cheers > > -- > PA, Onnay Equitursay > http://alt.textdrive.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Homepage for Tao Language: http://taoscript.sourceforge.net Tao Language project at sourceforge.net: http://sourceforge.net/projects/taoscript From zyqnews at 163.net Sat Jan 29 22:10:33 2005 From: zyqnews at 163.net (zyqnews at 163.net) Date: 29 Jan 2005 19:10:33 -0800 Subject: nedd help on using Installer Message-ID: <1107054633.283242.43930@f14g2000cwb.googlegroups.com> hello: I am using Install to create a standalone program for linux. What I has done is : [Installer]$cd source/linux [linux]$python Make.py [linux]$make [Installer]$cd ../../ [Installer]$python Configure.py [Installer]$python Makespec.py hello.py [Installer]$python Build.py hello Traceback (most recent call last): File "Build.py", line 823, in ? build(sys.argv[1]) File "Build.py", line 25, in build rthooks = eval(open(os.path.join(HOMEPATH, 'rthooks.dat'), 'r').read()) File "", line 1 { ^ SyntaxError: invalid syntax What is this? What is wrong? Please help me. Thanks From newsgroups at jhrothjr.com Mon Jan 3 12:32:13 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 3 Jan 2005 11:32:13 -0600 Subject: How can engineers not understand source-code control? (was: The Industry choice) References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> <41d8417e$0$14596$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: <10tj0cqfkor680c@news.supernews.com> > In article <41d8417e$0$14596$ed2619ec at ptn-nntp-reader01.plus.net>, > Mark Carter wrote: > . > . > . >>Don't start me! Dammit, too late ... ... >>Honestly, I thought (real) engineers were supposed to be clever. You might want to read this: http://alistair.cockburn.us/crystal/articles/teoseatsoecg/theendofsoftwareengineering.htm His thesis is very simple: engineering took a wrong turn after WW II, and the people who coined the term "software engineering" didn't have a clue. Of course, he puts it a bit more diplomatically, but he's got the data to demonstrate that software engineering is an oxymoron. John Roth From jeff at ccvcorp.com Thu Jan 13 14:40:52 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 13 Jan 2005 11:40:52 -0800 Subject: finding/replacing a long binary pattern in a .bin file In-Reply-To: <41e6293f.725257715@news.oz.net> References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> <41e6293f.725257715@news.oz.net> Message-ID: <10udjc3fmnhro9d@corp.supernews.com> Bengt Richter wrote: > BTW, I'm sure you could write a generator that would take a file name > and oldbinstring and newbinstring as arguments, and read and yield nice > os-file-system-friendly disk-sector-multiple chunks, so you could write > > fout = open('mynewbinfile', 'wb') > for buf in updated_file_stream('myoldbinfile','rb', oldbinstring, newbinstring): > fout.write(buf) > fout.close() What happens when the bytes to be replaced are broken across a block boundary? ISTM that neither half would be recognized.... I believe that this requires either reading the entire file into memory, to scan all at once, or else conditionally matching an arbitrary fragment of the end of a block against the beginning of the oldbinstring... Given that the file in question is only a few tens of kbytes, I'd think that doing it in one gulp is simpler. (For a large file, chunking it might be necessary, though...) Jeff Shannon Technician/Programmer Credit International From steve at holdenweb.com Mon Jan 10 19:54:04 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Jan 2005 19:54:04 -0500 Subject: python3: 'where' keyword In-Reply-To: <7xllb1jsdz.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> <7xllb2f3z4.fsf@ruckus.brouhaha.com> <1105355380.040837.189270@c13g2000cwb.googlegroups.com> <7xis65a5w6.fsf@ruckus.brouhaha.com> <1105357839.696387.309900@c13g2000cwb.googlegroups.com> <7xr7kt314a.fsf@ruckus.brouhaha.com> <1105364925.848973.73080@c13g2000cwb.googlegroups.com> <7xllb1jsdz.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Carl Banks" writes: > >>When I asked you to do this, it was just a rhetorical way to tell you >>that I didn't intend to play this game. It's plain as day you're >>trying to get me to admit something. I'm not falling for it. >> >>If you have a point to make, why don't you just make it? > > > You asked me to compare the notion of macros with the Zen list. I did > so. I didn't see any serious conflict, and reported that finding. > Now you've changed your mind and you say you didn't really want me to > make that comparison after all. > Well I for one disagreed with many of your estimates of the zen's applicability to macros, but I just couldn't be arsed saying so. > An amazing amount of the headaches that both newbies and experienced > users have with Python, could be solved by macros. That's why there's > been an active interest in macros for quite a while. It's not clear > what the best way to do design them is, but their existence can have a > profound effect on how best to do these ad-hoc syntax extensions like > "where". Arbitrary limitations that are fairly harmless without > macros become a more serious pain in the neck if we have macros. > This is not a justifiable assertion, IMHO, and if you think that newbies will have their lives made easier by the addition of ad hoc syntax extensions then you and I come from a different world (and I suspect the walls might be considerably harder in mine than in yours). > So, we shouldn't consider these topics separately from each other. > They are likely to end up being deeply related. I don't really understand why, if macros are so great (and you are reading the words of one who was using macros back in the days of Strachey's GPM) why somebody doesn't produce a really useful set of (say) M4 macros to prove how much they'd improve Python. Now that's something that would be a bit less ignorable than this apparently interminable thread. regards Steve PS: Your continued use of the NOSPAM.invalid domain is becoming much more irritating than your opinions on macros in Python. Using a bogus URL is piling crap on top of more crap. -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From davidf at sjsoft.com Fri Jan 7 01:31:08 2005 From: davidf at sjsoft.com (David Fraser) Date: Fri, 07 Jan 2005 08:31:08 +0200 Subject: Python evolution: Unease In-Reply-To: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> References: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Carlos Ribeiro wrote: > ... > >>wish I could simply plug & play DBAPI modules in a totally seamlessly >>way. Anyone who tried know how far are we of this dream. > > > If you manage to get there, you'll start fighting against the different > dialects of SQL supported by the various back-ends, as is well known by > anybody who tried, say, ODBC or ADO, which do manage good plug&play of > their components but still can't solve the real hard one:-( I've found I can get by nicely by just supporting stock standard bottom end SQL and not using any database-specific features. Just requires a little wrapper code for some functions David From pythongnome at hotmail.com Sun Jan 9 16:36:08 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Sun, 09 Jan 2005 21:36:08 GMT Subject: Old Paranoia Game in Python In-Reply-To: References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> Message-ID: Aahz wrote: > In article <5JcEd.1988$KJ2.907 at newsread3.news.atl.earthlink.net>, > Lucas Raab wrote: > >>Sean P. Kane wrote: >> >>>I ported the old (and long since removed) game from the bsd-game pacakge >>>called, Paranoia, based on the old Paranoia role playing game from C to >>>Python as a simple exercise in learning the language and pure late night >>>boredom. Anyways, here it is for anyone looking for a few minutes of >>>nostalgia. I may get around to posting this at >>>http://homepage.mac.com/spkane/ or http://www.spkane.org/, but for now >>>here it is. Improvements or corrections, welcome. >> >> >> >>>Equipment: Red Reflec Armour, Laser Pistol, Laser Barrel (red), >>> Notebook & Stylus, Knife, Com Unit 1, Jump suit, >>> Secret Illuminati Eye-In-The-Pyramid(tm) Decoder ring, >>> Utility Belt & Pouches >>>=============================================================================== >> >> >> >>The Illuminati really have infiltrated our society. > > > Stay alert! > Trust no one! > Keep your laser handy! Well, I really meant "Secret Illuminati Eye-In-The-Pyramid(tm) Decoder ring", but if you wanted to go in another direction... From http Mon Jan 10 19:21:56 2005 From: http (Paul Rubin) Date: 10 Jan 2005 16:21:56 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> <7xu0ppyjjg.fsf@ruckus.brouhaha.com> <9yzEd.9081$wZ2.6859@newssvr13.news.prodigy.com> Message-ID: <7xr7ksrf17.fsf@ruckus.brouhaha.com> "Roose" writes: > Well, then of course you know I have to say: An OS does not run inside a > browser. There's a sentence I never thought I'd utter in my lifetime. > > So that is an irrelevant example, since it obviously isn't a task scheduler > in the context of this thread. Huh? I'm just baffled why you think writing a scheduler in an OS is harder than writing one in an application. You have some means of doing a coroutine switch in one situation, and some means of doing a hardware context switch in the other. Aside from that the methods are about the same. Why do you think there's anything difficult about doing this stuff in Python, given the ability to call low level routines for some hardware operations as needed? From kbk at shore.net Sun Jan 16 14:24:37 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Sun, 16 Jan 2005 14:24:37 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200501161924.j0GJObqo029011@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 272 open ( +5) / 2737 closed (+10) / 3009 total (+15) Bugs : 793 open ( -5) / 4777 closed (+29) / 5570 total (+24) RFE : 165 open ( +0) / 141 closed ( +1) / 306 total ( +1) New / Reopened Patches ______________________ Enhance tracebacks and stack traces with vars (2005-01-08) http://python.org/sf/1098732 opened by Skip Montanaro Single-line option to pygettext.py (2005-01-09) http://python.org/sf/1098749 opened by Martin Blais improved smtp connect debugging (2005-01-11) CLOSED http://python.org/sf/1100140 opened by Wummel Log gc times when DEBUG_STATS set (2005-01-11) http://python.org/sf/1100294 opened by Skip Montanaro deepcopying listlike and dictlike objects (2005-01-12) http://python.org/sf/1100562 opened by Bj?rn Lindqvist ast-branch: fix for coredump from new import grammar (2005-01-11) http://python.org/sf/1100563 opened by logistix datetime.strptime constructor added (2005-01-12) http://python.org/sf/1100942 opened by Josh Feed style codec API (2005-01-12) http://python.org/sf/1101097 opened by Walter D?rwald Patch for potential buffer overrun in tokenizer.c (2005-01-13) http://python.org/sf/1101726 opened by Greg Chapman ast-branch: hacks so asdl_c.py generates compilable code (2005-01-14) http://python.org/sf/1102710 opened by logistix Fix for 926423: socket timeouts + Ctrl-C don't play nice (2005-01-15) http://python.org/sf/1102879 opened by Irmen de Jong Boxing up PyDECREF correctly (2005-01-15) CLOSED http://python.org/sf/1103046 opened by Norbert Nemec AF_NETLINK sockets basic support (2005-01-15) http://python.org/sf/1103116 opened by Philippe Biondi Adding the missing socket.recvall() method (2005-01-16) http://python.org/sf/1103213 opened by Irmen de Jong tarfile.py: fix for bug #1100429 (2005-01-16) http://python.org/sf/1103407 opened by Lars Gust?bel Patches Closed ______________ pydoc data descriptor unification (2004-04-17) http://python.org/sf/936774 closed by jlgijsbers xml.dom missing API docs (bugs 1010196, 1013525) (2004-10-21) http://python.org/sf/1051321 closed by jlgijsbers Fix for bug 1017546 (2004-08-27) http://python.org/sf/1017550 closed by jlgijsbers fixes urllib2 digest to allow arbitrary methods (2005-01-04) http://python.org/sf/1095362 closed by jlgijsbers Bug fix 548176: urlparse('http://foo?blah') errs (2003-03-30) http://python.org/sf/712317 closed by jlgijsbers bug fix 702858: deepcopying reflexive objects (2003-03-22) http://python.org/sf/707900 closed by jlgijsbers minor codeop fixes (2003-05-15) http://python.org/sf/737999 closed by jlgijsbers SimpleHTTPServer reports wrong content-length for text files (2003-11-10) http://python.org/sf/839496 closed by jlgijsbers improved smtp connect debugging (2005-01-11) http://python.org/sf/1100140 closed by jlgijsbers Boxing up PyDECREF correctly (2005-01-15) http://python.org/sf/1103046 closed by rhettinger New / Reopened Bugs ___________________ socket.setdefaulttimeout() breaks smtplib.starttls() (2005-01-08) http://python.org/sf/1098618 opened by Matthew Cowles set objects cannot be marshalled (2005-01-09) CLOSED http://python.org/sf/1098985 opened by Gregory H. Ball codec readline() splits lines apart (2005-01-09) CLOSED http://python.org/sf/1098990 opened by Irmen de Jong Optik OptionParse important undocumented option (2005-01-10) http://python.org/sf/1099324 opened by ncouture refman doesn't know about universal newlines (2005-01-10) http://python.org/sf/1099363 opened by Jack Jansen raw_input() displays wrong unicode prompt (2005-01-10) http://python.org/sf/1099364 opened by Petr Prikryl tempfile files not types.FileType (2005-01-10) CLOSED http://python.org/sf/1099516 opened by Frans van Nieuwenhoven copy.deepcopy barfs when copying a class derived from dict (2005-01-10) http://python.org/sf/1099746 opened by Doug Winter Cross-site scripting on BaseHTTPServer (2005-01-11) http://python.org/sf/1100201 opened by Paul Johnston Scripts started with CGIHTTPServer: missing cgi environment (2005-01-11) http://python.org/sf/1100235 opened by pacote Frame does not receive configure event on move (2005-01-11) http://python.org/sf/1100366 opened by Anand Kameswaran Wrong "type()" syntax in docs (2005-01-11) http://python.org/sf/1100368 opened by Facundo Batista TarFile iteration can break (on Windows) if file has links (2005-01-11) http://python.org/sf/1100429 opened by Greg Chapman Python Interpreter shell is crashed (2005-01-12) http://python.org/sf/1100673 opened by abhishek test_fcntl fails on netbsd2 (2005-01-12) http://python.org/sf/1101233 opened by Mike Howard test_shutil fails on NetBSD 2.0 (2005-01-12) CLOSED http://python.org/sf/1101236 opened by Mike Howard dict subclass breaks cPickle noload() (2005-01-13) http://python.org/sf/1101399 opened by Neil Schemenauer popen3 on windows loses environment variables (2005-01-13) http://python.org/sf/1101667 opened by June Kim popen4/cygwin ssh hangs (2005-01-13) http://python.org/sf/1101756 opened by Ph.E % operator bug (2005-01-14) CLOSED http://python.org/sf/1102141 opened by ChrisF rfc822 Deprecated since release 2.3? (2005-01-14) http://python.org/sf/1102469 opened by Wai Yip Tung pickle files should be opened in binary mode (2005-01-15) http://python.org/sf/1102649 opened by John Machin Incorrect RFC 2231 decoding (2005-01-15) http://python.org/sf/1102973 opened by Barry A. Warsaw raw_input problem with readline and UTF8 (2005-01-15) http://python.org/sf/1103023 opened by Casey Crabb send/recv SEGMENT_SIZE should be used more in socketmodule (2005-01-16) http://python.org/sf/1103350 opened by Irmen de Jong Bugs Closed ___________ typo in "Python Tutorial": 1. Whetting your appetite (2005-01-08) http://python.org/sf/1098497 closed by jlgijsbers xml.dom documentation omits hasAttribute, hasAttributeNS (2004-08-16) http://python.org/sf/1010196 closed by jlgijsbers xml.dom documentation omits createDocument, ...DocumentType (2004-08-21) http://python.org/sf/1013525 closed by jlgijsbers Documentation of DOMImplmentation lacking (2004-07-15) http://python.org/sf/991805 closed by jlgijsbers wrong documentation for popen2 (2004-01-29) http://python.org/sf/886619 closed by jlgijsbers test_inspect.py fails to clean up upon failure (2004-08-27) http://python.org/sf/1017546 closed by jlgijsbers weird/buggy inspect.getsource behavious (2003-07-11) http://python.org/sf/769569 closed by jlgijsbers SimpleHTTPServer sends wrong Content-Length header (2005-01-07) http://python.org/sf/1097597 closed by jlgijsbers urllib2: improper capitalization of headers (2004-07-19) http://python.org/sf/994101 closed by jlgijsbers urlparse doesn't handle host?bla (2002-04-24) http://python.org/sf/548176 closed by jlgijsbers set objects cannot be marshalled (2005-01-09) http://python.org/sf/1098985 closed by rhettinger codec readline() splits lines apart (2005-01-09) http://python.org/sf/1098990 closed by doerwalter tempfile files not types.FileType (2005-01-10) http://python.org/sf/1099516 closed by rhettinger for lin in file: file.tell() tells wrong (2002-11-29) http://python.org/sf/645594 closed by facundobatista Py_Main() does not perform to spec (2003-01-21) http://python.org/sf/672035 closed by facundobatista Incorrect permissions set in lib-dynload. (2003-02-04) http://python.org/sf/680379 closed by facundobatista Apple-installed Python fails to build extensions (2005-01-04) http://python.org/sf/1095822 closed by jackjansen test_shutil fails on NetBSD 2.0 (2005-01-12) http://python.org/sf/1101236 closed by jlgijsbers CSV reader does not parse Mac line endings (2003-08-16) http://python.org/sf/789519 closed by andrewmcnamara Bugs in _csv module - lineterminator (2004-11-24) http://python.org/sf/1072404 closed by andrewmcnamara % operator bug (2005-01-14) http://python.org/sf/1102141 closed by rhettinger test_atexit fails in directories with spaces (2003-03-18) http://python.org/sf/705792 closed by facundobatista SEEK_{SET,CUR,END} missing in 2.2.2 (2003-03-29) http://python.org/sf/711830 closed by loewis CGIHTTPServer cannot manage cgi in sub directories (2003-07-28) http://python.org/sf/778804 closed by facundobatista double symlinking corrupts sys.path[0] (2003-08-24) http://python.org/sf/794291 closed by facundobatista popen3 under threads reports different stderr results (2003-12-09) http://python.org/sf/856706 closed by facundobatista Signals discard one level of exception handling (2003-07-15) http://python.org/sf/771429 closed by facundobatista build does not respect --prefix (2002-10-27) http://python.org/sf/629345 closed by facundobatista urllib2 proxyhandle won't work. (2001-11-30) http://python.org/sf/487471 closed by facundobatista RFE Closed __________ popen does not like filenames with spaces (2003-07-20) http://python.org/sf/774546 closed by rhettinger From elephantum at dezcom.mephi.ru Sun Jan 9 05:51:49 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 13:51:49 +0300 Subject: python3: accessing the result of 'if' In-Reply-To: <1105236383.521393.40680@c13g2000cwb.googlegroups.com> References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> <1105236383.521393.40680@c13g2000cwb.googlegroups.com> Message-ID: <34cgm6F468o4tU1@individual.net> Carl Banks wrote: > As a compromise, howabout: > > . if m > 20 where m=something(): > . do_something_with(m) That's good, but first idea was about 'where' block that contains any expressions, that we need, for example function definition. the syntax you proposed has same problems as 'lambda'. > The main problem here (as some would see it) is that you can't do > something this: > > . if m > 20 where (def m(): a(); b()): exactly From maxm at mxm.dk Fri Jan 7 17:31:54 2005 From: maxm at mxm.dk (Max M) Date: Fri, 07 Jan 2005 23:31:54 +0100 Subject: Returning same type as self for arithmetic in subclasses Message-ID: <41df0d7b$0$190$edfadb0f@dread12.news.tele.dk> # -*- coding: latin-1 -*- """ I subclass datetime and timedelta >>> dt = myDatetime(1970,1,1) >>> type(dt) >>> td = myTimedelta(hours=1) >>> type(td) But when I do arithmetic with these classes, they return datetime and timedelta, where I want them to return myDatetime and myTimedelta >>> new_time = dt + td >>> new_time datetime.datetime(1970, 1, 1, 1, 0) >>> type(new_time) So I wondered if there was a simlpler way to coerce the result into my desired types rather than overwriting the __add__, __sub__ etc. methods? """ from datetime import datetime, timedelta class myDatetime(datetime): pass class myTimedelta(timedelta): pass if __name__ == "__main__": import os.path, doctest, dtime # import and test this file doctest.testmod(dtime) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From skip at pobox.com Mon Jan 31 14:55:36 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 31 Jan 2005 13:55:36 -0600 Subject: [ANN] Spike Asset Manager release 0.13 In-Reply-To: <1107196878.026930.154270@c13g2000cwb.googlegroups.com> References: <1107196878.026930.154270@c13g2000cwb.googlegroups.com> Message-ID: <16894.36152.345508.583247@montanaro.dyndns.org> Matt> Spike Asset Manager (SAM) is an open-source cross-platform Matt> framework written in python for probing a system for components Matt> and reporting them. Matt, That's a pretty generic description. Pardon my ignorance, but what's the advantage over, for example, "rpm -aq | grep httpd"? -- Skip Montanaro skip at mojam.com http://www.mojam.com/ From rbt at athop1.ath.vt.edu Mon Jan 10 13:42:05 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 10 Jan 2005 13:42:05 -0500 Subject: ftplib with unknown file names In-Reply-To: References: Message-ID: Jeremy Jones wrote: > rbt wrote: > >> How can I use ftplib to retrieve files when I do not know their names? >> I can do this to get a listing of the directory's contents: >> >> ftp_server.retrlines('LIST') >> >> >> The output from this goes to the console and I can't figure out how to >> turn that into something I can use to actually get the files (like a >> list of file names). I read a bit about the callback function that can >> be passed to retrlines but I couldn't figure out how to use it. >> >> Any help is appreciated. >> >> Thanks! > > > .nlst(argument) will return a list of file names. Here are > the docs for the nlst command: > > http://www.python.org/doc/current/lib/ftp-objects.html > > > HTH, > > Jeremy Jones Very good Jeremy! Thank you for pointing that out. It works great. From mt at 3planes.com Sun Jan 30 12:10:22 2005 From: mt at 3planes.com (Michael Tobis) Date: 30 Jan 2005 09:10:22 -0800 Subject: Coding style article with interesting section on white space In-Reply-To: <1107059169.510996.262480@z14g2000cwz.googlegroups.com> References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> Message-ID: <1107105022.827941.114510@c13g2000cwb.googlegroups.com> beliavsky at aol.com wrote: > Michael Tobis wrote: > > (unwisely taking the bait...) > > > > If you like your language to look like this > > http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html > > then more power to you. > > Thanks for pointing out that interesting article on Fortran 90 bugs. > How long would a comparable C++ list be? Even Python has gotchas, for > example the difference between deep and shallow copies. The reply "C++ is even worse", while debatable either way, seems to be a common response from Fortran defenders. It misses the point. What the scientific community needs, whether they know it or not, is high-performance Python if that's possible, or something as close to it as possible. Specifically, something with serious introspective power and economy of expression. > > I prefer my languages to be portable, terse and expressive. > > Fortran programmers are generally happy with the portability of the > language. Until they try to port something...? Honestly, I can't imagine where anyone would get this impression. Now, about the terseness and expressiveness? > For scientific computation, consider the case of Numeric > and Numarray. I'm not happy with these, because they either make temporary arrays with wild abandon, or enforce an unnatural style of expression. I could see how they would be useful to others but they are awkward in long-time spatially coarse finite difference/finite volume/spectral calculations, which is the problem space I care about. As for non-coarse (finite element) integrations (where rectangular decompositions do not suffice) it seems to me that using Fortran is sheer madness, even though there are real pointers now. I do not suggest that Python is currently competitive with C++ or Fortran. I simply agree with http://www.fortranstatement.com that something new ought to be designed, that a backward compatible Fortran2003 cannot possibly be it, and that attention to fortran diverts resources from teh osrt of genuine progress that ought to be possible. > The recent "Pystone Benchmark" message says that Python is only 75% as > fast on Linux as on Windows. Fortran programs do not suffer this > performance hit and are in this respect more portable. In theory, as > has been mentioned, one could use a faster compiler to compile CPython > on Linux, but AFAIK this has not yet been done. Without disagreeing with Alex Martelli's response to this, I find it nonsensical on other grounds. Performance portability has nothing to do with what I'm talking about. The answer belies the attitude that programmers are there to put in time and expend effort, because the only resource worth considering is production cycles on a big machine. This attitude explains why working with Fortran is so unpleasant an experience for anyone who has been exposed to other languages. An alternative attitude is that the amount of human effort put into solving a problem is a relevant factor. In this view, "portability" is actually about build effort, not runtime performance. Perhaps the Fortran community finds this idea surprising? Getting a python package working usually amounts to an install command to the OS and an import command to the interpreter. Then you can get down to work. Getting a Fortran package working involves not only an endless dance with obscure compiler flags and library links, but then a set of workarounds for codes that produce expected results on one compiler and compile failures or even different results on another. The day when project cost was dominated by machine time as opposed to programmer time is coming to a close. Fortran is a meaningful solution only to the extent that programmer time is not just secondary but actually negligible as a cost. The assumption that portability is somehow about performance belies total lack of concern for the programmer as a resource, and therefore to the time-to-solution of any new class of scientific problem. The result of this habit of thought (entirely appropriate to 1955) is that in an environment where fortran is expected, new problems are interpreted as changes to old problems, and the packages become vast and bloated. Since most of these legacy codes in practice predate any concept of design-for-test, they are also almost certainly wrong, in the sense that they are unlikely to implement the mathematics they purport to implement. Usually they are "close enough" for some purposes, but it's impossible to delimit what purposes are inside or outside the range of application. > Nobody is stopping Python developers from working on projects like > Psyco. They aren't helping either, for the most part. Psyco aside, institutions that ought to be supporting development of high-performance high-expressiveness scientific languages are not doing so. Institutions with a Fortran legacy base are confused between maintaining the existing investment and expanding it. The former is frequently a mistake already, but the latter is a mistake almost always. This mistake drives investment of effort in inefficient directions, where efficiency is about design and build cost-to-solution rather than runtime cost-of-execution. > So uninterested in interoperability is the Fortran standards committee > that they added interoperability with C in Fortran 2003 standard. Er, replaced the modest C interoperability they lost in F90, right? The codes I care about aren't new ones. So now I have to hack into the code and redeclare all my arrays, right? So that they'll have a defined structure? And hope that doesn't break some other assumptions? Except that I have to await someone actually releasing an F03 compiler, right? Thanks. It turns out that I need a compiler, not a specification, unfortunately. Even so, I understood that there was some resistance to even this level of interoperability, because it breaks the Fortran no-convention convention. C-interop vapor-mode will require, (oh horror!) a specification for which bytes represent what. Now each vendor will have to try to patch that back in to their idiosyncratic representation. They'll probably get it mostly right, eventually. > > Python fundamentally respects the programmer. > > What does that mean? > If you don't know by now, don't mess with it. mt From apardon at forel.vub.ac.be Thu Jan 13 08:33:02 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jan 2005 13:33:02 GMT Subject: Unclear On Class Variables References: Message-ID: Op 2005-01-13, harold fellermann schreef : > Hi Tim, > > If you have > > class Foo(object) : > x = 0 > y = 1 > > foo = Foo() > > foo.x # reads either instance or class attribute (class in this case) > > foo.x = val # sets an instance attribute (because foo is instance not > class) > > Foo.x = val # sets a class attribute > foo.__class.__x = val # does the same > > this might be sometimes confusing. IMHO, the following is especially > nasty: > > >>> foo = Foo() > >>> foo.x += 1 > >>> > >>> print foo.x > 1 > >>> print Foo.x > 0 > > although the += operator looks like an inplace add it isn't. > it is just syntactic sugar for foo.x = foo.x + 1. Except is x belongs to a mutable class that implements the += operator as an inplace add. Try the same but with x = [2] and foo.x += [3] -- Antoon Pardon From sara_fwd at yahoo.com Sat Jan 15 08:10:23 2005 From: sara_fwd at yahoo.com (Sara Fwd) Date: Sat, 15 Jan 2005 05:10:23 -0800 (PST) Subject: How can I get the names of the files in a directory? Message-ID: <20050115131023.36656.qmail@web50501.mail.yahoo.com> Can you guys also help me find a module that looks in a directory and print out the names of the files in there? __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail From f.geiger at vol.at Sat Jan 29 03:24:56 2005 From: f.geiger at vol.at (F. GEIGER) Date: Sat, 29 Jan 2005 09:24:56 +0100 Subject: boa constructor & mysql References: <2005012900090816807%mikybNO@SPAMinterfreeit> Message-ID: Look at the wx demos. Another idea: Use a virtual list control. In the OnGetItemText() you could do the appropriate SQL query. Workedpretty well for me. HTH Franz GEIGER "Michele" schrieb im Newsbeitrag news:2005012900090816807%mikybNO at SPAMinterfreeit... > I've search a lot to found how visualize a mysql table in a gui (wxpython). > I think to use wxgrid to visualize this table...but I don't know how... > > Anyone help me? > > Thanks a lot for the patience. > > Michele > From douardda at free.fr Sat Jan 29 13:29:41 2005 From: douardda at free.fr (David Douard) Date: Sat, 29 Jan 2005 19:29:41 +0100 Subject: Independence of programs! References: Message-ID: <41fbd33a$0$28942$636a15ce@news.free.fr> blade8472 wrote: > > Hey all, hope all is fine, I have a question; I am new in python > programming, I write the programs to a text doc then I run them with > the interpreter, so I wanna know whether I can save the programs as > exe so that they can be run independently on other PCs without the > python interpreter. > hope you help me, thanks alot! If you are under Microsoft Windows (which I guess, according your question), you may use py2exe ( http://starship.python.net/crew/theller/py2exe/ ). It will do all the required stuff for you to have a standalone executable. David From dwyoon at TpuruninfoD.TcoD.Tkr Wed Jan 5 01:36:30 2005 From: dwyoon at TpuruninfoD.TcoD.Tkr (Daewon YOON) Date: Wed, 05 Jan 2005 15:36:30 +0900 Subject: % operation Message-ID: ==== Python 1.5.2 (#1, Jul 5 2001, 03:02:19) [GCC 2.96 20000731 (Red Hat Linux 7.1 2 on linux-i386 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> x=9 >>> y=4 >>> x%y 1 >>> for z in range(44): ... z%9 File "", line 2 z%9 ^ SyntaxError: invalid syntax ==== What's wrong with the above operation and how can I get the correct modulo result with Python? -- ZOO-< From morphex at gmail.com Thu Jan 13 13:45:25 2005 From: morphex at gmail.com (morphex) Date: 13 Jan 2005 10:45:25 -0800 Subject: Creating text on images In-Reply-To: References: <1105591796.422252.190990@f14g2000cwb.googlegroups.com> Message-ID: <1105641925.111934.53400@c13g2000cwb.googlegroups.com> Yes, something like that. I was a bit confused when it came to using truetype fonts, but that was straightforward enough (just pass font objects to the text method). :) From hans at zephyrfalcon.org Tue Jan 4 11:46:21 2005 From: hans at zephyrfalcon.org (Hans Nowak) Date: Tue, 04 Jan 2005 11:46:21 -0500 Subject: Python evolution: Unease In-Reply-To: <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Iwan van der Kleyn wrote: > > >>to be determine the way foreward for Python: more features, increased >>complexity, less dynamism. Lots of syntax crud, without addressing the > > > As a student of human nature, I'm _really_ curious as to how one could > possibly read the key document: > http://www.python.org/peps/pep-3000.html > and think in consequence of "more features, increased complexity". > > Also, you keep talking about "the core python team" on the basis, it > would appear, of reading one document by Guido. Have you bothered doing > a MINIMUM of homework, such as, looking at > http://www.amk.ca/diary/archives/cat_python.html > and specifically AMK's entry for September 30? I'm trying to understand > whether you completely missed doing the most elementary amount of > background searching before venting on the group, or if you did find and > read the obvious documents and somehow STILL manage to completely ignore > their contents or read them as saying exactly the opposite of what they > _do_ say... Optimistic documents about a cleaner and smaller language (and an improved stdlib) are all well and good, but if you look what has actually been happening to Python over the last few years, then the OP's worries don't seem so far-fetched. "More features, increased complexity, less dynamism" pretty much sums it up. Guido's posts about optional static typing seem to suggest that this development will continue in the same vein. (He may just be putting his thoughts on paper, but it's the BDFL, so what is one supposed to think?) I for one will NOT welcome our new static typing overlords. ;-) -- Hans Nowak http://zephyrfalcon.org/ From steve at holdenweb.com Fri Jan 14 11:03:36 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 11:03:36 -0500 Subject: import problems *newbie* In-Reply-To: <41e7959b$0$385$636a15ce@news.free.fr> References: <1105682316.601321.118820@f14g2000cwb.googlegroups.com> <41e7959b$0$385$636a15ce@news.free.fr> Message-ID: <41E7ED58.80908@holdenweb.com> F. Petitjean wrote: > Le 13 Jan 2005 21:58:36 -0800, mike kreiner a ?crit : > >>I am having trouble importing a module I created. I'm running PythonWin >>on Windows XP if that helps. I saved my module in a folder called >>my_scripts in the site-packages directory. I edited the python path to >>include the my_scripts folder (it now reads >>C:\Python23\Lib;C:\Python23\DLLs;C:\Python23\Lib\lib-tk;C:\Python23\Lib\site-packages\my_scripts). > > Not a very godd idea to mess with the python path > Furthermore it should not be necessary! >>When I try to import the module, I get this error: >> >> >>>>>from PolyDraw import * >> >>Traceback (most recent call last): >>File "", line 1, in ? >>ImportError: No module named PolyDraw >> OK, have your modifications to the path worked? Try adding import sys print sys.path before the import statement to verify what Python is actually using as the path. >>When I select Browse PythonPath from the tools menu, I'm able to locate >>my module, PolyDraw.py. >> >>The problem goes away if I open PolyDraw.py from PythonWin, which I'm >>assuming is because opening the module makes my_scripts the current >>working directory. This is just a quick workaround, but I'd like to >>know how to fix the problem. Thanks. > > A quick fix is to promote your my_scripts folder to be a python package, > by creating a python module (file) named __init__.py right in the > package directory. The content of __init__.py can be for instance The __init__.py can actually be completely empty, but surely then you'd have to import the module by from my_scripts import PolyDraw which is a little less convenient. It would be easier (and also easier than modifying the PYTHONPATH) just to create a .pth file (say C:\Python23\Lib\site-packages\my.pth) containing the single line my_scripts and that should ensure that the directory really *is* on your path. The *name* of the .pth file is irrelevant, and you can actually have several lines naming different directories (whose paths can be absolute, or relative to the directory containing the .pth file). Obviously you should check that the path's setting is correct using the technique allowed above. > #!/usr/bin/env python > # -*- coding: Latin-1 -*- > """ > my_scripts package containing miscellaneous modules > PolyDraw > .... > """ > __author__ = 'mike kreiner' > > To import from this package the syntax is > from my_scripts import PolyDraw > Let's not recommend this as a way around the problem - let's find out what the problem actually *is* and fix it ;-) regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From steve at holdenweb.com Wed Jan 26 09:13:22 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 26 Jan 2005 09:13:22 -0500 Subject: PyCon: Early Bird Deadline two days away [really]! Message-ID: Pythonistas: If you have been putting off your registration, stop putting it off! Last year the early bird deadline was extended because we were a little late getting the program together. This year the program was published two weeks in advance of the deadline for early bird registrations, which is JANUARY 28 (and it's already January 26). So, don't delay: save yourself $75 and register by midnight Friday. Which time zone, you ask. Why wait and find out - it only takes a couple of minutes to register. http://www.python.org/pycon/2005/register.html regards Steve Holden Chairman, PyCON DC 2005 -- PyCon DC 2005: The third Python Community Conference http://www.pycon.org/ http://www.python.org/pycon/ The scoop on Python implementations and applications From sjmachin at lexicon.net Sun Jan 9 18:43:15 2005 From: sjmachin at lexicon.net (John Machin) Date: 9 Jan 2005 15:43:15 -0800 Subject: Python3: on removing map, reduce, filter In-Reply-To: <-7mdndrwD_1qOHzcRVn-qQ@comcast.com> References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> <-7mdndrwD_1qOHzcRVn-qQ@comcast.com> Message-ID: <1105314195.310792.163170@c13g2000cwb.googlegroups.com> Steven Bethard wrote: > Note that list comprehensions are also C-implemented, AFAIK. Rather strange meaning attached to "C-implemented". The implementation generates the code that would have been generated had you written out the loop yourself, with a speed boost (compared with the fastest DIY approach) from using a special-purpose opcode LIST_APPEND. See below. >>> def afunc(n): ... return [x*x for x in xrange(n)] ... >>> afunc(3) [0, 1, 4] >>> import dis >>> dis.dis(afunc) 2 0 BUILD_LIST 0 3 DUP_TOP 4 STORE_FAST 1 (_[1]) 7 LOAD_GLOBAL 1 (xrange) 10 LOAD_FAST 0 (n) 13 CALL_FUNCTION 1 16 GET_ITER >> 17 FOR_ITER 17 (to 37) 20 STORE_FAST 2 (x) 23 LOAD_FAST 1 (_[1]) 26 LOAD_FAST 2 (x) 29 LOAD_FAST 2 (x) 32 BINARY_MULTIPLY 33 LIST_APPEND 34 JUMP_ABSOLUTE 17 >> 37 DELETE_FAST 1 (_[1]) 40 RETURN_VALUE >>> def bfunc(n): ... blist=[]; blapp=blist.append ... for x in xrange(n): ... blapp(x*x) ... return blist ... >>> bfunc(3) [0, 1, 4] >>> dis.dis(bfunc) 2 0 BUILD_LIST 0 3 STORE_FAST 3 (blist) 6 LOAD_FAST 3 (blist) 9 LOAD_ATTR 1 (append) 12 STORE_FAST 2 (blapp) 3 15 SETUP_LOOP 34 (to 52) 18 LOAD_GLOBAL 3 (xrange) 21 LOAD_FAST 0 (n) 24 CALL_FUNCTION 1 27 GET_ITER >> 28 FOR_ITER 20 (to 51) 31 STORE_FAST 1 (x) 4 34 LOAD_FAST 2 (blapp) 37 LOAD_FAST 1 (x) 40 LOAD_FAST 1 (x) 43 BINARY_MULTIPLY 44 CALL_FUNCTION 1 47 POP_TOP 48 JUMP_ABSOLUTE 28 >> 51 POP_BLOCK 5 >> 52 LOAD_FAST 3 (blist) 55 RETURN_VALUE >>> From philippecmartin at sbcglobal.net Sun Jan 30 10:19:22 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Sun, 30 Jan 2005 09:19:22 -0600 Subject: naive doc question Message-ID: <1107098362.7164.1.camel@localhost> Gabriel B. wrote: > Is it just me that can't find a full reference in the docs? > > I wanted a list of all the methods of dict for example... where can i > find it? > > Thanks, and sorry if this question is just dumb, i really can't find > it Also if you are using mozilla or firefox, I suggest you try this documentation sidebar: http://projects.edgewall.com/python-sidebar/ Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From http Mon Jan 10 05:17:24 2005 From: http (Paul Rubin) Date: 10 Jan 2005 02:17:24 -0800 Subject: Python serial data aquisition References: <41e1b833$1_3@omega.dimensional.com> Message-ID: <7x4qhpeggb.fsf@ruckus.brouhaha.com> fccoelho at gmail.com (Flavio codeco coelho) writes: > I'll put your Ideas to the test ASAP, meanwhile, could you point me to > references to these bit operations in Python? I am new to this stuff, > and might need to do more of this to support other hardware... > > I havent been able to find anything about this on the python > documentation.. ord(ch) turns a character into an integer, i.e. ord('a') = 97, etc. You can use the << (left shift), >> (right shift), | (logical or), and & (logical and) operations just like in C. So for your diagram |-------------bits(1-8)-----------| Byte1: x x x n1 n2 n3 n4 n5 Byte2: x n6 n7 n8 n9 n10 n11 n12 assuming n1 is the high order bit, you'd just say value = ((ord(byte1) & 0x1f) << 7) | (ord(byte2) & 0x3f) or something like that. From Danielnord15 at yahoo.se Sun Jan 2 06:47:49 2005 From: Danielnord15 at yahoo.se (Svennglenn) Date: 2 Jan 2005 03:47:49 -0800 Subject: Problems programming with Tkinter Message-ID: <1104666469.813371.204280@c13g2000cwb.googlegroups.com> Hi ! I'm trying to create a graphical program using Tkinter. The program is supposed to save a string the user defines as a filename. I've made it work with the the first button in the program that's named "Spara ett v?rde i en str?ng till ett filnamn", that's swedish for "Save a value in a string as a file name". The button "Skriv ett v?rde till filen" (swedish for "Write a value to the file") But, i want the program to open a new dialogue when i press the button "Visa ruta" and in that dialogue will be a field where you can enter a value directly in the program, but a can't get it to work because is don't know how i shall do to open a new dialogue window in the program? Is there someone who can help me with my problem? Here's the sourcecode for my program: from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.hi_there = Button(frame, text="Spara ett v?rde i en str?ng till ett filnamn", command=self.say_hi) self.hi_there.pack(side=LEFT) self.skriv_varde = Button(frame, text="Skriv ett v?rde till filen", command=self.skriv_varde) self.skriv_varde.pack(side=LEFT) self.visa_ruta = Button(frame, text="Visa ruta", command=self.visa_ruta) self.visa_ruta.pack(side=LEFT) def say_hi(self): print "Sparar fil" S = "filen.fil" output = open(S, 'w') print "Filen sparad" def skriv_varde(self): print "Skriver v?rde till filen" myfile = open('filen.fil', 'w') myfile.write('Ny mening') myfile.close() print "V?rdet till filen skrivet" def visa_ruta(self, parent): top = self.top = Toplevel(parent) Label(top, text="Value").pack() self.e = Entry(top) self.e.pack(padx=5) b = Button(top, text="OK", command=self.ok) b.pack(pady=5) def ok(self): print "value is", self.e.get() self.top.destroy() root = Tk() app = App(root) root.mainloop() From m-le-van-kiem at bordeaux-port.fr Thu Jan 13 09:49:33 2005 From: m-le-van-kiem at bordeaux-port.fr (Michel LE VAN KIEM) Date: Thu, 13 Jan 2005 15:49:33 +0100 Subject: How to install pyparallel Message-ID: <41e689fc$0$15700$626a14ce@news.free.fr> Hi everybody ! I'm trying to install the pyparallel module for my Python 2.3.4 (runs on a FC3) but I do have some troubles. When I import the parallel module, python shows the following message : >>> import parallel /usr/lib/python2.3/site-packages/parallel/parallelppdev.py:32: FutureWarning: x<>> p=parallel.Parallel() ppdev0: failed to register device ! ... IOError: [No such device or address] Some help would be appreciated. Michel From premshree.pillai at gmail.com Tue Jan 4 11:32:35 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Tue, 4 Jan 2005 22:02:35 +0530 Subject: Cookbook 2nd ed Credits (was Re: The Industry choice) In-Reply-To: <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> Message-ID: Do contributors of less than 5 recipes get a copy too? :-? Btw, is there a comprehensive list of ALL contributors put up anywhere? On Tue, 4 Jan 2005 17:15:53 +0100, Alex Martelli wrote: > wrote: > > > But then I have THREE published recipes!! > > Does that mean that I get three free copies of the cookbook ? ;-) > > ...ti piacerebbe eh...?-) Sorry, "one each", even though you have > _five_ credits. For the curious, here's the roster of most credited > contributors (remember, significant comments we merged into other's > recipes also count!-)...: > > 1: 42 u'Alex Martelli' > 2: 26 u'Raymond Hettinger' > 3: 25 u'Luther Blissett' > 4: 22 u'Peter Cogolo' > 5: 10 u'John Nielsen' > 6: 10 u'Anna Martelli Ravenscroft' > 7: 8 u'J\x9frgen Hermann' > 8: 7 u'Scott David Daniels' > 9: 7 u'Chris Perkins' > 10: 6 u'S\x8ebastien Keim' > 11: 6 u'Paul Prescod' > 12: 6 u'Noah Spurrier' > 13: 6 u'Jeff Bauer' > 14: 6 u'Holger Krekel' > 15: 6 u'Danny Yoo' > 16: 6 u'Brent Burley' > 17: 5 u'Paul Moore' > 18: 5 u'Michele Simionato' > 19: 5 u'Mark Nenadov' > 20: 5 u'David Eppstein' > 21: 5 u'Brian Quinlan' > > If you wished to count only _authored_ recipes (but that's a bit > misleading, since in several recipes-as-published there is a merge of > two or three separately submitted and accepted recipes, and here I'm > counting only the first-listed-author per published-recipe...): > > 1: 25 u'Luther Blissett' > 2: 21 u'Alex Martelli' > 3: 9 u'John Nielsen' > 4: 8 u'Raymond Hettinger' > 5: 8 u'J\x9frgen Hermann' > 6: 6 u'S\x8ebastien Keim' > 7: 6 u'Peter Cogolo' > 8: 6 u'Anna Martelli Ravenscroft' > 9: 5 u'Scott David Daniels' > 10: 5 u'Paul Prescod' > 11: 5 u'Michele Simionato' > 12: 5 u'Mark Nenadov' > 13: 5 u'Jeff Bauer' > 14: 5 u'Brent Burley' > > ...but each still gets ONE free copy...!-) > > Alex > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From pythongnome at hotmail.com Sat Jan 15 13:36:16 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Sat, 15 Jan 2005 18:36:16 GMT Subject: porting C code In-Reply-To: References: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> <0NidnetRONZTgHrcRVn-oQ@powergate.ca> Message-ID: Peter Hansen wrote: > Lucas Raab wrote: > >> Sorry, the third "byte" is what I meant. > > > Fair enough. Note, however, that as someone pointed out, > it's actually the *fourth* of something, and it would not > necessarily be a byte. In fact, in your case, it's not: > >> typedef unsigned long int word32 ; >> void mu(word32 *a) >> { >> int i ; >> word32 b[3] ; > > > This defines an array of *3* long (32-bit) integers. > >> b[0] = b[1] = b[2] = 0 ; > > > Each of these is just indexing into that array, starting > as Python does with an index origin of zero. > >> The "a[#]" and "b[#]" are the parts that are giving me trouble. > > > Between the clarifications you've got and Duncan's post, > you shouldn't have much more trouble now. :-) > > -Peter Thanks. From eino at iki.fi Tue Jan 11 10:12:39 2005 From: eino at iki.fi (=?ISO-8859-1?Q?Eino_M=E4kitalo?=) Date: Tue, 11 Jan 2005 17:12:39 +0200 Subject: Python 2.4 and os.open question? In-Reply-To: References: <41e3e670$0$20038$39db0f71@news.song.fi> Message-ID: <41e3ece8$0$25434$39db0f71@news.song.fi> Antoon Pardon wrote: > Why? What is it about the exclusive flag that > makes you like to use it? Ok. Thanks, I misunderstood the meaning of flag. What I' like to do is to open file and keep it exclusive locked for me. Apparently this flag is not for me. Eino M?kitalo From dbickett at gmail.com Sun Jan 23 14:24:50 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 23 Jan 2005 14:24:50 -0500 Subject: OT: problems mirroring python-list to c.l.py? In-Reply-To: <20050123190637.GA4820@grulic.org.ar> References: <1d6cdae305012310535980e82d@mail.gmail.com> <20050123190637.GA4820@grulic.org.ar> Message-ID: <1d6cdae305012311245658711c@mail.gmail.com> John Lenton wrote: > > On Sun, Jan 23, 2005 at 01:53:52PM -0500, Daniel Bickett wrote: > > > > > > Is there a reason that Google Groups isn't mirroring python-list > > > exactly like it used to, or is it simply a conspiracy I'm not in on? > > > > You should not ask this kind of question in a public forum, > > and *you* should know better than to go around flapping your mouth > like that. Now I'm further confused, because I don't know what you quoted, but it isn't on the mailing list and it isn't on c.l.py :) Maybe I should give up trying to figure these things out. You didn't include a name at the beginning of your citation... Who had the audacity to take my joke seriously? ;-) Daniel Bickett From sifu at isohypse.org Fri Jan 21 23:18:22 2005 From: sifu at isohypse.org (Siegmund Fuehringer) Date: Sat, 22 Jan 2005 12:18:22 +0800 Subject: list unpack trick? In-Reply-To: References: Message-ID: <20050122041822.GA8007@m.0xx0.net> On Fri, Jan 21, 2005 at 08:02:38PM -0800, aurora wrote: > I find that I use some list unpacking construct very often: > > name, value = s.split('=',1) > > So that 'a=1' unpack as name='a' and value='1' and 'a=b=c' unpack as > name='a' and value='b=c'. > > The only issue is when s does not contain the character '=', let's say it > is 'xyz', the result list has a len of 1 and the unpacking would fail. Is > there some really handy trick to pack the result list into len of 2 so > that it unpack as name='xyz' and value=''? what about: s.find( '=' )!=-1 and s.split( '=', 1 ) or [s,''] bye bye - sifu From mensanator at aol.com Sun Jan 9 19:52:46 2005 From: mensanator at aol.com (mensanator at aol.com) Date: 9 Jan 2005 16:52:46 -0800 Subject: Old Paranoia Game in Python In-Reply-To: References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> Message-ID: <1105318366.966577.107460@c13g2000cwb.googlegroups.com> Aahz wrote: > Trust the computer, the computer is your friend. However, the computer isn't a fuckin' mind reader. If you're going to post source code on the usenet, don't have lines longer than 72 characters. Otherwise you'll find your code has wrapped lines. This not only causes syntax errors in your choose and print statements but also fucks up the formatting of of printed paragraphs. Stupid human. From fumanchu at amor.org Fri Jan 21 02:08:35 2005 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 20 Jan 2005 23:08:35 -0800 Subject: Dejavu 1.3, a Python ORM Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339823A@exchange.hqamor.amorhq.net> The Dejavu Object-Relational Mapper (version 1.3) is now available and in the public domain. Get it at svn://casadeamor.com/dejavu/trunk or http://www.aminus.org/rbre/python/. Dejavu is an Object-Relational Mapper for Python applications. It is designed to provide the "Model" third of an MVC application. Dejavu avoids making decisions in the framework which are better left to developers, and avoids forcing developers to make decisions which are better left to deployers. In particular, deployers are allowed to mix and match storage mechanisms, including how and when to cache objects in memory, making it easier for deployers to tune applications to their particular environment. Dejavu provides: MODELING LAYER 1. A base Unit class for persisting objects to storage. 2. A base Unit Property class for persistent object attributes. 3. ID Sequencers. 4. Associations between Unit classes. 5. Unit Engines, Rules, and Collections. 6. Aggregation and analysis tools. APPLICATION LAYER 1. Expressions: pure Python Unit queries. This is perhaps the most appealing feature of Dejavu. However, since it uses bytecode hacks, Dejavu only runs on CPython. 2. Sandboxes, which serve as Identity Maps and per-connection caches. Unit objects are "memorized" and "recalled" from a Sandbox, using Expressions. 3. An Arena class for application-level data. STORAGE LAYER 1. A base StorageManager class and specification. Unlike many ORMs, Dejavu does not require you to have complete control of the back end. 2. Specific StorageManagers for: a. Microsoft SQL Server/MSDE via ADO. b. Microsoft Access (Jet) via ADO. c. PostgreSQL. d. MySQL. e. SQLite. f. ODBC databases (not complete, and probably never will be). g. Shelve to dbm. Major changes from 1.2: 1. Support for PostgreSQL, MySQL, and SQLite. 2. New db module which abstracts common DB StorageManager code. 3. Full support for decimal and fixedpoint. 4. zoo_fixture.py brings common tests to all StorageManagers. Dejavu welcomes your use and feedback as an application developer. Dejavu also welcomes framework developers. New code for additional Storage Managers, analysis tools, or other portions will be gladly reviewed for inclusion in future releases. Drop me an email if you feel so inclined. Robert Brewer MIS Amor Ministries fumanchu at amor.org From ricardo.b at zmail.pt Tue Jan 18 17:45:48 2005 From: ricardo.b at zmail.pt (Ricardo Bugalho) Date: Tue, 18 Jan 2005 22:45:48 +0000 Subject: simultaneous multiple requests to very simple database References: Message-ID: On Tue, 18 Jan 2005 17:33:26 -0500, Eric S. Johansson wrote: > When I look at databases, I see a bunch of very good solutions that are > either overly complex or heavyweight on one hand and very nice and simple > but unable to deal with concurrency on the other. two sets of point > solutions that try to stretch themselves and the developers to fit other > application contexts. > Have you considerded SQLite/pySQLite ? -- Ricardo From __peter__ at web.de Wed Jan 26 06:26:59 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Jan 2005 12:26:59 +0100 Subject: string.atoi and string.atol broken? References: <1106700417.482871.45140@z14g2000cwz.googlegroups.com> Message-ID: Christos TZOTZIOY Georgiou wrote: > On Wed, 26 Jan 2005 08:58:45 +0100, rumours say that Peter Otten > <__peter__ at web.de> might have written: > >>By the way, does anyone know the Greek name for 36? > > triakontahexadecimal would be a nice compromise of greek and the > "hexadecimal" convention of having six before ten -- "???" ("hexi") is > six, "????" ("deka") is ten, "?????????" ("triakonta") is thirty. I > think in ancient Greek sometimes units came before tens, just like in > German (another similarity is the verb in the end of the sentence, as > Mark Twain also noted sometime in a humourous article AFAIR.) > > In current Greek hexadecimal is "????????????" ("dekaexadikon"). The Latin part escaped me. Now we need unicode names in Python, and the fun can really begin. I had you in mind with my question, thank you. Peter From gabriel.barros at gmail.com Sun Jan 23 21:00:52 2005 From: gabriel.barros at gmail.com (Gabriel B.) Date: Mon, 24 Jan 2005 00:00:52 -0200 Subject: python newt under win32 Message-ID: <5175a81c05012318003ff66a46@mail.gmail.com> Anyone has any info if there's something similar to Newt lib for win32? Thanks Gabriel From devries at idolstarastronomer.com Mon Jan 31 10:49:29 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: Mon, 31 Jan 2005 10:49:29 -0500 Subject: how to find number of processors in python In-Reply-To: <822e8fe0.0501302113.4716c2ba@posting.google.com> References: <822e8fe0.0501302113.4716c2ba@posting.google.com> Message-ID: <20050131154928.GA10363@miyu.cjas.org> "/usr/sbin/psrinfo -p" will print the number of physical processors on the system, though it does not indocate if they are on- or off-line. You could also write an extension which gets processor information using the sys/processor library. Example code is available in the "p_online" man page. Chris From harold.fellermann at upf.edu Tue Jan 11 05:46:37 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 11 Jan 2005 11:46:37 +0100 Subject: here document In-Reply-To: References: Message-ID: <1166F26E-63BE-11D9-B3E0-003065FB7B26@upf.edu> On 11.01.2005, at 11:34, Nader Emami wrote: > Would somebody help me how i can write the 'here document' in > Python script please? I have a csh script in which a program > is invoked with some argument in the form of here document: > > /bin/exe.x << End_Here > CategorY = GRIB > etc. > End_Here > > I translate this script to Python and i don't know how can I > do this! f = open("/bin/exe.x","w") print >>f , """CategoryY = GRIB etc. """ -- What if nothing exists and everything is an illusion? In this case I definitely overpayed my new carpet! -- Woody Allen From danperl at rogers.com Sun Jan 23 10:24:20 2005 From: danperl at rogers.com (Dan Perl) Date: Sun, 23 Jan 2005 10:24:20 -0500 Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: "Xah Lee" wrote in message news:1106472508.591411.40140 at c13g2000cwb.googlegroups.com... > the beginning two paragraphs should be deleted. Nobody gives a shit > except a few smug academicians where the author wrote it for pleasing > himself. For 99% of readers, it is incomprehensible and irrelevant. > > the first paragraph of 9.1 "A Word About Terminology" is epitome of > masturbation. The entire 9.1 is not necessary. > > Large part of 9.2 "Python Scopes and Name Spaces" is again > masturbatory. This is a perfect description for your own postings. Why don't you follow your own advice? From philippecmartin at sbcglobal.net Wed Jan 5 05:14:02 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Wed, 05 Jan 2005 11:14:02 +0100 Subject: smtp question Message-ID: <1104920042.7006.30.camel@localhost> Hi, I am testing the smtp module and have the following question: in the code below (taken from net sample) prior to adding the "Subject:" field, the email client found the "From" and the "To". Without the "Subject:" field on I get this: Email client = Evolution: the "From" field is blank Email client = KMail: the "To" field is blank Any clue ? Thanks and regards, Philippe ********************** import smtplib def prompt(prompt): return raw_input(prompt).strip() fromaddr = prompt("From: ") toaddrs = prompt("To: ").split() print "Enter message, end with ^D (Unix) or ^Z (Windows):" # Add the From: and To: headers at the start! msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs))) while 1: try: line = raw_input() except EOFError: break if not line: break msg = msg + line print "Message length is " + repr(len(msg)) server = smtplib.SMTP('smtp.sbcglobal.yahoo.com') server.set_debuglevel(1) server.login ('xxxxx','yyyyyyy') server.sendmail(fromaddr, toaddrs, 'Subject:from python\n\n'+msg) server.quit() -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From http Sat Jan 22 07:40:25 2005 From: http (Paul Rubin) Date: 22 Jan 2005 04:40:25 -0800 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> <1gqsayh.th49i518ixczeN%aleaxit@yahoo.com> Message-ID: <7xpszxljra.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > If it changed the semantics of for-loops in general, that would be quite > inconvenient to me -- once in a while I do rely on Python's semantics > (maintaining the loop control variable after a break; I don't recall if > I ever used the fact that the variable is also maintained upon normal > termination). Some languages let you say things like: for (var x = 0; x < 10; x++) do_something(x); and that limits the scope of x to the for loop. That seems like a reasonable way to offer for-loops that don't leak. > (musing...): I think the reason there's no real use case for using a > listcomp's control variable afterwards is connected to this distinction: > listcomps have no `break'... Of course you can still break out of listcomps: class oops: pass def f(x): if x*x % 11 == 3: raise oops return x*x try: lcomp = [f(x) for x in range(10)] except oops: pass print x prints "5" From sara_fwd at yahoo.com Tue Jan 25 12:52:14 2005 From: sara_fwd at yahoo.com (Sara Fwd) Date: Tue, 25 Jan 2005 09:52:14 -0800 (PST) Subject: module for 'po' files Message-ID: <20050125175214.61327.qmail@web50507.mail.yahoo.com> Hi all Is there a module for processing & handling '.po' files in python? __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From ptmcg at austin.rr._bogus_.com Sun Jan 9 18:38:10 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 09 Jan 2005 23:38:10 GMT Subject: pyparsing: how to negate a grammar References: <1105229039.136595.180640@c13g2000cwb.googlegroups.com> <1105280829.930207.169770@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1105280829.930207.169770 at c13g2000cwb.googlegroups.com... > Hi Paul, > > I am trying to extract HTTP response codes from a HTTP page send from > a web server. Below is my test program. The program just hangs. > > Thanks, > Khoa > ################################################## > > Khoa - Thanks for supplying a little more information to go on. The problem you are struggling with has to do with pyparsing's handling or non-handling of whitespace, which I'll admit takes some getting used to. In general, pyparsing works its way through the input string, matching input characters against the defined pattern. This gets a little tricky when dealing with whitespace (which includes '\n' characters). In particular, restOfLine will read up to the next '\n', but will not go past it - AND restOfLine will match an empty string. So if you have a grammar that includes repetition, such as OneOrMore(restOfLine), this will read up to the next '\n', and then just keep matching forever. This is just about the case you have in your code, ZeroOrMore(BodyLine), in which BodyLine is BodyLine = Group(nonHTTP + restOfLine) You need to include something to consume the terminating '\n', which is the purpose of the LineEnd() class. Change BodyLine to BodyLine = Group(nonHTTP + restOfLine + LineEnd()) and this will break the infinite looping that occurs at the end of the first body line. (If you like, use LineEnd.suppress(), to keep the '\n' tokens from getting included with your other parsed data.) Now there is one more problem - another infinite loop at the end of the string. By similar reasoning, it is resolved by changing nonHTTP = ~Literal("HTTP/1.1") to nonHTTP = ~Literal("HTTP/1.1") + ~StringEnd() After making those two changes, your program runs to completion on my system. Usually, when someone has some problems with this kind of "line-sensitive" parsing, I recommend that they consider using pyparsing in a different manner, or use some other technique. For instance, you might use pyparsing's scanString generator to match on the HTTP lines, as in for toks,start,end in StatusLine.scanString(data): print toks,toks[0].StatusCode, toks[0].ReasonPhrase print start,end which gives [['HTTP/1.1', '200', ' OK']] 200 OK 0 15 [['HTTP/1.1', '400', ' Bad request']] 400 Bad request 66 90 [['HTTP/1.1', '500', ' Bad request']] 500 Bad request 142 166 If you need the intervening body text, you can use the start and end values to extract it in slices from the input data string. Or, since your data is reasonably well-formed, you could just use readlines, or data.split('\n'), and find the HTTP lines using startswith(). While this is a brute force approach, it will run certainly many times faster than pyparsing. In any event, best of luck using pyparsing, and write back if you have other questions. -- Paul From pas at demail.svp Tue Jan 18 15:32:10 2005 From: pas at demail.svp (arN) Date: Tue, 18 Jan 2005 21:32:10 +0100 Subject: Window capture using WM_PRINT and Python Message-ID: <41ed7017$0$23339$7a628cd7@news.club-internet.fr> Hi ! I'm a Java developper and I wish to make a capture of an offscreen window (on WinXP). It's not possible in Java, so I use a python script and WM_PRINT, but it doesn't seem to work. Could someone have a look at my script and give me any advise ? TIA -- Arnaud my python script : python snap.py GraphicalContext_handle image_handle -------------------------------------------------------------------------------------------------- snap.py : " import win32api, win32con, sys win32api.SendMessage(sys.argv[2], win32con.WM_PAINT, sys.argv[3], 0) win32api.SendMessage(sys.argv[2], win32con.WM_PRINT, sys.argv[3], win32con.PRF_CHILDREN | win32con.PRF_CLIENT | win32con.PRF_OWNED) " ------------------------------------------------------------------------------------------------ snippet from Snapshot.java : " public static Image snapshot(Composite bean) { GC gc = new GC(bean); final Image image = new Image (null, bean.getBounds().width, bean.getBounds().height); String commmand = "python snap.py " + gc.handle + " " + image.handle; Runtime rt = Runtime.getRuntime(); try { Process p = rt.exec(command); } catch (.....) gc.dispose(); return image; } " From steve at holdenweb.com Wed Jan 19 16:46:32 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Jan 2005 16:46:32 -0500 Subject: Zen of Python In-Reply-To: References: Message-ID: Peter Hansen wrote: > Timothy Fitz wrote: > >> While I agree that the Zen of Python is an amazingly concise list of >> truisms, I do not see any meaning in: >> >> Flat is better than nested. >> [incrdeibly secret PSU facts blurted out] > > And with that out of the way, one is left with "there's a balance > along the flat/nested dimension which is appropriate to any > given situation, so nest with moderation and only when necessary". > They'd probably been talking to Antoon Pardon :-) > But that didn't fit in the list so they went with the shorter version... > regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From aahz at pythoncraft.com Tue Jan 25 23:45:57 2005 From: aahz at pythoncraft.com (Aahz) Date: 25 Jan 2005 23:45:57 -0500 Subject: re Insanity References: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> Message-ID: In article <4ln9c2-0mh1.ln1 at eskimo.tundraware.com>, Tim Daneliuk wrote: > >Given an arbitrary string, I want to find each individual instance of >text in the form: "[PROMPT:optional text]" > >I tried this: > > y=re.compile(r'\[PROMPT:.*\]') > >Which works fine when the text is exactly "[PROMPT:whatever]" but >does not match on: > > "something [PROMPT:foo] something [PROMPT:bar] something ..." > >The overall goal is to identify the beginning and end of each [PROMPT...] >string in the line. > >Ideas anyone? Yeah, read the Friedl book. (Okay, so that's not gonna help right now, but trust me, if you're going to write lots of regexes, READ THAT BOOK.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From richie at entrian.com Tue Jan 11 12:15:48 2005 From: richie at entrian.com (Richie Hindle) Date: Tue, 11 Jan 2005 17:15:48 +0000 Subject: OT: MoinMoin and Mediawiki? In-Reply-To: <7xu0pndi6n.fsf@ruckus.brouhaha.com> References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> Message-ID: <9128u0pnvb9vm8630mk99k89l4e7oes5r9@4ax.com> [Paul] > [MoinMoin] doesn't have [...] automatic update notification for > specific pages of your choice Yes it does. See http://entrian.com/sbwiki for example - register there and you'll see in your preferences "Subscribed wiki pages (one regex per line)" > The BogusMixedCaseLinkNames. I'd rather have ordinary words with > spaces between them, like we use in ordinary writing. MoinMoin has an option to display WikiWords with spaces between them (albeit still capitalised), again in the user preferences. I'm not saying that MoinMoin is better than MediaWiki, just that it really does have some of the features you say it doesn't (perhaps you've been looking at an old version). -- Richie Hindle richie at entrian.com From irmen at -nospam-remove-this-xs4all.nl Sat Jan 15 23:06:47 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 16 Jan 2005 05:06:47 +0100 Subject: there's a socket.sendall(), so why no socket.recvall()? In-Reply-To: <41e03ccc$0$6208$e4fe514c@news.xs4all.nl> References: <41e03ccc$0$6208$e4fe514c@news.xs4all.nl> Message-ID: <41e9e854$0$6212$e4fe514c@news.xs4all.nl> Irmen de Jong wrote: >>> Subject says it all; >>> there's a socket.sendall(), so why no socket.recvall()? [...] > I may even write a patch for socketmodule.c right now :-D And here it is: the missing socket.recvall(). http://www.python.org/sf/1103213 --Irmen From gregor.jan at NOSPAM.quick.cz Thu Jan 27 07:53:45 2005 From: gregor.jan at NOSPAM.quick.cz (Jan Gregor) Date: Thu, 27 Jan 2005 13:53:45 +0100 Subject: redirect of standard output of jython to JTextArea In-Reply-To: References: Message-ID: problem solved. in class: sys.stdout = StdOutRedirector(self) class StdOutRedirector: def __init__(self, console): self.console = console def write(self, data): #print >> sys.stderr, ">>%s<<" % data if data != '\n': # This is a sucky hack. Fix printResult self.console.textArea.append(data) Jan Jan Gregor wrote: > Hello > > I want to redirect output of jython's functions print and println to > JTextArea component. Is it possible ? > > I tried this (swingConsole.textArea is instance): > > In my class > > self.printStream= MyPrintStream(System.out) > System.setOut(self.printStream) > > ---------------------------------------------------- > class MyPrintStream (PrintStream): > > def println (str): > swingConsole.textArea.append(str) > > def print (str): > swingConsole.textArea.append(str) > > > Output is still directed to standard output. > > > Thanks for help, > Jan From ksenia.marasanova at gmail.com Fri Jan 7 14:59:33 2005 From: ksenia.marasanova at gmail.com (Ksenia Marasanova) Date: Fri, 7 Jan 2005 21:59:33 +0200 Subject: escape string for command line Message-ID: <130df19305010711593b514714@mail.gmail.com> Hi, I have a simple ecard creation script on a website, where user can add text to a graphic. I use ImageMagick for it: # template_file => path to image template file # new_file => path to generated file # text => user input command = '''convert %s -font OfficinaSanITC-BookOS -pointsize 12 -fill "#8C2F48" -draw "gravity north text 0,26 '%s'" %s''' % ( template_file, text, new_file) system(command) I was wondering, is there a general way to escape the string entered by the user, to prevent code injection into command line? Will it always be safe, even when binary data is submitted through POST? Or maybe some stable Python interface for ImageMagick that takes care of it :) Thanks in advance, -- Ksenia From martinnitram at excite.com Wed Jan 19 01:12:39 2005 From: martinnitram at excite.com (martinnitram at excite.com) Date: 18 Jan 2005 22:12:39 -0800 Subject: safest way to kill a thread In-Reply-To: References: <1106106497.429643.307440@f14g2000cwb.googlegroups.com> Message-ID: <1106115159.200989.60870@c13g2000cwb.googlegroups.com> limodou wrote: >Using Thread's method setDaemon() before you call the start() method. >Just like : >t.setDaemon(True) >t.start() thank for fast reply. from python.org doc, said that setDaemon() function as "The entire Python program exits when no active non-daemon threads are left." is it mean that when the main program exit (normally/abnormally), all threads created will also exit? Thank again. From xah at xahlee.org Sun Jan 16 09:45:53 2005 From: xah at xahlee.org (Xah Lee) Date: 16 Jan 2005 06:45:53 -0800 Subject: [perl-python] 20050116 defining a function Message-ID: <1105886753.149519.194980@z14g2000cwz.googlegroups.com> ? # the following is a example of defining ? # a function in Python. ? ? def fib(n): ? """This prints n terms of a sequence ? where each term is the sum of previous two, ? starting with terms 1 and 1.""" ? result=[];a=1;b=1 ? for i in range(n): ? result.append(b) ? a,b=b,a+b; ? result.insert(0,1) ? del result[-1] ? return result ? ? print fib(6) ? ? # note the use of .insert to insert 1 at ? # the beginning of a list, and ?del ? # result[-1]? to remove the last element ? # in a list. Also, the string ? # immediately following the function ? # definition is the function's ? # documentation. ? ? # the unusual syntax of a.insert() is ? # what's known as Object Oriented syntax style. ? ? # try writing a factorial function. ? ? ------------------- ? # the equivalent perl version is this: ? ? =pod ? ? fib(n) prints n terms of a sequence where each ? term is the sum of previous two, ? starting with terms 1 and 1. ? ? =cut ? ? use strict; ? my @result; ? my ($a, $b); ? ? sub fib($) { ? my $n= @_[0]; ? @result=();$a=1;$b=1; ? for my $i (1..$n){ ? push @result, $b; ? ($a,$b)=($b,$a+$b); ? } ? unshift @result, 1; ? pop @result; ? return @result; ? } ? ? use Data::Dumper; ? print Dumper [fib(5)]; ? ? # the =pod and =cut ? # is perl's way of demarking inline ? # documentation called POD. ? # see ?perldoc -t perlpod? ? # note: the empty line around it ? # is necessary, at least in perl version ? # 5.6 up to ~2002. ? ? # the ?use strict;? is to make perl's ? # loose syntax stricter by enforcement. ? # Its use is encouraged by ? # perl gurus, but not all standard ? # packages use it. ? ? # the ?my? are used to declare variables. ? # necessary under ?use strict;? ? # see ?perldoc -t strict? ? ? # the $ in fib($) is there to declare ? # that fib has a parameter of one scalar. ? # Its use is however optional and uncommon. ? # it is used for clarity but ? # has also met with controversy by ? # perl gurus as being unperl. ? # see ?perldoc perlsub? for ref. ? ? # the @_[0] is the first element of the ? # array @_. The @_ array is a predefined ? # array, holding arguments to subroutines. ? # see ?perldoc -t perlvar? ? ? # see ? # perldoc -tf unshift ? # perldoc -tf pop ? ? # the last line, [fib(5)], is basically ? # to make it a memory address of a copy of ? # the list returned by fib(5), so that ? # Dumper can print it. ? # see ?perldoc -t perldata? or perlref ? # for unix-styled technicalities. ? ? Xah ? xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html From forall2see_2000 at yahoo.com Mon Jan 3 08:58:02 2005 From: forall2see_2000 at yahoo.com (forall2see_2000 at yahoo.com) Date: Mon, 03 Jan 05 13:58:02 GMT Subject: website hosting Message-ID: <0501031358025172@news.usenetmonster.com> here is the place that I host my websites with . If your still looking for a good host check out http://frontpage-web-hosting.org From steve at ferg.org Fri Jan 7 16:15:29 2005 From: steve at ferg.org (Steve) Date: 7 Jan 2005 13:15:29 -0800 Subject: Tkinter: using a Listbox In-Reply-To: References: Message-ID: <1105132529.319205.311720@z14g2000cwz.googlegroups.com> > #Listbox > self.listbox = Listbox(self.selectFrame) > self.listbox.insert(END, "a list entry") > for item in ["A","B","C"]: > self.listbox.insert(END, item) Don't forget to pack the listbox. You may find this useful... http://www.ferg.org/thinking_in_tkinter/index.html From news at outbacklinux.com Mon Jan 24 07:06:13 2005 From: news at outbacklinux.com (Adrian Casey) Date: Mon, 24 Jan 2005 21:36:13 +0930 Subject: short programming projects for kids References: <1106332638.595750.150590@c13g2000cwb.googlegroups.com> Message-ID: <41f4e4b5@duster.adelaide.on.net> Andr? Roberge wrote: > bobdc wrote: >> I will be teaching an "Introduction to Programming" class to some >> middle school aged children and will be using Python, obviously. Does >> anyone have suggestions for simple little programs to create and >> analyze with them after I get past turtle graphics? >> >> Turtle graphics will be plenty for the first session, and I will leave >> time to ask them what they'd like to do in later sessions, but I was >> curious if anyone on the list has experience picking pedagogical >> programming examples appropriate for twelve-year-olds' attention spans. >> thanks, >> >> Bob >> > While it is not python per se, I suggest you have a look at GvR > (Guido van Robot) (The app is written in Python but is too complicated > for beginners). It is hosted on sourceforge (gvr.sourceforge.net). > It is a very interesting way (imho) to learn about programming, in > a pythonic way. > > (somewhat shameless plug follows:) > A 'more advanced version' of GvR which uses the full Python syntax > is RUR-PLE (rur-ple.sourceforge.net). The version currently hosted > there does NOT work under Linux (untested on Mac). > It uses wxPython 2.4 and will not work with 2.5. > An updated release that will work under both Linux and Windows, > and under both wxPython 2.4 and 2.5 will come out very soon, I hope. > > I'm working on it :-) I have two kids (ages 11 and 13) and plan to use > rur-ple to teach them about programming. Note that, even though > I plan it to be suitable for motivated children (with some guidance), > the end product (to be finished in a year?) is planned to be suitable > for a complete first-year university computer science. > > Andre Roberge I started teaching my 11 year old first of all by doing silly stuff like -: for i in range(10): print "Silly me!" Moving on to more useful stuff like times tables (which they have to learn anyway). After times tables, I plan to work on a simple number guessing game where the computer picks a random number between 1 and 100 and asks the user to take a guess. This will help demonstrate many basic programming concepts. Not sure how to introduce graphics though as so much is relatively abstract. Adrian. From mike at hobbshouse.org Fri Jan 7 11:40:30 2005 From: mike at hobbshouse.org (Michael Hobbs) Date: Fri, 07 Jan 2005 16:40:30 -0000 Subject: Getting rid of "self." References: <740c3aec05010705393048a374@mail.gmail.com> Message-ID: <10tteru3bh91j48@corp.supernews.com> Nick Coghlan wrote: > > Wait for Python 3k when this will work: > > class c: > def __init__(self): > with self: > .x = 1 > .y = 2 > .hi = "Hi there!" Python is looking more like JavaScript every day... From bokr at oz.net Sat Jan 22 05:42:57 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 22 Jan 2005 10:42:57 GMT Subject: Class introspection and dynamically determining function arguments References: <41f18d10.1471646806@news.oz.net> Message-ID: <41f2212f.1509565800@news.oz.net> On Fri, 21 Jan 2005 20:23:58 -0500, "Mike C. Fletcher" wrote: > >>On Thu, 20 Jan 2005 11:24:12 -0000, "Mark English" wrote: >> >> >> >>>I'd like to write a Tkinter app which, given a class, pops up a >>>window(s) with fields for each "attribute" of that class. The user could >>>enter values for the attributes and on closing the window would be >>>returned an instance of the class. The actual application I'm interested >>>in writing would either have simple type attributes (int, string, etc.), >>>or attributes using types already defined in a c-extension, although I'd >>>prefer not to restrict the functionality to these requirements. >>> >>> >Hmm, I missed the original post, but I'll jump in anyway: > > This sounds a heck of a lot like a property-editing system. When > creating a property-modeled system, the best approach is normally to > use something that actually models the properties, rather than > trying to guess at the metadata involved by poking around in an > arbitrarily structured object. I agree that "poking around in an arbitrarily structured object" is not a likely road to satisfaction, but sometimes the arbitrary can be taken out an something pretty simple can be done ;-) OTOH, I probably should have mentioned that there are ways to view these kinds of problems from a longer perspective. E.g., I googled for "model view controller" and found a nice wiki page at http://wact.sourceforge.net/index.php/ModelViewController that may be worth reading for the OP, just for ideas. There is interesting discussion of many MVC-related issues, but I don't know anything about the associated project. > > My BasicProperty system allows for this kind of interaction > (property-sheets) using wxPython (rather than Tkinter) when using > wxoo. You declare classes as having a set of data-properties (which > can have defaults or not, constraints or not, restricted data-types > or not, friendly names or not, documentation or not). Normally you > create these classes as subclasses of a class that knows how to > automatically assign __init__ parameters to properties, and knows > how to tell (e.g.) wxoo about the properties of the class. Does the BasicProperty base class effectively register itself as an observer of subclass properties and automatically update widgets etc., a la Delphi data-driven visual components? I've thought of doing a light-weight form extension class that would use a text (maybe CSV) definition to control contruction, and easy programmatic manipulation by python of the definition parameters, like a stripped-down version of the text view of Delphi forms. It could also be done via Tkinter, to prototype it. It would be interesting to allow dragging widgets and edges around in Tkinter and round-trip the parameter changes automatically into the text representation. A little (well, ok, a fair amount ;-) further and you'd have a drag-n-drop GUI design tool. But don't hold your breath ;-) > > Those same property classes also allow for editing properties of > database rows in PyTable, but that isn't likely relevant to your > case. We've also used them internally to create a rather large > web-based property-editing mechanism (applied to such databases), > but again, not really relevant to the case at hand. Who knows, the OP may only be revealing his concerns about a small part of his great tapestry ;-) > >Anyway, if you aren't interested in BasicProperty for this task; another >project on which I work, PyDispatcher provides fairly robust mechanism >(called robustApply) for providing a set of possible arguments and using >inspect to pick out which names match the parameters for a function in >order to pass them in to the function/method/callable object. That >said, doing this for __init__'s with attribute values from an object's >dictionary doesn't really seem like the proper way to approach the problem. Sounds like a workaround for parameter passing that maybe should have been keyword-based? Regards, Bengt Richter From sylvain.thenault at nospam.logilab.fr Tue Jan 18 11:03:09 2005 From: sylvain.thenault at nospam.logilab.fr (Sylvain Thenault) Date: Tue, 18 Jan 2005 17:03:09 +0100 Subject: MemoryError with parser.suite and wrong encoding declaration References: Message-ID: On Tue, 18 Jan 2005 16:16:32 +0100, Thomas Heller wrote: > Sylvain Thenault writes: > >> Hi there ! >> I've noticed the following problem with python >= 2.3 (actually 2.3.4 >> and 2.4): >> >> syt at musca:test$ python >> Python 2.3.4 (#2, Sep 24 2004, 08:39:09) [GCC 3.3.4 (Debian 1:3.3.4-12)] >> on linux2 Type "help", "copyright", "credits" or "license" for more >> information. >>>>> import parser >>>>> parser.suite('# -*- coding: IBO-8859-1 -*-') >> Traceback (most recent call last): >> File "", line 1, in ? >> MemoryError >>>>> parser.suite('# -*- coding: ISO-8859-1 -*-') >> >> >> Shouldn't parser.suite just ignore the wrong encoding declaration, or at >> least raise a more appropriate exception. IMHO the first solution would >> be better, since that's the behaviour of the (C) python interpreter. > > Ignore the wrong declaration? All Python's that I have (on windows, at > least) raise a SyntaxError: > > File "x.py", line 1 > SyntaxError: 'unknown encoding: IBO-8859-1' hum, right (with python >= 2.3 which is the first release using those declaration...). I was sure to have checked this but I've obviously missed something. Maybe the fact that being able to parse it anyway is the solution I wish has driven me to write this ;) I would like this behaviour so that pylint can check a module with a wrong encoding declaration anyway. But at least, SyntaxError would be better than MemoryError. > See also: > > http://www.python.org/sf/979739 thanks -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From ncoghlan at iinet.net.au Sat Jan 15 11:27:00 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 16 Jan 2005 02:27:00 +1000 Subject: How to del item of a list in loop? In-Reply-To: <34s7omF4emdsaU1@individual.net> References: <34rvjqF4f6l70U1@individual.net> <34s7omF4emdsaU1@individual.net> Message-ID: <41E94454.3010309@iinet.net.au> Reinhold Birkenfeld wrote: > Addition: In Py2.4, I can't find a problem with > > for i in reversed(lst) Some poking around suggests it's fine - and it avoids copying the list. Don't delete anything earlier in the list than the current element though (which list.remove() will do quite happily when data is duplicated). However, there will still be data movement costs when deleting elements from the middle of the list. In addition, remove() itself has to do a linear search for the value being removed. An off-place solution based on a list comprehension is usually going to be your best performer - it's an O(n) operation, based on the size of the original list. The in-place mechanisms can turn out to be O(n**2) due to worst-case memory movement effects (lists don't allow gaps, so deleting items will usually trigger data movement). I think this is about the best you can do for an in-place version: for i, x in enumerate(reversed(lst)): if x == 2: del lst[-i] The effbot's version is still going to be faster though: lst = [x for x in lst if x != 2] Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From anthony.briggs at gmail.com Wed Jan 12 13:33:13 2005 From: anthony.briggs at gmail.com (Anthony) Date: Wed, 12 Jan 2005 13:33:13 -0500 Subject: counting items In-Reply-To: References: Message-ID: <532716200501121033c8597db@mail.gmail.com> On Wed, 12 Jan 2005 17:42:50 GMT, It's me wrote: > Okay, I give up. > > What's the best way to count number of items in a list? How long is a piece of string? There are many different ways, which give you different trade offs. > For instance, > > a=[[1,2,4],4,5,[2,3]] > > I want to know how many items are there in a (answer should be 7 - I don't > want it to be 4) > > I tried: > > b=len([x for y in a for x in y]) > > That doesn't work because you would get an iteration over non-sequence. And is very unreadable. > I tried: > > g=lambda x: (1,len(x))[isinstance(x,(list,tuple,dict))] > b=sum(lambda(x) for x in a) > > and that didn't work because I get a TypeError from the len function (don't > know why) Because you're trying to get the length of an integer, which is what's failing. If you know that the list nesting is only one deep, you can do something like: === #!/usr/local/bin/python compoundList = [[1,2,4],4,5,[2,3]] listLengths = [len(item) for item in compoundList if type(item) not in [int,long,str,float]] print listLengths compoundLength = len(compoundList) - len(listLengths) + sum(listLengths) print compoundLength === If the nesting is 2 deep or more, then the next two options that I would explore would be: 1. Have a look in the standard library. I'm pretty sure that there are list-manipulation libraries that'll do what you want (not sure on names, though). 2. Write a function to do what you want. Some sort of recursive thing should be pretty easy to write. Of course it depends on how fast you need to go, but that should give you a good first approximation. Anthony -- ----------------------------------------------------- HyPEraCtiVE? HeY, WhO aRE YoU cALliNg HypERaCtIve?! aNthONy.BrIGgS at gmAiL.CoM ----------------------------------------------------- From peter at engcorp.com Sun Jan 9 14:59:53 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jan 2005 14:59:53 -0500 Subject: windows mem leak In-Reply-To: References: <41XDd.70234$Jk5.40626@lakeread01> <41E06C18.6050407@hotmail.com> Message-ID: Roel Schroeven wrote: >> Peter Hansen wrote: >>> How have >>> you proven that it is not *that* program which is at fault?) > > It would surprise me: even if it consumes much CPU-time, memory and > other resources, each instances returns all resources when it exits. I agree with that statement, but you assume that the program *is* exiting. And your initial analysis with "fake_nmap" suggests that, at least to the extent of having leftover cmd.exe's kicking around, maybe it is not. -Peter From gilles.no.lenfant.spam at ingeniweb.com Thu Jan 27 07:57:02 2005 From: gilles.no.lenfant.spam at ingeniweb.com (Gilles Lenfant) Date: Thu, 27 Jan 2005 13:57:02 +0100 Subject: how to pass attribute name via sys.argv In-Reply-To: <41f8e31a$1@idnews.unizh.ch> References: <41f8e31a$1@idnews.unizh.ch> Message-ID: Felix Hebeler a ?crit : > Hi all, > I am doing some Python scripting for a while, but I'm not too deep into > it yet. So I have a problem I can't solve. > > I need to call an object attribute: > > value = object.attrName[0] > > the problem is, that the attribute name can only be specified at runtime. > > So what I have is something like > > >>> attrName = sys.argv[1] > >>> attrName > 'cellsize' > > and I need to pass it on so I can call > > value = object.cellsize[0] > > > Can this be done using Python? > > Thanks for any hints > > Cheers > Felix The builtin "setattr" is your friend. "object" is now a reserved (builtin) name, use "objekt" instead. class Foo(object): pass objekt = Foo() attrName = sys.argv[1] values = ['foo', 'bar', 'whatever'] setattr(objekt, attrName, values) HTH -- Gilles From michel.levankiem at free.fr Thu Jan 13 15:58:37 2005 From: michel.levankiem at free.fr (Michel LE VAN KIEM) Date: Thu, 13 Jan 2005 21:58:37 +0100 Subject: How to install pyparallel In-Reply-To: References: <41e689fc$0$15700$626a14ce@news.free.fr> Message-ID: <41e6e0fa$0$11935$636a15ce@news.free.fr> The ppdev module is loaded and the lp module is unloaded, but I still have the error message. I used 'lsmod | grep ppdev' to check it. Is it necessary to plug the parallel cable ? Peter Hansen a ?crit : > Michel LE VAN KIEM wrote: > >> >> I'm trying to install the pyparallel module for my Python 2.3.4 (runs >> on a FC3) but I do have some troubles. >> >> >>> p=parallel.Parallel() >> ppdev0: failed to register device ! >> ... >> IOError: [No such device or address] >> >> Some help would be appreciated. > > > Did you read the notes in the parallelppydev.py file's > Parallel class? I suspect they may be of some help... > > (I don't see any other significant documentation of > pyParallel, so I'm not sure where else one would look > for assistance.) > > Also, perhaps one of these threads would be of help: > http://groups.google.ca/groups?q=parallel+ppdev0+failed+to+register+device > > -Peter From tconnors at no.spam.accepted.here-astro.swin.edu.au Wed Jan 12 00:45:08 2005 From: tconnors at no.spam.accepted.here-astro.swin.edu.au (TimC) Date: Wed, 12 Jan 2005 05:45:08 GMT Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: On Wed, 12 Jan 2005 at 02:06 GMT, humblythegreatest at usa.com (aka Bruce) was almost, but not quite, entirely unlike tea: > python.org = 194.109.137.226 > > 194 + 109 + 137 + 226 = 666 > > What is this website with such a demonic name and IP address? What > evils are the programmers who use this language up to? Writing code that has to be indented *exactly* or it just won't work. I bet they all use eVIl VI too. -- TimC -- http://astronomy.swin.edu.au/staff/tconnors/ A new verb was accidently created during a discussion about KDE 3 and Debian. It was said that KDE 3 will sid soon. -- Debian Weekly News Jan 14,2003 From xah at xahlee.org Tue Jan 25 11:13:34 2005 From: xah at xahlee.org (Xah Lee) Date: 25 Jan 2005 08:13:34 -0800 Subject: [perl-python] 20050125 standard modules Message-ID: <1106669614.666772.17750@z14g2000cwz.googlegroups.com> # -*- coding: utf-8 -*- # Python # some venture into standard modules import os # print all names exported by the module print dir(os) # print the module's online manual print help(os) # the above is also available in # interactive mode in Python terminal # example of using a function print 'current dir is:', os.getcwd() # this prints a list of existing modules print help('modules') # referecnce # http://python.org/doc/2.3.4/tut/node12.html # in Python terminal, type help() then # modules # to get a list # then a module name to see its doc. # take a gander of its richness and # suitability -------------------------- in perl, i don't think there is one way to list available modules. one can write a program to find out. Start by use Data::Dumper; print Dumper \@INC; to see where is the standard modules located, then search for *.pm files to get an idea. ------------------------- Note: this post is from the Perl-Python a-day mailing list at http://groups.yahoo.com/group/perl-python/ to subscribe, send an email to perl-python-subscribe @ yahoogroups.com if you are reading it on a web page, program examples may not run because html conversion often breaks the code. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From bob_smith_17280 at hotmail.com Sat Jan 8 20:45:12 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Sat, 08 Jan 2005 20:45:12 -0500 Subject: Windows XP Installation In-Reply-To: References: Message-ID: Smitsky wrote: > Hi. I am a newbie to Python. I am running Win XP and want to know what the > best course is for installing Python on my system. Could someone kindly > direct me to some related resources? Thanks in advance, Steve > > It's really easy on Windows. Just download the install package and click on it. It only takes one, maybe two minutes top. It's safe to just accept the default settings. Good luck. From simonwittber at gmail.com Tue Jan 11 20:49:50 2005 From: simonwittber at gmail.com (Simon Wittber) Date: Wed, 12 Jan 2005 09:49:50 +0800 Subject: Game programming in Python In-Reply-To: References: Message-ID: <4e4a11f8050111174931abc62e@mail.gmail.com> > I'm looking for any books or on-line resources on game programming > using Python. Does anyone have any advice? Hi Baza, If I you are as I assume, a programmer just starting out with game programming, the best suggestion I can give is head over to pygame.org, and after downloading and installing the library (also install PyOpenGL if you can), go through the tutorials listed at http://www.pygame.org/docs/ . You will also find the pygame mailing list very helpfu, and, if you are so inclined, the IRC #pygame channel on freenode.net Sw. From jerf at jerf.org Fri Jan 21 08:49:30 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 21 Jan 2005 08:49:30 -0500 Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> Message-ID: On Fri, 21 Jan 2005 03:08:50 -0800, Xah Lee wrote: > i've started to read python tutorial recently. > http://python.org/doc/2.3.4/tut/tut.html > > Here are some quick critique: You don't have the respect points for anyone to give a damn. Step one would be demonstrating that you understand the language enough to have a valid opinion, which we're all still waiting on. From peter at monicol.co.uk Mon Jan 10 14:24:14 2005 From: peter at monicol.co.uk (Peter Mott) Date: Mon, 10 Jan 2005 19:24:14 -0000 Subject: Uploading files Message-ID: <41e2d6d7$0$23059$bed64819@news.gradwell.net> If you upload a file using the cgi module is there anyway to discover the file name that the user submitted as well as the file data? I've googled till I squint but I can't find anything. Peter From bdesth.quelquechose at free.quelquepart.fr Mon Jan 10 15:49:39 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 10 Jan 2005 21:49:39 +0100 Subject: tuples vs lists In-Reply-To: References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dfe2a6$0$22729$636a15ce@news.free.fr> Message-ID: <41e2e8cf$0$5744$626a14ce@news.free.fr> Antoon Pardon a ?crit : > Op 2005-01-08, Bruno Desthuilliers schreef : > >>worzel a ?crit : >> >>>I get what the difference is between a tuple and a list, but why would I >>>ever care about the tuple's immuutability? >> >>Because, from a purely pratical POV, only an immutable object can be >>used as kay in a dict. s/kay/key/ > This is not true. Chapter and verse, please ? > >>So you can use tuples for 'composed key'. > > lists can be so used too. Just provide a hash. Please show us an example, and let's see how useful and handy this is from a "purely practical POV" ?-) Bruno From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 11:11:09 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?ISO-8859-2?Q?Martin_MOKREJ=A9?=) Date: Mon, 10 Jan 2005 17:11:09 +0100 Subject: Writing huge Sets() to disk Message-ID: <41E2A91D.7080006@ribosome.natur.cuni.cz> Hi, I have sets.Set() objects having up to 20E20 items, each is composed of up to 20 characters. Keeping them in memory on !GB machine put's me quickly into swap. I don't want to use dictionary approach, as I don't see a sense to store None as a value. The items in a set are unique. How can I write them efficiently to disk? To be more exact, I have 20 sets. _set1 has 1E20 keys of size 1 character. alphabet = ('G', 'A', 'V', 'L', 'I', 'P', 'S', 'T', 'C', 'M', 'A', 'Q', 'F', 'Y', 'W', 'K', 'R', 'H', 'D', 'E') for aa1 in alphabet: # l = [aa1] #_set1.add(aa1) for aa2 in alphabet: # l.append(aa2) #_set2.add(''.join(l)) [cut] The reason I went for sets instead of lists is the speed, availability of unique, common and other methods. What would you propose as an elegant solution? Actually, even those nested for loops take ages. :( M. From hans at zephyrfalcon.org Sat Jan 1 14:24:14 2005 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sat, 01 Jan 2005 14:24:14 -0500 Subject: The Industry choice In-Reply-To: <41d6ee45$1_2@127.0.0.1> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <41d6ee45$1_2@127.0.0.1> Message-ID: Donn Cave wrote: > Quoth Hans Nowak : > | Paul Rubin wrote: > | > |> You should write unit tests either way, but in Python you're relying > |> on the tests to find stuff that the compiler finds for you with Java. > | > | As I wrote on my weblog a while ago, I suspect that this effect is > | largely psychological. You jump through hoops, declaring types all over > | the place, checking exceptions, working around the language's > | limitations, etc. So when your code compiles, it *feels* safer. Like > | you're at least part of the way towards ensuring correctness. All that > | work must be good for *something*, right? Never mind that when writing > | unit tests for a dynamic language, you don't check for these things at > | all. How often do you explicitly check types in Python unit tests? > | IMHO, when using a dynamic language, you don't need most of the checks > | that Java, C# and their ilk force upon you. > > I have been fooling around with strongly, statically typed languages > for a couple of years, in my spare time - Objective CAML, Haskell, > O'Haskell. This is a little different experience than what you two > are talking about - I don't think Java, C# and their ilk are quite as > rigorous, nor do they use type inference - but as much as it would > probably gag an FP enthusiast to say this, the basic idea is the same. > > I can only believe that if you think the benefit of static typing is > psychological, either something is very different between the way you > and I write programs, or you're not doing it right. I do think it makes more sense in functional languages like the ones you mention... that's one of the reasons I am trying to learn OCaml. I don't think the type systems in OCaml, Haskell etc can quite be compared to what's used in Java, C#, C++ or Delphi. So far, I am getting the impression that the type system in OCaml is actually there to help you, rather than something that gets in your way. I concur that in my OCaml experiments so far, errors pointed out by the compiler made a lot more sense, because they pointed to actual problems, rather than being a case of "you didn't declare this method as public static final". Of course, it helps that, like Python, said languages (OCaml, Haskell) are higher-level than Java/C#/etc, so you can express things concisely and clearly. That might be one of the reasons why static, strong typing in VHLLs has a much higher "return on investment" than it has in lower-level languages, where you have to write acres of code just to get something done (availability of libraries notwithstanding). -- Hans Nowak http://zephyrfalcon.org/ From tim.peters at gmail.com Mon Jan 10 21:23:35 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 10 Jan 2005 21:23:35 -0500 Subject: Writing huge Sets() to disk In-Reply-To: References: Message-ID: <1f7befae05011018234684d84b@mail.gmail.com> [Istvan Albert] > #- I think that you need to first understand how dictionaries work. > #- The time needed to insert a key is independent of > #- the number of values in the dictionary. [Batista, Facundo] > Are you sure? > > I think that is true while the hashes don't collide. If you have collisions, > time starts to depend of element quantity. But I'm not sure > > Tim sure can enlighten us. I can only point the way to enlightenment -- you have to contemplate your own navel (or Guido's, but he's kind of shy that way). What Istvan Albert said is close enough in context. The *expected* (mean) number of collisions in a Python dict probe is less than 1, regardless of dict size. That assumes the collision distribution is no worse than random. It's possible that all dict keys hash to the same table slot, and then each insertion is O(len(dict)). It's possible to contrive such cases even if the hash function is a good one. But it's not going to happen by accident (and, when it does , open a bug report -- we'll improve the key type's hash function then). From petite.abeille at gmail.com Wed Jan 26 14:47:35 2005 From: petite.abeille at gmail.com (PA) Date: Wed, 26 Jan 2005 20:47:35 +0100 Subject: python without OO In-Reply-To: <200501262039.23260.francis.girard@free.fr> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <10vdt2bpr0m84db@corp.supernews.com> <200501262039.23260.francis.girard@free.fr> Message-ID: <1993411a01509c62cae1715b62fe16f5@gmail.com> On Jan 26, 2005, at 20:39, Francis Girard wrote: > When I think that comapnies > pay big money for these kind of monsters after having seen a few ppt > slides > about it, it makes me shiver. Right... but... since when does an implementation language of any sort save a project from its own doom? Project fails for many reasons but seldomly because one language is "better" or "worst" than another one. Cheers -- PA http://alt.textdrive.com/ From adamc at linuxmail.org Fri Jan 7 04:49:02 2005 From: adamc at linuxmail.org (adamc) Date: Fri, 07 Jan 2005 03:49:02 -0600 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41dcf582.122188317@news.oz.net> <7xd5wh7qdf.fsf@ruckus.brouhaha.com> <7xpt0h66yf.fsf@ruckus.brouhaha.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 2005-01-07, Paul Rubin wrote: > Roman Suzi writes: >> I do not like the idea of having stubs. Once I had an experience working with >> CPAN (I tried to install SpamAssassin and it required some specific modules.) >> "Magic" install shell, provided by Perl, upgraded half the Perl distro, >> including newer version of Perl! >> >> So, I do like Python distutils better. it is not a major problem to >> install something even if it required something else. Of course, >> this depends on the package authors. > > But distutils don't help the problem that the module requires stuff > that's missing. That's what happened with the thing I downloaded last > week, that needed wxPython. I don't understand why the author felt he > had to use wxPython instead of tkinter, since it wasn't a really fancy > gui, but after already-described hassles trying to instead wxPython, I > just used the application's command line interface instead, which > worked fine. But if wxPython is so much better, maybe it's time for > Python to include it. > > I want to start using Audacity pretty soon, which I think really does > depend on wxPython, so I'm going to have to deal with this wxPython > installation problem which is definitely not completely trivial. What > a pain. > I've not experienced problems installing wxPython on Debian (unstable). It just *works* out of the box with apt-get. Perhaps this is more of a problem with the package maintainers? Adam - -- http://www.monkeez.org PGP key: 7111B833 -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.5 (GNU/Linux) iD8DBQFB3lgd9F0IVXERuDMRAu49AJ4lBRrF10nHLtBK9NBVuznOnfJH/QCgx0vV Oqk8Vx/nASKJXvakVEYtHII= =kThY -----END PGP SIGNATURE----- From http Wed Jan 5 13:45:11 2005 From: http (Paul Rubin) Date: 05 Jan 2005 10:45:11 -0800 Subject: Securing a future for anonymous functions in Python References: <7x3bxnewmx.fsf@ruckus.brouhaha.com> Message-ID: <7xd5wjiuko.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > Do you consider generator expressions or list comprehensions deficient > because they don't allow several statements in the body of the for > loop? I don't see what it would mean to do otherwise. From newsgroups at jhrothjr.com Fri Jan 7 11:39:07 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 7 Jan 2005 10:39:07 -0600 Subject: Getting rid of "self." References: Message-ID: <10tteq0ahi8t2ff@news.supernews.com> "BJ?rn Lindqvist" wrote in message news:mailman.293.1105105152.22381.python-list at python.org... I think it would be cool if you could refer to instance variables without prefixing with "self." I know noone else thinks like me so Python will never be changed, but maybe you can already do it with Python today? ... It works! exec(magic()) does the needed hi = self.hi. Not so impressive in this case but much cooler when there is more instance variables around. But the solution is very ugly because you have to write exec(magic()) in every method. So I'm asking here if someone knows a better way, maybe using decorators or metaclasses or other black magic? [response] Having to specify the instance explicitly is something that Python needs because it isn't a statically typed language. In a statically typed language, all variables are pre-declared, so the compiler knows where they all are. Python's compiler knows about local variables. It doesn't know where any other variables are, so it has to search. Including the instance as one of the method parameters means that the search splits right at the front: either it starts looking up the instance, or it goes up the definition chain (usually empty) to the module namespace and then the builtins. Eliminating "self" would mean it would have to either search the instance before the module and builtins, or search the module and builtins before the instance. This is both a performance issue and a maintenance issue because of the increased possibility of one shadowing the other. This is distinct from the issue of how to spell "self". As another responder has already said, you can spell it any way you want; it's simply whatever you choose to call the first paramteter to the method. Going the other way, the word "self" could become a keyword, removing the necessity of specifying it among the method parameters. While I like the idea, there's enough dislike of the notion that it's not going to happen. John Roth -- mvh Bj?rn From carribeiro at gmail.com Wed Jan 5 04:17:13 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Wed, 5 Jan 2005 07:17:13 -0200 Subject: Python evolution: Unease In-Reply-To: <16859.16548.249527.30210@montanaro.dyndns.org> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <16859.16548.249527.30210@montanaro.dyndns.org> Message-ID: <864d37090501050117761a32e6@mail.gmail.com> On Tue, 4 Jan 2005 19:19:32 -0600, Skip Montanaro wrote: > > Terry> Numarray has a record array type. If there is not one publicly > Terry> available, perhaps you could write a CSV file to record-array > Terry> slurper and contribute it to the Recipes site or maybe even the > Terry> CSV module. > > -1 on putting such a beast into the CSV module, especially if, as it seems, > it would rely on something outside the core. Although I see your point, in the long term it will be required. Assuming that Numarray will, at some point in the future, be included in the stdlib... why not give these people some help, easing the integration? A recipe, or some code that can be provisionally included in Numarray itself (as a submodule), and then later migrated to the CSV module... it does make sense in the long run. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From nav+posts at bandersnatch.org Tue Jan 11 07:53:03 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: Tue, 11 Jan 2005 07:53:03 -0500 Subject: Ranting about the state of Python IDEs for Windows References: <1105222350.906941.83130@c13g2000cwb.googlegroups.com> Message-ID: <878y70dt5c.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> "AkioIto" writes: > Look at http://www.pspad.com/en/index.html. Thanks for the tip, looks perfect for the flash memory toolkit, since it can just run from the directory it was unpacked into. Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From bokr at oz.net Thu Jan 20 04:59:29 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 20 Jan 2005 09:59:29 GMT Subject: list item's position References: Message-ID: <41ef7697.1334881407@news.oz.net> On Wed, 19 Jan 2005 22:04:44 -0500, Bob Smith wrote: >Hi, > >I have a Python list. I can't figure out how to find an element's >numeric value (0,1,2,3...) in the list. Here's an example of what I'm doing: > >for bar in bars: > if 'str_1' in bar and 'str_2' in bar: > print bar > >This finds the right bar, but not its list position. The reason I need >to find its value is so I can remove every element in the list before it >so that the bar I found somewhere in the list becomes element 0... does >that make sense? > sneaky (python 2.4) one-liner (not tested beyond what you see, and not recommended as the best self-documenting version ;-) >>> bars = [ ... 'zero', ... 'one', ... 'str_1 and str_2 both in line two', ... 'three', ... 'four', ... 'str_1 and str_2 both in line five', ... 'last line'] >>> newbar=bars[sum(iter(('str_1' not in bar or 'str_2' not in bar for bar in bars).next, 0)):] >>> for s in newbar: print repr(s) ... 'str_1 and str_2 both in line two' 'three' 'four' 'str_1 and str_2 both in line five' 'last line' Alternatively: >>> newbar=bars[[i for i,v in enumerate(bars) if 'str_1' in v and 'str_2' in v][0]:] >>> for s in newbar: print repr(s) ... 'str_1 and str_2 both in line two' 'three' 'four' 'str_1 and str_2 both in line five' 'last line' Alternatively: >>> newbar = list(dropwhile(lambda x: 'str_1' not in x or 'str_2' not in x, bars)) >>> for s in newbar: print repr(s) ... 'str_1 and str_2 both in line two' 'three' 'four' 'str_1 and str_2 both in line five' 'last line' Regards, Bengt Richter From duncan.booth at invalid.invalid Sat Jan 22 06:17:09 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 Jan 2005 11:17:09 GMT Subject: re Insanity References: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> Message-ID: Tim Daneliuk wrote: > > I tried this: > > y=re.compile(r'\[PROMPT:.*\]') > > Which works fine when the text is exactly "[PROMPT:whatever]" but > does not match on: > > "something [PROMPT:foo] something [PROMPT:bar] something ..." > > The overall goal is to identify the beginning and end of each [PROMPT...] > string in the line. > The answer sort of depends on exactly what can be in your optional text: >>> import re >>> s = "something [PROMPT:foo] something [PROMPT:bar] something ..." >>> y=re.compile(r'\[PROMPT:.*\]') >>> y.findall(s) ['[PROMPT:foo] something [PROMPT:bar]'] >>> y=re.compile(r'\[PROMPT:.*?\]') >>> y.findall(s) ['[PROMPT:foo]', '[PROMPT:bar]'] >>> y=re.compile(r'\[PROMPT:[^]]*\]') >>> y.findall(s) ['[PROMPT:foo]', '[PROMPT:bar]'] >>> .* will match as long a string as possible. .*? will match as short a string as possible. By default this won't match any newlines. [^]]* will match as long a string that doesn't contain ']' as possible. This will match newlines. From fredrik at pythonware.com Mon Jan 17 03:42:21 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Jan 2005 09:42:21 +0100 Subject: why are some types immutable? References: Message-ID: Roy Smith wrote: > But, in a nutshell, the biggest reason for immutable types (tuples and > strings) is that this lets they be dictionary keys. if you think that's the biggest reason, you haven't spent enough time working on high-performance Python code and extensions (there's a reason why some languages adopt a "you can only assign to a variable once" approach). From newsgroups at jhrothjr.com Tue Jan 18 18:39:32 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 18 Jan 2005 17:39:32 -0600 Subject: Fuzzy matching of postal addresses References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> <$aq2IQPQ8X7BFwRy@at-andros.demon.co.uk> Message-ID: <10ur7ikcr3avdd4@news.supernews.com> "Andrew McLean" wrote in message news:$aq2IQPQ8X7BFwRy at at-andros.demon.co.uk... > Thanks for all the suggestions. There were some really useful pointers. > > A few random points: > > 1. Spending money is not an option, this is a 'volunteer' project. I'll > try out some of the ideas over the weekend. > > 2. Someone commented that the data was suspiciously good quality. The data > sources are both ones that you might expect to be authoritative. If you > use as a metric, having a correctly formatted and valid postcode, in one > database 100% the records do in the other 99.96% do. > > 3. I've already noticed duplicate addresses in one of the databases. > > 4. You need to be careful doing an endswith search. It was actually my > first approach to the house name issue. The problem is you end up matching > "12 Acacia Avenue, ..." with "2 Acacia Avenue, ...". > > I am tempted to try an approach based on splitting the address into a > sequence of normalised tokens. Then work with a metric based on the > differences between the sequences. The simple case would look at deleting > tokens and perhaps concatenating tokens to make a match. It's been a while since I did this stuff. The trick in dealing with address normalization is to parse the string backwards, and try to slot the pieces into the general pattern. In your case, the postal code, district (is that what it's called in the UK?) and city seem to be fine, it's when you get to the street (with or without house number), building name and flat or room number that there's a difficulty. We always had a list of keywords that could be trusted to be delimiters. In your examples, "the" should be pretty reliable in indicating a building name. Of course, that might have some trouble with Tottering on the Brink. John Roth > > -- > Andrew McLean From peter at somewhere.com Mon Jan 17 07:27:05 2005 From: peter at somewhere.com (Peter Maas) Date: Mon, 17 Jan 2005 13:27:05 +0100 Subject: (objects as) mutable dictionary keys In-Reply-To: References: Message-ID: Antoon Pardon schrieb: > Dictionary lookup with mutable types like lists is a source of > unpleasant surprises for the programmer and therefore impossible in > Python. > > > It is not impossible in Python. It may be discouraged but it is not > impossible since I have already done so. Wouldn't this raise a TypeError? Or did you wrap them with an object? -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From klapotec at chello.at Mon Jan 3 15:52:16 2005 From: klapotec at chello.at (Christopher Koppler) Date: Mon, 03 Jan 2005 20:52:16 GMT Subject: Bad Interpreter References: <1104783849.754892.47560@c13g2000cwb.googlegroups.com> Message-ID: On Mon, 03 Jan 2005 12:24:09 -0800, RajaSrinivasan wrote: > I have seen some previous messages about such a problem. I have this > problem but it is not clear what the solution really was. > > I am running FC2, python 2.3.3 > > the script i have sock.py runs if i say something like : > > python sock.py > > but ./sock.py results in a :bad interpreter error > how do i troubleshoot something like this? > Check the first line of your script - it should set the path to the Python interpreter. It should look something like this: #!/usr/bin/python or #!/usr/bin/env python which doesn't explicitly set the path to the interpreter, but checks the environment variable called python for that path. If your python executable lives somewhere the first line or the environment variable doesn't point to, you'll need to correct that. -- Christopher OutOfSigError From tim.peters at gmail.com Wed Jan 19 22:53:41 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 19 Jan 2005 22:53:41 -0500 Subject: Zen of Python In-Reply-To: <972ec5bd0501191641166972b0@mail.gmail.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> Message-ID: <1f7befae050119195356a64150@mail.gmail.com> [Carl Banks] >> The gist of "Flat is better than nested" is "be as nested as >> you have to be, no more," because being too nested is just a >> mess. [Timothy Fitz] > Which I agree with, and which makes sense. However your > "gist" is a different meaning. It's not that "Flat is better than > nested" it's that "Too flat is bad and too flat is nested so be as < nested (or as flat) as you have to be and no more." Perhaps Tim > Peters is far too concise for my feeble mind Always happy to help a fellow Tim, but I don't claim to understand the 20 Pythonic Theses, I just claim to have channelled them from Guido's inscrutable Python-mind. If you _were_ to ask me (and it's not something I recommend in general), I'd say your reading "X is better than Y" as "X is always good, and no matter how much; Y is always evil, and no matter how little" is unreasonably literal. For example, most would agree that full is better than hungry, but few would take that as meaning one should always be stuffing one's face. And I happen to know that Guido believes full is better than hungry, yet simultaneously sometimes refrains from eating until he's actually hungry. Or consider "accurate is better than vague". Go ahead: just _try_ to be 100% accurate! For that matter, just try to be 100% flat. Or 100% beautiful, 100% simple, or 100% sparse. If you were to ask for examples in Python, well, they're all over the place, and often in what's _not_ there. Guido is on record as saying that Python's original simple 3-level scope rules (local, global, builtin) were in part a reaction against the horrid abuses of deeply nested Pascal programs he had to wrestle with. Lexical scoping was added only after years of debate -- and it's still usually better to wrap state in objects (you can pass 'em around then, add useful methods to them, display them, mutate 'em, ...). Or note that you can't define a module inside another module, that Python's basic list type is a flat vector instead of a recursively-defined S-expression, and that there's no direct way to break out of a containing loop from a nested loop. Python encourages flatness of various kinds in all these (and other) ways. But that's just what I think -- nobody knows why Guido believes what he does, least of all Guido. Thanks to my remarkable channelling power, at least we know *what* he believes! I think he was grateful to find that out too . there's-just-no-disputing-divine-revelation-ly y'rs - tim From dmarcusanu at yahoo.com Mon Jan 31 21:13:00 2005 From: dmarcusanu at yahoo.com (Dana Marcusanu) Date: Mon, 31 Jan 2005 18:13:00 -0800 (PST) Subject: getting data from a port in use Message-ID: <20050201021301.4434.qmail@web52907.mail.yahoo.com> Hi to all, I am trying to use Python to get the data received at a specific port (in use) on my computer. I already tried below code which seems to hang at the statement accepting connections. I don't know what else I can try. Any suggestions will be welcome. import socket, select, os PORT = 2005 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((socket.gethostname(), PORT)) s.listen(1) work_socket, addr = s.accept() data = s.recv(1024) print data s.close() Thank you, Dana __________________________________ Do you Yahoo!? Meet the all-new My Yahoo! - Try it today! http://my.yahoo.com From steven.bethard at gmail.com Fri Jan 14 16:58:40 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 14 Jan 2005 14:58:40 -0700 Subject: Why would I get a TypeEror? In-Reply-To: References: <34ql1vF4dqd9pU1@individual.net> Message-ID: It's me wrote: > Say again??? Please stop top-posting -- it makes it hard to reply in context. > "Reinhold Birkenfeld" wrote... >>It's me wrote: >>>If this is true, I would run into trouble real quick if I do a: >>> >>>(1/x,1.0e99)[x==0] >> >>Lazy evaluation: use the (x==0 and 1e99 or 1/x) form! If you want short-circuting behavior, where only one of the two branches gets executed, you should use Python's short-circuiting boolean operators. For example, (x == 0 and 1.0e99 or 1/x) says something like: Check if x == 0. If so, check if 1.0e99 is non-zero. It is, so return it. If x != 0, see if 1/x is non-zero. It is, so return it. Note that if you're not comfortable with short-circuiting behavior, you can also code this using lazy evaluation: (lambda: 1/x, lambda: 1.0e99)[x==0]() This says something like: Create two functions, one to produce 1/x and one to produce 1.0e99. Select one of these functions depending on whether or not x==0 Invoke the chosen function. HTH, Steve From http Thu Jan 6 19:29:34 2005 From: http (Paul Rubin) Date: 06 Jan 2005 16:29:34 -0800 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <344l83F45rstqU1@individual.net> Message-ID: <7xzmzmaxox.fsf@ruckus.brouhaha.com> "Terry Reedy" writes: > > Which I find again wrong: suppose this developer used GPL-ed > > library A, developed patches B and C. He provided you with > > the source code of publicly available library A and a patch > > C, but he doesn't want to release patch B. > > Then he does not have to. As I understand the GPL, as long as he does not > release (distribute) the patch in any form (in particular, binary), then > the GPL has no effect. I think the hypothesis is that the developer distributed the patched library. The GPL then requires distributing source for all the patches. From benn at cenix-bioscience.com Thu Jan 13 07:49:56 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Thu, 13 Jan 2005 13:49:56 +0100 Subject: pyserial and com port interrupts In-Reply-To: <41E66D69.4050603@cenix-bioscience.com> References: <41E66D69.4050603@cenix-bioscience.com> Message-ID: <41E66E74.8070205@cenix-bioscience.com> Neil Benn wrote: > engsol wrote: > >> Has anyone done a script that will rspond to the serial com port(s) >> receive buffer interrupt, as opposed to polling and timeouts? Win2000 >> is the main interest right now. >> Thanks >> Norm B >> >> > Hello, > > I came across this problem as when I first used PySerial, I > came from a java background which has the ability to register > listeners to a serial comm instance and receive interrupts (although > some implementations use polling behind the scenes anyway). I don't > think that pyserial has this kind of thing so I used the following : Tabs got screwed up here is teh code again : def __checkSerial(self): self.__objLock.acquire() try: try: intNoChars = self.__objSerialPort.inWaiting() if (intNoChars > 0): strReceivedString = self.__objSerialPort.read(intNoChars) self.newMessage(strReceivedString) except: raise finally: self.__objLock.release() Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From cabrera at wrc.xerox.com Mon Jan 31 21:58:47 2005 From: cabrera at wrc.xerox.com (jose isaias cabrera) Date: Mon, 31 Jan 2005 21:58:47 -0500 Subject: Java Integer.ParseInt translation to python References: <1107217651.764967.258100@z14g2000cwz.googlegroups.com> Message-ID: <007701c50809$f59e3040$d6b8850d@jicman> thanks everyone...! ----- Original Message ----- From: "ech0" Newsgroups: comp.lang.python To: Sent: Monday, January 31, 2005 7:27 PM Subject: Re: Java Integer.ParseInt translation to python > buffer[0] = int(string,16) & 0xff > > that should work > > -- > http://mail.python.org/mailman/listinfo/python-list > From dbickett at gmail.com Sun Jan 30 23:22:57 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 30 Jan 2005 23:22:57 -0500 Subject: gmail access with python! In-Reply-To: References: Message-ID: <1d6cdae30501302022d198e25@mail.gmail.com> On Jeremy Bowers wrote: > Can you expand on that for us non-GMail users? A login is required to view > that page. I apologize, I wasn't aware :) It simply outlines all of the credentials to use gmail with pop3, I'll list it all here: Incoming server: pop.gmail.com Outgoing server: smtp.gmail.com Be sure to include @gmail.com for your username. For the incoming server (the topic at hand, if I'm not mistaken,) It instructs you to use an SSL connection and port 995, so that is sure to change some things. I believe that's all. -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ From aleaxit at yahoo.com Sat Jan 29 03:54:27 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 29 Jan 2005 09:54:27 +0100 Subject: Pystone benchmark: Win vs. Linux (again) References: <7xhdl0ll3t.fsf@ruckus.brouhaha.com> Message-ID: <1gr59wv.9tx8a21g2kdv9N%aleaxit@yahoo.com> Paul Rubin wrote: > Franco Fiorese writes: > > * Windows XP Pro: 16566.7 pystones/second > > * Linux (kernel 2.6.9 NPTL): 12346.2 pystones/second > > > > I have repeated the test, on Linux, also with other distributions and > > kernel but a relevant difference still exists with Windows offering a > > better performance. > > > > Is there any way, that you know, to get better performance under Linux? > > I hate to say this but the Windows C compiler may be beating GCC in > output code. Doing anything about it may require a lot of careful > profiling and tuning. ...or (just as hypothetically) purchasing some commercial compiler might help, under the assumption that the optimization and code generation of the compiler are the issues here. I have nothing but hearsay to go on, but IBM's compiler for PPC chips, and Intel's compiler for Intel chips, appear to claim that they have excellent code generation, for example. Alex From bokr at oz.net Fri Jan 14 02:10:57 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 14 Jan 2005 07:10:57 GMT Subject: Octal notation: severe deprecation References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> <39ednWfqlrgB6HvcRVn-iA@powergate.ca> <41e6f606.777680996@news.oz.net> Message-ID: <41e76278.805442965@news.oz.net> On Thu, 13 Jan 2005 17:43:01 -0600, Jeff Epler wrote: > >--LQksG6bCIzRHxTLp >Content-Type: text/plain; charset=us-ascii >Content-Disposition: inline >Content-Transfer-Encoding: quoted-printable > >On Thu, Jan 13, 2005 at 11:04:21PM +0000, Bengt Richter wrote: >> One way to do it consistently is to have a sign digit as the first >> digit after the x, which is either 0 or base-1 -- e.g., +3 and -3 would be >>=20 >> 2x011 2x101 >> 8x03 8x75 >> 16x03 16xfd >> 10x03 10x97 > >=2E.. so that 0x8 and 16x8 would be different? So that 2x1 and 2x01 would >be different? I guess I didn't make the encoding clear enough, sorry ;-/ 16x8 would be illegal as a literal, since the first digit after x is not 0 or f (base-1) 0x8 would be spelled 16x08 in x format. 2x1 _could_ be allowed as a degenerate form of the general negative format for -1, where any number of leading base-1 "sign digits" compute to the same value. Hence 2x1 == 1*2**0 - 2**1 == -1 2x11 == 1*2**0 + 1*2**1 - 2**2 == 1 + 2 -4 == -1 2x111 == 1*2**0 + 1*2**1 + 1*2**2 - 2**4 == 1 + 2 + 4 - 8 == -1 16f == 15*16**0 - 16**1 = 15 -16 == -1 16ff == 15*6**0 + 15*16**1 - 16**2 = 15 + 240 - 256 == -1 etc. Although IMO it will be more consistent to require a leading "sign digit" even if redundant. The one exception would be zero, since 00 doesn't look too cool in company with a collection of other numbers if output minimally without their (known) base prefixes, e.g., -2,-1,0,1,2 => 110 11 0 01 010 Of course these numbers can be output in constant width with leading pads of 0 or base-1 digit according to sign, e.g., 1110 1111 0000 0001 0010 for the same set width 4. That would be format '%04.2b' and if you wanted the literal-making prefix, '2x%04.2b' would produce legal fixed width literals 2x1110 2x1111 etc. Regards, Bengt Richter From steven.bethard at gmail.com Wed Jan 12 17:35:31 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 15:35:31 -0700 Subject: list and generators (WAS: counting items) In-Reply-To: <1105567784.297529.246800@c13g2000cwb.googlegroups.com> References: <1105559439.538736.87370@z14g2000cwz.googlegroups.com> <1105567784.297529.246800@c13g2000cwb.googlegroups.com> Message-ID: Michael Hartl wrote: > That's cool! Of course, walk returns a generator, so using a list > comprehension to turn it into a list seems natural, but I didn't > realize that list() does the same thing (and neither, apparently, did > the original implementor) -- although, with a little reflection, it > obviously must! Yup. Also worth noting is that if you want the scoping rules of generator expression, but need a list instead, you can just call list with the generator expression: py> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined py> [pow(x, 7, 23) for x in range(10)] [0, 1, 13, 2, 8, 17, 3, 5, 12, 4] py> x 9 py> del x py> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined py> list(pow(x, 7, 23) for x in xrange(10)) [0, 1, 13, 2, 8, 17, 3, 5, 12, 4] py> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined Note that with the generator expression, 'x' doesn't get leaked to the enclosing scope. Steve From paul at subsignal.org Thu Jan 27 18:49:36 2005 From: paul at subsignal.org (paul koelle) Date: Fri, 28 Jan 2005 00:49:36 +0100 Subject: Transparent (redirecting) proxy with BaseHTTPServer In-Reply-To: References: <35sfdaF4hka1hU1@individual.net> Message-ID: <35t9huF4rt829U1@individual.net> Thanks, aurora ;), aurora wrote: > If you actually want the IP, resolve the host header would give you that. I' m only interested in the hostname. > > The second form of HTTP request without the host part is for > compatability of pre-HTTP/1.1 standard. All modern web browser should > send the Host header. How safe is the assumtion that the Host header will be there? Is it part of the HTTP/1.1 spec? And does it mean all "pre 1.1" clients will fail? Hmm, maybe I should look on the wire whats really happening... thanks again Paul From jalil at feghhi.com Sun Jan 30 14:17:08 2005 From: jalil at feghhi.com (jalil at feghhi.com) Date: 30 Jan 2005 11:17:08 -0800 Subject: Exception from bsddb module Message-ID: <1107112627.990210.95160@z14g2000cwz.googlegroups.com> I am using Python 2.4 and get this exception when running my mod_python application. This used to work in my older environment. Any ideas on how I can debug this issue? -Jalil Mod_python error: "PythonHandler mod_python.psp" Traceback (most recent call last): File "/usr/local/lib/python2.4/site-packages/mod_python/apache.py", line 299, in HandlerDispatch result = object(req) File "/usr/local/lib/python2.4/site-packages/mod_python/psp.py", line 297, in handler p.run() File "/usr/local/lib/python2.4/site-packages/mod_python/psp.py", line 191, in run session = Session.Session(req) File "/usr/local/lib/python2.4/site-packages/mod_python/Session.py", line 389, in Session timeout=timeout, lock=lock) File "/usr/local/lib/python2.4/site-packages/mod_python/Session.py", line 294, in __init__ timeout=timeout, lock=lock) File "/usr/local/lib/python2.4/site-packages/mod_python/Session.py", line 124, in __init__ if self.load(): File "/usr/local/lib/python2.4/site-packages/mod_python/Session.py", line 185, in load dict = self.do_load() File "/usr/local/lib/python2.4/site-packages/mod_python/Session.py", line 315, in do_load dbm = self._get_dbm() File "/usr/local/lib/python2.4/site-packages/mod_python/Session.py", line 302, in _get_dbm result = self._dbmtype.open(self._dbmfile, 'c') File "/usr/local/lib/python2.4/anydbm.py", line 83, in open return mod.open(file, flag, mode) File "/usr/local/lib/python2.4/dbhash.py", line 16, in open return bsddb.hashopen(file, flag, mode) File "/usr/local/lib/python2.4/bsddb/__init__.py", line 285, in hashopen e = _openDBEnv() File "/usr/local/lib/python2.4/bsddb/__init__.py", line 339, in _openDBEnv e.open('.', db.DB_PRIVATE | db.DB_CREATE | db.DB_THREAD | db.DB_INIT_LOCK | db.DB_INIT_MPOOL) DBError: (153777744, 'Unknown error 153777744') From reinhold-birkenfeld-nospam at wolke7.net Tue Jan 11 11:53:03 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 11 Jan 2005 17:53:03 +0100 Subject: tuples vs lists In-Reply-To: References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dfe2a6$0$22729$636a15ce@news.free.fr> <41e2e8cf$0$5744$626a14ce@news.free.fr> Message-ID: <34iejgF4akofdU1@individual.net> Antoon Pardon wrote: > Op 2005-01-10, Bruno Desthuilliers schreef : >> Antoon Pardon a ?crit : >>> Op 2005-01-08, Bruno Desthuilliers schreef : >>> >>>>worzel a ?crit : >>>> >>>>>I get what the difference is between a tuple and a list, but why would I >>>>>ever care about the tuple's immuutability? >>>> >>>>Because, from a purely pratical POV, only an immutable object can be >>>>used as kay in a dict. >> >> s/kay/key/ >> >>> This is not true. >> >> Chapter and verse, please ? > > I don't need chapter and verse. I have already used mutable > objects as keys and it works just fine. > >>>> class hlst(list): >>>> >>>> def __hash__(self): >>>> sum = 0 >>>> for el in self: >>>> sum += hash(el) >>>> return sum % 0x37777777 >>>> Given this hash function, how do you handle changed keys? .class hlst(list): . def __hash__(self): . sum = 0 . for el in self: . sum += hash(el) . return sum % 0x37777777 . .lst = hlst([1,2,3]) . .d = {} .d[lst] = 1 . .lst[0] = 0 . .print d .try: . print d[hlst([0,2,3])] .except KeyError: . print "0,2,3: KeyError" .try: . print d[hlst([1,2,3])] .except KeyError: . print "1,2,3: KeyError" raises the KeyError twice. How do you access the element then? And if you can't access the element when it's changed, what is the advantage over using tuples? Reinhold From josh at yucs.org Thu Jan 13 15:53:10 2005 From: josh at yucs.org (josh at yucs.org) Date: Thu, 13 Jan 2005 15:53:10 -0500 Subject: why not datetime.strptime() ? In-Reply-To: <16870.32896.616979.730581@montanaro.dyndns.org> References: <20050111021152.GA20127@yucs.org> <16867.59681.423983.244528@montanaro.dyndns.org> <20050111173335.GB26246@yucs.org> <16869.62773.572880.581805@montanaro.dyndns.org> <16870.32896.616979.730581@montanaro.dyndns.org> Message-ID: <20050113205310.GA26290@yucs.org> On Thu, Jan 13, 2005 at 08:06:56AM -0600, Skip Montanaro wrote: > > Skip> I just checked in your changes. Thanks for the effort. > > Jeez Skip... That reads poorly. How about "Thanks for your contribution"? > In any case, thanks. My pleasure. Thanks for helping me to help. And I liked the first thanks just fine (the "checked in" was the important part :) ). From chris.lasher at gmail.com Thu Jan 13 16:22:33 2005 From: chris.lasher at gmail.com (Chris Lasher) Date: 13 Jan 2005 13:22:33 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <10udfj4c4rgkvcc@corp.supernews.com> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <41e5ebee.709560864@news.oz.net> <1105632841.461042.68310@c13g2000cwb.googlegroups.com> <10udfj4c4rgkvcc@corp.supernews.com> Message-ID: <1105651353.769879.229690@f14g2000cwb.googlegroups.com> >And besides, for long-term archiving purposes, I'd expect that zip et >al on a character-stream would provide significantly better >compression than a 4:1 packed format, and that zipping the packed >format wouldn't be all that much more efficient than zipping the >character stream. This 105MB FASTA file is 8.3 MB gzip-ed. From rootshell at gazeta.pl Fri Jan 14 12:01:40 2005 From: rootshell at gazeta.pl (rootshell at gazeta.pl) Date: 14 Jan 2005 09:01:40 -0800 Subject: Free python server. References: <002301c4f99a$cb4dcd50$55a01d53@unqku4k1fl8nea7> Message-ID: <1105722100.306305.107950@z14g2000cwz.googlegroups.com> > Your file probably need to (a) be in the cgi-bin, not public_html, (b) > be flagged executable ("chmod a+x file.py"), and (c) begin with the > line: '#!/usr/bin/env python' > > If the server doesn't provide you with CGI (or, strongly preferable, > SCGI or mod_python), you're probably out of luck. You're probably right, this machine doesn't provide with CGI, I'll send an e-mail to administrator of arbornet.org and make sure. So, I ask once again: does anyone know where I can put my *.py files? Greetings. Rootshell. From lutherrevisited at aol.com Sun Jan 2 02:45:24 2005 From: lutherrevisited at aol.com (LutherRevisited) Date: 02 Jan 2005 07:45:24 GMT Subject: What can I do with Python ?? References: Message-ID: <20050102024524.07592.00003025@mb-m01.aol.com> Speaking of the many libraries people have written I thought I'd mention pychess. Don't remember where I found it, but it's easy enough to find on a search engine. That's the whole reason I discovered python, searching for a good algorithm to use in parsing chess pgn files. From elephantum at dezcom.mephi.ru Sun Jan 9 09:01:53 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 17:01:53 +0300 Subject: Pygame and pyopengl with py2exe ? In-Reply-To: References: Message-ID: <34crqiF47stihU1@individual.net> Nyx42 wrote: > Second program (pygame + pyopenGL): > Py2exe can't import OpenGL.GL and OpenGL.GLU :( about that, may be names of imports are generated in runtime, so you can try to specify them directly options = {"py2exe": {"packages": ["OpenGL.GL","OpenGL.GLU"]}}, From ville at spammers.com Mon Jan 10 08:42:06 2005 From: ville at spammers.com (Ville Vainio) Date: 10 Jan 2005 15:42:06 +0200 Subject: Securing a future for anonymous functions in Python References: <7xvfa90w6g.fsf@ruckus.brouhaha.com> Message-ID: >>>>> "James" == James Stroud writes: James> I think we should not try too hard to make everything James> "English" like. Its a crappy language anyway (though its James> the only one I speak good). Matt Neuberg, QOTW material, unless you stole this from someone else :-). -- Ville Vainio http://tinyurl.com/2prnb From steven.bethard at gmail.com Fri Jan 21 14:37:25 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 12:37:25 -0700 Subject: Unbinding multiple variables In-Reply-To: <1106334800.868412.27650@f14g2000cwb.googlegroups.com> References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> <35bnkeF4jpeetU1@individual.net> <1106334800.868412.27650@f14g2000cwb.googlegroups.com> Message-ID: <7pidncPdVepvxGzcRVn-jQ@comcast.com> Johnny Lin wrote: > my understanding about locals() from the nutshell book was that i > should treat that dictionary as read-only. is it safe to use it to > delete entries? No it's not: py> def f(): ... x = 1 ... del locals()['x'] ... print x ... py> f() 1 py> def f(): ... x = 1 ... del x ... print x ... py> f() Traceback (most recent call last): File "", line 1, in ? File "", line 4, in f UnboundLocalError: local variable 'x' referenced before assignment Steve From jayjbee at hotmail.com Tue Jan 11 21:39:37 2005 From: jayjbee at hotmail.com (jay j bee) Date: Wed, 12 Jan 2005 03:39:37 +0100 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: On 12-01-2005 03:06, in article 1105495569.479185.166340 at z14g2000cwz.googlegroups.com, "humblythegreatest at usa.com" wrote: > python.org "Python - why settle for snake oil when you can have the whole snake?" Greetzzzzz From fuzzyman at gmail.com Fri Jan 14 05:53:45 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 14 Jan 2005 02:53:45 -0800 Subject: file uploading via urllib2 (multipart/form-data) In-Reply-To: References: Message-ID: <1105700025.763417.149110@c13g2000cwb.googlegroups.com> Clark C. Evans wrote: > Hello. I was wondering if anyone has built a module that works with > urllib2 to upload file content via POST multipart/form-data. I'm > aware of ASPN 146306, however, I need to use urllib2 beacuse I'm > using HTTP Digest over SSL. > > Cheers, > > Clark There is an example showing exactly that over at voidspace. I think it's on the cgi page, as it is a companion to the cgi demo showing how to receive file uploads. Try : http://www.voidspace.org.uk/python/cgi.shtml Regards, Fuzzy http://www.voidspac.org.uk/python/index.shtml From reinhold-birkenfeld-nospam at wolke7.net Fri Jan 21 14:47:21 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 21 Jan 2005 20:47:21 +0100 Subject: make install with python In-Reply-To: References: Message-ID: <35d4i9F4makucU1@individual.net> Uwe Mayer wrote: > Hi, > > I am writing a Python application and use the GNU auto-tools to compile what > needs compilation (i.e. Qt's .ui files). > However, I don't know how to write an automake file that installs the main > file (lmc.py) and some library files (i.e. ClassA.py, ClassB.py) into the > appropriate directories. The regular way is to use distutils and a setup.py file (google for documentation). Reinhold From bokr at oz.net Sat Jan 8 21:49:35 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 09 Jan 2005 02:49:35 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> Message-ID: <41e09808.360402200@news.oz.net> On Sat, 08 Jan 2005 12:47:52 -0500, Peter Hansen wrote: >Paul Rubin wrote: >> When Unix was first written, people thought implementing an OS in C >> was ludicrous. Everyone knew OS's had to be written in assembler. > >Actually, when Unix was first written that belief was entirely >correct, and OSes *did* have to be written in assembler. > >That is, pure C did not have the capability to handle all >that was required. I recall it taking a good decade before it >became *common* to find C compilers with, for example, @interrupt >support to let the compiler generate code that properly saved >all registers and used RTI instead of RTS (or whatever it might >have been called one one's particular flavour of CPU). > >Now, once you added a few tiny interrupt handlers, and some context >switching (stack manipulation) routines, pretty much everything else >*could* be done in C, but that doesn't invalidate the point. > >I think it's safe to say that none of pure C, pure Lisp, or pure Python >are really capable of being used as the *sole* language to build >an operating system. > >It's also safe to say that this is a largely irrelevant point. >It would probably only be of academic interest to try to do >something like that. Any practical attempt would not think more >than twice of resorting to a little "glue" in assembler or in >the form of "canned" byte sequences built by hand and stuck >into the appropriate places in memory... Well, usually there's more than one tool in the chain from source to bootable loader and OS image, even if you are writing in C and assembler, and there's usually more to an OS than the bootable image contains. So ISTM "writing an OS in " is pretty loose talk ;-) Regards, Bengt Richter From mexica13 at aol.com Fri Jan 21 03:13:15 2005 From: mexica13 at aol.com (Gerardo C. Ruiz) Date: 21 Jan 2005 08:13:15 GMT Subject: Quick And EZ Money!!! Message-ID: <20050121031315.12769.00000162@mb-m11.aol.com> Dear Internet User, (Testimonial of Participant) Good day, This article I've written is all about the fact where I earned an ASTOUNDING amount of money in just over a month and I've decided to share or reveal the secrets behind making big bucks in the Mail Order Business. So all money seekers read this carefully. Hi, I'm 30 years old and I make more money now from my home than I ever did before by working, and so can you! Turn $6.00 into $30,000...read this to find out how!!! READING THIS COULD CHANGE YOUR LIFE! I found this on a bulletin board like this one and decided to try it. A little while back, I was browsing through several newsgroups, just like you are now, and came across an article similar to this that said you could make thousands of dollars within weeks with only an initial investment of $6.00! So I thought, "Yeah right, this must be a scam", but like most of us, I was curious, so I kept reading. Anyway, it said that you need to send $1.00 to each of the 6 names and addresses stated in the article, to have your name placed on their mailing list. You then place your own name and address in the bottom of the list at #6, and post the article in at least 200 newsgroups. (There are millions) No catch, that was it. So after thinking it over, and talking to a few people first, I thought about trying it. I figured: "what have I got to lose except 6 stamps and $6.00, right?" Then I invested the measly $6.00. Well GUESS WHAT!!... Within 7 days, I started getting money in the mail! I was shocked! I figured it would end soon, but the money just kept coming in. In my first week, I made about $25.00. By the end of the second week I had made a total of over $1,000.00! In the third week I had over $5,000.00 and it's still growing. By the fourth week, I have made just over $12,000.00 and it's still coming in rapidly. It's certainly worth $6.00, and 6 stamps, I have spent more than that on the lottery!! Let me tell you how this works and most importantly, why it works....Also, make sure you print a copy of this article NOW, so you can get the information off of it, as you need it. I promise you that if you follow the directions exactly, that you will start making more money than you thought possible by doing something so easy! SUGGESTION: Read this entire message carefully! (Print it out or download it.) Follow the simple directions and watch the money come in! It's easy. It's legal. And, your investment is only $6.00 (Plus postage). IMPORTANT: This is not a rip-off; it is not indecent; it is not illegal; and it is virtually no risk - it really works!!!! If all of the following instructions are adhered to, you will receive extraordinary dividends. PLEASE NOTE: Please follow these directions EXACTLY, and $30,000 or more can be yours in 20 to 60 days. This program remains successful because of the honesty and integrity of the participants. Please continue its success by carefully adhering to the instructions. You will now become part of the Mail Order business. In this business your product is not solid and tangible, it's a service. You are in the business of developing Mailing Lists. Many large corporations are happy to pay big bucks for quality lists. However, the money made from the mailing lists is secondary to the income, which is made from people like you and me asking to be included in that list. ~~>HERE ARE 4 EASY STEPS TO GET STARTED<~~ STEP 1: Get 6 separate pieces of paper and write the following on each piece of paper "PLEASE PUT ME ON YOUR MAILING LIST." Now get 6 US $1.00 bills and place ONE inside EACH of the 6 pieces of paper so the bill will not be seen through the envelope (Please make sure that the bill wouldn't be noticed in the envelope to prevent thievery). Send out US $ DOLLAR, so it would be more acceptable. STEP 2: Next, place one paper in each of the 6 envelopes and seal them properly. You should now have 6 sealed envelopes, each with a piece of paper stating the phrase, "PLEASE PUT ME ON YOUR MAILING LIST.", your name and address, and a $1.00 bill. What you are doing is creating a service. THIS IS ABSOLUTELY LEGAL! You are requesting for a legitimate service and you are paying for it! Like most of us, I was a little skeptical and a little worried about the legal aspects of it all. So I checked it out with the U.S. Post Office (1-800-725-2161) and they confirmed that it is indeed legal! Mail the 6 envelopes to the following addresses below: #1) Wilson Davis~ 2209 Continental Blvd. Orlando, Fl. 32808 USA #2) Wilson Darren Matsu~3052 11th Ave, Los Angeles, CA 90018 USA #3) Darren Matsu~3052 11th Ave, Los Angeles, CA 90018 USA #4) Jeremy West ~ 25 Wisteria Way, Wrentham, MA 02093 #5) J. Haze ~91 Prince St. Apt. 16, Boston, MA 02113-1732 #6)Gerardo Ruiz~706 Boone St., Uvalde, Tx 78801 STEP 3: Now take the #1 name off the list that you see above, move the other names up (6 becomes 5, 5 becomes 4, etc...) and add YOUR Name as number 6 on the list. STEP 4: Copy this article. Change anything you need to, but try to keep this article as close to original as possible. Now, post your amended article to at least 200 newsgroups. (I think there are close to 2.4million groups) All you need is 200, but remember, the more you post, the more money you make! This is perfectly legal! If you have any doubts, refer to Title 18, Section 1302 and 1341, US Postal and Lottery Laws or Title 18, Section 3005 in the US code, also in the code of Federal regulations, Volume 16, Sections 255 and 436, which states; "a product or service must be exchanged for money received. " The simple note in the letter, "PLEASE PUT ME ON YOUR MAILING LIST", makes it legal because you are paying for exchange of a service, (adding the purchasers name to his mailing list) for a $1.00 fee. Keep a copy of these steps for yourself and, whenever you need money, you can use it again, and again. PLEASE REMEMBER that this program remains successful because of the honesty and integrity of the participants and by their carefully adhering to the directions. Look at it this way. If you are of integrity, the program will continue and the money that so many others have received will come your way. NOTE: You may want to retain every name and address sent to you, either on a computer or hard copy and keeps the notes people send you. This VERIFIES that you are truly providing a service. So, as each post is downloaded and the directions carefully followed, six members will be reimbursed for their participation as a List Developer with one dollar each. Your name will move up the list geometrically so that when your name reaches the #1 position you will be receiving thousands of dollars in CASH!!! What an opportunity for only $6.00 ($1.00 for each of the first six people listed above) Send it now, add your own name to the list and you're in business! ~~>DIRECTIONS FOR HOW TO POST TO NEWSGROUPS~~> Step 1) You do not need to re-type this entire letter to do your own posting. Simply put your mouse cursor at the beginning of this letter, click and drag your cursor to the bottom of this document, right click and select 'copy' from the edit menu. This will copy the entire letter into the computer's memory. Step 2) Open a blank 'notepad' file and place your mouse cursor at the top of the blank page. Right click and from the 'edit' menu select 'paste'. This will paste a copy of the letter into notepad so that you can add your name and postal address to the list. Step 3) Save your new notepad file as a .txt file. If you want to do your postings in different settings, you'll always have this file to go back to. Step 4) Use Netscape or Internet explorer and try searching for various newsgroups (on-line forums, message boards, chat sites, discussions.) Step 5) Visit these message boards and post this article as a new message by highlighting the text of this letter and selecting paste from the edit menu. Fill in the Subject, this will be the header that everyone sees as they scroll through the list of postings in a particular group, click the "post" message button. You're done with your first one! NOTE: Please don't SPAM or send unsolicited emails. It's completely illegal. Send emails to all the people you know or any ways that allows you to, instead of SPAMMING. (Just a reminder). Congratulations...THAT'S IT! All you have to do is jump to different newsgroups and post away, after you get the hang of it, it will take about a minute for each newsgroup! **REMEMBER, THE MORE NEWSGROUPS YOU POST IN, THE MORE MONEY YOU WILL MAKE!! BUT YOU HAVE TO POST A MINIMUM OF 200** That's it! You will begin receiving money from around the world within days! You may eventually want to rent a P.O.Box due to the large amount of mail you will receive. If you wish to stay anonymous, you can invent a name to use, as long as the postman will deliver it. *JUST MAKE SURE ALL THE ADDRESSES ARE CORRECT.* *Now the WHY part; Out of 200 postings, say I receive only 5 replies (a very low example). So then I made $5.00 with my name at #6 on the letter. Now, each of the 5 persons who just sent me $1.00 make the MINIMUM 200 postings, each with my name at #5 and only 5 persons respond to each of the original 5, that is another $25.00 for me, now those 25 each make 200 MINIMUM posts with my name at #4 and only 5 replies each, I will bring in an additional $125.00! Now, those 125 persons turn around and post the MINIMUM 200 with my name at #3 and only receive 5 replies each, I will make an additional $626.00! OK, now here is the fun part, each of those 625 persons post a MINIMUM 200 letters with my name at #2 and they each only receive 5 replies, that just made me $3,125.00!!! Those 3,125 persons will all deliver this message to 200 newsgroups with my name at #1 and if still ONLY 5 persons per 200 newsgroups react I will receive $15,625,00! With an original investment of only $6.00! AMAZING! When your name is no longer on the list, you just take the latest posting in the newsgroups, and send out another $6.00 to names on the list, putting your name at number 6 again. And start posting again. The thing to remember is: do you realize that thousands of people all over the world are joining the internet and reading these articles everyday? JUST LIKE YOU are now!! So, can you afford $6.00 and see if it really works?? I think so... People have said, "what if the plan is played out and no one sends you the money? So what! What are the chances of that happening when there are tons of new honest users and new honest people who are joining the internet and newsgroups everyday and are willing to give it a try? Estimates are at 20,000 to 50,000 new users, every day, with thousands of those joining the actual internet!!! REMEMBER, PLAY FAIRLY AND HONESTLY AND THIS WILL WORK FOR YOU!!! From stewart.midwinter at gmail.com Wed Jan 26 16:25:12 2005 From: stewart.midwinter at gmail.com (stewart.midwinter at gmail.com) Date: 26 Jan 2005 13:25:12 -0800 Subject: smtplib bug with Windows XP In-Reply-To: References: <1106614880.586616.19780@f14g2000cwb.googlegroups.com> <1106673048.851591.324490@f14g2000cwb.googlegroups.com> Message-ID: <1106774712.617069.310000@z14g2000cwz.googlegroups.com> it works! you da man! At the same time as my desktop was upgraded to Windows XP, the IT people switched virus checker products to McAfee Enterprise. And indeed, as soon as I disabled that 'mass worm sending' option, my Python scripts is once again able to send mail. thanks so much for this tip! 247 karma points for you. S From http Fri Jan 7 06:33:05 2005 From: http (Paul Rubin) Date: 07 Jan 2005 03:33:05 -0800 Subject: Excluded and other middles in licensing References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> <75r0b2-ohg.ln1@lairds.us> <1gq0jpn.1es49j7jrk3k5N%aleaxit@yahoo.com> <7x3bxd5ywz.fsf@ruckus.brouhaha.com> <1gq0o3c.1lnjwhxjgcefmN%aleaxit@yahoo.com> Message-ID: <7xmzvlxymm.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > > Note also from the Heine-Borel theorem that every closed source > > program can be covered by some finite collection of open source > > programs. > > Every _compact_ one, surely? Quoting by heart from old memories, but, > isn't Heine-Borel about (being able reduce any open covering of X to a > finite subcovering) <-> (X is compact) ...? Yeah, whoops, that's what I meant; your old memories are clearer than mine. Actually sometimes the definitions and theorems interchange. I do remember something about Tikhonov's Theorem that says that no matter how often bounded closed source programs multiply, the product is still closed source. So, for example, Adobe Acrobat is still closed source even if you can download it from Adobe's web site infinitely often. But that theorem doesn't apply to noncompact (i.e. unbounded) closed source programs. So ordering Microsoft to release parts of Windows as open source was one of the potential remedies discussed in the penalty phase of the US Justice Dept's antitrust suit. Unfortunately, the DoJ lawyers were not good topologists so they didn't give enough consideration to this possibility. From zanesdad at bellsouth.net Fri Jan 21 12:32:21 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Fri, 21 Jan 2005 12:32:21 -0500 Subject: DevX: "Processing EDI Documents into XML with Python" In-Reply-To: <35c0hcF4jnr7pU1@individual.net> References: <35c0hcF4jnr7pU1@individual.net> Message-ID: <41F13CA5.3050901@bellsouth.net> Claudio Grondi wrote: >"You don't have to rely on expensive and proprietary EDI conversion software >to parse, validate, and translate EDI X12 data to and from XML; you can >build your own translator with any modern programming language, such as >Python." > > by Jeremy Jones > http://www.devx.com/enterprise/Article/26854 > > Excerpt: > "Python is an object-oriented, byte-compiled language with a clean >syntax, clear and consistent philosophy, and a strong user community. These >attributes (both of the language and the community) make it possible to >quickly write working, maintainable code, which in turn makes Python an >excellent choice for nearly any programming task. Processing any "flavor" of >EDI is no exception." > > >Hi, >just wanted to share with you, that the last issue >of the DevX newsletter comes with a Python related >article as first item in the list of subjects. > >Claudio > > > > Anyone interested in processing EDI with Python will probably be interested in giving it a read. Please feel free to scrutinize the code mercilessly. I plan on creating a project on Sourceforge with the code that is attached to that article (and hopefully with modifications coming from user input in the ensuing months). Comments are greatly appreciated. Thanks for posting this, Claudio. Jeremy Jones From sam.wun at authtec.com Mon Jan 24 01:25:33 2005 From: sam.wun at authtec.com (sam) Date: Mon, 24 Jan 2005 14:25:33 +0800 Subject: compile python to binary In-Reply-To: References: <1d6cdae3050123080242bf8994@mail.gmail.com> Message-ID: Peter Hansen wrote: > Daniel Bickett wrote: > >> Fredrik Lundh wrote: >> >>> oh, you mean that "python compiler" didn't mean "the python compiler". >>> [snip] >> >> >> I simply inferred that he was using the wrong terminology, being that >> he said "binary" twice ;-) > > > While I suspect you've guessed correctly at what the OP > meant, one should also consider that the word "binary" > can be quite ambiguous in the hands of a newbie. > > After all, source code is stored in binary too... > Sorry for the vagues terms. I meant compile a python script into a binary program. Thanks Sam > -Peter From hanzspam at yahoo.com.au Wed Jan 12 20:28:32 2005 From: hanzspam at yahoo.com.au (hanz) Date: 12 Jan 2005 17:28:32 -0800 Subject: dict.updated References: <5GiFd.8571$Vj3.3354@newssvr17.news.prodigy.com> Message-ID: <1105579712.506893.316070@f14g2000cwb.googlegroups.com> Rick Morrison wrote: > >>> [updated(d, {'c':3}) for d in [{'a':1, 'b':2}, {'x':10, 'y':'11'}]] > [{'a': 1, 'c': 3, 'b': 2}, {'y': '11', 'x': 10, 'c': 3}] I don't really understand the use of this. Can you give a less toy example? I'd probably just do dicts = [{'a':1, 'b':2}, {'x':10, 'y':'11'}] for d in dicts: d.update({'c':3}) This isn't really more typing or any clumsier IMO, so I can't see why you'd want to use list comprehensions in this case. From michaels at rd.bbc.co.uk Mon Jan 10 05:23:34 2005 From: michaels at rd.bbc.co.uk (Michael Sparks) Date: Mon, 10 Jan 2005 10:23:34 +0000 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> Message-ID: Roose wrote: ... > I was thinking that there would be a Lisp interpreter in a kernel, > which afaik doesn't exist. There's an implementation of scheme that runs as a kernel module in Linux - it's designed to allow people to experiment with exploring kernel data structures at run time, and other fun things. It's a case in point for avoiding saying that something that doesn't necessarily sound sensible doesn't exist - there's a good chance it does :) Michael -- Michael.Sparks at rd.bbc.co.uk British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From sharidas at zeomega.com Thu Jan 27 08:04:17 2005 From: sharidas at zeomega.com (Satchidanand Haridas) Date: Thu, 27 Jan 2005 18:34:17 +0530 Subject: Please suggest on the book to follow In-Reply-To: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> Message-ID: <41F8E6D1.9060201@zeomega.com> Hi, Probably the best resources for learning Python are available online. Here are a few sites that you might find helpful: 1. http://byteofpython.info/ 2. http://www.diveintopython.org/ -- Writted by Mark Pilgrim, covers many advanced material. The site says /"Dive into Python"/ is a "Python book for experienced programmers." 3. http://gnosis.cx/TPiP/ -- "Site for Text Processing in Python", a book by David mertz. You will find many other very good Python related material on his website. regards, Satchit ---- Satchidanand Haridas (sharidas at zeomega dot com) ZeOmega (www.zeomega.com) Open Minds' Open Solutions #20,Rajalakshmi Plaza, South End Road, Basavanagudi, Bangalore-560 004, India santanu wrote: >Hi all, > >I know a little python (not the OOP part) learnt by studying the online > >tutorial. Now I would like to learn it more thoroughly. > >I have access to 'Programming Python' which I liked (on flipping >through the >pages), but the problem is it deals only with version 2.0 of Phython. > >So, I would be glad if you could suggest me whether it would be really >a good >idea to learn from this book. In other words, will I have to unlearn >too much >after I complete this book (by the time I am done with this book, I >believe >we will be having Python 2.6 or so). > >Please suggest. > >Regards, >Santanu > > > From simon.brunning at gmail.com Thu Jan 6 06:59:27 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Thu, 6 Jan 2005 11:59:27 +0000 Subject: OT: spacing of code in Google Groups In-Reply-To: References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> Message-ID: <8c7f10c60501060359537dcff1@mail.gmail.com> On Wed, 05 Jan 2005 22:57:33 GMT, JanC wrote: > Rectangular selection only works with the mouse in SciTE/Scintilla: > alt-click-drag. Nope - hold down alt-shift, and select with the cursor keys. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From gene.tani at gmail.com Sun Jan 30 20:21:58 2005 From: gene.tani at gmail.com (gene.tani at gmail.com) Date: 30 Jan 2005 17:21:58 -0800 Subject: a sequence question In-Reply-To: References: Message-ID: <1107134518.436145.309020@z14g2000cwz.googlegroups.com> cookbook's not an easy grep but: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303060 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303279 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/347689 From tim.golden at viacom-outdoor.co.uk Fri Jan 28 04:06:15 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 28 Jan 2005 09:06:15 -0000 Subject: win32com/makepy question Message-ID: <9A28C052FF32734DACB0A288A3533991035A06@vogbs009.gb.vo.local> [Tom Willis] | It seems in COM late binding is something that should be | avoided if possible. | | Because python seems to be really good at doing thing dynamically I'm | wondering why no one has figured out how to make the functionality in | makepy fire automagically when you need it. I (nearly) always use win32com.client.gencache.EnsureDispatch. There are a few occasions when it refuses to play, and then I'm back to Dispatch. import win32com.client word = win32com.client.gencache.EnsureDispatch ("Word.Application") # # does the same as Dispatch ("Word.Application") but does # the makepy stuff first if it needs to. # TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From ncoghlan at iinet.net.au Fri Jan 7 10:20:31 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 01:20:31 +1000 Subject: Getting rid of "self." In-Reply-To: <740c3aec05010705393048a374@mail.gmail.com> References: <740c3aec05010705393048a374@mail.gmail.com> Message-ID: <41DEA8BF.5020608@iinet.net.au> BJ?rn Lindqvist wrote: > So I'm asking here if someone > knows a better way, maybe using decorators or metaclasses or other > black magic? Wait for Python 3k when this will work: class c: def __init__(self): with self: .x = 1 .y = 2 .hi = "Hi there!" Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jgrahn-nntq at algonet.se Wed Jan 12 17:00:01 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 12 Jan 2005 22:00:01 GMT Subject: encryption/decryption help References: <7xwtuibd26.fsf@ruckus.brouhaha.com> <1105562345.525224.319120@z14g2000cwz.googlegroups.com> Message-ID: On 12 Jan 2005 12:39:05 -0800, Kartic wrote: > Hi, > > Can you use ssh tunneling? You will not be changing anything except add > an extra ssh layer to tunnel your data through. Or, rather, he wouldn't be changing anything at all in the program itself. The approach would be "Ok, so this protocol is insecure. If you want to protect yourself from eavesdropping and man-in-the-middle attacks along the ways, you have to feed it through an ssh tunnel or something similar". But we don't really know what this person wants to accomplish, so this may or may not be a viable option. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From peter at engcorp.com Sat Jan 8 12:53:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Jan 2005 12:53:05 -0500 Subject: python3: 'where' keyword In-Reply-To: <3480qqF46jprlU1@individual.net> References: <3480qqF46jprlU1@individual.net> Message-ID: Andrey Tatarinov wrote: > >>> print words[3], words[5] where: > >>> words = input.split() > > - defining variables in "where" block would restrict their visibility to > one expression Then your example above doesn't work... print takes a sequence of expressions, not a tuple as you seem to think. -Peter From marcel.vandendungen at gmail.com Fri Jan 14 17:17:49 2005 From: marcel.vandendungen at gmail.com (Marcel van den Dungen) Date: Fri, 14 Jan 2005 23:17:49 +0100 Subject: Index server In-Reply-To: <1105735030.574794.74400@z14g2000cwz.googlegroups.com> References: <1105735030.574794.74400@z14g2000cwz.googlegroups.com> Message-ID: python at hope.cz wrote: > Is there an Index server available in Python? For example: > I have large intranet with several servers and I would like to index > documents like search engines do. Users then can search for a domument > in ALL intranet servers like I do on Google. > Thanks for answers > L.A. > Take a look at the following URLs: http://www.methods.co.nz/docindexer/ http://www.divmod.org/Home/Projects/Lupy/index.html http://www.divmod.org/Home/Projects/Pyndex/index.html HTH, -- Marcel From tim.peters at gmail.com Sun Jan 9 12:59:49 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 9 Jan 2005 12:59:49 -0500 Subject: time module precision In-Reply-To: <1105268967.629064.154850@c13g2000cwb.googlegroups.com> References: <1105268967.629064.154850@c13g2000cwb.googlegroups.com> Message-ID: <1f7befae0501090959442af517@mail.gmail.com> [Tim Peters] >> Python's time.sleep() calls the Win32 API Sleep() function on >> Windows. All behavior is inherited from the latter. See MS's docs: >> >> >> [janeaustine50 at hotmail.com] > Oh, after a short research, I found that time.sleep uses its customized > way of sleeping using "select". > > [http://groups.google.com/groups?threadm=ud7i1c9ck.fsf%40ctwd0143.fitlinxx.com] > > So I think its behaviour is more complicated than single MS Sleep call, > I suppose. Sorry, the information you found is wrong, as a brief look at Python's timemodule.c will confirm. select() is used to implement time.sleep() on Unixish boxes, but, contrary to the thread you found, it's not possible to do that on Windows -- the Winsock select() requires at least one of its socket-set arguments to be non-empty (see MS's select() docs -- they're telling the truth too ). Abusing select() for "short sleeps" is an ugly (but effective) hack limited to Unixish systems. ... > What I want to do is waiting(not busy-delaying) for a few tens to > hundreds of microseconds in some threads. The closet solution I got is > using windows QueryPerformanceCounter (in Python, time.clock) with busy > looping checking if we have past the target time. However, that makes > the cpu usage upto almost 100%. > > So the problem (waiting tens to hundreds of us without busy looping) > still remains... I agree with Peter Hansen's reply here, so please respond to it. Windows is not a real-time OS, so what you want to do either cannot be done on Windows, or you're approaching your actual problem (whatever that may be) in a way that doesn't make good sense. From chrisdewinN0SPAM at yahoo.com.au Wed Jan 19 03:36:40 2005 From: chrisdewinN0SPAM at yahoo.com.au (Dfenestr8) Date: Wed, 19 Jan 2005 18:36:40 +1000 Subject: python/cgi/html bug References: <1106113858.360940.298900@c13g2000cwb.googlegroups.com> Message-ID: On Tue, 18 Jan 2005 21:50:58 -0800, Dan Bishop wrote: > > Dfenestr8 wrote: >> Hi. >> >> I've written a cgi messageboard script in python, for an irc chan I > happen >> to frequent. >> >> Bear with me, it's hard for me to describe what the bug is. So I've >> divided this post into two sections: HOW MY SCRIPTS WORKS, and WHAT > THE >> BUG IS. >> ... >> The problem is when someone posts a new topic, and that topic happens > to >> have "" double quotes, or any other strange character, some strange >> glitches occur. > > Use cgi.escape(topic, True) to convert HTML special characters to the > equivalent ampersand escape sequences. Thanx. Seems to work now. :) From chris.lasher at gmail.com Thu Jan 13 10:52:48 2005 From: chris.lasher at gmail.com (Chris Lasher) Date: 13 Jan 2005 07:52:48 -0800 Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <1105576444.510743.93120@f14g2000cwb.googlegroups.com> Message-ID: <1105631568.401570.255720@z14g2000cwz.googlegroups.com> >Before you get too carried away, how often do you want to do this and >how grunty is the box you will be running on? Oops, I should have specified this. The script will only need to be run once every three or four months, when the sequences are updated. I'll be running it on boxes that are 3GHz/100GB Ram, but others may not be so fortunate, and so I'd like to keep that in mind. >BTW, you need to clarify "don't have access to an RDBMS" ... surely >this can only be due to someone stopping them from installing good >free software freely available on the Internet. I understand your and others' sentiment on this. I agree, the open-source database systems are wonderful. However, keeping it Python-only saves me hassle by only having to assist in instances where others need help downloading and installing Python. I suppose if I keep it in Python, I can even use Py2exe to generate an executable that wouldn't even require them to install Python. A solution using interaction with a database is much sexier, but, for the purposes of the script, seems unnecesary. However, I certainly appreciate the suggestions. >My guess is that you don't need anything much fancier than the >effbot's index method -- which by now you have probably found works >straight out of the box and is more than fast enough for your needs. I think Mr. Lundh's code will work very well for these purposes. Thanks very much to him for posting it. Many thanks for posting that! You'll have full credit for that part of the code. Thanks very much to all who replied! Chris From apardon at forel.vub.ac.be Tue Jan 18 09:39:32 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Jan 2005 14:39:32 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-18, Steve Holden schreef : > Antoon Pardon wrote: > >> Op 2005-01-18, Nick Coghlan schreef : > [...] >> But don't use mutable keys is not a general principle. It is a principle >> introduced by the limitations of the python implementations. >> > Sorry, but it *is* a general principle, adduced from the potential > pitfalls available to inexperienced programmers when breaking the principle. But if these inexperienced programmers would have used dictionaries that were implemented more safely, those pitfalls would have been avoided. So are the pitfalls caused by breaking the principle or by using an unsafe dictionary implementation? >> I don't like it when a good rule of thumb because of implementation >> limitations is sold as a general principle. >> > So, since you are so good at nit-picking, perhaps you will explain the > difference between "rule of thumb" and "general principle". A rule of thumb is context sensitive. If circumstances change, so do the rules of thumb. Principles have a broader field of application. IMO there is nothing principally wrong with using a mutable object as a dictionary key. But avoiding doing so is a good rule of thumb if you have a python-like implementation of a dictionary. -- Antoon Pardon From gsakkis at rutgers.edu Thu Jan 6 12:45:51 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Thu, 6 Jan 2005 19:45:51 +0200 Subject: How about "pure virtual methods"? References: <10shetjeo2cbpfa@corp.supernews.com> <1gp9wjb.18uqvfi1ibk5wxN%aleaxit@yahoo.com> <86zn017miy.fsf@guru.mired.org> Message-ID: <345bqeF47qstbU1@individual.net> "Noam Raphael" wrote: > Thanks for your suggestion, but it has several problems which the added > class solves: > > * This is a very long code just to write "you must implement this > method". Having a standard way to say that is better. > * You can instantiate the base class, which doesn't make sense. > * You must use testing to check whether a concrete class which you > derived from the base class really implemented all the abstract methods. > Testing is a good thing, but it seems to me that when the code specifies > exactly what should happen, and it doesn't make sense for it not to > happen, there's no point in having a separate test for it. Here's a more refined implementation of the one posted before that addresses these issues. It defines 'abstractclass', which would be a nice class decoraror when (and if) class decorators make it into the language. The extra benefit compared to the MustImplement metaclass is that it allows a class with no abstract methods to be defined as abstract. This makes no sense if one defines an abstract class as "a class with one or more abstract (deferred) methods". Perhaps a more useful and general definition of an abstract class is "a class that is not allowed to be instantiated". Deferred methods are one reason for making a class uninstantiable, but it's not the only one. Sometimes it is useful to define a base class that provides a default implementation of a full protocol, yet disallow its direct instantiation, as in the example below. George #=========================================================== # test_abstract.py import unittest from abstract import abstractclass class AbstractTestCase(unittest.TestCase): def test_no_abstractmethods(self): class SomeBase(object): # This class has no abstract methods; yet calling foo() or bar() # on an instance of this class would cause infinite recursion. # Hence it is defined as abstract, and its concrete subclasses # should override at least one of (foo,bar) in a way that breaks # the recursion. def __init__(self, x): self._x = x def foo(self, y): return self.bar(self._x + y) def bar(self, y): return self.foo(self._x - y) SomeBase = abstractclass(SomeBase) class Derived(SomeBase): def __init__(self,x): SomeBase.__init__(self,x) def foo(self,y): return self._x * y self.assertRaises(NotImplementedError, SomeBase, 5) self.assertEquals(Derived(5).bar(2), 15) if __name__ == '__main__': unittest.main() #=========================================================== # abstract.py import inspect __all__ = ["abstractclass", "abstractmethod", "AbstractCheckMeta"] def abstractclass(cls): '''Make a class abstract. Example:: # hopefully class decorators will be supported in python 2.x # for some x, x>4 #@abstractclass class SomeBase(object): @abstractmethod def function(self): """Implement me""" # the only way as of python 2.4 SomeBase = abstractclass(SomeBase) @param cls: A new-style class object. @return: A surrogate of C{cls} that behaves as abstract. The returned class raises NotImplementedError if attempted to be instantiated directly; still its subclasses may call its __init__. A subclass of the returned class is also abstract if it has one or more abstract methods, or if it is also explicitly decorated by this function. A method is declared abstract by being assigned to NotImplemented (or decorated by L{abstractmethod}). @raise TypeError: If there is a metaclass conflict between C{type(cls)} and L{AbstractCheckMeta}, or if C{cls} has an C{__abstractmethods__} attribute. ''' # check if cls has AbstractCheckMeta (or a subtype) for metaclass metaclass = type(cls) if not issubclass(metaclass, AbstractCheckMeta): # it doesn't; try to make AbstractCheckMeta its metaclass by # inheriting from _AbstractCheck cls = metaclass(cls.__name__, (_AbstractCheck,) + cls.__bases__, dict(cls.__dict__)) # replace __init__ with a proxy ensuring that __init__ is called by a # subclass (but not directly) old_init = getattr(cls,'__init__',None) def new_init(self,*args,**kwds): if self.__class__ is cls: raise NotImplementedError("%s is an abstract class" % cls.__name__) if old_init is not None: old_init(self,*args,**kwds) setattr(cls,'__init__',new_init) return cls def abstractmethod(function): '''A method decorator for those who prefer the parameters declared.''' return NotImplemented class AbstractCheckMeta(type): '''A metaclass to detect instantiation of abstract classes.''' def __init__(cls, name, bases, dict): if '__abstractmethods__' in cls.__dict__: raise TypeError("'__abstractmethods__' is already defined in " "class '%s': %s" % (cls.__name__, cls.__dict__['__abstractmethods__'])) type.__init__(cls, name, bases, dict) cls.__abstractmethods__ = [name for name, value in inspect.getmembers(cls) if value is NotImplemented] def __call__(cls, *args, **kwargs): if cls.__abstractmethods__: raise NotImplementedError( "Class '%s' cannot be instantiated: Methods %s are abstract." % (cls.__name__,", ".join(map(repr,cls.__abstractmethods__)))) return type.__call__(cls, *args, **kwargs) class _AbstractCheck(object): ''' A class to stick anywhere in an inheritance chain to make its descendants being checked for whether they are abstract. ''' __metaclass__ = AbstractCheckMeta From jdhunter at ace.bsd.uchicago.edu Mon Jan 31 23:14:11 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Mon, 31 Jan 2005 22:14:11 -0600 Subject: Python's idiom for function overloads In-Reply-To: <200502010417.10481.frans.englich@telia.com> (Frans Englich's message of "Tue, 1 Feb 2005 04:17:10 +0000") References: <200502010417.10481.frans.englich@telia.com> Message-ID: >>>>> "Frans" == Frans Englich writes: Frans> Hello, Frans> Since Python doesn't have static typing, how is the same Frans> result as traditional function overloads results in Frans> acheived? With function overloads the "selection of code Frans> path depending on data type" is transparent and automatic Frans> since the typing system figure out what goes to what. Frans> But in Python, when one wants to be able to pass different Frans> data types into a single "entry point" for functionality, Frans> how is that best done? To in a function do an if statement Frans> with the type() function? Using type or isinstance is one way to do it. The other way is "duck typing". If it walks like a duck and talks like a duck, it probably is a duck. The core idea is that we care less about what type an object is, and more about what services the object provides. Eg def myoverload(x): try: noise = x.quack() except AttributeError: # do something else... else: # do something with noise Variants to the try/except approach include hasattr, getattr and so on.. googling python duck typing should speed you on your way. JDH From steve at holdenweb.com Wed Jan 12 18:00:34 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 12 Jan 2005 18:00:34 -0500 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: <7xmzvfn096.fsf@ruckus.brouhaha.com> References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > michele.simionato at gmail.com writes: > >>2. One could proposed hygienic pattern-matching macros in Python, >>similar to >>Scheme syntax-rules macros. Again, it is not obvious how to >>implement pattern-matching in Python in a non-butt-ugly way. Plus, >>I feel hygienic macros quite limited and not worth the effort. > > > It wasn't obvious how to do it in Scheme either. There was quite > a bit of head scratching and experimental implementation before > there was consensus. > > >>3. We would add to Python the learning curve of macros and their >>subtilities and we do not want it. > > > I can't imagine how it could be worse than the learning curve of > __metaclass__, which we already have. If it was done in a way that > most of us would just rely on a few standard ones, that would be fine. > Well the necessity to understand metaclasses could in some ways be regarded as the push for the summit, and therefore isn't something that would trouble newbies. Given that we are having this discussion in the context of a posited "where" clause intended to allow "multi-statement expressions" (whatever they turn out to be) I would still argue you are discussing the totally unnecessary. Given that Guido is on record as saying that expressions aren't statements because he wants those things to be separate, I don't really see why there's this consistent pressure to reverse that decision. > >>4. Macros would complicate a lot Python module system. > > > I don't see how, but maybe I'm missing something. > > >>5. We have Guido providing a good syntax for us all, why we should be >>fiddling with it? More seriously, if some verbosity is recognized >>in the language (think to the "raison d'etre" of decorators, for >>instance) I very much prefer to wait for Guido to take care of >>that, once and for all, than having 100 different custom made >>solutions based on macros. > > > Every time some newbie asks an innocent "how do I ..." question, we > see unbelievably horrid answers from gurus. Just check the FAQ about > conditional expressions, etc. I just don't see Python syntax changes > as forthcoming. > There's a reason for this ... > >>What I would be interested in is a Lisp/Scheme implementation >>compiling to Python bytecode, but I am not aware of any project >>in that direction. > > > But that sounds like a bizarre idea. Python bytecode is just a > CPython artifact, not part of the language. And it's not even that > good an artifact. Good Lisp/Scheme implementations compile to native > code that beats the pants off of CPython bytecode. It would make much > more sense to have a Python implementation that compiles Python to > S-expressions and then lets a high performance Lisp or Scheme system > take care of the rest. Which would be a worthier goal than trying to graft macros on to Python. You responded that macros would be difficult to implement in m4 because (in essence) of the indented structure of Python. I'm not convinced they'd be any easier in Python, and I'm *certainly* not convinced that their addition would improve Python's readability. At best it would offer new paradigms for existing constructs (violating the "there should be one obvious way to do it" zen); at worst it would obfuscate the whole language. If you really see the need for Python macros then a preprocessor would surely be the best way to prove the validity of such ideas? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From remi at cherrypy.org Mon Jan 3 15:56:14 2005 From: remi at cherrypy.org (remi at cherrypy.org) Date: 3 Jan 2005 12:56:14 -0800 Subject: Ann: CherryPy-2.0-beta released References: <1104774372.943278.302050@f14g2000cwb.googlegroups.com> <1104783888.664232.72720@f14g2000cwb.googlegroups.com> Message-ID: <1104785774.524707.214290@f14g2000cwb.googlegroups.com> > I'm a great believer that avoiding query strings in URL's is good > practise ( http://www.holloway.co.nz/book/9 for good arguments why). CherryPy also supports that out of the box: class Book: def default(self, categoryName, bookId): ... cpg.root.book = Book() If you go to "http://domain/book/science/9", CherryPy will call book.default('science', '9') > Also how > much does it complicate matters to run cherryPy under an existing > webserver? Is any functionality lost? Well, you can easily run CherryPy behind Apache (see http://trac.cherrypy.org/cgi-bin/trac.cgi/wiki/BehindApache). Since CherryPy provides a WSGI interface (although it's still experimental), you can also run your CherryPy app with any WSGI-compatible HTTP server (although I don't really see any advantage to doing this). Remi From nick at craig-wood.com Thu Jan 27 10:30:01 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 27 Jan 2005 15:30:01 GMT Subject: Help With Python References: <87ekg8c4d0.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: Steven Bethard wrote: > Nick Vargish wrote: > > # this is one viking making one order repeated 511 times. if you want > > # 511 vikings making seperate orders, you'll have to write a loop. > > No need to write a loop: > > py> class Viking(object): > ... def order(self): > ... return 'Spam' > ... > py> v = Viking() > py> orders = [v.order()] * 7 > py> ', '.join(orders) > 'Spam, Spam, Spam, Spam, Spam, Spam, Spam' > py> orders = [Viking().order()] * 7 > py> ', '.join(orders) > 'Spam, Spam, Spam, Spam, Spam, Spam, Spam' Thats still one Viking making 7 orders surely? Eg >>> vikings = [Viking()] * 7 >>> vikings[0] is vikings[1] True whereas >>> vikings = [Viking() for _ in range(7)] >>> vikings[0] is vikings[1] False So you want this... >>> orders = [ Viking().order() for _ in range(7) ] -- Nick Craig-Wood -- http://www.craig-wood.com/nick From pfhreak at mac.com Fri Jan 21 16:38:53 2005 From: pfhreak at mac.com (Pfhreak) Date: Fri, 21 Jan 2005 16:38:53 -0500 Subject: Xah Lee's Unixism References: <7fe97cc4.0408251356.34f2102a@posting.google.com> <1gj5eeq.gb3dk41wup9zwN%otto.wyss@orpatec.ch> <87hdqptl96.fsf_-_@thalassa.informatimago.com> <4PGdnfsOfdDPi63cRVn-tA@speakeasy.net> <41337FC9.8070902@hotmail.com> <%T%Yc.29567$Es2.11957889@news4.srv.hcvlny.cv.net> <2mmdj0t6mjgif88en11skbo3n8uiuj46nc@4ax.com> <1094141001.125507@teapot.planet.gong> Message-ID: Patrick, I maintain the web page that Rupert mentions in responce to your message about Nextstep and Mach. (http://www.macos.utah.edu/Documentation/MacOSXClasses/macosxone/unix.html) I'm curious to learn more about the development of Mach and its use in Nextstep. Can you point me to your sources -- preferably online so I can put them in the Bibliography section -- especially those that mention when Mach was turned into a Microkernel? From rbt at athop1.ath.vt.edu Mon Jan 10 12:34:22 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 10 Jan 2005 12:34:22 -0500 Subject: ftplib with unknown file names Message-ID: How can I use ftplib to retrieve files when I do not know their names? I can do this to get a listing of the directory's contents: ftp_server.retrlines('LIST') The output from this goes to the console and I can't figure out how to turn that into something I can use to actually get the files (like a list of file names). I read a bit about the callback function that can be passed to retrlines but I couldn't figure out how to use it. Any help is appreciated. Thanks! From jhefferon at smcvt.edu Tue Jan 18 13:03:12 2005 From: jhefferon at smcvt.edu (Jim) Date: 18 Jan 2005 10:03:12 -0800 Subject: script to automate GUI application (newbie) In-Reply-To: References: Message-ID: <1106071392.908441.262500@c13g2000cwb.googlegroups.com> It sounds like a case for the Expect program, to me. Try Google-ing for "Expect". If you are looking for a Python approach, then try googling for "Expect Python". Jim From aahzpy at panix.com Sun Jan 9 23:53:24 2005 From: aahzpy at panix.com (aahzpy at panix.com) Date: Sun, 9 Jan 2005 23:53:24 -0500 Subject: BayPIGgies: January 13, 7:30pm Message-ID: <20050110045324.GA16439@panix.com> WARNING: the last meeting of BayPIGgies at Stanford is currently scheduled for March. Our host, Danny Yoo, is leaving Stanford, and we need to find a new location. If you wish to assist with the search, please join the BayPIGgies mailing list. Meanwhile, let's all give hearty thanks to Danny for helping us find a stable meeting location for so long! The next meeting of BayPIGgies will be Thurs, January 13 at 7:30pm. Danny Yoo leads a discussion of Python coding tricks and techniques. Please join the BayPIGgies mailing list to discuss which sample code will be demonstrated. The web site will contain more details. BayPIGgies meetings are in Stanford, California. For more information and directions, see http://www.baypiggies.net/ Before the meeting, we may meet at 6pm for dinner in downtown Palo Alto. Discussion of dinner plans is handled on the BayPIGgies mailing list. Advance notice: The February 10 meeting agenda has not been set. Please send e-mail to baypiggies at baypiggies.net if you want to make a presentation. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From s_david_rose at hotmail.com Wed Jan 19 14:35:22 2005 From: s_david_rose at hotmail.com (GMane Python) Date: Wed, 19 Jan 2005 14:35:22 -0500 Subject: Automatic Windows printer creation? Message-ID: Anyone know if there's a module which will allow me to 'create' windows printer definitions? Not from a Windows domain network, but just to add a printer that sends to a jet-direct-attached printer. Thanks! Dave From fredrik at pythonware.com Fri Jan 21 12:54:50 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 21 Jan 2005 18:54:50 +0100 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> Message-ID: "rm" wrote: > well, I did look at it, and as a text format is more readable than XML is. judging from http://yaml.org/spec/current.html (750k), the YAML designers are clearly insane. that's the most absurd software specification I've ever seen. they need help, not users. From rkern at ucsd.edu Thu Jan 13 15:34:07 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 13 Jan 2005 12:34:07 -0800 Subject: News Reader In-Reply-To: References: Message-ID: Daniel Bowett wrote: > Is anyone reading this list through thunderbird as news? If so - how did > you set it up? I subscribed to comp.lang.python under my USENET news server account. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From fuzzyman at gmail.com Sat Jan 29 08:09:21 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Jan 2005 05:09:21 -0800 Subject: Help with web dashboard In-Reply-To: References: <1106924984.507889.265070@c13g2000cwb.googlegroups.com> Message-ID: <1107004161.954148.206750@f14g2000cwb.googlegroups.com> Chris wrote: > In article <1106924984.507889.265070 at c13g2000cwb.googlegroups.com>, > fuzzyman at gmail.com says... > > Ifd you want to use standard CGI I've written a CGI user > > authentication/management module called logintools. > > > > Would this be preferred (or easier) than using an application server > (ie. Zope or Webware)? > > If possible, I think it would be nice if the security aspect of it was > already built-in so I would not need to write/test it myself. > > Thanks for your help. For simple applications, writing CGIs is going to be quite a lot easier than using something like Zope. If your final product is big and complex then CGIs probably aren't suitable anyway. logintools is a module providing user authentication/administration and user management specifically for CGIs. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From exarkun at divmod.com Thu Jan 6 09:40:01 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 06 Jan 2005 14:40:01 GMT Subject: sorting on keys in a list of dicts In-Reply-To: Message-ID: <20050106144001.25734.834316519.divmod.quotient.3738@ohm> On Thu, 06 Jan 2005 15:31:22 +0100, J Berends wrote: >Suppose I have a list of dictionaries and each dict has a common keyname > with a (sortable) value in it. > > How can I shuffle their position in the list in such way that they > become sorted. > In Python 2.4, import operator L.sort(key=operator.itemgetter(key)) In Python 2.3, L2 = [(d[key], i, d) for (i, d) in enumerate(L)] L2.sort() L = [d for (v, i, d) in L2] Jp From gregor.jan at NOSPAM.quick.cz Thu Jan 27 06:07:57 2005 From: gregor.jan at NOSPAM.quick.cz (Jan Gregor) Date: Thu, 27 Jan 2005 12:07:57 +0100 Subject: redirect of standard output of jython to JTextArea Message-ID: Hello I want to redirect output of jython's functions print and println to JTextArea component. Is it possible ? I tried this (swingConsole.textArea is instance): In my class self.printStream= MyPrintStream(System.out) System.setOut(self.printStream) ---------------------------------------------------- class MyPrintStream (PrintStream): def println (str): swingConsole.textArea.append(str) def print (str): swingConsole.textArea.append(str) Output is still directed to standard output. Thanks for help, Jan From donn at u.washington.edu Fri Jan 7 14:53:37 2005 From: donn at u.washington.edu (Donn Cave) Date: Fri, 07 Jan 2005 11:53:37 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> Message-ID: In article , Steven Bethard wrote: > Andrey Tatarinov wrote: > > It would be great to be able to reverse usage/definition parts in > > haskell-way with "where" keyword. Since Python 3 would miss lambda, that > > would be extremly useful for creating readable sources. > > > > Usage could be something like: > > > > >>> res = [ f(i) for i in objects ] where: > > >>> def f(x): > > >>> #do something > > > > or > > > > >>> print words[3], words[5] where: > > >>> words = input.split() > > > > - defining variables in "where" block would restrict their visibility to > > one expression > > How often is this really necessary? Could you describe some benefits of > this? I think the only time I've ever run into scoping problems is with > lambda, e.g. > > [lambda x: f(x) for x, f in lst] > > instead of > > [lambda x, f=f: for x, f in lst] > > Are there other situations where you run into these kinds of problems? Note that he says "would be extremely useful for creating readable sources", so the "these kinds of problems" he would have been thinking of would be where source was not as readable as it could be. You seem to be concerned about something else. I don't by any means agree that this notation is worth adopting, and in general I think this kind of readability issue is more or less a lost cause for a language with Python's scoping rules, but the motive makes sense to me. One way to look at it might be, if I observe that "words" is assigned to in a where clause, then I know it will not be used elsewhere in the surrounding scope so I can forget about it right away. If the name does occur elsewhere, it evidently refers to something else. Donn Cave, donn at u.washington.edu From skip at pobox.com Tue Jan 4 10:19:13 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 Jan 2005 09:19:13 -0600 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) In-Reply-To: <1104849206.111461.70500@c13g2000cwb.googlegroups.com> References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> Message-ID: <16858.46065.784624.754021@montanaro.dyndns.org> michele> BTW what's the difference between .encode and .decode ? I started to answer, then got confused when I read the docstrings for unicode.encode and unicode.decode: >>> help(u"\xe4".decode) Help on built-in function decode: decode(...) S.decode([encoding[,errors]]) -> string or unicode Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registerd with codecs.register_error that is able to handle UnicodeDecodeErrors. >>> help(u"\xe4".encode) Help on built-in function encode: encode(...) S.encode([encoding[,errors]]) -> string or unicode Encodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors. It probably makes sense to one who knows, but for the feeble-minded like myself, they seem about the same. I'd be happy to add a couple examples to the string methods section of the docs if someone will produce something simple that makes the distinction clear. Skip From rnd at onego.ru Tue Jan 4 17:04:49 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 5 Jan 2005 01:04:49 +0300 (MSK) Subject: Python evolution: Unease In-Reply-To: <41DAFF93.7030502@pythonapocrypha.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> Message-ID: On Tue, 4 Jan 2005, Dave Brueck wrote: >> What about generic programming coming into fashion anytime soon? >Roman, I think I've read every single thread in the past year or three >wherein you've brought up generic programming, and I think you'd do well to >choose a new term for the idea you're trying to convey. Or, yes, and I forgot to mention that generic programming is much clearer idea than OO programming, as it is not so vague. At least for me: I still don't fully comprehend OOP (after N years of "studying" it!) and understanding of GP came after just one book on the topic. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From annaraven at gmail.com Mon Jan 10 13:16:12 2005 From: annaraven at gmail.com (Anna) Date: 10 Jan 2005 10:16:12 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: <10u5fu3o7v4h9e3@corp.supernews.com> References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <10u5fu3o7v4h9e3@corp.supernews.com> Message-ID: <1105380972.666888.75280@f14g2000cwb.googlegroups.com> Same here. From holywill at gmail.com Tue Jan 11 20:27:09 2005 From: holywill at gmail.com (Will) Date: Wed, 12 Jan 2005 14:27:09 +1300 Subject: Game programming in Python In-Reply-To: References: Message-ID: <11a4311705011117277e31db2e@mail.gmail.com> Hi Baza, On Tue, 11 Jan 2005 18:32:50 +0000, Baza wrote: > I'm looking for any books or on-line resources on game programming using > Python. Does anyone have any advice? You're probably beyond this book, however, for other newbies like moi checking this thread in future, I started with: "Python Programming for the absolute beginner" By Michael Dawson (Premier Press- www.premierpressbooks.com. ISBN: 1-59200-073-8) It's a great read and easy to follow, but more importantly in this instance, one learns Python by creating games (and then you can put this knowledge to use elsewhere). It comes with a CD that has Python 2.2.3, Pygame 1.5.6 and Livewires 2.0, the source code for the projects in the book, & useful links (as well as The Gimp for Windows and a demo version of the Cool Edit Pro multitrack recording studio). HTH. L8r, Will # Living & loving in Aotearoa, New Zealand. Kia ora Kiwis! From nick at craig-wood.com Sat Jan 22 04:30:07 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 22 Jan 2005 09:30:07 GMT Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Here's the message I had in mind: > > http://groups-beta.google.com/group/comp.lang.python/msg/adfbec9f4d7300cc > > It came from someone who follows Python crypto issues as closely as > anyone, and refers to a consensus on python-dev. I'm not on python-dev > myself but I feel that the author of that message is credible and is > not just "anyone". And here is the relevant part... "A.M. Kuchling" wrote: > On Fri, 27 Feb 2004 11:01:08 -0800 Trevor Perrin wrote: > > Are you and Paul still looking at adding ciphers to stdlib? That would > > make me really, really happy :-).... > > No, unfortunately; the python-dev consensus was that encryption raised > export control issues, and the existing rotor module is now on its way to > being removed. I'm sure thats wrong now-a-days. Here are some examples of open source software with strong crypto Linux kernel: http://www.kernel.org/ GNU crypto project: http://www.gnu.org/software/gnu-crypto/ TryCrypt: http://truecrypt.sourceforge.net/ OpenSSL: http://www.openssl.org/ AEScrypt: http://aescrypt.sourceforge.net/ Note that some of these are being worked on at sourceforge just like python. Surely it must be possible to add a few simple crypto modules to python? That said a) IANAL b) 'apt-get install python-crypto' works for me ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jacek.generowicz at cern.ch Tue Jan 11 03:26:09 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 11 Jan 2005 09:26:09 +0100 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <1105381339.922714.23200@c13g2000cwb.googlegroups.com> <1oFEd.71967$Jk5.45632@lakeread01> Message-ID: Steve Holden writes: > Well, I suspect that Church originally chose lambda precisely because > of its meaninglessness, IAANM, Church didn't choose lambda at all. He chose to put a "hat" (like a circumflex accent) above the bound name. Then, because of some typesetting difficulties, this was transformed into the nearest thing that looked like it: a capital lambda in front of the name ... and later the capital lambda turned into a lowercase one. From http Thu Jan 6 02:19:39 2005 From: http (Paul Rubin) Date: 05 Jan 2005 23:19:39 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> Message-ID: <7x652bnhx0.fsf@ruckus.brouhaha.com> bokr at oz.net (Bengt Richter) writes: > What do you think of automated secure importing/installing from a > remote server? You know, you try to import something and it imports > a stub that was included as a battery-place-holder and that has > basic help info and will give you reasonable options in directing > the installation of the full thing (or subset you are interested in). You mean for Python modules, in ordinary operation? I'd hate that. For things like apt-get, used for installing nonstandard programs or getting security updates, I guess it's about as good as one can hope for. The user has to activate it explicitly though. I definitely don't want my computer opening internet connections unless I specifically ask it to. Doing otherwise is almost spyware. This may sound a little extreme but my distribution philosophy is I'd like to get closer to an environment where users normally never install any software of any type, ever. Microsoft cornered the OS market cornered by acheiving something pretty close to this: they deliver Windows with no installation needed. When people buy new computers, Windows is already on the hard drive, so the user just turns the computer on and Windows is there. Fedora Core (what I'm running now) isn't shipped that way by any computer makers that I know of, but it makes up for it by having lots of applications included. So I buy a new computer, put in the bootable Fedora DVD-ROM, and sit back for half an hour while a one-time installation runs. That's about as close as I can get to just turning on the new computer and having Fedora already there. > I don't see why every gee whiz thing has to be on your hard disk > from the first. And for those that want a big grabbag, the stubs > ought to be designed to to be runnable from a configured script, so > you can turn it loose and see what's up IRL. If I have a 400 gig hard drive, I don't see why I need 99.99% of it empty instead of 99.0% after I do my OS install. I don't want to hassle over downloading stuff for hours or days at a time, or about what components depend on other components, if the distro can just include it. I just tried to install a Python program that uses wxPython, except that meant I had to download both wxPython and wxWidgets, and the installations failed because of some version mismatch between the current wxWidgets distro and the version of GTK included with FC3. I spent an hour or so messing with it and then said screw it and gave up on the GUI part of that program. I'm more technical than most users (I'm a programmer) yet this installation stuff is too much hassle even for me. So I'd really rather that all that stuff be pre-configured. If a system has N downloadable components that are supposedly independent, there are 2**N combinations of them that anyone might have installed. In reality the indepdence is never that complete, so something can easily go wrong if you pick a combination that hasn't been tested and debugged by someone, and there's no way to test more than a few of the possibilities. So I'd rather that all N components already be included with the OS so that the combination will have been tested by the distro maintainers before the end user has to deal with it. Hard drives and distro media (DVD) are big enough now that it's quite reasonable for distros to include just about everything that most users could want. From andy at andygross.org Wed Jan 5 16:10:02 2005 From: andy at andygross.org (Andy Gross) Date: Wed, 5 Jan 2005 16:10:02 -0500 Subject: Embedding a restricted python interpreter In-Reply-To: References: Message-ID: <2A8E5F75-5F5E-11D9-923E-000A95CED3AC@andygross.org> Check out http://mail.python.org/pipermail/python-dev/2003-January/031851.html for a historical thread on rexec.py's vulnerabilities. Right now, the answer for people who want restricted execution is usually "wait for pypy", due to the number of tricks that can subvert the rexec model. There are probably some one-off, application-specific things you can do that might meet your requirements, like special import hooks, sys.settrace() callbacks that inspect each running frame (and are slow), and namespace restrictions on stuff passed to exec or eval. If you really need sandboxing, your probably out of luck. Setting up a usermode linux instance or chrooted jail is probably the best bet today. /arg On Jan 4, 2005, at 6:38 PM, Rolf Magnus wrote: > Hi, > > I would like to embed a python interpreter within a program, but since > that > program would be able to automatically download scripts from the > internet, > I'd like to run those in a restricted environment, which basically > means > that I want to allow only a specific set of modules to be used by the > scripts, so that it wouldn't be possible for them to remove files from > the > hard drive, kill processes or do other nasty stuff. > Is there any way to do that with the standard python interpreter? > > -- > http://mail.python.org/mailman/listinfo/python-list From mcfletch at rogers.com Mon Jan 24 10:14:40 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 24 Jan 2005 10:14:40 -0500 Subject: Weakref.ref callbacks and eliminating __del__ methods In-Reply-To: <5lr9v0tg2i16irskb798f7rcti955j0c64@4ax.com> References: <41F427EB.3000200@rogers.com> <1f7befae0501231720428ca3c@mail.gmail.com> <5lr9v0tg2i16irskb798f7rcti955j0c64@4ax.com> Message-ID: <41F510E0.40301@rogers.com> Richie Hindle wrote: >[Tim] > > >>I'll note that one fairly obvious pattern works very well for weakrefs >>and __del__ methods (mutatis mutandis): don't put the __del__ method >>in self, put it in a dead-simple object hanging *off* of self. Like >>the simple: >> >>class BTreeCloser: >> def __init__(self, btree): >> self.btree = btree >> >> def __del__(self): >> if self.btree: >> self.btree.close() >> self.btree = None >> >>Then give self an attribute refererring to a BTreeCloser instance, and >>keep self's class free of a __del__ method. The operational >>definition of "dead simple" is "may or may not be reachable only from >>cycles, but is never itself part of a cycle". >> >> > >This is very nice - I've been wondering about just this problem recently, >and this will be very useful. Many thanks! > > From me too :) >One question: why the `self.btree = None` in the last line? Isn't >`self.btree` guaranteed to go away at this point anyway? (If the answer >is "it's necessary for weird cases that would take an hour to explain" >then I'll be more than happy to simply use it. 8-) > > It's to allow the Closer object to act as a substitute for a .close() method on the object, the final full code of the Closer looks like this: class Closer( object ): """Close the OIDStore""" def __init__( self, client ): """Initialise the closer object""" self.btree = client.btree def __call__( self ): """Close and cleanup to prevent multiple calls""" if self.btree: self.btree.close() self.btree = None def __del__( self ): """Handle deletion of the closer object (close btree if necessary)""" self() and we store one of these as self.close in the OIDStore instance' dictionary. self.close = Closer( self ) If the user explicitly calls storage.close() we don't want the __del__ trying to re-close the storage later. In other words, its an explicit requirement for *this* __del__, not a general requirement. Have fun, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From usenet_spam at janc.invalid Fri Jan 21 23:05:48 2005 From: usenet_spam at janc.invalid (JanC) Date: Sat, 22 Jan 2005 04:05:48 GMT Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> Message-ID: Robin Becker schreef: > well since rotor is a german (1930's) invention And AES is a Belgian invention... ;-) > it is a bit late for > Amricans (Hollywood notwithstanding) to be worried about its export -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From jack at performancedrivers.com Sun Jan 30 09:49:19 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Sun, 30 Jan 2005 09:49:19 -0500 Subject: limited python virtual machine In-Reply-To: <41FC3F8B.9080800@iinet.net.au> References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr58wn.m3n0xac2j9qbN%aleaxit@yahoo.com> <41FC3F8B.9080800@iinet.net.au> Message-ID: <20050130144919.GV1607@performancedrivers.com> On Sun, Jan 30, 2005 at 11:59:39AM +1000, Nick Coghlan wrote: > Alex Martelli wrote: > >It didn't seem to me that Steven's question was so restricted; and since > >he thanked me for my answer (which of course is probably inapplicable to > >some custom interpreter that's not written yet) it appears to me that my > >interpretation of his question was correct, and my answer useful to him. > > Yes, I'd stopped following the thread for a bit, and the discussion had > moved further afield than I realised :) > > >If you _can_ execute (whatever) in a separate process, then an approach > >based on BSD's "jail" or equivalent features of other OS's may be able > >to give you all you need, without needing other restrictions to be coded > >in the interpreter (or whatever else you run in that process). > > I think that's where these discussion have historically ended. . . making a > Python-specific sandbox gets complicated enough that it ends up making more > sense to just use an OS-based sandbox that lets you execute arbitrary > binaries relatively safely. > > The last suggestion I recall along these lines was chroot() plus a > monitoring daemon that killed the relevant subprocess if it started > consuming too much memory or looked like it had got stuck in an infinite > loop. > The Xen virtual server[1] was recently metnioned on slashdot[2]. It is more lightweight and faster than full scale machine emulators because it uses a modified system kernel (so it only works on *nixes it has been ported to). You can set the virtual memory of each instance to keep programs from eating the world. I don't know about CPU, you might still have to monitor & kill instances that peg the CPU. If anyone does this, a HOWTO would be appreciated! -Jack From jwaixs at gmail.com Mon Jan 3 09:56:44 2005 From: jwaixs at gmail.com (Noud Aldenhoven) Date: Mon, 03 Jan 2005 15:56:44 +0100 Subject: removing comments form a file References: <5b617$41d956df$53e8229a$22273@freeler.nl> <1104765734.888089.279470@f14g2000cwb.googlegroups.com> Message-ID: <6e9c$41d969fe$53e8229a$23742@freeler.nl> Ah, Thank you, I never thaught about the re module. Now I can do some cool stuf. Greetings, Noud Aldenhoven ps. Zal ik een keer langs komen? ;-P wittempj at hotmail.com wrote: > You cold do something like this: > >>>> import re >>>> commentpattern = re.compile('.*(?=//)|.*(?!//)') >>>> stringwithcomment = 'Blah di blah // some comment' >>>> match = commentpattern.match(stringwithcomment) >>>> match.group() > 'Blah di blah ' >>>> stringwithoutcomment = 'Blah di blah' >>>> match = commentpattern.match(stringwithoutcomment) >>>> match.group() > 'Blah di blah' >>>> blankline = '\n' >>>> match = commentpattern.match(blankline) >>>> match.group() > '' >>>> > > and put this in a loop where you iterate over your file. > Martin (The Netherlands, Amsterdam, bij Diemen) > > Noud Aldenhoven wrote: >> Hello everyone, >> >> I was wondering how to remove comments away form a file. >> So that's why I made this script. >> >> =============================== >> #!/usr/bin/env python >> >> import sys >> import string >> import time >> >> helptext = "usage: python rmcomment [oldfile] [newfile] [comment]" >> >> def rmcomment(oldfile, newfile, comment): >> oldfile = open(oldfile, 'r') >> newfile = open(newfile, 'w') >> ccount = 0 >> lcount = 0 >> for line in oldfile.readlines(): >> splitline = string.split(line) >> pstest = 0 >> fileline = "" >> for word in splitline: >> if word[:2] == comment: >> pstest = -1 >> ccount += 1 >> pass >> elif pstest == -1: >> pass >> else: >> fileline += word + " " >> if len(fileline) == 0: >> pass >> else: >> newfile.write(fileline + "\n") >> lcount += 1 >> print "Done... in %s seconds\nRemoved comment from %s > lines\nWrote % >> lines to %s" % (time.time()-start , ccount, lcount, newfile) >> raw_input("Push the enter button to quit>") >> >> if __name__ == "__main__": >> if sys.argv[1] == "-h" or sys.argv[1] == "-help": >> print helptext >> else: >> start = time.time() >> oldfile = sys.argv[1] >> newfile = sys.argv[2] >> comment = sys.argv[3] >> rmcomment(oldfile, newfile, comment) >> >> >> ======================================== >> >> This script works fine with standard text files. An example is this > one: >> >> example.txt: >> >> Hello Fuckin' World //how are you doing today >> //I think it delete this sentence and the next sentence too! >> >> But this one not! #Even not this comment >> >> end example.txt >> >> If I use my script, named rmcomment.py I get this: >> >> jwaixs at linux:~/programmeren/python/rmcomment$ cat example.txt >> Hello Fuckin' World //how are you doing today >> //I think it delete this sentence and the next sentence too! >> >> But this one not! #Even not this comment's >> jwaixs at linux:~/programmeren/python/rmcomment$ python rmcomment.py >> example.txt newexample.txt // >> Done... in 0.00104999542236 seconds >> Removed comment from 2 lines >> Wrote 2nes to >> Push the enter button to quit> >> jwaixs at linux:~/programmeren/python/rmcomment$ cat newexample.txt >> Hello Fuckin' World >> But this one not! #Even not this comment >> jwaixs at linux:~/programmeren/python/rmcomment$ >> >> works fine... but here's my problem. If I use rmcomment.py also the >> whitelines will be removed. And I don't want that to happen. Here's > another >> example: >> >> jwaixs at linux:~/programmeren/python/rmcomment$ cat otherexample.txt >> //This shows what whitelines are doing here >> left from me is a nice white line tabs >> and here left are at least 3 white line tabs >> >> //and ofcourse, comments will be deleted >> jwaixs at linux:~/programmeren/python/rmcomment$ python rmcomment.py >> otherexample.txt newotherexample.txt // >> Done... in 0.0011351108551 seconds >> Removed comment form 2 lines >> Wrote 2nes to 0x403e1c60> >> Push the enter button to quit> >> jwaixs at linux:~/programmeren/python/rmcomment$ cat newotherexample.txt >> left from me is a nice white line tabs >> and here left are at least 3 white line tabs >> jwaixs at linux:~/programmeren/python/rmcomment$ >> >> My beautiful whitelines are gone! And I don't want that! >> I've thaught how to fix this for a time, but I can't make it on my > own. Too >> less programming experiance, I'm afraid. >> Could someone help me with this problem? Or fix the script or give a > hint or >> something? >> >> Thank you at least for reading this post, >> >> Noud Aldenhoven >> The Netherlands (In de beurt bij Nijmegen, voor de nieuwschierigen) >> >> ps. Yes, I'm a Dyslextion and can't write correct english. I'm sorry > for >> that. From peter at engcorp.com Tue Jan 18 20:01:01 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Jan 2005 20:01:01 -0500 Subject: file copy portability In-Reply-To: References: Message-ID: Bob Smith wrote: > Is shutil.copyfile(src,dst) the *most* portable way to copy files with > Python? I'm dealing with plain text files on Windows, Linux and Mac OSX. Yes, provided you don't need any of the features provided by the other shutil.copy functions, and assuming you can live with the Caveat listed in the docs for the MacOS system... -Peter From ncoghlan at iinet.net.au Thu Jan 20 07:27:05 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 20 Jan 2005 22:27:05 +1000 Subject: Class introspection and dynamically determining function arguments In-Reply-To: <359lfnF4hd6e3U1@individual.net> References: <359lfnF4hd6e3U1@individual.net> Message-ID: <41EFA399.6080504@iinet.net.au> Diez B. Roggisch wrote: > Mark English wrote: > As youself already mentioned that maybe you have to impose certain > prerequisites, you maybe want to extend this to the point where for each > class you want to make dynamically instantiatable you need some > declaration. This of course depends on your desired application - whatfor > is it planned? If this only has to work for classes created for the purpose (rather than for an arbitrary class): Py> class Buildable(object): ... __slots__ = ["x", "y"] ... def __init__(self, **kwds): ... super(Buildable, self).__init__(self, **kwds) ... for attr in Buildable.__slots__: ... setattr(self, attr, kwds[attr]) ... Py> b = Buildable(x = 1 , y = 2) Py> b.x 1 Py> b.y 2 (Note that you don't *have* to use slots, you can use a non-special class attribute if you don't want the other side effects) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jbperez808 at wahoo.com Sun Jan 2 14:08:30 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Mon, 03 Jan 2005 03:08:30 +0800 Subject: Continuations Based Web Framework - Seaside. In-Reply-To: <41d7f5eb$0$10383$e4fe514c@dreader18.news.xs4all.nl> References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <41d7f5eb$0$10383$e4fe514c@dreader18.news.xs4all.nl> Message-ID: <33qumeF4319dcU1@individual.net> none wrote: > Does Python really need yet another framework? Apart from the > intellectual excersise, wouldn't it be nice if Python would get a > framework "for the rest of us" (meaning: mere mortals) which would focus > upon getting work done in a simple manner instead of creating yet > another, new, hip, exciting, way of creating dynamic websites? If Python > cannot deliver a PHP clone, at least you would expect a Rails lookalike. Spyce (http://spyce.sf.net) would be the superior Python-based PHP clone you are looking for. From steve at holdenweb.com Mon Jan 3 14:45:36 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Jan 2005 14:45:36 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com><7xmzvu1ycn.fsf@ruckus.brouhaha.com><7xd5wqd14y.fsf@ruckus.brouhaha.com><7xfz1lal5d.fsf@ruckus.brouhaha.com><7xekh423b6.fsf@ruckus.brouhaha.com> <_rTBd.66275$Jk5.46@lakeread01> Message-ID: Terry Reedy wrote: > "Steve Holden" wrote in message > news:_rTBd.66275$Jk5.46 at lakeread01... > >>Well clearly there's a spectrum. However, I have previously written that >>the number of open source projects that appear to get stuck somewhere >>between release 0.1 and release 0.9 is amazingly large, and does imply >>some dissipation of effort. > > > And how do the failure and effort dissipation rates of open source code > compare to those of closed source code? Of course, we have only anecdotal > evidence that the latter is also 'amazingly large'. And, to be fair, the > latter should include the one-programmer proprietary projects that > correspond to the one-programmer open projects. > > Also, what is 'amazing' to one depends on one's expectations ;-). It is > known, for instance, that some large fraction of visible retail business > fail within a year. And that natural selection is based on that fact that > failure is normal. > Well, since everything you say is true, I suppose there's not much wriggle room for me. But when a shop goes belly up, it's most often replaced by another business in fairy short order, and proprietary project failures are usually hushed up by firing the programmers and promoting the managers. Whereas the bleached bones of the failed open source projects are visible for all to see on the SourceForge beach. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From pdemb at illx.org Sun Jan 2 06:55:40 2005 From: pdemb at illx.org (Peter Dembinski) Date: Sun, 02 Jan 2005 12:55:40 +0100 Subject: [OT] Re: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7x4qi2yik8.fsf@ruckus.brouhaha.com> <87mzvumz20.fsf@hector.domek> <7x8y7ed0yn.fsf@ruckus.brouhaha.com> Message-ID: <87oeg8avur.fsf_-_@hector.domek> Paul Rubin writes: > Peter Dembinski writes: >> If it has to be both reliable and secure, I suggest you used more >> redundant language such as Ada 95. > > That's something to think about and it's come up in discussions, > but probably complicates stuff since it's not currently available > on the target platform. Also, the people on the project have > significant Java and Python experience but haven't used Ada. > Do you think it has real advantages over Java? As I wrote before, it is more redundant language[1], plus (AFAIR) it has the strongest type checking of all the programming languages I know about. Plus, most of Ada compilers (such as gnat) generate machine/operating system - specific code[2], not bytecode, which could be advantage if performance is one of priorities. I may have a little skewed viewpoint because Ada 95 is the language I have recently studied on my RTS labs :> [1] for example, one has to define interface and implementation parts of each module in separate files [2] AFAIR gnat generates C code, which is then compiled with gcc. From john at grulic.org.ar Mon Jan 17 00:39:49 2005 From: john at grulic.org.ar (John Lenton) Date: Mon, 17 Jan 2005 02:39:49 -0300 Subject: strange note in fcntl docs Message-ID: <20050117053949.GA28456@grulic.org.ar> In the fnctl docs for both python 2.3 and 2.4 there is a note at the bottom that says The os.open() function supports locking flags and is available on a wider variety of platforms than the lockf() and flock() functions, providing a more platform-independent file locking facility. however, in neither of those versions does os.open support any kind of mysterious "locking flags", nor is there any reference in os to any kind of locking magic (nor do any C open()s I know of support any kind of locking semantics). The note seems bogus; am I missing something, or should it be elided? -- John Lenton (john at grulic.org.ar) -- Random fortune: Are Linux users lemmings collectively jumping off of the cliff of reliable, well-engineered commercial software? -- Matt Welsh -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From ncoghlan at iinet.net.au Sat Jan 8 01:47:16 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 16:47:16 +1000 Subject: python3: 'where' keyword In-Reply-To: <7xvfa8l9fb.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <7xvfa8l9fb.fsf@ruckus.brouhaha.com> Message-ID: <41DF81F4.6040306@iinet.net.au> Paul Rubin wrote: > the suite has its own scope so any variable created there is local to > the suite plus the following statement. The scope vanishes after the > statement. The second part of the idea is to give the statement greater prominence and 'hide' the uninteresting setup (the contents of the where clause). Putting the statement of interest after the where suite still gives the benefits of avoiding namespace clutter, but doesn't really help readability (it makes it worse, if you ask me). Particularly, what if the next statement is a compound statement? Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From rkern at ucsd.edu Mon Jan 3 20:21:38 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 03 Jan 2005 17:21:38 -0800 Subject: Howto Extract PNG from binary file @ 0x80? In-Reply-To: <1104797038.407042.32580@z14g2000cwz.googlegroups.com> References: <1102753727.706459.105920@f14g2000cwb.googlegroups.com> <1104797038.407042.32580@z14g2000cwz.googlegroups.com> Message-ID: flamesrock wrote: [snip] > flamesrock at flames:~/score$ python sc4png.py > Traceback (most recent call last): > File "sc4png.py", line 26, in ? > pngcopy(infile, outfile) > File "sc4png.py", line 14, in pngcopy > size, cid = struct.unpack("!l4s", chunk) > struct.error: unpack str size does not match format > > Any ideas on how to fix it? If I understand this page correctly, > http://www.python.org/doc/current/lib/module-struct.html > a png is basically a 'big endian string of 14 chars'? Changing it to > !14b" gives a"ValueError: unpack tuple of wrong size" > -thanks in advance for any help No, the chunk header is specified as "!l4s" where that second character is a lower-case "L", not one "1". The struct is "a 4-byte long integer in big-endian format followed by a 4-character string". I think the error you are running into is that the chunk you are passing in does not have 8 characters. Is your input truncated somehow? -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From steve at holdenweb.com Thu Jan 6 11:56:34 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Jan 2005 11:56:34 -0500 Subject: curses is not imported under Linux (and Python 2.4) In-Reply-To: <41dd65bd.785984171@news.compuserve.de> References: <41dd65bd.785984171@news.compuserve.de> Message-ID: Konrad Koller wrote: > import curses > produces the ImportError: No module named _curses > ("from _curses import *" in line 15 in __init__.py) > Of course imp.find_module ("_curses") reports the same error. > How can I make use of the curses package for writing a Python script > with curses? I get the same thing under Windows: _curses is the compiled extension supporting the curses library, so I must presume that isn't supported by default on Windows. No problems under Cygwin or on Linux. Googling for "python curses windows" might provide a few pointers. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From roy at panix.com Sun Jan 2 09:06:33 2005 From: roy at panix.com (Roy Smith) Date: Sun, 02 Jan 2005 09:06:33 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> Message-ID: Stefan Axelsson wrote: > Yes, ignoring most of the debate about static vs. dynamic typing, I've > also longed for 'use strict'. You can use __slots__ to get the effect you're after. Well, sort of; it only works for instance variables, not locals. And the gurus will argue that __slots__ wasn't intended for that, so you shouldn't do it. > Sure Python isn't as bad as (say) Awk in this respect; you have to at > least assign a variable to make it spring into existence I think you've hit the nail on the head. In awk (and perl, and most shells, and IIRC, FORTRAN), using an undefined variable silently gets you a default value (empty string or zero). This tends to propagate errors and make them very difficult to track down. In Python, you raise NameError or AttributeError, so you find out about your mistake quickly, and you know exactly where it is. The only time you can really go wrong is when you've got multiple assignment statements with the same lhs and you make a typo in one of them. And even then, as you say, things like Pychecker will probably catch the mistake. In perl, I always use "use strict", but in Python, I just don't feel the need. Between the exception mechanism and unit tests, the odds of a typo going unnoticed for very long are pretty slim. I'll admit I don't use Pychecker, but if I was doing production code, I would probably use it as part of my QA process. > I don't think that anyone could argue that typing 'use apa' before > the first actual use (or words to that effect) would 'slow them > down', or be very onerous. Well, I'll have to (respectfully) disagree with you on that. It's not that there's no value in explicit declarations, it's just that (IMHO) the cost exceeds the value, given the other tools we have in Python to catch the mistake. From jdhunter at ace.bsd.uchicago.edu Sun Jan 30 23:25:10 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Sun, 30 Jan 2005 22:25:10 -0600 Subject: python and gpl Message-ID: I have a question about what it takes to trigger GPL restrictions in python code which conditionally uses a GPL library. Here is the context of my question. matplotlib, which I develop, is a plotting module which is distributed under a PSF compatible license, and hence we avoid using GPLd code so as to not trigger the GPL requirements. matplotlib has rigid segregation between the front end (plotting commands, figure objects, etc) and backends (gtk, wx, ps, svg, etc). The backend is chosen dynamically at runtime -- eg the same python script could trigger the import gtk, wx, or ps, depending an some rc settings or command line opts. The question is: does shipping a backend which imports a module that links with GPL code make some or all of the library GPL. This question is complicated, in my mind at least, by several factors. Here are some sub-questions: * If a backend module somebackend does import somelib where somelib is a python wrapper of GPL code, is somebackend GPLd? * Assuming the answer to the above question is yes, is matplotlib GPLd if it distributes somebackend? I think this is a nuanced situation because matplotlib would work just fine w/o somemodule, and only uses somemodule's code if it is selected at runtime by the user. Ie, no other part of the code depends on it since it is one of many interchangeable backends. * To further complicate the question, the backend in question is qt, which is dual licensed, commercial and GPL. The qt backend code just needs to 'import qt', and neither the backend writer nor the matplotlib frontend knows whether the deployed qt on the system is commercial or GPLd. To date, the only GPL-like backend is GTK, which is LGPL. Since we're only linking and not using the src, we're protected from the GPL requirements. With QT, which has a pure (non L) GPL variant, the situation is less clear to me. Thoughts, links, etc, appreciated... JDH From David.Holt at mmm.com Wed Jan 5 12:30:52 2005 From: David.Holt at mmm.com (DavidHolt) Date: 5 Jan 2005 09:30:52 -0800 Subject: Python 2.4 on Windows XP Message-ID: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> I have a problem that I see on two different machines, one running XP SP1 and one XP SP 2. On both I installed Python 2.4. I can't seem to start IDLE. When I try to start it, I get an hourglass cursor for a short time then nothing more happens. This happens whether I click the IDLE shortcut or click the pythonw.exe directly, or attempt to launch pythonw from a command line. I don't have any trouble running the python command line version. Any ideas? Thanks, David Holt Software Developer HighJump Software, a 3M Company From klachemin at comcast.net Sun Jan 2 21:49:47 2005 From: klachemin at comcast.net (Kamilche) Date: 2 Jan 2005 18:49:47 -0800 Subject: Calling Function Without Parentheses! In-Reply-To: <1104719332.876804.193020@c13g2000cwb.googlegroups.com> References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> <1104719332.876804.193020@c13g2000cwb.googlegroups.com> Message-ID: <1104720586.976564.307900@c13g2000cwb.googlegroups.com> Yep. Definitely time download PyChecker. Thanks for the tip! From snacktime at gmail.com Sun Jan 23 19:00:48 2005 From: snacktime at gmail.com (snacktime) Date: Sun, 23 Jan 2005 16:00:48 -0800 Subject: Quoting sql queries with the DB-API Message-ID: <1f060c4c050123160027d8145f@mail.gmail.com> I'm used to using the perl DBI and not very familiar with the python DB-API. I am using PyGreSQL. My question is what is the standard way to quote strings in sql queries? I didn't see any quoting functions in the DB-API docs. Is quoting handled internally by the PyGreSQL module? Also, is this a good way to use variables in an insert/update statement, or is there a better way? sql = "insert into test(a,b) values('%s','%s')" % (a,b) cursor.execute(sql) Chris From ncoghlan at iinet.net.au Sat Jan 29 20:59:39 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 30 Jan 2005 11:59:39 +1000 Subject: limited python virtual machine In-Reply-To: <1gr58wn.m3n0xac2j9qbN%aleaxit@yahoo.com> References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr58wn.m3n0xac2j9qbN%aleaxit@yahoo.com> Message-ID: <41FC3F8B.9080800@iinet.net.au> Alex Martelli wrote: > It didn't seem to me that Steven's question was so restricted; and since > he thanked me for my answer (which of course is probably inapplicable to > some custom interpreter that's not written yet) it appears to me that my > interpretation of his question was correct, and my answer useful to him. Yes, I'd stopped following the thread for a bit, and the discussion had moved further afield than I realised :) > If you _can_ execute (whatever) in a separate process, then an approach > based on BSD's "jail" or equivalent features of other OS's may be able > to give you all you need, without needing other restrictions to be coded > in the interpreter (or whatever else you run in that process). I think that's where these discussion have historically ended. . . making a Python-specific sandbox gets complicated enough that it ends up making more sense to just use an OS-based sandbox that lets you execute arbitrary binaries relatively safely. The last suggestion I recall along these lines was chroot() plus a monitoring daemon that killed the relevant subprocess if it started consuming too much memory or looked like it had got stuck in an infinite loop. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From stephen.thorne at gmail.com Tue Jan 18 08:52:24 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Tue, 18 Jan 2005 23:52:24 +1000 Subject: generator expressions: performance anomaly? In-Reply-To: <377Hd.77904$Jk5.30235@lakeread01> References: <377Hd.77904$Jk5.30235@lakeread01> Message-ID: <3e8ca5c805011805522032ddf8@mail.gmail.com> On Tue, 18 Jan 2005 07:12:18 -0500, Steve Holden wrote: > Since it doesn't yet optimize 2+5 to a constant-folded 7 you should > realize that you are suggesting a large increase in the compiler's > analytical powers. As in interesting aside to this, you might be interested to know that PHP has constant folding, allowing you to do things like $foo = 7+9; and have it generate bytecode that is "let 'foo' equal 16" or somesuch. PHP achieves this by having a subset of expression parsing available only for situations where a folded constant is allowed. i.e. class Foo { var $bar = 1+4; /* this constant is folded */ } static_scalar: /* compile-time evaluated scalars */ common_scalar | T_STRING | '+' static_scalar | '-' static_scalar | T_ARRAY '(' static_array_pair_list ')' ; common_scalar: /* all numbers, strings-not-containing-variable-interpolation and a few hacks like __FILE__ and __LINE__ */ ; As you can see from the grammar, there are any number of ways this can break. i.e. Parse Error, * isn't allowed: class Foo { var $bar = 60*60*24; } Parse Error, neither is anything except + and -: class Foo { var $bar = 256 & 18; } Parse Error, and definately not variables: $baz = 12; class Foo { var $bar = $baz*2; } I compute 60*60*24 every time around the loop: foreach ($myarray as $value) { $x = 60*60*24*$value; } Thankful, Former PHP Programmer, Stephen Thorne. From bokr at oz.net Sun Jan 9 00:05:03 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 09 Jan 2005 05:05:03 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <41e09808.360402200@news.oz.net> <10u19a32e5affc1@news.supernews.com> Message-ID: <41e0abd1.365467113@news.oz.net> On Sat, 8 Jan 2005 21:29:47 -0600, "John Roth" wrote: > >"Bengt Richter" wrote in message >news:41e09808.360402200 at news.oz.net... >> On Sat, 08 Jan 2005 12:47:52 -0500, Peter Hansen >> wrote: >> >>>Paul Rubin wrote: >>>> When Unix was first written, people thought implementing an OS in C >>>> was ludicrous. Everyone knew OS's had to be written in assembler. >>> >>>Actually, when Unix was first written that belief was entirely >>>correct, and OSes *did* have to be written in assembler. >>> >>>That is, pure C did not have the capability to handle all >>>that was required. I recall it taking a good decade before it >>>became *common* to find C compilers with, for example, @interrupt >>>support to let the compiler generate code that properly saved >>>all registers and used RTI instead of RTS (or whatever it might >>>have been called one one's particular flavour of CPU). >>> >>>Now, once you added a few tiny interrupt handlers, and some context >>>switching (stack manipulation) routines, pretty much everything else >>>*could* be done in C, but that doesn't invalidate the point. >>> >>>I think it's safe to say that none of pure C, pure Lisp, or pure Python >>>are really capable of being used as the *sole* language to build >>>an operating system. >>> >>>It's also safe to say that this is a largely irrelevant point. >>>It would probably only be of academic interest to try to do >>>something like that. Any practical attempt would not think more >>>than twice of resorting to a little "glue" in assembler or in >>>the form of "canned" byte sequences built by hand and stuck >>>into the appropriate places in memory... >> Well, usually there's more than one tool in the chain from source >> to bootable loader and OS image, even if you are writing in C and >> assembler, >> and there's usually more to an OS than the bootable image contains. >> >> So ISTM "writing an OS in " is pretty loose talk ;-) > >Most people who work in the field know what it means, though. Even if they know the whole story intimately, IMO it is not unlikely that they are talking about particular chapters, and it may not be clear whether they are thinking totally radically of rewriting ALL software in the system in Python, visualizing a holy grail of saying goodby to both GNU and M$ and having a purely Python-defined system (which would mean Python tool chains that could prepare binary images (no theoretical problem) for a computer's boot BIOS and on from there, as a tour de force project, or whether they want e.g. to integrate Python front end to gcc (or at one remove via C as is easier), and not reinvent so many wheels. >One of the touchstones of language design is whether you can >write the compiler and runtime in that language. PyPy is working >on that for Python, Squeak Smalltalk is written in Smalltalk and >then converted to C for compilation of the runtime. Both of them This "runtime" is then represented as an executable file that an OS shell you are using will ask its host OS kernel to load and execute as an OS-managed user process, right? Or is it bootable? If so, in what format that what loader understands? >are completely virtualizable: you can run them (very slowly) under >themselves for testing. But what binary is running? The compiled C output of the backend? Interpeting the Python source of itself to spit out the same C that it itself was compiled from? That's cool. And it shows that you can prepare a binary with the help of the C compiler+linker (most likely with gcc libraries) to produce a userland program executable. But I suspect some are thinking that Python source should implement the whole environment it runs in. That's more radical ;-) I would guess a cross development system hosted on a normal PC OS but targeting some limited embedded environment would be where I'd expect to see this kind of thing first. But still going via C tools to the end product most likely, since C is so ubiquitous. > >Given that everything in Python is an object, I see no reason >why one couldn't create a set of objects that are appropriate >for an operating system kernel and can also be converted >cleanly to the operating system subset of C, and write a converter >that does it. OSCTypes? > >That's the easy part. The hard part is writing the operating >system. Look at the (lack of) progress the GNU HURD >project has been making recently. > There are more interesting things to do than reinvent wheels though, even if it is fun doing it in Python ;-) Regards, Bengt Richter From peter at engcorp.com Fri Jan 21 09:16:51 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Jan 2005 09:16:51 -0500 Subject: Funny Python error messages In-Reply-To: <1106315907.551660.276380@c13g2000cwb.googlegroups.com> References: <1106315907.551660.276380@c13g2000cwb.googlegroups.com> Message-ID: Will Stuyvesant wrote: > Perhaps this will even be a useful thread, to brighten the > life of the brave people doing the hard work of providing us > with error messages. > > My first one (i'm learning, i'm learning) is > > TypeError: 'callable-iterator' object is not callable > > # >>> it = iter(lambda:0, 0) > # >>> it() > # TypeError: 'callable-iterator' object is not callable Given that the supposed humour depends on the *name* of the object, which is "callable-iterator", I'd say it's probably not hard to come up with lots of "funny" error messages this way. For example: >>> def a(): ... print is_not ... is_not = 0 ... >>> a() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in a UnboundLocalError: local variable 'is_not' referenced before assignment My funny bone must be broken today, though, because I don't see these as very funny... (Did you understand *why* you got your error? You don't call iterators, you call .next() on them...) -Peter From ed at leafe.com Wed Jan 12 15:45:03 2005 From: ed at leafe.com (Ed Leafe) Date: Wed, 12 Jan 2005 15:45:03 -0500 Subject: py2exe Excludes Message-ID: I'm trying to make a Windows runtime for Dabo, and I want to exclude the framework code itself from the exe file, so that people can update with new releases as they are made. The relevant section of setup.py has: setup( # The first three parameters are not required, if at least a # 'version' is given, then a versioninfo resource is built from # them and added to the executables. version = "0.3.0", description = "Dabo Runtime Engine", name = "daborun", # targets to build console = ["daborun.py"], #exclude the actual framework options = { "py2exe": {"excludes" : ["dabo"]} }, ) Yet the generated library.zip still contains all of the Dabo module code. Why is this? What am I doing wrong? ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From ville at spammers.com Tue Jan 4 08:48:03 2005 From: ville at spammers.com (Ville Vainio) Date: 04 Jan 2005 15:48:03 +0200 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <7xpt0liawq.fsf@ruckus.brouhaha.com> Message-ID: >>>>> "Paul" == Paul Rubin writes: Paul> Ville Vainio writes: >> Also, Python is not a monolithic entity. Guido certainly isn't >> going to write a better IDE for Python, so the time used on >> language features isn't removed from improving the >> infrastructure around the language. Paul> There aren't THAT many people working on Python. Any time Paul> spent on feature X does tend to divert resources from Paul> feature Y. But the people working on wxPython, pygtk, pyqt, pydev, whatever, are largely not the same guys that commit stuff to CPython CVS. Paul> fully deployed. Too much of Python as we know it today is Paul> shaped by the weirdness of CPython. We ought to be able to Paul> get away from that. Type declarations are a feature that might benefit IronPython and Jython more than they would CPython. -- Ville Vainio http://tinyurl.com/2prnb From beliavsky at aol.com Wed Jan 5 09:03:20 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 5 Jan 2005 06:03:20 -0800 Subject: is python more popular than coldfusion? References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1104933800.156835.91350@f14g2000cwb.googlegroups.com> >is python more popular than coldfusion? >I realsie that is a very general question as one thing does not directly >relate to the other. My issue is that I am ditching coldfusion due to >there being next to no work for it, and I am thinking of taking on >python as a second language to java in the hope of improving my resume. For your specific purpose of learning a language to get a job, I suggest visiting the site http://mshiltonj.com/sm/categories/languages/ , where it appears that Python is mentioned about as often as Fortran or Ada in job listings at dice.com . Apart from Java, two languages in demand are C++ and Visual Basic. C++ may be easier to learn along with Java since the syntax is similar, but VB is a very easy language to learn and use. From bokr at oz.net Sun Jan 23 03:22:36 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 23 Jan 2005 08:22:36 GMT Subject: list unpack trick? References: Message-ID: <41f35e59.1590759250@news.oz.net> On Sun, 23 Jan 2005 15:43:43 +1000, Nick Coghlan wrote: >aurora wrote: >> I am think more in the line of string.ljust(). So if we have a >> list.ljust(length, filler), we can do something like >> >> name, value = s.split('=',1).ljust(2,'') > >Eh? > >Py> s.split('=',1).ljust(2,'') >Traceback (most recent call last): > File "", line 1, in ? >AttributeError: 'list' object has no attribute 'ljust' > Python 2.4b1 (#56, Nov 3 2004, 01:47:27) [GCC 3.2.3 (mingw special 20030504-1)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> help(''.ljust) Help on built-in function ljust: ljust(...) S.ljust(width[, fillchar]) -> string Return S left justified in a string of length width. Padding is done using the specified fill character (default is a space). I should upgrade too ;-) Regards, Bengt Richter From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Tue Jan 11 17:51:59 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (=?UTF-8?Q?Michel_Claveau_-_abstraction_m=C3=A9t?= =?UTF-8?Q?a-galactique_non_triviale_en_fui?= =?UTF-8?Q?te_perp=C3=A9tuelle.?=) Date: Tue, 11 Jan 2005 23:51:59 +0100 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> Message-ID: <41e458a9$1$7090$8fcfb975@news.wanadoo.fr> Hi ! >>> import math >>> ? = math.pi Good sample ! I like too : e=mc? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rschroev_nospam_ml at fastmail.fm Sun Jan 9 15:49:35 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 09 Jan 2005 20:49:35 GMT Subject: windows mem leak In-Reply-To: References: <41XDd.70234$Jk5.40626@lakeread01> <41E06C18.6050407@hotmail.com> Message-ID: Peter Hansen wrote: > Roel Schroeven wrote: > >>> Peter Hansen wrote: >>> >>>> How have >>>> you proven that it is not *that* program which is at fault?) >> >> >> It would surprise me: even if it consumes much CPU-time, memory and >> other resources, each instances returns all resources when it exits. > > > I agree with that statement, but you assume that the program *is* > exiting. And your initial analysis with "fake_nmap" suggests > that, at least to the extent of having leftover cmd.exe's kicking > around, maybe it is not. I see. The number of cmd.exe's running was not *that* big though: about 5-10 I would say. And their PID's kept changing. I took a look with Process Explorer from sysinternals, which shows the processes as a tree instead of a simple list. Apparently each fake_nmap is a child of a cmd.exe, meaning that os.popen indead uses the shell to run processes. I wouldn't be surprise if cmd.exe would be the culprit here. -- "Codito ergo sum" Roel Schroeven From foo at bar.com Tue Jan 18 21:39:51 2005 From: foo at bar.com (Steve Menard) Date: Tue, 18 Jan 2005 21:39:51 -0500 Subject: Integration with java (Jpype vs. JPE) In-Reply-To: References: <34s5krF4c85d5U1@individual.net> Message-ID: <41EDC877.8000101@bar.com> Istvan Albert wrote: > Steve Menard wrote: > >> To asnwer your question more fully, the jpype-specific cide is only >> for looking up the Classes and startting/stopping the environment. For >> everything else, Java objects and classes are used as regular Python >> objects. > > > Thanks for the response. Currently I don't need to use java but > in the past when I explored such a possibility I looked at jpype > and I was unable to understand from the documentation what it > actually does. > > There is a lot of text there, but it is all concerning catching > errors or other subtleties. For a new visitor the most important > question is about how it works, what does it do, and how can it be > applied for the given problem. > > > everything else, Java objects and classes are used as regular Python > > objects. > > This is too generic. My question was a little more specific, > how would I pass a python list as an argument of a java class/method or > transform a java list into a python one? You don't have to > answer it here, I'm just pointing out the kind of > questions that I was unable to get an answer for on the jpype > website. > > best, > > Istvan. I see what you mean. And I agree fully. I guess that's one more thing to put on the TODO list hehe. Thanks for the input. Steve From carribeiro at gmail.com Thu Jan 6 05:05:47 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 6 Jan 2005 08:05:47 -0200 Subject: Python evolution: Unease In-Reply-To: <1104982313.217034.308760@z14g2000cwz.googlegroups.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> <1104982313.217034.308760@z14g2000cwz.googlegroups.com> Message-ID: <864d3709050106020568bd8b8e@mail.gmail.com> On 5 Jan 2005 19:31:53 -0800, michele.simionato at gmail.com wrote: > John Roth: > > The bottom line is that I'm not going to be writing any > > extensive pieces of Python documentation. My time > > is better spent elsewhere. > > Well, a couple of years ago I realized that some documentation on the > MRO > was missing. I wrote a document in reST, posted here, and Guido put it > on > python.org. It was as easy as it sounds. So I don't see your problem. > > Dave Kulhman wrote some utility to convert reST in latex using the same > style of the standard library docs; I haven't used it myself, but you > may check > with him: http://www.rexx.com/~dkuhlman/ Couldn't a better document-writing interface be implemented? This is the kind of stuff Zope & Plone are used for on a daily basis; not to mention other countless web frameworks & CMS available in Python. Even a simple automated service to process & publish reST or SGML files would be better than requiring aspiring Python doc writers to install the full toolchain, as pointed out. But, whatever it is (and that's a difficult choice, politically speaking), it should be hosted on the main Python site... because that's the place where people look for info first place. > P.S. since you cite descriptors, what's wrong with Raimond Hetting > documentation? > http://users.rcn.com/python/download/Descriptor.htm > > The only problem I see is that it is not integrated with the official > docs, but this is a > minor issue, I think. The docs are great, but it took me some time to find them out after searching inside Python docs. This is not a minor issue IMHO. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From sjmachin at lexicon.net Tue Jan 4 15:40:15 2005 From: sjmachin at lexicon.net (John Machin) Date: 4 Jan 2005 12:40:15 -0800 Subject: why does UserDict.DictMixin use keys instead of __iter__? In-Reply-To: <1RxCd.847728$8_6.18665@attbi_s04> References: <1104836152.639270.196200@z14g2000cwz.googlegroups.com> <1RxCd.847728$8_6.18665@attbi_s04> Message-ID: <1104871215.023027.46040@f14g2000cwb.googlegroups.com> Steven Bethard wrote: > John Machin wrote: > > Steven Bethard wrote: > > > >>So I was looking at the Language Reference's discussion about > >>emulating container types[1], and nowhere in it does it mention that > >> .keys() is part of the container protocol. > > > > I don't see any reference to a "container protocol". > > Sorry, I extrapolated "container protocol" from this statement: > > "Containers usually are sequences (such as lists or tuples) or mappings > (like dictionaries), but can represent other containers as well. The > first set of methods is used either to emulate a sequence or to emulate > a mapping" > > and the fact that there is a "sequence protocol" and a "mapping protocol". > > But all I was really reading from this statement was that the "first set > of methods" (__len__, __getitem__, __setitem__, __delitem__ and > __iter__) were more integral than the second set of methods (keys(), > values(), ...). > > > > What I do see is > > (1) """It is also recommended that mappings provide the methods keys(), > > ...""" > > You skipped the remaining 13 methods in this list: > > "It is also recommended that mappings provide the methods keys(), > values(), items(), has_key(), get(), clear(), setdefault(), iterkeys(), > itervalues(), iteritems(), pop(), popitem(), copy(), and update() > behaving similar to those for Python's standard dictionary objects." > > This is the "second set of methods" I mentioned above. I don't > understand why the creators of UserDict.DictMixin decided that keys(), > from the second list, is more important than __iter__, from the first list. > > > >>Because of this, I would assume that to > >>use UserDict.DictMixin correctly, a class would only need to define > >>__getitem__, __setitem__, __delitem__ and __iter__. > > > > > > So I can't see why would you assume that, given that the docs say in > > effect "you supply get/set/del + keys as the building blocks, the > > DictMixin class will provide the remainder". This message is reinforced > > in the docs for UserDict itself. > > Sorry, my intent was not to say that I didn't know from the docs that > UserDict.DictMixin required keys(). Clearly it's documented. Sorry, the combination of (a) "assume X where not(X) is documented" and (b) posting of tracebacks that demonstrated behaviour that is both expected and documented lead to my making an unwarranted assumption :-) > My > question was *why* does it use keys()? Why use keys() when keys() can > be derived from __iter__, and __iter__ IMHO looks to be a more basic > part of the mapping protocol. Now that I understand your question: Hmmm, good question. __iter__ arrived (2.2) before DictMixin (2.3), so primacy is not the reason. Ease of implementation by the user of DictMixin: probably not, "yield akey" vs "alist.append(akey)" -- not much in it in Python, different story in C, but a C extension wouldn't be using DictMixin anyway. > > > In any case, isn't UserDict past history? Why are you mucking about > > with it? > > UserDict is past history, but DictMixin isn't. OK, I'll rephrase: what is your interest in DictMixin? My interest: I'm into mappings that provide an approximate match capability, and have a few different data structures that I'd like to implement as C types in a unified manner. The plot includes a base type that, similarly to DictMixin, provides all the non-basic methods. From steven.bethard at gmail.com Thu Jan 27 18:26:57 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 16:26:57 -0700 Subject: String Fomat Conversion In-Reply-To: <1106865747.829698.119740@c13g2000cwb.googlegroups.com> References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> <1106865747.829698.119740@c13g2000cwb.googlegroups.com> Message-ID: <57ednS3MJPRs5WTcRVn-gA@comcast.com> enigma wrote: > Do you really need to use the iter function here? As far as I can > tell, a file object is already an iterator. The file object > documentation says that, "[a] file object is its own iterator, for > example iter(f) returns f (unless f is closed)." It doesn't look like > it makes a difference one way or the other, I'm just curious. Nope, you're right -- that's just my obsessive-compulsive disorder kicking in. ;) A lot of objects aren't their own iterators, so I tend to ask for an iterator with iter() when I know I want one. But for files, this definitely isn't necessary: py> file('temp.txt', 'w').write("""\ ... x y ... 1 2 ... 3 4 ... 5 6 ... """) py> f = file('temp.txt') py> f.next() 'x y\n' py> for line in f: ... print [float(f) for f in line.split()] ... [1.0, 2.0] [3.0, 4.0] [5.0, 6.0] And to illustrate Alex Martelli's point that using readline, etc. before using the file as an iterator is fine: py> f = file('temp.txt') py> f.readline() 'x y\n' py> for line in f: ... print [float(f) for f in line.split()] ... [1.0, 2.0] [3.0, 4.0] [5.0, 6.0] But using readline, etc. after using the file as an iterator is *not* fine, generally: py> f = file('temp.txt') py> f.next() 'x y\n' py> f.readline() '' In this case, if my understanding's right, the entire file contents have been read into the iterator buffer, so readline thinks the entire file's been read in and gives you '' to indicate this. Steve From jzgoda at gazeta.usun.pl Fri Jan 14 15:40:08 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 14 Jan 2005 21:40:08 +0100 Subject: python connect to db2 In-Reply-To: References: <1105689253.3167.0.camel@linux.tister.com> Message-ID: yuzx wrote: > >>> conn = DB2.connect(dsn='sample', uid='db2inst1', pwd='ibmdb2') > > but i don't know about dsn, If the database is DB2/400 and you try to connect from iSeries, dsn would be '*local' for local database, or its name (not hostname or IP address!) as returned by dsprdbdire command for remote databases. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From bill.mill at gmail.com Wed Jan 19 15:51:26 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 19 Jan 2005 15:51:26 -0500 Subject: a question In-Reply-To: References: Message-ID: <797fe3d405011912511a609c1c@mail.gmail.com> Nader, You've got a couple problems. First, you need to end the string before putting a continuation in. Secondly, you have 6 variables to be substituted and only provide 4. Here's some code, edited to show how to use continutations to join strings: >>> mosbin, jaar, filetype = (1,1,1) >>> cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s'\ ... '%s' % (mosbin, jaar, filetype, filetype, filetype, filetype) >>> cmd '1/mos user wmarch, cd /fa/wm/1/1, mkdir 1, put 1, chmod 6441' Peace Bill Mill bill.mill at gmail.com On Wed, 19 Jan 2005 16:16:32 +0000, Nader Emami wrote: > L.S., > > I have a long command in Unix and I have to use os.system(cmd) > statement. I do the following: > > cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s, chmod 644 > %s' % (mosbin, jaar, filetype, filetype) > status = os.system(cmd) > > This is not very clear, and I have to break this long line in two > segment by means of the next character '\' : > cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s, \ > chmod 644 %s' % (mosbin, jaar, filetype, filetype) > > But in this case I get a syntax error! I don't know how I can solve this > problem. Could somebody tell me about this? > > With regards, > Nader > > (this > -- > http://mail.python.org/mailman/listinfo/python-list > From tzot at sil-tec.gr Wed Jan 26 11:53:20 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 26 Jan 2005 18:53:20 +0200 Subject: string.atoi and string.atol broken? [OT] References: <1106700417.482871.45140@z14g2000cwz.googlegroups.com> Message-ID: On Wed, 26 Jan 2005 12:26:59 +0100, rumours say that Peter Otten <__peter__ at web.de> might have written: >> In current Greek hexadecimal is "????????????" ("dekaexadikon"). > >The Latin part escaped me. By Latin I suppose you jokingly mean the Greek parts... :) Just in case it didn't show up correctly in your ng/mail client, it does on groups.google.com (the post was in UTF-8, dammit! --excuse my romance language) message link (long URL): -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From lee at example.com Sat Jan 8 09:26:23 2005 From: lee at example.com (Lee Harr) Date: Sat, 08 Jan 2005 14:26:23 GMT Subject: Python/Qt Problem References: Message-ID: On 2005-01-08, Michael wrote: > Hi, > > I am experiencing something very weird with PyQt. I have created several > windows based on QWidget using Designer. I can easily hide and show > these with the hide and show methods. However I have just created a new > window with Designer and the show method works in my main script but not > inside the button action method (not using proper temrinology, sorry) of > another window. Why is that? This works fine for the other windows. > If you do not get a satisfactory answer here, you should try the dedicated PyQt mailing list: http://mats.imk.fraunhofer.de/mailman/listinfo/pykde The other thing I would suggest is to post some code along with your description of what you believe it should do. I do not think anyone will be able to diagnose the problem without seeing the code. From fuzzyman at gmail.com Mon Jan 24 10:34:40 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Jan 2005 07:34:40 -0800 Subject: urllib2 and proxy question In-Reply-To: References: <1106575675.520424.155310@f14g2000cwb.googlegroups.com> Message-ID: <1106580880.119328.240890@c13g2000cwb.googlegroups.com> rbt wrote: > Fuzzyman wrote: > > urllib2 (under windows) will auto-detect your proxy settings and use > > those. > > > > Normally that's a good thing (I guess), except when it's not ! > > > > How do I switch off this behaviour ? I'm behind a censoring proxy and > > wanting to test things *locally*. IE is set to not use the proxy when > > fetching local adresses, but urllib2 ignores that part of the setting > > and uses the proxy for everything. > > > > The only way I can test are changing my IE settings back and forth > > every time. Most annoying. > > > > I can see how to *add* a new proxy to urllib2, but not how to force it > > to not use a proxy. I may well be missing something obvious though. > > Anyone able to help ? > > Regards, > > > > Fuzzy > > http://www.voidspace.org.uk/python/index.shtml > > > > "Alternatively, the optional proxies argument may be used to explicitly > specify proxies. > It must be a dictionary mapping scheme names to proxy URLs, where an > empty dictionary causes no proxies to be used" > > # Don't use any proxies > filehandle = urllib.urlopen(some_url, proxies={}) Wikkid... I'll try that. Nice one, thanks for your help. It *still* means I have to have a different version for testing locally - but it's better than the alternative. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From sjmachin at lexicon.net Sat Jan 8 21:25:56 2005 From: sjmachin at lexicon.net (John Machin) Date: 8 Jan 2005 18:25:56 -0800 Subject: Speed revisited References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> Message-ID: <1105237556.402188.126980@c13g2000cwb.googlegroups.com> Bulba! wrote: > On 4 Jan 2005 14:33:34 -0800, "John Machin" > wrote: > > >(b) Fast forwarding 30+ years, let's look at the dictionary method, > >assuming you have enough memory to hold all your data at once: > > > >Step 1: read the "left" table; for each row, if english not in mydict, > >then do mydict[english] = MyObject(). In any case, do > >mydict[english].left_list.append(row) > >Step 2: same for the "right" table. > >Step 3: for english, obj in mydict.iteritems(): process(english, obj) > > >As your datasets are stored in MS Excel spreadsheets, N < 64K so > >whether your solution is O(N) or O(N*log(N)) doesn't matter too much. > >You are however correct to avoid O(N**2) solutions. > > Following advice of two posters here (thanks) I have written two > versions of the same program, and both of them work, but the > difference in speed is drastic, about 6 seconds vs 190 seconds > for about 15000 of processed records, taken from 2 lists of > dictionaries. > > I've read "Python Performance Tips" at > > http://manatee.mojam.com/~skip/python/fastpython.html > > ..but still don't understand why the difference is so big. > > Both versions use local variables, etc. Both have their > lists initially sorted. Both essentially use a loop with > conditional for comparison, > then process the record in the > same way. "process the record in the same way"??? That's an interesting use of "same". > The overhead of second version is that it also > uses cmp() function and two additional integer > variables - that should not slow the program _so much_. > > I have measured the run of snippet 2 with time checkpoints > written to a log (write time delta to log every 200 records), > even made a graph of time deltas in spreadsheet and in fact > snippet 2 seems after initial slowdown looks exactly linear, > like that: > > ^ (time) > | > | /----------- > | / > |/ > ---------------> (# of records written) > > So yes, it would scale to big files. On your empirical evidence, as presented. However, do read on ... >However, why is it so > frigging slow?! Mainly, because you are (unnecessarily) deleting the first item of a list. This requires copying the remaining items. It is O(N), not O(1). You are doing this O(N) times, so the overall result is O(N**2). Your graph has no obvious explanation; after how many cycles does the speed become constant? Secondly, you are calling cmp() up to THREE times when once is enough. Didn't it occur to you that your last elif needed an else to finish it off, and the only possible action for the else suite was "assert False"? It would appear after reading your "snippet 2" a couple of times that you are trying to implement the old 3-tape update method. It would also appear that you are assuming/hoping that there are never more than one instance of a phrase in either list. You need something a little more like the following. Note that in your snippet2 it was not very obvious what you want to do in the case where a phrase is in "new" but not in "old", and vice versa -- under one circumstance (you haven't met "end of file") you do nothing but in the the other circumstance you do something but seem to have not only a polarity problem but also a copy-paste-edit problem. In the following code I have abstracted the real requirements as handle_XXX_unmatched() !o = n = 0 !lenold = len(oldl) !lennew = len(newl) !while o < lenold and n < lennew: ! cmp_result = cmp(oldl[o]['English'], newl[n]['English']) ! if cmp_result == 0: ! # Eng phrase is in both "new" and "old" ! cm.writerow(matchpol(oldl[o], newl[n])) ! o += 1 ! n += 1 ! elif cmp_result < 0: ! # Eng phrase is in "old", not in "new" ! handle_old_unmatched(o) ! o += 1 ! else: ! assert cmp_result > 0 # :-) ! # Eng phrase is in "new", not in "old" ! handle_new_unmatched(n) ! n += 1 !while o < lenold: ! # EOF on new, some old remain ! handle_old_unmatched(o) ! o += 1 !while n < lennew: ! # EOF on old, some new remain ! handle_new_unmatched(n) ! n += 1 Some general hints: Try stating your requirements clearly, to yourself first and then to us. Try to ensure that your code is meeting those requirements before you bother timing it. Try not to use single-letter names -- in particularly using l (that's "L".lower(), not 1 i.e. str(4-3)) is barf-inducing and makes people likely not to want to read your code. HTH, John From paschott at no.worldnet.spamm.att.net Tue Jan 11 18:47:55 2005 From: paschott at no.worldnet.spamm.att.net (Peter A. Schott) Date: Tue, 11 Jan 2005 23:47:55 GMT Subject: Best way to trap errors in ftplib? Message-ID: <45p8u0t9cq0k6ar17s1udt0h3tj70ajhsa@4ax.com> Using ftplib.FTP object for a project we have here to upload/download files. I know that I can wrap everything in try/except blocks, but I'm having trouble getting the exact error messages out of the Exceptions. I'd like to either send an e-mail or log the failure to a database. It would also be nice to see what the message is and perhaps add some additional logic for delay/retry or something similar. Has anyone done any of the above? Willing to share some samples? Here's a little of my code - maybe you can see what I'm doing/not doing. def myuploadbinaryfunction(args here): objFTP = ftplib.FTP(HostName, UserName, Password) objFTP.cwd(RemotePath) try: objFTP.storbinary("STOR " + RemoteFile, file(os.path.join(LocalPath, LocalFile), "rb")) SQLLogging.LogFTP(LocalFile, Company, 1) except Exception, errObj: SQLLogging.LogFTP(LocalFile, Company, 0) reportError("Failed to upload " + LocalFile, str(errObj)) print Exception print errObj In the above, reportError will send an e-mail to alert. I realize that the errObj in this case may not have the ability to convert to string, but am not sure how to get the output otherwise. Not sure how to handle a retry of a failure, either. Thank you for your help! -Peter Schott From assafs at ixi.com Mon Jan 24 09:25:18 2005 From: assafs at ixi.com (assaf) Date: 24 Jan 2005 06:25:18 -0800 Subject: TCP server Message-ID: <1106576718.263709.280380@c13g2000cwb.googlegroups.com> i am try to create a server what am i suppose to send to SocketServer.TCPServer what is the client_address ("127.0.0.1:80" ?) and BaseRequestHandler = ? thanks From irmen at -nospam-remove-this-xs4all.nl Sat Jan 8 20:22:33 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 09 Jan 2005 02:22:33 +0100 Subject: Windows XP Installation In-Reply-To: References: Message-ID: <41e08757$0$6204$e4fe514c@news.xs4all.nl> Smitsky wrote: > Hi. I am a newbie to Python. I am running Win XP and want to know what the > best course is for installing Python on my system. Could someone kindly > direct me to some related resources? Thanks in advance, Steve The Python beginners guide contains a lot of information for you: http://www.python.org/moin/BeginnersGuide There's some info on downloading and installing Python too. Good luck and have fun with Python! --Irmen From pushlinque at hotmail.com Wed Jan 12 10:15:34 2005 From: pushlinque at hotmail.com (Jane) Date: Wed, 12 Jan 2005 10:15:34 -0500 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: wrote in message news:1105495569.479185.166340 at z14g2000cwz.googlegroups.com... > python.org = 194.109.137.226 > > 194 + 109 + 137 + 226 = 666 > > What is this website with such a demonic name and IP address? What > evils are the programmers who use this language up to? > Some people have too much time on their hands... Jane From daniel at bowettsolutions.com Tue Jan 25 15:43:54 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Tue, 25 Jan 2005 20:43:54 +0000 Subject: MySQLdb Message-ID: <41F6AF8A.3040102@bowettsolutions.com> I have just started playing around with MySQLdb for a project I am planning. As a test I have written a script that executes 3000 insert statements on a table. The table contains 10 fields with a mix of text and numbers - its a product table for a website eg UPC, ProductName, Price etc. The problem I have is that it takes just over two minuted to execute the 3000 insert statements which seems really slow! I am running it on a machine with a 1.5 Ghz Pentium M Processor and Gig Of Ram. I dont think the machine is to blame for the speed because during execution the processor sits at about 10% and there is loads of free RAM. Does anyone know if this sort of speed sounds right? Cheers, Dan. From drs at remove-to-send-mail-ecpsoftware.com Wed Jan 12 15:21:37 2005 From: drs at remove-to-send-mail-ecpsoftware.com (drs) Date: Wed, 12 Jan 2005 20:21:37 GMT Subject: encryption/decryption help Message-ID: Hi, I need to send secure data over an insecure network. To that end, I am needing to encrypt serialized data and then decrypt it. Is there a builtin way to do this in Python? MD5, SHA, etc encrypt, but I am not seeing a way to get back my data. Encryption is totally new to me, so any pointers of what to read up on would be appreciated. As a side note, I understand that I could use https, but this would involve changing things that I may not be at liberty to change -- though if this turns out to be the best solution, then I'll find a way to use it. Thanks From tdickenson at geminidataloggers.com Tue Jan 25 07:57:39 2005 From: tdickenson at geminidataloggers.com (Toby Dickenson) Date: Tue, 25 Jan 2005 12:57:39 +0000 Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) In-Reply-To: References: Message-ID: <200501251257.39751.tdickenson@geminidataloggers.com> On Tuesday 25 January 2005 12:40, Richie Hindle wrote: > > [Steven] > > Can someone give me an example of where __-mangling really solved a problem > > for them, where a simple leading underscore wouldn't have solved the > > same problem? > > http://cvs.sourceforge.net/viewcvs.py/spambayes/spambayes/spambayes/Dibbler.py?r1=1.13&r2=1.13.4.1 > > That's a bugfix to SpamBayes, where I'd inadvertently named an instance > variable '_map' without realising that the base class > (asynchat.async_chat) also had an instance variable of that name. Using > double underscores fixed it, and had I used them from the beginning the > bug would never have cropped up (even if asynchat.async_chat had an > instance variable named '__map', which is the whole point (which you know, > Steven, but others might not)). I have a counterexample. Consider refactoring a class from.... class B(A): etc ....into.... class C(A): etc class B(C): etc Usage of some double-undescore attributes moved from B to the new intermediate base class C. Unit tests on B still passed, so that change is safe. right? The problem occured because the double-underscore mangling uses the class name, but ignores module names. A related project already had a class named C derived from B (same name - different module). My refactoring caused aliasing of some originally distinct double-underscore attributes. -- Toby Dickenson ____________________ Important Notice: This email and any attachments are confidential and may contain trade secrets or be legally privileged. If you have received this email in error you must not use, rely upon, disclose, copy or distribute the contents. Please reply to the sender so that proper delivery can be arranged and delete the email from your computer. Gemini Data Loggers monitor incoming and outgoing email to ensure satisfactory customer service, maintain company security and prevent abuse of their email system. However, any views expressed in this email are not necessarily those of Gemini and Gemini cannot be held responsible for the content. Gemini makes best efforts to ensure emails are virus free; however you are advised to carry out your own checks. Gemini does not accept responsibility for any damage resulting from email viruses. ____________________ From max at alcyone.com Fri Jan 7 23:31:56 2005 From: max at alcyone.com (Erik Max Francis) Date: Fri, 07 Jan 2005 20:31:56 -0800 Subject: "A Fundamental Turn Toward Concurrency in Software" In-Reply-To: References: Message-ID: aurora wrote: > Just gone though an article via Slashdot titled "The Free Lunch Is Over: A > Fundamental Turn Toward Concurrency in Software" > [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that the > continous CPU performance gain we've seen is finally over. And that future > gain would primary be in the area of software concurrency taking advantage > hyperthreading and multicore architectures. Well, I think it's reasonable to expect that _eventually_ (whether soon or relatively soon or not for a long time) Moore's law will fail, and the exponential increase in computing power over time will cease to continue. At that point, it seems reasonable to assume you'll do your best to take advantage of this with parallelization -- if your CPU won't get faster, just put more and more in the box. So I've always had it in the back of my mind that languages that can easily support massive (especially automatic) parallelization will have their day in the sun, at least someday. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis All the people in my neighborhood turn around and get mad and sing -- Public Enemy From aleaxit at yahoo.com Sun Jan 30 03:22:07 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 30 Jan 2005 09:22:07 +0100 Subject: limited python virtual machine References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr58wn.m3n0xac2j9qbN%aleaxit@yahoo.com> Message-ID: <1gr72vj.1mp35qg1ftc49dN%aleaxit@yahoo.com> Nick Coghlan wrote: ... > > If you _can_ execute (whatever) in a separate process, then an approach > > based on BSD's "jail" or equivalent features of other OS's may be able > > to give you all you need, without needing other restrictions to be coded > > in the interpreter (or whatever else you run in that process). > > I think that's where these discussion have historically ended. . . making a > Python-specific sandbox gets complicated enough that it ends up making more > sense to just use an OS-based sandbox that lets you execute arbitrary binaries > relatively safely. > > The last suggestion I recall along these lines was chroot() plus a monitoring > daemon that killed the relevant subprocess if it started consuming too much > memory or looked like it had got stuck in an infinite loop. "Yes, but" -- that ``if'' at the start of this quote paragraph of mine is, I believe, a meaningful qualification. It is not obvious to me that all applications and platforms can usefully execute untrusted Python code in a separate jail'd process; so, I think there would still be use cases for an in-process sandbox, although it's surely true that making one would not be trivial. Alex From xah at xahlee.org Thu Jan 13 05:18:26 2005 From: xah at xahlee.org (Xah Lee) Date: 13 Jan 2005 02:18:26 -0800 Subject: [perl-python] 20050112 while statement Message-ID: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> # here's a while statement in python. a,b = 0,1 while b < 20: print b a,b = b,a+b --------------- # here's the same code in perl ($a,$b)=(0,1); while ($b<20) { print $b, "\n"; ($a,$b)= ($b, $a+$b); } Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From wittempj at hotmail.com Mon Jan 31 03:58:42 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 31 Jan 2005 00:58:42 -0800 Subject: Nested scopes and class variables In-Reply-To: References: Message-ID: <1107161922.285810.8510@f14g2000cwb.googlegroups.com> To me it seems you should do it something like this: -def f(x): - class C(object): - def __init__(self, x): - self.x = x # here you set the attribute for class C - c = C(x) # instantiate a C object - print c.x -f(5) From francis.girard at free.fr Thu Jan 27 16:19:41 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 27 Jan 2005 22:19:41 +0100 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: <200501272219.42090.francis.girard@free.fr> Le jeudi 27 Janvier 2005 22:07, Steven Bethard a ?crit?: > Francis Girard wrote: > > Le jeudi 27 Janvier 2005 21:29, Steven Bethard a ?crit : > >>So None being smaller than anything (except itself) is hard-coded into > >>Python's compare routine. My suspicion is that even if/when objects of > >>different types are no longer comparable by default (as has been > >>suggested for Python 3.0), None will still compare as smaller than > >>anything... > > > > Well, here's python doesn't seem to confirm what you're saying : > >>>>a = "10" > >>>>b = 10 > >>>>a > b > > > > True > > > >>>>b > a > > > > False > > > >>>>id(a) > > > > 1077467584 > > > >>>>id(b) > > > > 134536516 > > Actually, this code doesn't contradict what I said at all. I said that > None (and only None) was special-cased. > You're right. I just posted too soon. Sorry. > > It really looks like the addresses are compared when objects are of > > different types if there is no __cmp__ or __lt__ user made specification > > to compare objects of different types. > > Use the source Luke! ;) Download it from CVS and take a look. The end > of default_3way_compare: > Just want to know the specifications. No matter how it had been implemented. > static int > default_3way_compare(PyObject *v, PyObject *w) > { > ... > /* None is smaller than anything */ > if (v == Py_None) > return -1; > if (w == Py_None) > return 1; > > /* different type: compare type names; numbers are smaller */ > if (PyNumber_Check(v)) > vname = ""; > else > vname = v->ob_type->tp_name; > if (PyNumber_Check(w)) > wname = ""; > else > wname = w->ob_type->tp_name; > c = strcmp(vname, wname); > if (c < 0) > return -1; > if (c > 0) > return 1; > /* Same type name, or (more likely) incomparable numeric types */ > return ((Py_uintptr_t)(v->ob_type) < ( > Py_uintptr_t)(w->ob_type)) ? -1 : 1; > } > > So it looks like Python uses the type name. Testing this: > > py> A = type('A', (object,), {}) > py> Z = type('Z', (object,), {}) > py> lst = [str('a'), dict(b=2), tuple(), Z(), A()] > py> [type(o).__name__ for o in lst] > ['str', 'dict', 'tuple', 'Z', 'A'] > py> sorted(type(o).__name__ for o in lst) > ['A', 'Z', 'dict', 'str', 'tuple'] > py> sorted(lst) > [<__main__.A object at 0x011E29D0>, <__main__.Z object at 0x011E29F0>, > {'b': 2}, 'a', ()] > > Yup. Looks about right. (Note that the source code also special-cases > numbers...) > > So, the order is consistent, but arbitrary, just as Fredrik Lundh > pointed out in the documentation. > Ok. Thank you, Francis Girard > Steve From jeff at ccvcorp.com Tue Jan 25 14:46:04 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 25 Jan 2005 11:46:04 -0800 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <41f6162f.1768893674@news.oz.net> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> <41f6162f.1768893674@news.oz.net> Message-ID: <10vd84er6bjr2ad@corp.supernews.com> Bengt Richter wrote: > On 25 Jan 2005 08:30:03 GMT, Nick Craig-Wood wrote: > >>If you are after readability, you might prefer this... >> >>def hamming(): >> def _hamming(): >> yield 1 >> for n in imerge(imap(lambda h: 2*h, iter(hamming2)), >> imerge(imap(lambda h: 3*h, iter(hamming3)), >> imap(lambda h: 5*h, iter(hamming5)))): >> yield n >> hamming2, hamming3, hamming5, result = tee(_hamming(), 4) >> return result > > Are the long words really that helpful? > > def hamming(): > def _hamming(): > yield 1 > for n in imerge(imap(lambda h: 2*h, iter(hg2)), > imerge(imap(lambda h: 3*h, iter(hg3)), > imap(lambda h: 5*h, iter(hg5)))): > yield n > hg2, hg3, hg5, result = tee(_hamming(), 4) # four hamming generators > return result Well, judging by the fact that shortening the identifiers made it so that you felt the need to add a comment indicating what they were identifying, I'd say that yes, the long words *are* helpful. ;) Comments are good, but self-documenting code is even better. Jeff Shannon Technician/Programmer Credit International From chris.cavalaria at free.fr Mon Jan 3 17:07:40 2005 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Mon, 03 Jan 2005 23:07:40 +0100 Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: <41d9c22c$0$31927$626a14ce@news.free.fr> eeykay at gmail.com wrote: > Hello All, > I am trying to convince my client to use Python in his new product. He > is worried about the license issues. Can somebody there to point me any > good commercial applications developed using python ?. The licence > clearly says Python can be used for commercial applications. Is there > any other implications like that of GPL to make the source open ? > Thanks for any help. > eeykay Troika games use Python in their games. It seems you can even get the source .py files for Vampires: Bloodlines :) From adam at cognitcorp.com Tue Jan 4 22:38:14 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Tue, 04 Jan 2005 22:38:14 -0500 Subject: what is lambda used for in real code? In-Reply-To: References: Message-ID: <1104894385.5050.31.camel@localhost.localdomain> On Sat, 2005-01-01 at 11:42, Steve Holden wrote: > Adam DePrince wrote: > [...] > > > > In sort, we must preserve the ability to create an anonymous function > > simply because we can do so for every other object type, and functions > > are not special enough to permit this special case. > > > And you'd create an anonymous type how, exactly? > Okay, you got me. Let me rephrase: ... functions, types, classes and moduless are not special enough ... I had things like, um, strings, lists, integers, etc in mind. - adam > regards > Steve > -- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/ > Holden Web LLC +1 703 861 4237 +1 800 494 3119 Adam DePrince From pdemb at illx.org Sun Jan 2 06:46:40 2005 From: pdemb at illx.org (Peter Dembinski) Date: Sun, 02 Jan 2005 12:46:40 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <41d6ee45$1_2@127.0.0.1> Message-ID: <87sm5kaw9r.fsf@hector.domek> "Donn Cave" writes: [...] > For me, the effect is striking. I pound out a little program, > couple hundred lines maybe, and think "hm, guess that's it" and save > it to disk. Run the compiler, it says "no, that's not it - look > at line 49, where this expression has type string but context > requires list string." OK, fix that, iterate. I believe program-specific unit tests are more effective than compiler typechecking :) From "root\" at (none) Fri Jan 14 00:36:58 2005 From: "root\" at (none) (none) Date: Fri, 14 Jan 2005 13:36:58 +0800 Subject: Interesting gDeskCal Message-ID: <41e75a60$1_3@rain.i-cable.com> I found that gDeskCal is also written in Python. So if I have a theme used by gDesklets, how can I make the whole thing standalone so that it can be similar to the case of gDeskCal?? From craig at postnewspapers.com.au Sat Jan 1 13:00:48 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sun, 02 Jan 2005 02:00:48 +0800 Subject: exposing C array to python namespace: NumPy and array module. In-Reply-To: <41D6CF86.1040902@rice.edu> References: <41D6CF86.1040902@rice.edu> Message-ID: <1104602448.9326.5.camel@albert.localnet> On Sat, 2005-01-01 at 10:27 -0600, Bo Peng wrote: > Sorry if I was not clear enough. I was talking about the differece > between python array module > (http://docs.python.org/lib/module-array.html, Modules/arraymodule.c in > the source tree) and NumPy array. They both use C-style memory block > arrangement for efficient memory access. While NumPy has both, the array > module is designed to be used purely in Python so there is no header > file and no function to build an array from a pointer. Thanks for clarifying that - I had misunderstood your reference to arraymodule.c . I guess the core language doesn't have an array type, but as there's a standard lib module that does (I'd forgotten it was there), it hardly matters. It would seem sensible to extend that module with a C API for mapping an existing array. That would be a rather handy thing to have in the standard library. > One of the methods you suggested (creating a new type) already > implemented in arraymodule.c. I am not sure if it is appropriate to add > the file into my project and add a 'CreateFromLenAndBuf' function. That sounds like a reasonable approach to me, but I'm hardly an expert. The code's license permits you to do so, and it's hardly worth repeating the work if you don't have to. -- Craig Ringer From steve at holdenweb.com Mon Jan 31 09:51:14 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 09:51:14 -0500 Subject: re module - cannot make expression In-Reply-To: References: Message-ID: Laszlo Zsolt Nagy wrote: > Hi All! > > I would like to match strings not beginning with '/webalizer'. How can I > do this? > The only one negation command is ^ inside [] but it cannot be used here. > I looked > over "re" examples on the net but I could not find an example about how > to match > "not beginning with" type expressions. > > Thanks, > > Laci 2.0 > You can do taht with Python re's. Look in the re documentation for "negative lookahead assertion". regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From jepler at unpythonic.net Mon Jan 3 21:04:38 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 3 Jan 2005 20:04:38 -0600 Subject: Controlling newlines when writing to stdout (no \r\n). In-Reply-To: References: Message-ID: <20050104020437.GA11833@unpythonic.net> Well, here's the first page turned up by google for the terms 'python binary stdout': http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65443 Code from that page: import sys if sys.platform == "win32": import os, msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) Thanks, Google & the Python Cookbook website! Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steve at holdenweb.com Fri Jan 14 11:53:29 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 11:53:29 -0500 Subject: newbie q In-Reply-To: <41e7098e.782680124@news.oz.net> References: <34mgq0F4dq4buU1@individual.net> <34mku4F4c8bdkU1@individual.net> <41e7098e.782680124@news.oz.net> Message-ID: <41E7F909.9020307@holdenweb.com> Bengt Richter wrote: > On Thu, 13 Jan 2005 09:16:40 -0500, Steve Holden wrote: > [...] > >>Any statement of the form >> >> for i in [x for x in something]: >> >>can be rewritten as >> >> for i in something: >> >>Note that this doesn't mean you never want to iterate over a list >>comprehension. It's the easiest way, for example, to iterate over the >>first item of each list in a list of lists: >> >> for i in [x[0] for x in something]: >> > > As I'm sure you know, with 2.4's generator expressions you > don't have to build the temporary list. > Which could be important if 'something' > is (or generates) a huge sequence. > > for i in (x[0] for x in something): > Yes. While I haven't yet done any more than play with generator sequences I do really feel that more of "the best of Icon" has arrived in Python with this new addition. > >>> something = ([x] for x in xrange(10,20)) > >>> something > > >>> list(something) > [[10], [11], [12], [13], [14], [15], [16], [17], [18], [19]] > >>> for i in (x[0] for x in something): print i, > ... > > oops, that list() used it up ;-) > > >>> something = [[x] for x in xrange(10,20)] > >>> for i in (x[0] for x in something): print i, > ... > 10 11 12 13 14 15 16 17 18 19 > > Really nice. > I quite agree. It's particularly useful for infinite sequences :-) regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From annaraven at gmail.com Sun Jan 9 11:49:51 2005 From: annaraven at gmail.com (Anna) Date: 9 Jan 2005 08:49:51 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> Message-ID: <1105289391.534192.74060@c13g2000cwb.googlegroups.com> Jacek Generowicz wrote: > "Anna" writes: > > > Having taken some calculus (derivatives, limits, some integrals) but > > never even heard of lambda calculus, to me, lambda means absolutely > > NOTHING. Less than nothing. > > And before you took calculus, the chances are that derivatives, limits > and integrals meant less than nothing to you. > > But now, I am quite sure, you know that in Python lambda is a keyword > which creates anonymous functions. Now that you know what lambda does, > what's the problem with it? (It certainly doesn't mean "Less than > nothing" to you now.) > > > So, I guess I don't like the word itself > > Fair enough. I guess there are people out there who might have a > distaste for the word "class" or "def" or any of the other words which > are keywords in Python. > > > Every other word in Python has an obvious meaning. lambda doesn't. > > Obvious to whom? > > The meaning of every word is obvious, once you have been taught it; > and a complete mystery if you have not. > > What do you make of "seq[2:-2]"? It means "less than nothing" to the > uninitiated. Just like lambda. Actually - whether or not I understood the [2:-2] notation, knowing nothing else, the "seq" would clue me in that we're probably doing something with sequences... Personally, I like lambdas less than regular expressions (of which I'm particularly UNfond but understand their usefulness at times). At least with regular expressions - I know that the gibberish I need to decipher (probably) has to do with text parsing... With class and def, I at least have a *name* to start with - class Square pretty obviously is going to have something to do with geometric shapes, I would hope (or maybe with boring people...). def getfoo() tells me I'm the function is likely to go elsewhere and get something. It's a *start*, a handle, to deciphering whatever the following statements are doing. (Yes, I realize that often class and function names suck - but more often than not, they give *some* clue). Whereas, with lambda - I have *nothing* to go on. With lambdas, all I know is that the programmer wanted to hide whatever it is the program is doing behind the curtain... (at least that's the way it comes across). So, not only is the word itself not descriptive of anything to me - even knowing that it means "anonymous function" - the use of it precludes descriptiveness, as compared to defining a function. IMHO, YMMV, etc etc Anna From maxm at mxm.dk Sat Jan 8 11:32:34 2005 From: maxm at mxm.dk (Max M) Date: Sat, 08 Jan 2005 17:32:34 +0100 Subject: Another look at language comparisons In-Reply-To: References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> <1105188426.955508.263030@c13g2000cwb.googlegroups.com> Message-ID: <41e00ac1$0$265$edfadb0f@dread12.news.tele.dk> Jan Dries wrote: > beliavsky at aol.com wrote: > And there is hope for Python, as Guido has recently been seen with a > beard :-) > http://www.tbray.org/ongoing/When/200x/2004/12/08/-big/IMG_3061.jpg LOL, he is working on linux, isn't he? So it was about bloody time. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From dishking at mwqrvdua.com Fri Jan 7 04:55:40 2005 From: dishking at mwqrvdua.com (me to you) Date: Fri, 7 Jan 2005 01:55:40 -0800 Subject: Here is $50 for signing up free Message-ID: Hello, I'm trying out a new auto poster, and dont know how to use it very good, so if this end up in the wrong places, please forgive me, and disreguard, sorry for your incovenience, but everyone else, ENJOY!! KEEP READING TO GET YOUR $50.00 NOW!!! This is not spam, it is a legitament way to make money on the net, reading e-mail, and other things as well, plus you get $50.00 dollars for signing up. This is tottaly free, and requires no credit card on out of pocket money. You will get paid for various things on the net, hope you enjoy and find some usefull info here that will help you out. Plus you will get fifty dollars. this is not spam, its usefull news for all newsgroups readers, from me to you, hope you can use it for your benifit, please enjoy. If your not sure, get a new email address, and then try, you wont get spammed, and all info is carefully guarded, and not given out or traded or sold. Enjoy your $50.00, I did, so did my friends and family. You'll also be able to do survays if you want, P.S. forgive my spelling. Just copy and paste into your browser, thanks again. URL: http://www.CashRead.com/cgi-bin/signup.cgi?r=fogylight at yahoo.com Dont be mean and hatefull, if you dont want to Participate, DON'T. If you don't want $50.00, let someone else have it. From klachemin at comcast.net Tue Jan 25 02:06:58 2005 From: klachemin at comcast.net (Kamilche) Date: 24 Jan 2005 23:06:58 -0800 Subject: Open Folder in Desktop Message-ID: <1106635751.661619.253930@c13g2000cwb.googlegroups.com> Is there a command you can execute in Python that will open a window on the desktop, such as 'My Documents'? Kind of like 'system', but for folder names, not just programs. I'm running on Windows 2000. From steve at holdenweb.com Thu Jan 6 22:34:03 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Jan 2005 22:34:03 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> <1gpwrh7.b7z8qtablx7gN%aleaxit@yahoo.com> <41DD4E62.1020404@holdenweb.com> Message-ID: Bulba! wrote: > On Thu, 06 Jan 2005 09:42:42 -0500, Steve Holden > wrote: > >>>You see, I'm not disagreeing with you that your model applies >>>_where it applies_. I only disagree that it applies in face of >>>stronger forces. Now what kind of forces is dominant in >>>most frequent scenarios would have to be worked out in tedious >>>empirical research I think. Which I haven't done, because >>>learning some economics is just a hobby to me. > > >>Yes, by all means let's just spout our opinions without any of that >>inconvenient tedious empirical research which might invalidate them. > > > Err, but what did I do that got you visibly pissed off? > > I certainly did not mean offending anyone. If I did smth > that did, I apologize, but honestly I didn't mean that. I > just expressed my opinion and cited some small bits of evidence, > which I think I'm entitled to. > I am probably not as pissed off as you might think, but I'm beginning to find (what I regard as) your naivety a little irritating. However, nothing I have said was intended to question your integrity. > [...] > >>>Oh, and by the way that installation doesn't get used much. >>>Somebody at the office didn't check carefully enough the >>>energy prices before ordering it and later someone discovered >>>that off-site specialized cutting firms that take advantage of >>>energy available at low prices at special times in other countries >>>can get it produced cheaper. Moving it elsewhere or selling >>>is not an option, since it is a specially constructed, low, 50-meters >>>long hall that stands inside the huge manufacturing hall of the >>>company. > > >>And you are using this example to try and argue that engineers are >>better-educated than sales people? > > > Nope. The context was that behavior of companies tends to > be highly rational, optimized and not wasting resources. My > naturally individual experience was that it was oft not the case, > and that was the example. > Well, anyone who *does* believe that companies are managed in a way that's any more rational than the way individual humans manage their own lives is deluding themselves. But perhaps I'm a little clearer now about *your* thinking on this. > Which was my point when explaining the clustering that > demonstrably happened: if the behavior of decisionmakers > is highly informed, rational and not really induced much by > risk avoidance as Alex claims, then the clusters are created > by "natural economic forces". > The agent of economic forces, however, are always individual humans. It just isn't possible to factor them out. > However, if the process is not that rational, then maybe > clusters are the correlation of "cover your ass" aspect > in managers' behavior all wanting to get their branch office > in yesterday in Tokyo, today in Beijing, and during > speculative craze in Russia in Moscow "because everybody > is doing that". Which observations of Paul Krugman on > "defective investors" seem to support. > > Now, I'm very strongly opposed to saying that all that > somehow invalidates economics, including economics > of software, as _science_. > > All I'm saying is that maybe this particular model is not > what some people think it is. This is the problem with > economics, people tend to get hot under the collar about > it for some reason and it's oft hard to debate that calmly. > Which personally I find a pity, because e.g. economics > of software is such an interesting subject.. > I can live with that, I guess. > >>Who sold this installation? Who >>bought it? > > > I have no idea, as I were not a manager there and it > didn't really pertain my work. > I was merely trying to point out that the sales people may well have worked a flanker on the "better educated" engineers who might have bought the plant. > >>>I was utterly shocked. Having grown up in Soviet times I have >>>been used to seeing precious resources wasted by organizations >>>as if resources were growing on trees, but smth like this?! In a >>>shining ideal country of Germany?! Unthinkable. > > > >>Indeed not. Quite often the brown paper bag is a factor in purchases >>like this. I wouldn't be at all surprised if somebody with a major input >>to the decision-making process retired to a nice place in the country >>shortly afterwards. You appear to be making the mistake of believing >>that people will act in the larger interest, when sadly most individuals >>tend to put their own interests first (some would go as far as to define >>self-interest as the determinant of behavior). > > > But there is a subtler point here: most likely it was NOT in the > short-term personal interest to make this mistake (as I believe > corruption was not the case in this decision)! > > After all, whoever responsible was still running the considerable risk > of getting fired. It is an example that precisely negates either > collective or individual, long-term or short-term, interest was > primary factor in this decision. > Well, you would know better than me, but believe me when I say that such decisions being made for the economic benefit of a single individual are far from rare. > >>>>The firm I was working for had a consensus decision-making process (even >>>>I was involved) and managers (and other employees) and stockholders were >>>>mostly the same people -- it wasn't all that large a firm at the time. >>>>Nobody needed to practice risk avoidance. > > >>>Again, you may have had good luck. Where I worked (including >>>some places in Germany and UK) it was almost the only factor >>>that seemed to matter to people - they'd do ANYTHING not to >>>take a risky decision, to "pass the buck", not to stick their necks >>>out, not to declare doing some work that involved challenges. > > > >>Some people are like that. I chose a long time ago to try not to work >>with them whenever I could avoid it and, while that may have had >>negative economic consequences I an convinced it has improved my quality >>of life immensely. Of course, I have no proof for such an assertion. > > > Which in economic terms could mean that your "utility function" > is "modeled" in this particular way (well, strictly speaking utility > functions regard simple consumption), while most people tend > to misunderstand it as the idea that supposedly is "vulgar > consumption of as much stuff as possible is what makes people > happy" and they feel rightly repulsed from such an idiotic idea. > The trouble is, well-informed people do not to argue that, while > people tend to think economists actually do... > Well, even assuming I were to allow that such an intellectual thing as a utility function were to apply to my behavior in this case (which would be allowing economists more credence than I believe most of them deserve, but what the heck), all we are really taking about is that "it takes all sorts to make a world". I'm as fond of what money can buy as the next guy, but there are still limits on what I will do to acquire it. So really a utility function is a very dry and abstract way of looking at human behavior, and is simply incapable (at the present stage of the game) of modeling human behavioral complexity. > > > -- > It's a man's life in a Python Programming Association. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From __peter__ at web.de Sat Jan 22 04:23:35 2005 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Jan 2005 10:23:35 +0100 Subject: default value in a list References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: Peter Otten wrote: > Paul McGuire wrote: > >>> Is there an elegant way to assign to a list from a list of unknown >>> size? For example, how could you do something like: >>> >>> >>> a, b, c = (line.split(':')) >>> if line could have less than three fields? > >> I asked a very similar question a few weeks ago, and from the various >> suggestions, I came up with this: >> >> line = "AAAA:BBB" >> expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen] >> a,b,c = expand( line.split(":"), "", 3 ) > > Here is an expand() variant that is not restricted to lists but works with > arbitrary iterables: > > from itertools import chain, repeat, islice > > def expand(iterable, length, default=None): > return islice(chain(iterable, repeat(default)), length) Also nice, IMHO, is allowing individual defaults for different positions in the tuple: >>> def expand(items, defaults): ... if len(items) >= len(defaults): ... return items[:len(defaults)] ... return items + defaults[len(items):] ... >>> expand((1, 2, 3), (10, 20, 30, 40)) (1, 2, 3, 40) >>> expand((1, 2, 3), (10, 20)) (1, 2) Peter From gerrit at nl.linux.org Mon Jan 10 05:53:44 2005 From: gerrit at nl.linux.org (Gerrit) Date: Mon, 10 Jan 2005 11:53:44 +0100 Subject: tuples vs lists In-Reply-To: References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dff650$0$29357$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <20050110105344.GA8384@topjaklont.student.utwente.nl> Steve Holden wrote: > worzel wrote: > >'Two-Pull' it is then, thanks. > > > Well, it might be "Two-Pull" in American, but in English it's "tyoopl" > -- NOT "choopl" (blearch!). I've also heard people say "tuppl". > > So, basically, say whatever you want. Language is about communication :-) Or just write it down and don't say the word at all (-: regards, Gerrit, who actually says t?pel. -- Weather in Lulea / Kallax, Sweden 10/01 10:20: -12.0?C wind 0.0 m/s None (34 m above NAP) -- In the councils of government, we must guard against the acquisition of unwarranted influence, whether sought or unsought, by the military-industrial complex. The potential for the disastrous rise of misplaced power exists and will persist. -Dwight David Eisenhower, January 17, 1961 From a at b.c Sun Jan 23 02:33:35 2005 From: a at b.c (Doug Holton) Date: Sun, 23 Jan 2005 01:33:35 -0600 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fpq0F4mh1ffU1@individual.net> Message-ID: <_cSdnRo1keDOzm7cRVn-ug@comcast.com> Daniel Bickett wrote: > In my (brief) experience with YAML, it seemed like there were several > different ways of doing things, and I saw this as one of it's failures > (since we're all comparing it to XML). However I maintain, in spite of > all of that, that it can easily boil down to the fact that, for > someone who knows the most minuscule amount of HTML (a very easy thing > to do, not to mention most people have a tiny bit of experience to > boot), the transition to XML is painless. YAML, however, is a brand > new format with brand new semantics. That's true and a very good point. Like you said, that's probably the reason XML took off, because of our familiarity with HTML. > As for the human read-and-write-ability, I don't know about you, but I > have no trouble whatsoever reading and writing XML. You might like programming in XML then: http://www.meta-language.net/ :) From sjmachin at lexicon.net Tue Jan 11 18:08:06 2005 From: sjmachin at lexicon.net (John Machin) Date: 11 Jan 2005 15:08:06 -0800 Subject: Importing Problem on Windows References: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> Message-ID: <1105484886.837430.248940@f14g2000cwb.googlegroups.com> brolewis wrote: > I have a directory that has two files in it: > > parse.py > parser.py > > parse.py imports a function from parser.py and uses it to parse out the > needed information. On Linux, the following code works without a > problem: > > parse.py, line 1: > from parser import regexsearch > > However, when I run the same command in Windows, I get the following > error: > > ImportError: cannot import name regexsearch > Any suggestions on why this would work on Linux but not on Windows? Hint for the future: use the -v argument (python -v yourscript.py yourarg1 etc) to see where modules are being imported from. Example (I don't have a module named parser anywhere): python -v [big snip] >>> from parser import regexsearch import parser # builtin <<<<==== aha! Traceback (most recent call last): File "", line 1, in ? ImportError: cannot import name regexsearch >>> From christiancoder at gmail.com Mon Jan 17 15:41:25 2005 From: christiancoder at gmail.com (christiancoder at gmail.com) Date: 17 Jan 2005 12:41:25 -0800 Subject: Cygwin Popen object Message-ID: <1105994485.770313.141910@f14g2000cwb.googlegroups.com> Is anybody else getting the following error with the Popen object in cygwin? The code works fine in windows and linux. File "d:\atg\personal\python\buildroot\util.py", line 100, in System pipe = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True ) File "/usr/local/lib/python2.4/subprocess.py", line 554, in __init__ errread, errwrite) File "/usr/local/lib/python2.4/subprocess.py", line 914, in _execute_child self.pid = os.fork() OSError: [Errno 11] Resource temporarily unavailable From larry_wallet at yahoo.com Sat Jan 29 23:46:21 2005 From: larry_wallet at yahoo.com (Larry) Date: 29 Jan 2005 20:46:21 -0800 Subject: what's OOP's jargons and complexities? References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> Message-ID: <1107060381.623163.19850@z14g2000cwz.googlegroups.com> Xah Lee wrote: > in computer languages, often a function definition looks like this: > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html Your ideas are original, insightful and simply reflect incredibly deep creative genius. I have read your work and I want to hire you for highly classified work in software design and philosophical writing. Would you possibly be available to meet with me in my secret mountain compound to discuss terms? Larry From wuwei23 at gmail.com Wed Jan 5 17:38:57 2005 From: wuwei23 at gmail.com (alex23) Date: 5 Jan 2005 14:38:57 -0800 Subject: Python evolution: Unease In-Reply-To: <10to8qulnc3vke1@news.supernews.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> Message-ID: <1104964736.965029.96160@c13g2000cwb.googlegroups.com> John Roth wrote: > I've been reading this thread and quietly congratulating myself > on staying out of it, but this statement takes the cake. Honestly, I feel the same way about statements of your's like this: > The bottom line is that I'm not going to be writing any > extensive pieces of Python documentation. My time > is better spent elsewhere. The question is: *whose* time do you consider better spent on writing Python documentation *for you*? That is what I'm so incredulous about, the tone of demand in the original post (and also very visible in your quoted remark above) that insists this is *someone else's* responsibility. Again: if you want the documentation that badly, then you want to do what said documentation would illustrate. If you *really* want to do that, then you'll take the time to find out how it's done *anyway*, document it up as you go, no matter how briefly, and make a *start* on filling in what *you* perceive as being a void in the current documentation. But to point out how laborious a process it is and how your time is too valuable to undertake it personally...it's difficult to parse that any other way than "I want other people to do all the hard work for me". From beliavsky at aol.com Tue Jan 25 12:40:35 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 25 Jan 2005 09:40:35 -0800 Subject: Browsing text ; Python the right tool? References: Message-ID: <1106674835.862387.79030@z14g2000cwz.googlegroups.com> Here is an elementary suggestion. It would not be difficult to write a Python script to make a csv file from your text files, adding commas at the appropriate places to separate fields. Then the csv file can be browsed in Excel (or some other spreadsheet). A0 and C1 records could be written to separate csv files. There are Python programs to create Excel spreadsheets, and they could be used to format the data in more sophisticated ways. From http Sun Jan 9 23:50:27 2005 From: http (Paul Rubin) Date: 09 Jan 2005 20:50:27 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> Message-ID: <7xu0ppyjjg.fsf@ruckus.brouhaha.com> "Roose" writes: > Are you actually going to answer any of my questions? Let's see > this "JavaScript task scheduler" you have written! I wrote it at a company and can't release it. It ran inside a browser. There was nothing terribly amazing about it. Obviously the tasks it scheduled were not kernel tasks. Do you know how Stackless Python (with continuations) used to work? That had task switching, but those were not kernel tasks either. From matthew_shomphe at countrywide.com Wed Jan 26 16:31:30 2005 From: matthew_shomphe at countrywide.com (Matt) Date: 26 Jan 2005 13:31:30 -0800 Subject: Help With Python In-Reply-To: <87ekg8c4d0.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> References: <87ekg8c4d0.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: <1106775090.890952.40590@c13g2000cwb.googlegroups.com> Nick Vargish wrote: > Here's my Monty Pythonic answer: > > ## cut here > class Viking(): > > def __init__(): > pass > > def order(): > return 'Spam' > > # this is one viking making one order repeated 511 times. if you want > # 511 vikings making seperate orders, you'll have to write a loop. > v = Viking() > orders = [ v.order() ] * 511 > > print ', '.join(orders) > ## cut here > > With no apologies to Eric Idle, > > Nick > > > -- > # sigmask || 0.2 || 20030107 || public domain || feed this to a python > print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') Not to be nit-picky, but you got some issues here ;-). Never forget the importance of "self"! ####################### class Viking: . def __init__(self): . pass . def sing(self): . return 'Spam' v = Viking() spam_song = [ v.sing() ] * 511 print ', '.join(spam_song) From david at qssp.com Sat Jan 8 00:42:37 2005 From: david at qssp.com (D Flint) Date: Fri, 7 Jan 2005 21:42:37 -0800 Subject: Real Election Reform Message-ID: <_tadnQpw77cViX3cRVn-ow@comcast.com> What do you think about this and have you seen this popular site before? This was taken from a web site http://www.afvr.org How can we safeguard the integrity of each vote? Today we have technology that protects our financial systems, military weapon systems and national intelligent organizations. These proven systems can be combined in a way to issue serialized equipment to authorize personnel for the dates and hours needed. Each would have their own level of clearance to perform the tasks they are responsible for. Each action would be recorded and verified with a higher levels of network authority and again, only available during the hours and dates needed. Ballots would only be printed after the voter has cast their vote but before they leave the booth. If the voter made a mistake he could put the printed ballot into the booth's scanner for correction. All ballots scanned at the booth would go into a shredder and the voter could then correct his ballot on the screen and reprint his ballots. Once the voter accepts the printed ballot he submits his vote on the screen and takes the two ballots to the depository. So two computer generated, serialized and scanner perfect receipts of the completed ballot are printed.* One for the voter and one for the public record. This would eliminate all the extra ballots that could be used for unauthorized voting as well as any question of voter intent. Each piece of equipment involved in the issuing of the receipt would be linked to the serial# of that ballot and an electronic document would be generated that exactly matched the two printed receipts. So the voter themselves has validate the printed ballots, keeping one for themselves, while the other electronic time-stamped document is deposited into an optical scanner used as a secure depository. This second scanned count which should always match the electronic count. This paper ballot could also be used for recounts if needed. The voter could use the receipt to inquire about their vote in the future. The stuffing of the ballot box or "finding ballots" would be eliminated. With this system, if you find a ballot, you have to find the voter that cast that ballot too. This is not so in any of the current systems in place today nor have we ever heard such a system ever proposed. http://www.afvr.org From steven.bethard at gmail.com Wed Jan 12 13:47:13 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 11:47:13 -0700 Subject: counting items In-Reply-To: References: Message-ID: <1oOdnQwciYEy7XjcRVn-gQ@comcast.com> Mark McEahern wrote: > It's me wrote: > >> Okay, I give up. >> >> What's the best way to count number of items in a list [that may >> contain lists]? >> >> > a = [[1,2,4],4,5,[2,3]] > > def iterall(seq): > for item in seq: > try: > for subitem in iterall(item): > yield subitem > except TypeError: > yield item > > all = [x for x in iterall(a)] > print len(all) > Beware: py> list(iterall(['a'])) Traceback (most recent call last): File "", line 1, in ? File "", line 4, in iterall ... File "", line 4, in iterall RuntimeError: maximum recursion depth exceeded You need to special-case strings. I would do this explicitly, e.g.: py> def iterall(seq): ... for item in seq: ... if isinstance(item, basestring): ... yield item ... else: ... try: ... for subitem in iterall(item): ... yield subitem ... except TypeError: ... yield item ... py> list(iterall(['a'])) ['a'] but you can also do this by checking for __iter__ as in one of the other posted solutions. (This takes advantage of the fact that strings use the __getitem__ protocol for iteration instead of __iter__.) Steve From fredrik at pythonware.com Mon Jan 24 15:51:31 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 21:51:31 +0100 Subject: Question about reading a big binary file and write it into severaltext (ascii) files References: <1106599472.099182.312130@z14g2000cwz.googlegroups.com> Message-ID: Albert Tu wrote: > I am learning and pretty new to Python and I hope your guys can give me > a quick start. > > I have an about 1G-byte binary file from a flat panel x-ray detector; I > know at the beggining there is a 128-byte header and the rest of the > file is integers in 2-byte format. > > What I want to do is to save the binary data into several smaller files > in integer format and each smaller file has the size of 2*1024*768 > bytes. > > I know I can do something like >>>>f=open("xray.seq", 'rb') >>>>header=f.read(128) >>>>file1=f.read(2*1024*768) >>>>file2=f.read(2*1024*768) >>>>...... (using a loop might help) >>>>f.close() > > Bur I don't them how to save files in integer format (converting from > binary to ascii files) and how to do this in an elegant and snappy way. I think you have to define "integer format" a bit better. A text file with integer values, written out in decimal? If so, take a look at the array module: http://docs.python.org/lib/module-array.html Here's an (untested) example; tweak as necessary: linesize = 1024 data = array("h", filedata) for i in range(0, len(data), linesize): # convert to list of decimal integers list = map(str, data[i:i+linesize]) print " ".join(list) tools like PIL and NumPy may also come in handy, but I suspect they're overkill in this case. From andreasp at qbcon.com Thu Jan 27 08:07:47 2005 From: andreasp at qbcon.com (Andreas Pauley) Date: Thu, 27 Jan 2005 15:07:47 +0200 (SAST) Subject: Point of Sale Message-ID: Hi, My company has given me a rather cool project: I have to provide them with an open-source python-based point-of-sale / cash register system that can integrate with their existing ERP backend. The project will include development to ensure that the features they require are included in the open-source POS system. Can you recommend anything that I can use? Regards, Andreas From sjmachin at lexicon.net Sun Jan 23 21:08:36 2005 From: sjmachin at lexicon.net (John Machin) Date: 23 Jan 2005 18:08:36 -0800 Subject: Set parity of a string In-Reply-To: References: Message-ID: <1106532516.483892.292900@z14g2000cwz.googlegroups.com> Peter Hansen wrote: > snacktime wrote: > > Is there a module that sets the parity of a string? I have an > > application that needs to communicate with a host using even parity > > So what I need is before sending the message, convert it from space to > > even parity. And when I get the response I need to convert that from > > even to space parity. > > By what means are the messages being delivered? I've rarely > seen parity used outside of simple RS-232-style serial communications. > Certainly not (in my experience, though it's doubtless been done) > in TCP/IP based stuff. And if it's serial, parity can be > supplied at a lower level than your code. > > As to the specific question: a module is not really required. > The parity value of a character depends only on the binary > value of that one byte, so a simple 128-byte substitution > table is all you need, plus a call to string.translate for > each string. > > -Peter And for converting back from even parity to space parity, either a 256-byte translation table, or a bit of bit bashing, like chr(ord(c) & 127), on each byte. The bank story sounds eminently plausible to me. Pick up old system where branch manager had to dial HO every evening, insert phone into acoustic coupler, etc etc and dump it on the internet ... From skip at pobox.com Fri Jan 14 20:17:16 2005 From: skip at pobox.com (skip at pobox.com) Date: 14 Jan 2005 17:17:16 -0800 Subject: Handling fractions of seconds in strftime/strptime Message-ID: <1105751836.456124.69970@z14g2000cwz.googlegroups.com> I'm looking for a solution (or ideas about a solution) to the problem that strftime(3) and strptime(3) don't understand time increments of less than one second. Most operating systems can provide times with subsecond resolution and like Python I'm pretty sure Ruby, Perl and Tcl have objects or packages that can manipulate such times in a sane manner. I'm casting my net to a broader community than just Python (where I generally hang out) to see if/how others have addressed this problem. Here's my typical use case. I generate log files with subsecond resolution using Python's datetime module. By default it generates printable timestamps in an ISO format that includes fractions of seconds, e.g., "2005-01-14 18:56:54.546607". I often need to parse such times, and therein lies the rub. Python's date parsing is based on strptime(3) which can't handle fractions of seconds. I wind up worming around the problem with a little hackery, but it bothers me that given an otherwise complete solution to formatting and parsing times I can't handle this common (for me) case. I realize that other languages may not base their current time formatting and parsing on strftime(3) and strptime(3), but I suspect those two functions were at least the root of what is commonly used by most languages. In my investigation I came across a DateTime module in Perl that uses "%N" (or optionally "%nN" where n is a digit) to identify integers as nanoseconds or some other subsecond time. I belive "%3N" would cause "123" to be interpreted as 123 milliseconds, for instance. I've considered extending "%S" to accept fractional seconds or adding a new format specifier like "%F" to handle this case. I'm interested to know what solutions have been devised or considered for other languages. (Has this been addressed in some more recent version of the C or C++ standards I'm unaware of?) Rather than reinventing the wheel I'd like to adopt an existing solution if possible. At the very least I'd like to know how others have approached the problem. I think there's an opportunity to add some value that everyone can take advantage of. Thanks for your time, Skip Montanaro skip at pobox.com From eurleif at ecritters.biz Wed Jan 19 01:17:09 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 19 Jan 2005 01:17:09 -0500 Subject: Solutions for data storage? Message-ID: <356c7tF4g3f64U1@individual.net> I'm writing a relatively simple multi-user public Web application with Python. It's a rewrite of a similar application which used PHP+MySQL (not particularly clean code, either). My opinions on various Web frameworks tends to vary with the phase of the moon, but currently, I'm planning to use Quixote. Needless to say, my application will need some kind of persistent data storage. The previous PHP+MySQL application uses around 1.1GB of storage, so something like PyPerSyst where everything is kept in memory is out. I've looked at SQLObject, and it's very nice, but it doesn't provide certain features I really want, like the ability to store lists of strings or integers directly in the database (using commas in a varchar column or something). ZODB is very nice, but IndexedCatalog doesn't seem to provide any automatic mechanisms for things like ensuring attribute uniqueness (for e.g. usernames). I suppose I could implement manual checking in every class that needs it, but it really seems like very error-prone code to be implementing at the application level. My ideal solution would be an object database (or object-relational mapper, I guess) which provided total transparency in all but a few places, built-in indexing, built-in features for handling schema changes, the ability to create attributes which are required to be unique among other instances, and built-in querying with pretty syntax. Atop seems to come pretty close, but since it's meant to be used in the asynchronous Twisted environment, it doesn't provide any thread safety. So basically, I'm wondering if there are any Python data storage solutions I haven't noticed that come a bit closer to what I'm looking for. I could live without built-in schema evolution; the querying is really the most important feature I want. From andre.roberge at gmail.com Fri Jan 21 12:42:15 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Fri, 21 Jan 2005 13:42:15 -0400 Subject: Simple (newbie) regular expression question In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> Message-ID: Sorry for the simple question, but I find regular expressions rather intimidating. And I've never needed them before ... How would I go about to 'define' a regular expression that would identify strings like __alphanumerical__ as in __init__ (Just to spell things out, as I have seen underscores disappear from messages before, that's 2 underscores immediately followed by an alphanumerical string immediately followed by 2 underscore; in other words, a python 'private' method). Simple one-liner would be good. One-liner with explanation would be better. One-liner with explanation, and pointer to 'great tutorial' (for future reference) would probably be ideal. (I know, google is my friend for that last part. :-) Andre From ptmcg at austin.rr._bogus_.com Sun Jan 16 19:42:39 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 17 Jan 2005 00:42:39 GMT Subject: List problems in C code ported to Python References: Message-ID: <3SDGd.22010$Z%.6947@fe1.texas.rr.com> "Lucas Raab" wrote in message news:vrzGd.817$Rs.803 at newsread3.news.atl.earthlink.net... > I'm done porting the C code, but now when running the script I > continually run into problems with lists. I tried appending and > extending the lists, but with no avail. Any help is much appreciated > Please see both the Python and C code at > http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py > > TIA I didn't actually run your script, but you have some fundamental things to fix first. Here are some corrections that will get you closer: - Single-character strings are still strings as far as Python is concerned. Unlike C's distinction of single quotes for single characters (which allow you to do integer arithmetic) and double quotes for string literals (which don't support integer arithmetic), Python uses either quoting style for strings. So "A" == 'a' is true in Python, not true in C. To do single-char arithmetic, you'll need the ord() and asc() functions, so that instead of c-'A' you'll need ord(c)-ord('A') (and another little tip - since the ord('A') is likely to be invariant, and used *heavily* in a function such as an Enigma simulator, you're best off evaluating it once and stuffing it into a global, with an unimaginitive name like ord_A = ord('A') -Line 42: You are testing c == string.alpha_letters, when I think you *really* want to test c in string.alpha_letters. - encipher_file - the C version of this actually reads the file and calls encipher() with each character in it. Your Python version just calls encipher() with the complete file contents, which is certain to fail. (another tip - avoid variable names like 'file', 'string', 'list', 'dict', etc. as these collide with global typenames - also, your variable naming is pretty poor, using "file" to represent the filename, and "filename" to represent the file contents - err???) - usage() - print("blahblah \n") - the trailing \n is unnecessary unless you want to double-space your text Although you say you are "done porting the C code", you really have quite a bit left to do yet. You should really try to port this code a step at a time - open a file, read its contents, iterate through the contents, call a method, etc. "Big-bang" porting like this is terribly inefficient! -- Paul From peter at engcorp.com Sun Jan 30 13:05:10 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 30 Jan 2005 13:05:10 -0500 Subject: Disassembling strings and turning them into function parameters In-Reply-To: <1107107283.694377.286360@c13g2000cwb.googlegroups.com> References: <1107107283.694377.286360@c13g2000cwb.googlegroups.com> Message-ID: mercuryprey at gmail.com wrote: > Hi, > I'm pretty new to Python, to programming overall...so how would I make > something where the user inputs multiple words in a string - like > "connect 123.123.123.123 21 user password" or similar, and then I can > split this string up to pass these arguments to a function like > ftp_connect(ip, port, user, pw) etc...? I have no idea how to "break" > the string up so I can get these out of it.. The .split() method of strings should work for you. If you need more, provide more background... and maybe let us know that this isn't homework. ;-) -Peter From secun at yahoo.com Wed Jan 26 14:17:19 2005 From: secun at yahoo.com (secun at yahoo.com) Date: 26 Jan 2005 11:17:19 -0800 Subject: Web front-end for python scripts Message-ID: <1106767039.927592.49450@z14g2000cwz.googlegroups.com> I've written some python scripts to handle different tasks on my Windows network. I would like to have them accessible via a single web page (kind of like a dashboard) and have the scripts run on the server on which the web server resides (also a Windows box) This is an internal server only, but the scripts need to be secure since the server will have administrative rights on the network. Can anyone recommend a way of doing this? Security is important since this page will be accessible inside the company, but only people with the appropriate user name / password will be able to run the scripts. From firemoth at gmail.com Fri Jan 21 08:52:24 2005 From: firemoth at gmail.com (Timothy Fitz) Date: Fri, 21 Jan 2005 08:52:24 -0500 Subject: PyCon Preliminary Program Announced! In-Reply-To: <1f7befae0501201952139c57a8@mail.gmail.com> References: <20050121000607.DE1261E4010@bag.python.org> <41F061C3.3000802@gmail.com> <1f7befae0501201952139c57a8@mail.gmail.com> Message-ID: <972ec5bd0501210552512154aa@mail.gmail.com> > I don't care much for "parallel tracks" myself, because I want to hear > basically everything. But we had more proposals of higher quality > this year than ever before, so it came down to scheduling more talks > in parallel than ever before too, or rejecting perfectly good > proposals. Will there be recordings of any of these presentations? There are quite a few times when I want to be at all three tracks at the same time. From aurora00 at gmail.com Wed Jan 26 13:39:18 2005 From: aurora00 at gmail.com (aurora) Date: Wed, 26 Jan 2005 10:39:18 -0800 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> Message-ID: It is really necessary to build a VM from the ground up that includes OS ability? What about JavaScript? > On Wed, Jan 26, 2005 at 05:18:59PM +0100, Alexander Schremmer wrote: >> On Tue, 25 Jan 2005 22:08:01 +0100, I wrote: >> >> >>>> sys.safecall(func, maxcycles=1000) >> > could enter the safe mode and call the func. >> >> This might be even enhanced like this: >> >> >>> import sys >> >>> sys.safecall(func, maxcycles=1000, >> allowed_domains=['file-IO', 'net-IO', 'devices', >> 'gui'], >> allowed_modules=['_sre']) >> >> Any comments about this from someone who already hacked CPython? > > Yes, this comes up every couple months and there is only one answer: > This is the job of the OS. > Java largely succeeds at doing sandboxy things because it was written > that > way from the ground up (to behave both like a program interpreter and an > OS). > Python the language was not, and the CPython interpreter definitely was > not. > > Search groups.google.com for previous discussions of this on c.l.py > > -Jack From stephen.thorne at gmail.com Wed Jan 12 21:19:06 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 12:19:06 +1000 Subject: Refactoring; arbitrary expression in lists In-Reply-To: <41e5cb07.701137402@news.oz.net> References: <41e5cb07.701137402@news.oz.net> Message-ID: <3e8ca5c805011218193394b465@mail.gmail.com> On Thu, 13 Jan 2005 01:24:29 GMT, Bengt Richter wrote: > extensiondict = dict( > php = 'application/x-php', > cpp = 'text/x-c-src', > # etcetera > xsl = 'test/xsl' > ) > > def detectMimeType(filename): > extension = os.path.splitext(filename)[1].replace('.', '') > try: return extensiondict[extension] > except KeyError: > basename = os.path.basename(filename) > if "Makefile" in basename: return 'text/x-makefile' # XXX case sensitivity? > raise NoMimeError Why not use a regexp based approach. extensionlist = [ (re.compile(r'.*\.php') , "application/x-crap-language"), (re.compile(r'.*\.(cpp|c)') , 'text/x-c-src'), (re.compile(r'[Mm]akefile') , 'text/x-makefile'), ] for regexp, mimetype in extensionlist: if regexp.match(filename): return mimetype if you were really concerned about efficiency, you could use something like: class SimpleMatch: def __init__(self, pattern): self.pattern = pattern def match(self, subject): return subject[-len(self.pattern):] == self.pattern Regards, Stephen Thorne From mefjr75 at hotmail.com Sat Jan 1 02:47:55 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 31 Dec 2004 23:47:55 -0800 Subject: More baby squeaking - iterators in a class In-Reply-To: <1104548797.050583.19030@c13g2000cwb.googlegroups.com> References: <1104511354.639920.246830@c13g2000cwb.googlegroups.com> <1104548797.050583.19030@c13g2000cwb.googlegroups.com> Message-ID: <1104565675.172883.40190@z14g2000cwz.googlegroups.com> py> from __future__ import generators Hello again, I was thinking about the __iter__ and what you were saying about generators, so I opened up pyshell and started typing. py> class R3: ... def __init__(self, d): ... self.d=d ... self.i=len(d) ... def __iter__(self): ... d,i = self.d, self.i ... while i>0: ... i-=1 ... yield d[i] ... py> r = R3('qwerty') py> r.__class__ py> r.__iter__ > py> r.__iter__() py> a = r.__iter__() py> a.next() 'y' py> a.next() 't' py> a.next() 'r' py> a.next() 'e' py> a.next() 'w' py> a.next() 'q' py> a.next() Traceback (most recent call last): File "", line 1, in ? StopIteration >>> Doh! ok now I get it __iter__ RETURNS a generator ;) It seems so obvious now I look at it. Sometimes I am a bit slow to catch on , but I never forget, much. M.E.Farmer Deeper down the rabbit hole. M.E.Farmer wrote: > Terry , > Thank you for the explanation . That is much clearer now, I have played > a bit with generators but have never tried to create a custom iterator. > I am just now getting into the internals part of python objects... this > langauage is still amazing to me! > The reason I asked the question was because I tried that code I posted > and it worked fine in python2.2.3 ? > > >Ignoring the older iteration method based on __getitem__, which I > recommend > >you do ignore, yes, you cannot do that. > > py>class R3: > ... def __init__(self, d): > ... self.d=d > ... self.i=len(d) > ... def __iter__(self): > ... d,i = self.d, self.i > ... while i>0: > ... i-=1 > ... yield d[i] > ... > py>a = R3('qwerty') > py>dir(a) > ['__doc__', '__init__', '__iter__', '__module__', 'd', 'i'] > py>for i in a: > ... print i > ... > y > t > r > e > w > q > Ok I don't see __getitem__ anywhere in this object. > Still scratchin my head? Why does this work? > M.E.Farmer From t-meyer at ihug.co.nz Sun Jan 9 20:38:55 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 10 Jan 2005 14:38:55 +1300 Subject: Please Contribute Python Documentation! In-Reply-To: Message-ID: > It *is* in the docs now -- see the top of > http://www.python.org/doc/2.4/doc/doc.html Oops. I ought to have checked rather than going by memory (I suppose the last time I looked 2.3 would have been current). Thanks for correcting me! =Tony.Meyer From spam at nospam.org Wed Jan 26 23:56:49 2005 From: spam at nospam.org (Erik Johnson) Date: Wed, 26 Jan 2005 21:56:49 -0700 Subject: building Python: up arrow broken on SuSE Linux 8.2 References: <41f6c3f7$1@nntp.zianet.com> <41f85dd8@nntp.zianet.com> Message-ID: <41f87288@nntp.zianet.com> "Erik Johnson" wrote in message news:41f85dd8 at nntp.zianet.com... > So I downloaded & built libreadline version 5.0. I have libreadline.a > and shlib/libreadline.so.5.0 files. Having done Python & other scripting > languages for a while, I have sort of forgotten all the ugly details about C > compilation. I'm trying to figure out how to get Python2.3.4. statically > linked with the .a file and not muck with the system shared libraries and > let other applications fend for themselves. Any advice on how to statically > link in this library so the Python build is happy? What I thought might be obvious and easy does not work, BTW... In the Modules/Setup file I put this... readline readline.c -I/home/ej/readline-5.0 -L/home/ej/readline-5.0 -lreadline re-ran configure and tried the make again. No joy. :( Now I remember why I ended up using things like Perl & Python in the first place... ej at sand:~/Python-2.3.4> make gcc -pthread -c -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototyp es -I. -I./Include -DPy_BUILD_CORE -o Modules/config.o Modules/config.c gcc -pthread -c -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototyp es -I. -I./Include -DPy_BUILD_CORE -DPYTHONPATH='":plat-linux2:lib-tk"' \ -DPREFIX='"/usr/local"' \ -DEXEC_PREFIX='"/usr/local"' \ -DVERSION='"2.3"' \ -DVPATH='""' \ -o Modules/getpath.o ./Modules/getpath.c gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DPy_BUILD_CORE -I/home/ej/readline-5.0 -c ./Modules/readline.c -o Modules/readline.o Modules/readline.c:26:31: readline/readline.h: No such file or directory Modules/readline.c:27:30: readline/history.h: No such file or directory Modules/readline.c: In function `parse_and_bind': Modules/readline.c:49: warning: implicit declaration of function `rl_parse_and_bind' Modules/readline.c: In function `read_init_file': Modules/readline.c:68: warning: implicit declaration of function `rl_read_init_file' Modules/readline.c: In function `read_history_file': Modules/readline.c:89: warning: implicit declaration of function `read_history' Modules/readline.c: In function `write_history_file': Modules/readline.c:111: warning: implicit declaration of function `write_history' Modules/readline.c:113: warning: implicit declaration of function `history_truncate_file' Modules/readline.c: In function `set_completer_delims': Modules/readline.c:287: error: `rl_completer_word_break_characters' undeclared (first use in this function) Modules/readline.c:287: error: (Each undeclared identifier is reported only once Modules/readline.c:287: error: for each function it appears in.) From claird at lairds.us Thu Jan 27 11:08:06 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 27 Jan 2005 16:08:06 GMT Subject: Another scripting language implemented into Python itself? References: <0juic2-68k.ln1@lairds.us> Message-ID: In article , Arthur wrote: . . . >As long as we include the cost of treating adults as children, and >take it seriously as the kind of cost it is, I'm OK. > >I think Terry's point covers a wide range of the real world >situations. Though certainly not all. > >My "real" life is in the mid-market business world, not as a geometry >software developer. And I see a sort of hysteria descending, in this >realm on this subject. Of theY2k ilk, but with actually, it seems to >me, less substance. Family businesses out on the limb, as a business, >in a myriad of ways - because they are after all in business, focusing >on remote scenarios because they are somehow becoming convinced that >is what business people do (they don't), and demoralizing folks in the >process. Folks who know that if they wanted to hurt this business >they could have done so a hundred times in a hundred ways over the >years. But it wouldn't be by screwing with their computer system >because they wouldn't know how. So isn't it funny that is what the >boss is so concerned about - all of a sudden? > >(They always knew they were smarter then him. More proof) > >Art > > Pronouns quickly overload me. If you're saying that there's hysteria afoot, much of it about the harm that might come through use of computers left unprotected from evildoers, well, yes, I'm with you. Most people have far more important hazards in their lives and work than "security violations" as we technologists generally conceive them. From deetsNOSPAM at web.de Fri Jan 21 05:20:47 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 21 Jan 2005 11:20:47 +0100 Subject: Python and SOAP References: Message-ID: <35c39jF4im71aU1@individual.net> > I'd like to write a SOAP client and a SOAP server > in Python. > > Is SOAPy still the way to go, or are there better > methods? If you really need SOAP, Nelson did answer your question. But if you are only communicating between two python processes, I suggest pyro. -- Regards, Diez B. Roggisch From jepler at unpythonic.net Thu Jan 13 18:57:28 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 13 Jan 2005 17:57:28 -0600 Subject: directory bug on linux; workaround? In-Reply-To: References: Message-ID: <20050113235727.GB1513@unpythonic.net> Python is at the whim of the services the OS provides. Maybe you should ask in a linux-related newsgroup or mailing list, they might know more about the specifics of both detecting and working around "weird" filesystems like "fat". To find the type of a filesystem, Linux provides the statfs(2) function, but no built-in Python module includes access to that function. Writing the wrapper would be an easy first exercise in extending Python, or using Pyrex or ctypes. The filesystem "magic numbers" also aren't available in Python. A partial list can be found by "grep _SUPER_MAGIC /usr/include/linux/*" Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From peter at engcorp.com Thu Jan 13 08:41:06 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 08:41:06 -0500 Subject: why are people still using classic classes? In-Reply-To: <7x6522gegg.fsf@ruckus.brouhaha.com> References: <7x6522gegg.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Simon Wittber writes: > >>>Is there a reason NOT to use them? If a classic class works fine, what >>>incentive is there to switch to new style classes? >> >>Perhaps classic classes will eventually disappear? > > It just means that the formerly "classic" syntax will define a > new-style class. Try to write code that works either way. Unfortunately, if we should follow the recent advice about always using "super()" in the __init__ method, it's hard to do what you suggest (though it sounds like good advice) without resorting to extreme ugliness: >>> class Classic: ... def __init__(self): ... super(Classic, self).__init__() ... >>> c = Classic() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in __init__ TypeError: super() argument 1 must be type, not classobj Could classic classes ever be removed without us having manually to fix all __init__ calls to the superclass? -Peter From tim.golden at viacom-outdoor.co.uk Thu Jan 20 05:02:25 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 20 Jan 2005 10:02:25 -0000 Subject: Oddity is shutil.copyfileobj Message-ID: <9A28C052FF32734DACB0A288A35339910359D3@vogbs009.gb.vo.local> [Neil Benn] | I'm running a program which is using | shutil.copyfileobj on a Win2K Pro, python 2.3 box. Just for (possible) reassurance, I've just run the following code snippet on my Win2k Python 2.3.4 box and it seemed to work without adding any oddities to the file name. I'm copying to a "real" Windows file share, not a Samba box, so it may make a difference. import shutil f = open ("test.py", "rt") g = open (r"\\tdi_nt4a\user\goldent\temp\test.py", "wt") try: shutil.copyfileobj (f, g) finally: f.close () g.close () | The source and dest file are both opened in | textual mode as 'w' Well my first question (which may or may not be relevant) is: what do you mean by this? Are they both opened for *writing*, which is what the "w" implies? Or was that merely a typo for "t", meaning that you had explcitly selected text mode as opposed to binary mode? | The files are copied across perfectly (diffing them shows | they are identical), however I have one small problem, | the destination filename has .read appended to the end. | I've checked my code again and again and I'm definatly | not apeending this. Any chance you could *post* the code (at least the section in question)? The source for copyfileobj, which was the first place I looked is this: def copyfileobj(fsrc, fdst, length=16*1024): """copy data from file-like object fsrc to file-like object fdst""" while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf) And unless there's something *really* subtle going on, I'm not sure I could spot any filename changing there. I'm afraid that, short of some obscure bug in Samba, which should show up regardless of what you're copying across, your own code is the most likely culprit. TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From steven.bethard at gmail.com Mon Jan 31 02:06:11 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 31 Jan 2005 00:06:11 -0700 Subject: a Python bug in processing __del__ method ?? In-Reply-To: <1107154011.859866.23480@z14g2000cwz.googlegroups.com> References: <1107154011.859866.23480@z14g2000cwz.googlegroups.com> Message-ID: Baoqiu Cui wrote: > Today I was playing with a small Python program using Python 2.4 > on Cygwin (up-to-date version, on Windows XP), but ran into a > strange error on the following small program (named bug.py): > > ------------------------------- > #!/usr/bin/python > > class Person: > population = 0 > def __del__(self): > Person.population -= 1 > > peter = Person() > ------------------------------- > > The error returned is this: > > $ python bug.py > Exception exceptions.AttributeError: "'NoneType' object has no > attribute 'population'" in <__main__.Person instance at 0xa0c9fec>> ignored > > However, if I rename variable name 'peter' to something like 'peter1' > or 'david', the error is gone. Looks to me the > error only happens to variable name 'peter'. > > Does anyone know what is wrong? Is this a bug only on Cygwin? I get this error on a normal Python WinXP install too. Looks like Python deletes globals in order when exiting, so the Person class gets deleted before the Person instances: ---------- bug.py ---------- class Person(object): population = 0 def __del__(self): Person.population -= 1 = Person() print list(globals()) ---------------------------- I tried this with a few different names. Here are the results for 'apple', 'banana' and 'cranberry'. Only when the name appears after 'Person' in the globals do I get the error that you get. [D:\Steve]$ bug.py ['apple', '__builtins__', '__file__', 'Person', '__name__', '__doc__'] [D:\Steve]$ bug.py ['__builtins__', '__file__', 'banana', 'Person', '__name__', '__doc__'] [D:\Steve]$ bug.py ['__builtins__', '__file__', 'Person', 'cranberry', '__name__', '__doc__'] Exception exceptions.AttributeError: "'NoneType' object has no attribute 'population'" in > ignored I don't know whether this is a bug or a "feature". ;) Steve From rbt at athop1.ath.vt.edu Sat Jan 29 21:03:49 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Sat, 29 Jan 2005 21:03:49 -0500 Subject: Description Field in WinXP Services In-Reply-To: References: <41fc0646$1_1@127.0.0.1> Message-ID: rbt wrote: > Roger Upole wrote: > >> ChangeServiceConfig2 is the api functions that sets the description, >> but it's not in the win32service module (yet). >> >> Roger > > > OK, I can use _winreg to add the 'Description' field under the > appropriate registry key. Here's an example of it... kludgey but it works ;) from _winreg import * import time def Svc_Description(): try: key_location = r"SYSTEM\CurrentControlSet\Services\test_py_service" svc_key = OpenKey(HKEY_LOCAL_MACHINE, key_location, 0, KEY_ALL_ACCESS) SetValueEx(svc_key,'Description',0,REG_SZ,u"Brad's Test Python Service") CloseKey(svc_key) except Exception, e: print e Svc_Description() time.sleep(10) From bokr at oz.net Fri Jan 21 19:31:33 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 22 Jan 2005 00:31:33 GMT Subject: Class introspection and dynamically determining function arguments References: Message-ID: <41f18d10.1471646806@news.oz.net> On Thu, 20 Jan 2005 11:24:12 -0000, "Mark English" wrote: >I'd like to write a Tkinter app which, given a class, pops up a >window(s) with fields for each "attribute" of that class. The user could >enter values for the attributes and on closing the window would be >returned an instance of the class. The actual application I'm interested >in writing would either have simple type attributes (int, string, etc.), >or attributes using types already defined in a c-extension, although I'd >prefer not to restrict the functionality to these requirements. My first reaction is that if you can limit the problem, it could be done fairly simply. [... having read to the end by now, I see you were thinking of inspecting the __init__ method, so you are close to what I was thinking, but maybe this will be useful anyway, so since it's done, I'll post it ;-) ] E.g., if the attributes of interest are all set by simple attribute assignment in the __init__ method of the class, using __init__ arguments with default arguments, then you could inspect the __init__ function for parameter names and infer types from the default arguments. If the instance attribute name are bound in the __new__ method, you could still conceivably do something if you had a similar known signature, but the for unrestricted general case your Tkinter app would have to supply too much information than can't be inferred or be known by the user. E.g., how would a Tkinter app (or any other) know what to ask the user to supply to set the attributes of class WhatEver: def __init__(self, attr): self.attr = attr ? > >The only way I can imagine to do this is to create an instance of the >class in question, and then start poking around in its attributes >dictionary (initially just using dir). So firstly, if there is instead a >way to do this without creating an instance I'd be interested. As above. IMO you will have to restrict the problem. But perhaps that is no so bad. > >Secondly, the code won't know exactly how to initialise the class >instance used to determinte the attributes. Do I need to make it a >prerequesite that all instances can be created with no arguments ? I think that is a byproduct of the approach I suggested (i.e., all args having default values for type inference), but there's probably other ways. >Should I force/allow the user to pass an instance instead of a class ? I would say no. Especially considering possible side effects. >Should I be using inspect.getargspec on the class __init__ method and >then a loop with a try and a lot of except clauses, or is there a nicer I don't know if you need a _lot_ of except clauses, but yes, at least one, and a loop to allow retrying after typos etc. >way to do this ? Presumably the pickling code knows how do >serialise/deserialise class instances but I'm not sure how I'd use this >without already having a class instance to hand. > >Lastly, does such an app already exist ? Don't know. Wouldn't be surprised. > >Thanks for any help. This shows you are probably close to solving your own problem with inspect.getargspec: >>> class C(object): ... def __init__(self, a=1, b='bee', c=1.2): ... self.a = a ... self.b = b ... self.c = c ... >>> inspect.getargspec(C.__init__) (['self', 'a', 'b', 'c'], None, None, (1, 'bee', 1.2)) >>> print inspect.getargspec.__doc__ Get the names and default values of a function's arguments. A tuple of four things is returned: (args, varargs, varkw, defaults). 'args' is a list of the argument names (it may contain nested lists). 'varargs' and 'varkw' are the names of the * and ** arguments or None. 'defaults' is an n-tuple of the default values of the last n arguments. >>> args,_,_,defaults = inspect.getargspec(C.__init__) >>> values = [] Obviously you need an inner loop for correcting typos etc., and try/except to catch relevant errors, but I'm just typing interactively here, so her goes: >>> for name, defv in zip(args[-len(defaults):], defaults): ... vstr = raw_input('Please enter a string suitable for %s(s): '%type(defv).__name__) ... values.append(type(defv)(vstr)) ... Please enter a string suitable for int(s): 123 Please enter a string suitable for str(s): 'this is a string' Please enter a string suitable for float(s): 1.5 >>> values [123, "'this is a string'", 1.5] >>> c = C(*values) >>> c.a 123 >>> c.b "'this is a string'" >>> c.c 1.5 >>> cdef = C() >>> cdef.a, cdef.b, cdef.c (1, 'bee', 1.2) I guess the single quotes on the str(s) entry shows that all the characters get entered ;-) You might want to think about whether to process backslashes as escapes in your input. E.g., >>> raw_input('Enter some escape example: ') Enter some escape example: Not an newline: \n -- nor '\n' ;-) "Not an newline: \\n -- nor '\\n' ;-)" >>> print raw_input('Enter some escape example: ') Enter some escape example: Not an newline: \n -- nor '\n' ;-) Not an newline: \n -- nor '\n' ;-) BTW, You can avoid importing inspect and get the data of >>> inspect.getargspec(C.__init__) (['self', 'a', 'b', 'c'], None, None, (1, 'bee', 1.2)) that you want by looking at the unbound method C.__init__ (though im_func may be deprecated eventually?): >>> C.__init__.im_func.func_code.co_varnames ('self', 'a', 'b', 'c') >>> C.__init__.im_func.func_defaults (1, 'bee', 1.2) or by getting the __init__ function as such, by avoiding the attribute access that makes it and unbound or bound method >>> C.__dict__['__init__'].func_code.co_varnames ('self', 'a', 'b', 'c') >>> C.__dict__['__init__'].func_defaults (1, 'bee', 1.2) Regards, Bengt Richter From nun at example.com Mon Jan 31 17:34:36 2005 From: nun at example.com (Mitja) Date: Mon, 31 Jan 2005 23:34:36 +0100 Subject: "Mail receiver server" References: <41feaff2$0$2068$626a14ce@news.free.fr> Message-ID: On Mon, 31 Jan 2005 23:23:46 +0100, manatlan wrote: > in fact, i'd like to control "computer A" by sending smtp email from > "computer B". > > What kind of server should i write on computer "B", a smtp server ? a > pop server ? It would be easier if you used an existing mail server (which OS are you running on comp B?), then use its redirecting features to pipe the incoming mail to your python script. AFAIK most servers support that. Less hassle, though probably a wee bit more intensive for the computer. From craig at postnewspapers.com.au Fri Jan 21 17:38:03 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 22 Jan 2005 06:38:03 +0800 Subject: Tuple size and memory allocation for embedded Python In-Reply-To: References: Message-ID: <1106347083.19065.80.camel@bucket.localnet> On Fri, 2005-01-21 at 17:20 -0500, Steve Holden wrote: > Jinming Xu wrote: > > > Hi Folks, > > > > Python seems unstable, when allocating big memory. For example, the > > following C++ code creates a tuple of tuples: > > > > PyObject* arCoord = PyTuple_New(n); > > double d = 1.5; > > for(int i=0; i > { > > PyObject* coord = PyTuple_New(2); > > PyTuple_SetItem(coord,0, PyFloat_FromDouble(d));//x > > PyTuple_SetItem(coord,1, PyFloat_FromDouble(d));//y > > PyTuple_SetItem(arCoord,i, coord); > > } > > > > When the n is small, say 100, the code works fine. when n is big, say > > 10,000, Python has trouble allocating memory, saying: > > > > "Exception exceptions.IndexError: 'tuple index out of range' in 'garbage > > collection' ignored > > Fatal Python error: unexpected exception during garbage collection > > Aborted" > > > > Could anyone please give me some insight or a fix for this? > > > > Thanks in advance for your answer. > > > I'm going to guess that the problem is related to incorrect reference > counts. It's usually a safe bet, after all. Another biggie is unchecked return codes leaving the exception state set, though... that can cause _really_ _weird_ problems. ALWAYS check return values. > I don't see any IncRefs in there. In this case it looks OK. PyFloat_FromDouble() reuturns a new reference, as does PyTuple_New(), and PyTuple_SetItem() steals a reference to its PyObject* argument. Of course, there could be refcount errors outside the shown code segment, but in this case I'd say the immediate error will be because of an unhandled exception. As to why that exception is being thrown.... Also, forget my comment in my last post about not resizing - I'd failed to notice the initial creation size of the tuple (the creation of which isn't checked, but would segfault the app on failure). > Python is pretty stable, so it's usually best to suspect our own code > unless you're heavily into using the C API (which I'm not, so feel free > to ignore me). That's been my experience - stability issues in my Python/C code have almost always come down to refcounting bugs and/or failing to detect and handle or propagate an exception. -- Craig Ringer From http Fri Jan 7 16:29:29 2005 From: http (Paul Rubin) Date: 07 Jan 2005 13:29:29 -0800 Subject: DOS problem (simple fix??) References: Message-ID: <7xis690vye.fsf@ruckus.brouhaha.com> Gavin Bauer writes: > Thank you, and please make all answers simple enough to be understood > by a highschool student and his father :) . You might like to try IDLE, which is included with Python. From fredrik at pythonware.com Sun Jan 16 05:44:43 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 16 Jan 2005 11:44:43 +0100 Subject: generator expressions: performance anomaly? References: <1105854381.117059.59940@c13g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > Given a requirement to mutate the original list, this necessitates the assignment > to lst[:]. do you always pull requirements out of thin air? From fu.limin.tao at gmail.com Fri Jan 28 05:42:47 2005 From: fu.limin.tao at gmail.com (Limin Fu) Date: Fri, 28 Jan 2005 11:42:47 +0100 Subject: ANN: Tao Scripting Language 0.8.5 beta released! In-Reply-To: <20a7bea6e3332d34a1b170ffb808502f@gmail.com> References: <397cc8578b5e9adf0e31f18ffa556593@gmail.com> <20a7bea6e3332d34a1b170ffb808502f@gmail.com> Message-ID: I should admit I only read a little bit very simple introductions of Lua, so I can't answer you question exactly now. Maybe you can found the answer by yourself by spending some minutes to read the brief documentation of Tao. Depending how much time I have, probably I will make a comparison between Tao and other languages, and make it available in the website of Tao. But it will not be soon. Cheers On Thu, 27 Jan 2005 23:47:27 +0100, PA wrote: > > On Jan 27, 2005, at 23:42, Limin Fu wrote: > > > at that time I didn't heard about Lua. I knew it about > > 2 or 3 months after I began to implement Tao. > > So, compared to Lua for example, what does Tao brings to the table that > you found worthwhile? > > Cheers > > -- > PA, Onnay Equitursay > http://alt.textdrive.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Homepage for Tao Language: http://taoscript.sourceforge.net Tao Language project at sourceforge.net: http://sourceforge.net/projects/taoscript From ricardo.b at zmail.pt Thu Jan 13 21:41:38 2005 From: ricardo.b at zmail.pt (Ricardo Bugalho) Date: Fri, 14 Jan 2005 02:41:38 +0000 Subject: Unicode conversion in 'print' References: <1105655600.059496.70350@z14g2000cwz.googlegroups.com> Message-ID: Hi, thanks for the information. But what I was really looking for was informaion on when and why Python started doing it (previously, it always used sys.getdefaultencoding())) and why it was done only for 'print' when stdout is a terminal instead of always. On Thu, 13 Jan 2005 14:33:20 -0800, Serge Orlov wrote: > Sure. It uses the encoding of you console. Here is explanation why it uses > locale to get the encoding of console: > http://www.python.org/moin/PrintFails > -- Ricardo From FBatista at uniFON.com.ar Tue Jan 25 16:12:22 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 25 Jan 2005 18:12:22 -0300 Subject: MySQLdb Message-ID: [Daniel Bowett] #- The problem I have is that it takes just over two minuted to #- execute the #- 3000 insert statements which seems really slow! I am running it on a #- machine with a 1.5 Ghz Pentium M Processor and Gig Of Ram. I #- dont think #- the machine is to blame for the speed because during execution the #- processor sits at about 10% and there is loads of free RAM. #- #- Does anyone know if this sort of speed sounds right? Well, I made the following code. mod_mysql is mine, but is just a wrapper around the standard module. Here I only use the .accion() method of the Consulta object, that let me send an action (query, insert, etc) to the database. So I generate a temporary table of four fields, and prepared a list of 3000 entries, each one is a tuple of four elements: ten characters choosed randomly. --- import random, string, time import mod_mysql bdd = mod_mysql.Consulta("pytonisa", "fbatista", "password", "otainfo") bdd.accion("create temporary table tmp.prueba (c1 char(10), c2 char(10), c3 char(10), c4 char(10));") r = random.Random() let = string.letters + string.digits fuente = [tuple([''.join(r.sample(let, 10)) for j in range(4)]) for x in range(3000)] t = time.time() for reg in fuente: bdd.accion('insert into tmp.prueba values ("%s", "%s", "%s", "%s");' % tuple(reg)) print time.time() - t --- I only measure the time of the inserts. It took 0.269818067551 seconds. I'm using a Pentium 4 2.8 GHz, 256 MB of RAM, with Fedora Core 2, kernel 2.4.22, python 2.3.3 (GCC 3.3.2), and MySQL 4.0.18. Regards, . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From craig at postnewspapers.com.au Fri Jan 7 11:11:34 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 08 Jan 2005 00:11:34 +0800 Subject: missing sys.setappdefaultencoding In-Reply-To: <1gq0pd4.id8j3sexmiexN%aleaxit@yahoo.com> References: <1gq0pd4.id8j3sexmiexN%aleaxit@yahoo.com> Message-ID: <1105114293.30384.6.camel@rasputin.localnet> On Fri, 2005-01-07 at 19:06, Alex Martelli wrote: > Uwe Mayer wrote: > > well, I wrote a nice python program which won't work if the default encoding > > has not been set from ascii to latin-1 or latin-15. > > Then your program is not very nice...;-) Agreed. I prefer to use explicit str.encode(), str.decode() and unicode() calls where appropriate. On a side note, PEP 263 handles the text encoding interpretation of Python program source, and is well worth reading and following. http://python.org/peps/pep-0263.html -- Craig Ringer From bokr at oz.net Thu Jan 13 03:13:14 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 08:13:14 GMT Subject: finding/replacing a long binary pattern in a .bin file References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> Message-ID: <41e6293f.725257715@news.oz.net> On Thu, 13 Jan 2005 16:51:46 +1000, Stephen Thorne wrote: >On 12 Jan 2005 22:36:54 -0800, yaipa wrote: >> What would be the common sense way of finding a binary pattern in a >> .bin file, say some 200 bytes, and replacing it with an updated pattern >> of the same length at the same offset? >> >> Also, the pattern can occur on any byte boundary in the file, so >> chunking through the code at 16 bytes a frame maybe a problem. The >> file itself isn't so large, maybe 32 kbytes is all and the need for >> speed is not so great, but the need for accuracy in the >> search/replacement is very important. > >Okay, given the requirements. > >f = file('mybinfile') >contents = f.read().replace(oldbinstring, newbinstring) >f.close() >f = file('mybinfile','w') >f.write(contents) >f.close() > >Will do it, and do it accurately. But it will also read the entire >file into memory. > You must be on linux or such, otherwise you would have shown opening the _binary_ files (I assume that's what a .bin file is) with 'rb' and 'wb', IWT. Not sure what system the OP was/is on. BTW, I'm sure you could write a generator that would take a file name and oldbinstring and newbinstring as arguments, and read and yield nice os-file-system-friendly disk-sector-multiple chunks, so you could write fout = open('mynewbinfile', 'wb') for buf in updated_file_stream('myoldbinfile','rb', oldbinstring, newbinstring): fout.write(buf) fout.close() (left as an exercise ;-) (modifying a file "in place" is another exercise) (doing the latter with defined maximum memory buffer usage even when mods increase the length of the file is another ;-) Regards, Bengt Richter From premshree.pillai at gmail.com Wed Jan 5 08:21:22 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Wed, 5 Jan 2005 18:51:22 +0530 Subject: is python more popular than coldfusion? In-Reply-To: <41dbe722$0$23057$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dbe722$0$23057$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: On Wed, 5 Jan 2005 21:09:54 +0800, worzel wrote: > How seriuosly do folk take the TIOBE index? Is it a good way to ague what > you should be keeping up to speed with or just a 'vague' guide? I use the TIOBE index -- sometimes -- when I give presentations on Python (and Ruby) to people who haven't heard of the languages. The index is not something to be relied upon (take a look at the calculation mechanism). However, more often than not, the indices seems to reflect what *I* perceive the indices are in reality. So I kinda use them. The thing about introducing a "new" language to a bunch of folks used to their "favorite" language is that they wouldn't care much for a language it isn't popular, or if it isn't "growing in popularity". Beyond these things, I don't think anybody uses the index. I mean I wouldn't tell people to learn languages that hold the top position on TIOBE ;). > > "Premshree Pillai" wrote in message > news:mailman.189.1104927428.22381.python-list at python.org... > > On Wed, 5 Jan 2005 19:59:21 +0800, worzel wrote: > >> > >> > >> > >> is python more popular than coldfusion? > > > > I don't know if Coldfusion _was_ ever more "popular" than Python, but > > Python is definitely more "popular" _now_. > > > > This might be of some help: http://www.tiobe.com/tpci.htm > > > >> > >> I realsie that is a very general question as one thing does not directly > >> relate to the other. My issue is that I am ditching coldfusion due to > >> there > >> being next to no work for it, and I am thinking of taking on python as a > >> second language to java in the hope of improving my resume. > >> -- > >> http://mail.python.org/mailman/listinfo/python-list > >> > >> > > > > > > -- > > Premshree Pillai > > http://www.livejournal.com/~premshree > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From jerf at jerf.org Sun Jan 9 19:01:55 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 09 Jan 2005 19:01:55 -0500 Subject: Getting rid of "self." References: <1gq4ery.1v79c2t9lsfinN%aleaxit@yahoo.com> <10u2dlj4p45psf0@news.supernews.com> Message-ID: On Mon, 10 Jan 2005 01:51:07 +0100, BJ?rn Lindqvist wrote: > This is promising, I'm content with whatever slowdowns necessary as long > as I can prove those who say "you can't do it" wrong. :) Since I think I'm the only person in this discussion that said anything about what you can't do, be clear on what I said. You can't have both of undeclared attributes on self and no use of "self", in particular to add new attributes. This is, if you take the time to understand what I mean, trivially true; *somewhere* you need to declare whether a var is local to the function or an instance member. For me, I prefer the explicit "self" and getting rid of "self" now leaves you with the need to declare member variables *somehow*, which I don't consider progress. But no matter what other magic Alex works, you're only going to get one or the other; it's impossible for the compiler to divine what you mean otherwise. My point here isn't that you "can't" hack together code to do something like what you want, and it is certainly a valid exercise in plumbing the depths of Python and learning. My point is that you'll have to pay a price in other ways. You can't make self go away "for free". And that "can't" I do mean. (You weren't necessarily claiming you could. But I thought it still worth saying; even if you weren't trying to remove "self" "for free", others certainly would mean it.) From stian at soiland.no Sun Jan 16 16:42:17 2005 From: stian at soiland.no (Stian Soiland) Date: Sun, 16 Jan 2005 22:42:17 +0100 Subject: Why would I get a TypeEror? In-Reply-To: References: <34ql1vF4dqd9pU1@individual.net> Message-ID: <7E2FF4BA-6807-11D9-90E4-000D934525B6@soiland.no> P? 14. jan 2005 kl. 22:58 skrev Steven Bethard: (Any mac users? How do I fix this to appear in Norwegian? =) > Note that if you're not comfortable with short-circuiting behavior, > you can also code this using lazy evaluation: > > (lambda: 1/x, lambda: 1.0e99)[x==0]() .. and people wonder why so many Python people want to get rid of Lambda =) -- Stian S?iland You can't say civilization don't Trondheim, Norway advance, however, for in every war http://www.soiland.no/ they kill you in a new way. [Rogers] =/\= From pdemb at illx.org Thu Jan 6 16:42:01 2005 From: pdemb at illx.org (Peter Dembinski) Date: Thu, 06 Jan 2005 22:42:01 +0100 Subject: [OT] Re: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <86ekh3qv1o.fsf@guru.mired.org> <03mlt0di3rcntvu7rlrk9k2m9bq8435bs5@4ax.com> Message-ID: <87r7kyck0m.fsf_-_@hector.domek> Bulba! writes: [...] > That's remarkable, first time I see smth like this - > out of curiosity, could you say a word where was that? Are you the same Bulba I know from alt.pl.comp.os.hacking? From dave.benjamin at gmail.com Wed Jan 19 10:50:33 2005 From: dave.benjamin at gmail.com (Dave Benjamin) Date: Wed, 19 Jan 2005 08:50:33 -0700 Subject: delay and force in Python In-Reply-To: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> Message-ID: Will Stuyvesant wrote: > . def delay(exp): return lambda: exp If you look at the definition of "delay" in SICP, you'll notice that it's defined as "syntax sugar", in other words, a macro. Since Python does not have macros, you'll have to just use "lambda", because by defining "delay" as a function, you're forcing the expression "exp" to evaluate immediately. In other words, theres a crucial difference between:: delay(sys.stdout.write('evaluated\n')) and:: lambda: sys.stdout.write('evaluated\n') If you type in those two snippets, you'll see what I mean. Coincidentally, I attempted a similar experiment just a couple of days ago, and here's what I came up with:: # Stream.py - Stream class inspired by SICP class Stream(object): pass class EndOfStream(Exception): pass class Item(Stream): def __init__(self, current, nextf): self.current = current self.nextf = nextf next = property(lambda self: self.nextf()) def fold(self, f, init): return f(self.current, self.next.fold(f, init)) def __getitem__(self, n): if n == 0: return self.current else: return self.next[n - 1] def __str__(self): return '' % self.current __repr__ = __str__ class End(Stream): def fold(self, f, init): return init def __getitem__(self, n): raise EndOfStream() def _fail(self): raise EndOfStream() current = property(_fail) next = property(_fail) def __str__(self): return '' __repr__ = __str__ Here's how it works:: Python 2.4 (#1, Dec 4 2004, 20:10:33) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import Stream >>> s = Stream.Item(1, lambda: Stream.Item(2, lambda: Stream.End())) >>> s >>> s.current 1 >>> s.next >>> s.next.current 2 >>> s.next.next >>> s.next.next.next Traceback (most recent call last): File "", line 1, in ? File "Stream.py", line 37, in _fail raise EndOfStream() Stream.EndOfStream >>> def evens(n=0): ... return Stream.Item(n, lambda: evens(n + 2)) ... >>> s = evens() >>> s.current 0 >>> s.next.current 2 >>> s.next.next.current 4 I don't know if this is useful or not, but it was an interesting exercise nonetheless. Dave From nbbalane at gmail.com Wed Jan 26 02:57:17 2005 From: nbbalane at gmail.com (jrlen balane) Date: Wed, 26 Jan 2005 15:57:17 +0800 Subject: Graph, how to? Message-ID: <2cad20900501252357531a1eb0@mail.gmail.com> i'm going to use now the matplotlib in plotting a graph. i'm currently using python 2.3(enthought edition) on win 2000/xp. i'm using boa constructor on the GUI part. i am using an MDIParentFrame. one of the child frame will be used for the table part. then another child frame will be used to show the graph, how am i going to do this? will i just import the child frame containing the tables and then i'll be able to just get the data from the table and use it to plot a graph? how am i going to assign to a variable each input to the table? can you please show me a sample code to do this? i'm a little lost since i'm a bit new to python. also, how am i going to assign to a variable anything that a user inputs to a wxTxtCtrl? any help would greatly be appreciated. thanks and more power From cr999 at ir.hit.edu.cn Tue Jan 11 05:54:44 2005 From: cr999 at ir.hit.edu.cn (cr999) Date: Tue, 11 Jan 2005 18:54:44 +0800 Subject: "Architecture of Python" was removed ? Message-ID: <004801c4f7cb$f62d1d30$1d02a8c0@cr> I found the "Architecture of Python" ( http://wiki.cs.uiuc.edu/cs427/PYTHON By Jim Jackson, Kar-Han Tan )is very useful for my understanding of the Python's architecture. But I found the link is not link to that document today. It seems that the document was removed. Who knows what happened? Does anyone here have a copy of that document? Or who can tell me what is the email address of Jim Jackson or Kar-Han Tan. Thanks a lot. Best Regards. :) Robert. From smartinham at hotmail.com Thu Jan 27 09:37:36 2005 From: smartinham at hotmail.com (smartin) Date: 27 Jan 2005 06:37:36 -0800 Subject: python IIS cgi working but loading extremely slow Message-ID: <1106836656.699887.286600@c13g2000cwb.googlegroups.com> python IIS cgi loading extremely slow I recently uninstalled python 1.5.2 and installed python 2.3 on a Windows 2000 server running IIS 5.0. The issue is that when submitting a cgi request to a python script, it takes about 1 minute to process the python (2.3 code) and load the page on this particular server. Running a simple "print hi" script takes at least a minute. I have tested the uninstall and reinstall on a test Windows 2000 server and did not have any performance issues. I have tried the uninstall and reinstall twice, including removing all registry entries of the previous 1.5.2 python install. I have reverted back to python 1.52 and my 1.5.2 code and it runs slower than it did before the uninstall but not as slow as the 2.3.4 code. Has anyone every experienced this issue with speed? From bulba at bulba.com Wed Jan 5 21:28:20 2005 From: bulba at bulba.com (Bulba!) Date: Thu, 06 Jan 2005 03:28:20 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: On 04 Jan 2005 19:25:12 -0800, Paul Rubin wrote: >"Rob Emmons" writes: >> Me personally, I believe in free software, but always talk about open >> source. My answer regarding forcing people to share -- I like the GPL >> -- and I am perfectly happy to have anyone who does not like the GPL >> not to use any GPLed software. I don't feel compelled to share. >I'd go further. It's not possible to force anyone to share, but the >GPL aims to remove software from a system that instead aims to force >people NOT to share. Nope. IMHO, GPL attempts to achieve the vendor lock-in. For different purposes than another well-known vendor, but it still does. It's actually even worse: the only thing you can't share on a well-known vendor's platform is the software written by that well-known vendor -- you can choose to share or choose not to share whatever you or other people write on this platform. If GPL folks had their way, it would not be possible not to "share" _anything_ you create. It is widely acknowledged that GPL license has the "viral" aspect of extending itself on your software - can you point to closed-source licenses that would have this aspect? None of the licenses I've read except GPL has this aspect. LGPL is still a different story, though. > As the MPAA knows, people do want to share, and >forcing them not to do so is impossible without turning the world into >a police state. What's the cost of copying music files vs cost of combining some programs together, even in the form of e.g. using an external library? >Maybe if Python were GPL, then Bulba wouldn't use it, >but since it's not GPL, some people find themselves much less willing >to contribute to it than if it were GPL. Personally, I have precisely opposite impression: the OSS licensed with BSD/MIT/Artistic/Python-like license gets contributed to a lot simply because people like to use it and they are not afraid of licensing issues. When people share: _it is not because this or that license of software used by them says so, but because they want to for reasons orthogonal to licensing issues_. >(I myself contribute bug >reports and maybe small patches, but resist larger projects since >there are GPL'd things that I can do instead). So catering to the >wishes of Bulba and Microsoft may actually be impeding Python >development. Yes, there are some people selfless enough to do long >and difficult unpaid software tasks so that Bulba and Bill G can get >richer by stopping people from sharing it, but others of us only want >to do unpaid programming if we can make sure that the results stay >available for sharing. Actually, I get the impression that GPL-ed software is written by programmers for programmers, not really for end users. GPL folks just insulate themselves in their ghetto from the rest of the world. More and more of the successful OSS projects have non-GPLed licenses: Apache, Postgres, Perl, Mozilla, Python. Do you _really_ see few contributions made to those? -- It's a man's life in a Python Programming Association. From news+0409 at henrikholm.com Wed Jan 12 13:17:36 2005 From: news+0409 at henrikholm.com (Henrik Holm) Date: Wed, 12 Jan 2005 12:17:36 -0600 Subject: Iteration over two sequences References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> <1105549514.563799.307030@z14g2000cwz.googlegroups.com> Message-ID: <1gq9z5q.1x7si1us4kgmcN%news+0409@henrikholm.com> John Lenton wrote: > > def dotproduct(a, b): > > psum = 0 > > for i in range(len(a)): > > psum += a[i]*b[i] > > return psum > > for this particular example, the most pythonic way is to do nothing at > all, or, if you must call it dotproduct, > >>> from Numeric import dot as dotproduct Downloading, installing, and getting to know numerical modules for Python is mext on my list :). However, I was under the impression that Numarray is preferred to Numeric -- is that correct? Are these two competing packages? (Hopefully this is not flame war bait...) -- "On some great and glorious day the plain folks of the land will reach in their heart's desire at last and the White House will be adorned by a downright moron." -H.L. Mencken (1880-1956) American Writer From cdavisNOSP at NOSPstaffmail.ed.ac.uk Wed Jan 12 08:30:59 2005 From: cdavisNOSP at NOSPstaffmail.ed.ac.uk (Cory Davis) Date: Wed, 12 Jan 2005 13:30:59 +0000 Subject: distutils linux script installation broken? In-Reply-To: <1105535625.443343.326560@z14g2000cwz.googlegroups.com> References: <1105535625.443343.326560@z14g2000cwz.googlegroups.com> Message-ID: Hi Christopher > distutils should replace that first line with the location of the > binary used to run setup.py. Are you running setup with the following > command line? > > python setup.py install > Yes. A possible complication is that I also have python 2.3.? on that machine, which I am reluctant to remove incase it disturbs my linux distribution (Fedora Core 2). Its also possible that I have done something silly to an environment variable. To check this I will try installing my package either as root or another user. Cheers, Cory. From rkern at ucsd.edu Fri Jan 7 04:43:33 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 07 Jan 2005 01:43:33 -0800 Subject: Excluded and other middles in licensing In-Reply-To: <1gq0jpn.1es49j7jrk3k5N%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> <75r0b2-ohg.ln1@lairds.us> <1gq0jpn.1es49j7jrk3k5N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Robert Kern wrote: > ... > >>>>While most people may not think of such programs as "closed source", >>>>they most definitely ARE: the definition of open source is very strict >>>>about this aspect. > > ... > >>>With my mathematical background, I'm consistent about calling >>>these "non-open" rather than "closed". I don't insist others >>>adopt my nomenclature ... >> >>I'm with Cameron on this one. > > > There is no "official" definition of closed-source as there is of > open-source, but I'm with the Wikipedia: > > http://en.wikipedia.org/wiki/Closed_source > > "any program whose licensing terms do not qualify as open source". A definition with a nice big "This article may need to be reworded to conform to a neutral point of view" warning at the top. ;-) > I'm not disputing it would be useful to draw many distinctions within > the universe of programs with non-opensource licenses, just pointing out > that such distinctions are not currently reflected in a popular > definition. Since it's a wiki, it may be worthwhile editing it to add > some materials to start influencing popular usage and perception, maybe. There seems to be such an edit on the way: http://en.wikipedia.org/wiki/Talk:Closed_source -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From marklists at mceahern.com Wed Jan 5 17:42:42 2005 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 05 Jan 2005 16:42:42 -0600 Subject: Building unique comma-delimited list? In-Reply-To: References: Message-ID: <41DC6D62.5010801@mceahern.com> Roy Smith wrote: >You've got a list of words (actually, they're found by searching a >data structure on the fly, but for now let's assume you've got them as >a list). You need to create a comma-delimited list of these words. >There might be duplicates in the original list, which you want to >eliminate in the final list. You don't care what order they're in, >except that there is a distinguised word which must come first if it >appears at all. > >Some examples ("foo" is the distinguised word): > >["foo"] => "foo" >["foo", "bar"] => "foo, bar" >["bar", "foo"] => "foo, bar" >["bar", "foo", "foo", "baz", "bar"] => "foo, bar, baz" or "foo, baz, bar" > >The best I've come up with is the following. Can anybody think of a >simplier way? > > Who knows whether this is "simpler", but it does demonstrate that you can customize the sort of a list: #!/usr/bin/env python def makesorter(first): """Return a sort function that sorts first to the top.""" def sorter(x, y): if x == first: return -1 elif y == first: return 1 else: return 0 return sorter words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"] first = 'foo' sorter = makesorter(first) unique = {} for word in words: unique[word] = word keys = unique.keys() keys.sort(sorter) print ', '.join(keys) From hanzspam at yahoo.com.au Thu Jan 13 12:04:35 2005 From: hanzspam at yahoo.com.au (hanz) Date: 13 Jan 2005 09:04:35 -0800 Subject: dynamically inserting function into an object References: Message-ID: <1105634097.319563.156260@c13g2000cwb.googlegroups.com> # class Cell(object): # def __init__(self, initialvalue = 0): # self._func = lambda x: x # self.__value = initialvalue # # def setvalue (self, newvalue): # self.__value = self._func(newvalue) # # def getvalue (self): # return self.__value # # def delvalue (self): # del self.__value # # value = property(getvalue, setvalue, delvalue, "I'm the 'value' property.") # # def curry(self, func, *args): # self._func = lambda x: func(x, *args) From tim.peters at gmail.com Wed Jan 5 14:53:22 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 5 Jan 2005 14:53:22 -0500 Subject: Restore a unified diff In-Reply-To: <86hdlvptpx.fsf@guru.mired.org> References: <86hdlvptpx.fsf@guru.mired.org> Message-ID: <1f7befae05010511536d7d3a7f@mail.gmail.com> [Nick Allen] >>> Unfortunately, restore does not do the same for unified_diff. I do >>> not see any similar function that is intended for unified_diff. >>> Does anyone know how to "restore" from a unified diff generated >>> delta? [Tim Peters] >> That's in general impossible, since unified diffs generally omit >> most lines that compared equal to begin with. Unified and >> context diffs are, in part, compression gimmicks, showing only >> what changed plus a bit of context. ndiff shows everything, so >> can restore everything too. [Mike Meyer] > The unix patch utility seems to do a fine job of handling the unix > unified and context diffs. Of course it does, but "the diff" isn't the only input to `patch`, you also need to give `patch` the original source file (or one closely related to it). `patch` would be deep magic indeed if it could deduce either the "before" or "after" file from a context or unified diff *alone*. But both the "before" and "after" files *can* be deduced from an ndiff diff alone. This remains a truly trivial observation: ndiff can do this because the full text of both input files is part of the output it produces. unified/context diffs cannot generally do this because they don't generally contain the full text of either input file. From michele.simionato at gmail.com Mon Jan 3 09:51:21 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 3 Jan 2005 06:51:21 -0800 Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) In-Reply-To: <1104763204.261322.59520@c13g2000cwb.googlegroups.com> References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <87u0py6elt.fsf@sme.intra.citec.fi> <1104763204.261322.59520@c13g2000cwb.googlegroups.com> Message-ID: <1104763881.161544.302910@z14g2000cwz.googlegroups.com> (Not sure if my other message arrived) I am guilty of using this idiom, too. The standard library http://www.python.org/dev/doc/devel/lib/module-sys.html#l2h-396 says: """ __stdin__ __stdout__ __stderr__ These objects contain the original values of stdin, stderr and stdout at the start of the program. They are used during finalization, and could be useful to restore the actual files to known working file objects in case they have been overwritten with a broken object. """ Notice the "during finalization" sentence. Maybe you should change the doc and explain what __stdout__ is intended for? Michele Simionato From skip at pobox.com Thu Jan 27 07:44:56 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 27 Jan 2005 06:44:56 -0600 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: <16888.57928.771177.303998@montanaro.dyndns.org> >> Finally, what if, saints be preserved, your whizbang new module is phr> It is not a whizbang module. It is a stripped-down, basic phr> implementation of a well-accepted set of standards that are being phr> used in thousands of other applications in other languages. Then there should be a library already out there already. All you should need to do is wrap it (manually, with SWIG, whatever). >> included in the core distribution and it's just not as popular as was >> first thought? phr> There is demand for it. Look at how this thread started: some phr> crypto user noticed that rotor was gone and wanted to know what to phr> do instead. Yes, and putting rotor back would be the wrong thing to do. phr> The issue of whether there's enough desire for a crypto module to phr> warrant including one in the stdlib was decided a long time ago. phr> The proof of that somebody decided to accept the rotor module into phr> the distro. No, rotor was added in Python's early days (July 1992). Times have changed. As long as we are discussing cryptography, what's wrong with m2crypto? http://sandbox.rulemaker.net/ngps/m2/ Why not incorporate it into the standard distribution? Or, what about Andrew Kuchling's crypto toolkit? http://www.amk.ca/python/code/crypto.html I believe both have been around awhile. If crypto-in-the-core is really what's needed why not see if one of them is ready to go? phr> The rotor module is gone (and good riddance). That's how this phr> thread started, remember? It shows that bogus modules can be phr> removed. Yeah, but it was there for over 10 years. phr> Have you ever used a crypto library in a serious way? Nope, never directly. Don't make this about me. I'm interested in the Python development process and how you'd like to turn it on its head. >> When it's the category king and there is substantial community >> support for inclusion, phr> It's already the category king, because there are precisely zero phr> other entrants in the category. See my above references. Note, I don't use crypto at all, yet I was aware of both of these (no Googling required). My guess would be they are substantially more mature than your proposed module. phr> I read those as saying that no crypto module will be considered for phr> inclusion whether or not it's the category king, because any such phr> module might conflict with crypto regulations in some countries. That may be a problem, sure. I'm not sure how the discussion here changes that. That's just life as we know it. phr> So tell me again what to do after writing and releasing a C module. phr> There's just no reason to write one, if the module can't go into phr> the stdlib. Why in the heck is inclusion in the standard library a requirement for you to write this thing? If it's useful to you, write it and get on with your life. >> Python is popular in part because of its fairly conservative >> development strategy. That goes for the libraries as well as the >> language itself. phr> Tell me again how rotor got into the distribution. Okay. It was 1992. Bill Clinton had recently been elected president. It was pretty much pre-WWW as we know it. Definitely pre-comp.lang.python and pre-Google (heck, pre-Yahoo, pre-Win98 and pre-Mac OSX as well). Pre-string methods. Pre-triple-quoted strings. Pre-spammers. Pre-DSL. Pre-lots of stuff. There was an Emacs python-mode and s, both thanks to Tim. People opined about Python's performance, just as they do today. Python's version number was around 0.9.4, definitel < 1.0. Guido was the only person with direct repository access. Including something in the distribution was probably the only convenient way to make new modules available. If nothing else, the rotor module (along with anything else included in the distribution back then) may have been a good exercise in and demonstration of writing extension modules, so it probably served a useful non-crypto purpose. Python's user community was probably a few hundred people. Guido likely had no thoughts of world domination with the little language that could. Times have changed. You seem think there was a PEP process and distutils and Wikis. I suspect some of the algorithms one might include in a robust crypto toolkit today weren't even invented in 1992. So throw away the rotor crutch and put your money where your mouth is. Skip From richie at entrian.com Mon Jan 24 07:59:57 2005 From: richie at entrian.com (Richie Hindle) Date: Mon, 24 Jan 2005 12:59:57 +0000 Subject: Weakref.ref callbacks and eliminating __del__ methods In-Reply-To: <1f7befae0501231720428ca3c@mail.gmail.com> References: <41F427EB.3000200@rogers.com> <1f7befae0501231720428ca3c@mail.gmail.com> Message-ID: <5lr9v0tg2i16irskb798f7rcti955j0c64@4ax.com> [Tim] > I'll note that one fairly obvious pattern works very well for weakrefs > and __del__ methods (mutatis mutandis): don't put the __del__ method > in self, put it in a dead-simple object hanging *off* of self. Like > the simple: > > class BTreeCloser: > def __init__(self, btree): > self.btree = btree > > def __del__(self): > if self.btree: > self.btree.close() > self.btree = None > > Then give self an attribute refererring to a BTreeCloser instance, and > keep self's class free of a __del__ method. The operational > definition of "dead simple" is "may or may not be reachable only from > cycles, but is never itself part of a cycle". This is very nice - I've been wondering about just this problem recently, and this will be very useful. Many thanks! One question: why the `self.btree = None` in the last line? Isn't `self.btree` guaranteed to go away at this point anyway? (If the answer is "it's necessary for weird cases that would take an hour to explain" then I'll be more than happy to simply use it. 8-) -- Richie Hindle richie at entrian.com From roy at panix.com Fri Jan 14 18:33:24 2005 From: roy at panix.com (Roy Smith) Date: Fri, 14 Jan 2005 18:33:24 -0500 Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: In article <1105569967.129284.85470 at c13g2000cwb.googlegroups.com>, "Chris Lasher" wrote: > Hello, > I have a rather large (100+ MB) FASTA file from which I need to > access records in a random order. The FASTA format is a standard format > for storing molecular biological sequences. Each record contains a > header line for describing the sequence that begins with a '>' > (right-angle bracket) followed by lines that contain the actual > sequence data. Three example FASTA records are below: > > >CW127_A01 > TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG > TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA > GCATTAAACAT > >CW127_A02 > TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG > TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA > GCATTAAACATTCCGCCTGGGGAGTACGGTCGCAAGATTAAAACTCAAAGGAATAGACGG > >CW127_A03 > TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG > TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA > GCATTAAACATTCCGCCTGGG > ... > > Since the file I'm working with contains tens of thousands of these > records, I believe I need to find a way to hash this file such that I > can retrieve the respective sequence more quickly than I could by > parsing through the file request-by-request. First, before embarking on any major project, take a look at http://www.biopython.org/ to at least familiarize yourself with what other people have done in the field. The easiest thing I think would be to use the gdbm module. You can write a simple parser to parse the FASTA file (or, I would imagine, find one already written on biopython), and then store the data in a gdbm map, using the tag lines as the keys and the sequences as the values. Even for a Python neophyte, this should be a pretty simple project. The most complex part might getting the gdbm module built if your copy of Python doesn't already have it, but gdbm is so convenient, it's worth the effort. From tim.peters at gmail.com Fri Jan 14 15:56:40 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 14 Jan 2005 15:56:40 -0500 Subject: Pickled text file causing ValueError (dos/unix issue) In-Reply-To: References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> Message-ID: <1f7befae0501141256755a8b1b@mail.gmail.com> [Tim Peters] >>Yes: regardless of platform, always open files used for pickles >> in binary mode. ... [John Machin] > Tim, the manual as of version 2.4 does _not_ mention the need > to use 'b' on OSes where it makes a difference, not even in the > examples at the end of the chapter. Further, it still refers to > protocol 0 as 'text' in several places. There is also a reference to > protocol 0 files being viewable in a text editor. > > In other words, enough to lead even the most careful Reader of > TFM up the garden path :-) Take the next step: submit a patch with corrected text. I'm not paid to work on the Python docs either <0.5 wink>. (BTW, protocol 0 files are viewable in a text editor regardless, although the line ends may "look funny") From mike at maibaum.org Fri Jan 14 05:02:11 2005 From: mike at maibaum.org (Michael Maibaum) Date: Fri, 14 Jan 2005 02:02:11 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <41e5ebee.709560864@news.oz.net> <1105632841.461042.68310@c13g2000cwb.googlegroups.com> <10udfj4c4rgkvcc@corp.supernews.com> <1105651353.769879.229690@f14g2000cwb.googlegroups.com> <10ue4s49jl8s6d7@corp.supernews.com> Message-ID: <20050114100211.GC75688@remote.gene-hacker.net> On Thu, Jan 13, 2005 at 04:41:45PM -0800, Robert Kern wrote: >Jeff Shannon wrote: > >>(Plus, if this format might be used for RNA sequences as well as DNA >>sequences, you've got at least a fifth base to represent, which means >>you need at least three bits per base, which means only two bases per >>byte (or else base-encodings split across byte-boundaries).... That gets >>ugly real fast.) > >Not to mention all the IUPAC symbols for incompletely specified bases >(e.g. R = A or G). > >http://www.chem.qmul.ac.uk/iubmb/misc/naseq.html Or, for those of us working with proteins as well, all the single letter codes for proteins: http://www.chem.qmul.ac.uk/iupac/AminoAcid/A2021.html lots more bits. I have a db with approx 3 million proteins in it and would not want to be using a pure python approach :) Michael From fuzzyman at gmail.com Wed Jan 5 08:44:03 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jan 2005 05:44:03 -0800 Subject: Reaching the real world In-Reply-To: References: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> Message-ID: <1104932643.699168.75640@c13g2000cwb.googlegroups.com> Thank you very much (to all who replied). There;'s more than enough here to make very good further enquiries. Much appreciated. Fuzzyman http://www.voidspace.org.uk/python/index.shtml From udias at ixi.com Sun Jan 16 11:36:33 2005 From: udias at ixi.com (nell) Date: 16 Jan 2005 08:36:33 -0800 Subject: protecting the python code. In-Reply-To: <41EA92A7.3080706@holdenweb.com> References: <1105884196.461107.28120@z14g2000cwz.googlegroups.com> <41EA92A7.3080706@holdenweb.com> Message-ID: <1105893393.214111.227550@f14g2000cwb.googlegroups.com> Hi Steve, First the "10x in advance" means thanks in advance. The main importance of protecting my code is to save headache of customers that want to be smart and change it and then complain on bugs and problems. 10x From steven.bethard at gmail.com Tue Jan 4 09:22:25 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 04 Jan 2005 14:22:25 GMT Subject: why does UserDict.DictMixin use keys instead of __iter__? In-Reply-To: References: Message-ID: Nick Coghlan wrote: > Steven Bethard wrote: > >> Sorry if this is a repost -- it didn't appear for me the first time. >> >> >> So I was looking at the Language Reference's discussion about emulating >> container types[1], and nowhere in it does it mention that .keys() is >> part of the container protocol. Because of this, I would assume that to >> use UserDict.DictMixin correctly, a class would only need to define >> __getitem__, __setitem__, __delitem__ and __iter__. So why does >> UserDict.DictMixin require keys() to be defined? > > > Because it's a DictMixin, not a ContainerMixin? "Containers usually are sequences (such as lists or tuples) or mappings (like dictionaries)". > .keys() is definitely part of the standard dictionary interface, and not > something the mixin can derive from the generic container methods. Why is that? Isn't keys derivable as: def keys(self): return list(self) if __iter__ is defined? Steve From andy at wild-flower.co.uk Thu Jan 20 13:47:53 2005 From: andy at wild-flower.co.uk (andy) Date: Thu, 20 Jan 2005 18:47:53 +0000 Subject: What's the best python web-developer's editor Message-ID: <41EFFCD9.7060302@wild-flower.co.uk> Anybody like to comment on which editor they use for python web app development - for both discrete and mixed python and html code, and why? I'm comfortable with IDLE (used it for years) but of course it lacks ftp or webDAV abilities, obviously because it's not intended for that type of use. I've had a look at Screem - and that seems to do python syntax highlighting, but it dosn't seem to be python syntax aware (unless there's a hidden option somewhere). Although I can live without auto indent, I'd rather not... I'm sure emacs, xemacs, vi, elvis and so on can do the same, but I have no experience with them for heavy python or html coding, nor the time to trip off down a blind-alley to find out! I know Enough Vi To Get By(tm) but it's by no means my favourite editor. Emacs is a complete mystery to me. I guess I *could* use IDLE and Screem together, but that's a clunky solution! all opinions greatfully received, -andyj From a at b.c Sun Jan 23 02:27:36 2005 From: a at b.c (Doug Holton) Date: Sun, 23 Jan 2005 01:27:36 -0600 Subject: [OT] XML design intent [was Re: What YAML engine do you use?] In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> <41F2C840.2050304@comcast.net> Message-ID: Peter Hansen wrote: > Good question. The point is that an XML document is sometimes > a file, sometimes a record in a relational database, sometimes an > object delivered by an Object Request Broker, and sometimes a > stream of bytes arriving at a network socket. > > These can all be described as "data objects". > """ > > I would ask what part of that, or of the simple phrase > "data object", or even of the basic concept of a markup language, > doesn't cry out "data interchange metalanguage" to you? Actually I don't see any explicit mention that XML was meant to be limited to data interchange only. "data object" has to do with more than data interchange. There is data entry as well. And people are having to hand enter XML files all the time for things like Ant, XHTML, etc. I guess all those people who learned how to write web pages by hand were violating some spec and so they have no cause to complain about any difficulties doing so. Tim Berners-Lee never intended people to have to type in URLs, either, but here we are. From cam.ac.uk at mh391.invalid Sat Jan 15 19:50:01 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 16 Jan 2005 00:50:01 +0000 Subject: deleting from tarfile In-Reply-To: References: Message-ID: Uwe Mayer wrote: > is it possible to delete a file from a tar-archive using the tarfile module? The tarlib.py in pyNMS claims to be able to do it. It doesn't use the tarfile module, though. http://cvs.sourceforge.net/viewcvs.py/pynms/pyNMS/lib/tarlib.py?rev=1.1.1.1&view=auto -- Michael Hoffman From steve at holdenweb.com Fri Jan 14 09:42:03 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 09:42:03 -0500 Subject: [Fwd: Re: Embedding Multiplr Python interpreter in C++] Message-ID: <41E7DA3B.9000005@holdenweb.com> Yogesh Sharma wrote: > one more question to add: > Is there a way to have 2 local copies of python interpreter ? > > Yogesh Sharma wrote: >> Hi, >> >> I have following setup: >> OS Linux Fedora Core 3 >> Python 2.3.4 >> >> How can I embed two python interpreters in one C++ program ? >> >> Thanks > Take a look at mod_python's code: that allows several independent interpreters in the same Apache process using Py_NewInterpreter(), which may well be what you want - initially, see http://www.modpython.org/live/mod_python-3.1.3/doc-html/pyapi-interps.html regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From davidf at sjsoft.com Thu Jan 20 03:04:30 2005 From: davidf at sjsoft.com (David Fraser) Date: Thu, 20 Jan 2005 10:04:30 +0200 Subject: Accessing MDB files on Windows In-Reply-To: <1575169.hWfiKyiV09@strongwill.g2ctech> References: <1635068.ZTfiooUzB4@strongwill.g2ctech> <4262806.PViGKJWPeZ@strongwill.g2ctech> <1575169.hWfiKyiV09@strongwill.g2ctech> Message-ID: Jorge Luiz Godoy Filho wrote: > Jorge Luiz Godoy Filho, Quarta 19 Janeiro 2005 14:25, wrote: > > >>Thanks! I'm looking at it. > > > Worked like a charm! And just now I noticed who's the author of the > recipe ;-) You may also be interested in using a DB-API compatible driver for ADO - see for example http://adodbapi.sourceforge.net/ That way if you want to switch to a different database you can more easily... David From bulba at bulba.com Thu Jan 6 17:41:18 2005 From: bulba at bulba.com (Bulba!) Date: Thu, 06 Jan 2005 23:41:18 +0100 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <344l83F45rstqU1@individual.net> Message-ID: On Thu, 06 Jan 2005 12:20:35 +0100, Stefan Axelsson wrote: >> If GPL folks had their way, it would not be possible not to "share" >> _anything_ you create. It is widely acknowledged that GPL >> license has the "viral" aspect of extending itself on your >> software - can you point to closed-source licenses that would >> have this aspect? None of the licenses I've read except GPL has >> this aspect. >Then you haven't read very many source code licenses, many (perhaps >most?) that state that if you've as much as looked at the code you're >not even allowed to write somethings similar twenty years down the line, >or anything that remotely resembles something similar. I've read Novell license of internal development tools it provides (which I reviewed for some purpose). This is I think relevant part: "Novell grants you a non-exclusive license to use the Software free of charge if (a) you are [...] (b) you are a contracted vendor (c) your use of the Software is for the purpose of evaluating whether to purchase an ongoing license to the Software. [...] You may not: * permit other individuals to use the Software except under the terms listed above; * permit concurrent use of the Software; * modify, translate, reverse engineer, decompile, disassemble (except to the extent applicable laws specifically prohibit such restriction), or create derivative works based on the Software; * copy the Software other than as specified above; * rent, lease, grant a security interest in, or otherwise transfer rights to the Software; or * remove any proprietary notices or labels on the Software. Novell may have patents or pending patent applications, trademarks, copyrights, or other intellectual property rights covering the Software. You are not granted any license to these patents, trademarks, copyrights, or other intellectual property rights except as expressly provided herein. Novell reserves all rights not expressly granted." Other than that, the license had to do only with usual stuff of disclaimers, different jurisdictions, export controls, "US govt restricted rights", etc. Didn't find there anything that forbids me to develop smth similar, unless it's very well hidden in hooking into the technicalities of specific intellecatual property laws. I've also read similar IBM licenses -- granted, not very carefully. The thing that pissed off various bosses most strongly in my impression was that the EULAs typically limited or prohibited transferring the rights to use this thing, e.g. to spin-offs or organizations cooperating with us. It's bothersome in practice. None of that had anything to do with source code or reverse-engineering or developing similar products (if we wanted to develop similar products, we would not be using this thing in the first place, except for 'discovery' purposes). I'm not saying licenses like you claim don't exist. Sure, they may exist and they suck. The point is, they have _limited impact_ and by the very fact of their "exclusion" nature, this aspect tends to repel users than attract them to use this thing. >(Most do in fact >Now, Stallman might or might not want to achieve world domination, not >by sharks with lasers on their heads, but by aiming for all software to >be free software, but the GPL is actually a lot less ambitious than >that. All the GPL says is that: if you received a binary, the person who > provided you with it, must provide you with the source code that built >it. *All* the source code, not just what he happened to receive, on the >off chance that he's modified it. Which I find again wrong: suppose this developer used GPL-ed library A, developed patches B and C. He provided you with the source code of publicly available library A and a patch C, but he doesn't want to release patch B. Now, I know that it would cost you the effort to recreate patch B or maybe it wouldn't work without modifying patch C. But that's an economic concern, which is orthogonal to GPL, as GPL is (supposedly) about "free as in speech, not free as in beer". >And as having the source code without >being able to modify it would be rather pointless, you're allowed to do >that too, it's a given. If you don't want to distribute binaries, that's >fine, and all of the GPL falls. The GPL doesn't *force* you to share >anything. It only says what must happen if you do. True, not directly. However, by attempting to create the context in which it's IMPRACTICAL to use any non-GPLed software, it's attempting to achieve vendor lock-in effect, and while in such situation you FORMALLY would not have to give away, you PRACTICALLY would have to give away. It's not there in license that you "have to give away whatever you create". It's just attempting to create particular _economic_ context with those licenses, just like the licenses and practices of a well-known vendor do, even though that is not spelled out explicitly, obviously. >And I'm rather tired of the GPL's so called 'viral' nature. Look, if >you're using my code, you play by my rules, that's called copyright. Of course. The point is, _what is specific content of those rules_. Python's copyrighted, too: http://www.python.org/2.3.2/license.html And yes, we have to play by those rules, too. That obviously doesn't mean that specific conditions are the same, and those specific conditions are the crux of controversy. > If >you don't want to play by my rules, fine, don't use my code. Do I have to point at who is also attempting to achieve this particular context - "you don't like our licenses, don't use our software"? >So far I'm >no better than Microsoft, or Sun (though that might change) or IBM for >that matter. With the GPL I'm actually not as bad as that, I'll even let >you look at the code, modify it, and distribute copies willy nilly >(though you I'm not forcing you to), in fact, I'll even *forbid* others >from taking that right away from you. If you use it, however, as a small >token of your appreciation, you'll have to also agree to not take the >same rights you had away from others. I don't believe person A automatically has this sort of "right" of reading/using whatever they want. >Finally, what *you* do with *your* code is of no concern to the GPL. As >long as you don't use *my* code you can do whatever you please. But, and >that's a big 'BUT', it really irks me when people release code under >e.g. the BSD (or as has happened to me in the past, public domain), and >then bitch and moan when I incorporate parts of it in *my* software and >release the whole under the GPL. As if that was somehow 'unfair'. In a way, it is: you're taking liberties with their source and use it in a way they did not _intend_ to. Just because this person doesn't lock they house in hope other people will be considerate enough not to rearrange the furniture in it just for fun... Yes, their license _allows it_. So what. > Look, >(and I'm obviously not saying this to the parent poster as he never >expressed any such sentiment, I'm just venting) that's what *you* wanted >when you released the code under that license. If you don't want me to >do that, then don't use those licenses, mkay. Sure, if too many people do that, they will "lock" their house. And only then I think we will be back on the way to the 17th century style "secret science". You're talking about taking the maximum liberties of agreements and situations to achieve ideological goals. I claim that maybe it would be nicer to base this thing on good-willed consensus rather than paranoia and legal technicalities. -- It's a man's life in a Python Programming Association. From ptmcg at austin.rr._bogus_.com Sun Jan 9 22:41:02 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 10 Jan 2005 03:41:02 GMT Subject: Old Paranoia Game in Python References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> <1105318366.966577.107460@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1105318366.966577.107460 at c13g2000cwb.googlegroups.com... > > Aahz wrote: > > Trust the computer, the computer is your friend. > > However, the computer isn't a fuckin' mind reader. > > If you're going to post source code on the usenet, don't > have lines longer than 72 characters. Otherwise you'll > find your code has wrapped lines. This not only causes > syntax errors in your choose and print statements but > also fucks up the formatting of of printed paragraphs. > > Stupid human. > I copy-and-pasted to a file named para1.py, then wrote the following python script with pyparsing to fix the erroneous line breaks. -- Paul =============================== from pyparsing import * extraLineBreak = White(" ",exact=1) + LineEnd().suppress() text = file("para1.py").read() newtext = extraLineBreak.transformString(text) file("para2.py","w").write(newtext) From tim.peters at gmail.com Thu Jan 20 22:52:13 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 20 Jan 2005 22:52:13 -0500 Subject: PyCon Preliminary Program Announced! In-Reply-To: <41F061C3.3000802@gmail.com> References: <20050121000607.DE1261E4010@bag.python.org> <41F061C3.3000802@gmail.com> Message-ID: <1f7befae0501201952139c57a8@mail.gmail.com> [Bryan] > can anyone tell me how the talks work? there are between 9 > and 12 talks for each time slot. do all talks start at the same > time? or are there just four talks at a time and the columns show > what talks are in a given room? The web page needs better formatting. In general, there are no more than 3 presentations going on at any given time, each presentation is scheduled for 30 minutes (including setup time, teardown time, and Q&A time), and all (up to 3) talks in a given time slot begin and end at the same time. All the talks in a given column in a given time block occur in the same room, and these are generally 1.5 hour blocks (so 3 30-minute presentations per block, and up to 3 concurrent blocks). > is it easy to go to the talks you want? I'd say it's impossible when you want to attend two or three presentations occurring at the same time. Otherwise, yes, it's easy -- all the presentation rooms are on the same floor in the same building. The program committee spent a lot of time trying to group "similar" presentations into blocks, so that there's a good chance someone (and especially a "one-issue" person) can sit in the same room for 1.5 hours and hear what they want to hear. That can't work for everyone simultaneously, though, and some amount of room-switching during blocks is unavoidable. I don't care much for "parallel tracks" myself, because I want to hear basically everything. But we had more proposals of higher quality this year than ever before, so it came down to scheduling more talks in parallel than ever before too, or rejecting perfectly good proposals. Because of time constraints, we had to reject some good proposals despite having 3 concurrent presentation tracks, and adding (compared to last year) an additional 6-talk block on Wednesday. It looks to be another great PyCon! From ods at strana.ru Fri Jan 14 09:52:48 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Fri, 14 Jan 2005 17:52:48 +0300 Subject: Python.org, Website of Satan In-Reply-To: References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: <20050114175248.55749afe.ods@strana.ru> On Fri, 14 Jan 2005 11:16:59 +0000 Michael Hoffman wrote: > from socket import gethostbyaddr, herror > > for a in xrange(256): > if a < 666-255*3: > continue > for b in xrange(256): > if a+b < 666-255*2: > continue > for c in xrange(256): > if a+b+c < 666-255: > continue > for d in xrange(256): > if a + b + c + d == 666: Certainly, it can be done more efficient: for a in xrange(256): for b in xrange(max(0, (666-255*2)-a), 256): for c in xrange(max(0, (666-255)-a-b), min(666-a-b+1, 256)): d = 666-a-b-c ... I've checked these IPs with ip2cc (which can miss entries registered last month): there are 2907248 "evil" addresses, most of them (1568430) in USA. Too many to resolve. -- Denis S. Otkidach http://www.python.ru/ [ru] From paschott at no.worldnet.spamm.att.net Mon Jan 17 15:11:52 2005 From: paschott at no.worldnet.spamm.att.net (Peter A. Schott) Date: Mon, 17 Jan 2005 20:11:52 GMT Subject: FTPLIB - retry files? Message-ID: Is there any way to retry sending files with some delay up to a set number on failure? Sometimes we encounter a locked file on our server or the destination server and we want to retry that file in X seconds. Not exactly sure how to go about that right now short of moving the files elsewhere and then queuing them up again. Anyone done this? I'm still kind of new to this so am open to suggestions on how this might be possible as well. Thanks for your help. -Pete Schott From rnd at onego.ru Tue Jan 4 17:20:28 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 5 Jan 2005 01:20:28 +0300 (MSK) Subject: Python evolution: Unease In-Reply-To: <41DB11DB.4090805@colorstudy.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> <41DB11DB.4090805@colorstudy.com> Message-ID: On Tue, 4 Jan 2005, Ian Bicking wrote: >Umm... this isn't helpful. "Generic" and "concept" are not terms that >belong to Boost or STL or whatever. They are just words. Coining the >term doesn't mean anyone else knows what it means, nor that anyone >*should* know what they mean -- personally I get very suspicious of >ideas that are based on redefined words, that tends to be a way of >hiding complexity or fuzziness. > >But anyway, if you use these terms, you really must provide references, >otherwise no one will know what you mean. "Python could have honest >support of concepts" is simply an incomplete sentence. "Python could >have honest support of Concepts (url)" would be more reasonable. Sorry. I use definitions from there sources: 1. http://www.cs.rpi.edu/~musser/gp/ 2. "A Formalization of Concepts for Generic Programming" (google could find PDF of that). If I am correct, this one: http://www.osl.iu.edu/publications/pubs/2004/willcock04:_formal_concep_gener_progr.pdf (it is safe to skip till example on Fig.1 to grasp the idea behind a concept. Relations between concepts are also very logical and remind of inheritance, association and aggregation) 3. "The Boost Graph Library" by Jeremy Siek, et al with A.Stepanov's foreword is a good way to see GP != STL. Probably Boost docs contain some knowledge on the topic, at least Boost Graph Library's ones (which I read). >"Python could have honest support of Concepts (url)" - of course, right now those sources are C++-specific. But I could see that Python has even greater potential to have concepts ahead of C++ and with greater usefulness at the same time. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From gabriel.barros at gmail.com Sat Jan 29 13:16:14 2005 From: gabriel.barros at gmail.com (Gabriel B.) Date: Sat, 29 Jan 2005 16:16:14 -0200 Subject: tk global bindings Message-ID: <5175a81c05012910162b5ae608@mail.gmail.com> I'm starting to write a POS application UI's module. There's no mouse, just a bunch of global shortcuts. the problem is that TK doesn't have global shortcuts! Is there a work-around or i will have to attach 80 or so bindings for every input element? Thanks, Gabriel From sizelji at insightbb.com Fri Jan 21 14:51:14 2005 From: sizelji at insightbb.com (Jim Sizelove) Date: Fri, 21 Jan 2005 19:51:14 GMT Subject: Configuring Python for Tk on Mac In-Reply-To: References: Message-ID: Martyn Quick wrote: > On my desk here at work I have a Mac G4 running Mac OS X v10.2.8. > > When I go into a terminal and type "python" up comes a nice python > interface and all seems great. However when I type "import Tkinter" > I'm greeted by the following error. > > >>>>import Tkinter > > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 35, in ? > import _tkinter # If this fails your Python may not be configured > for Tk > ImportError: No module named _tkinter > > So I guess something about this implementation is not appropriately > configured. I'm guessing this is the default behaviour since I don't > think anyone did anything special about python when they set up my > machine. > > What do I do to set it up so I can use Tkinter? > > Thanks... and sorry if this is an FAQ... but I couldn't find the info > easily. > > Yours, > Martyn You probably need to install Tcl/Tk Aqua: http://tcltkaqua.sourceforge.net After downloading and installing on my Mac running OS X v 10.2, I am able to open IDLE and other Tk apps. HTH, Jim Sizelove From flupke at nonexistingdomain.com Thu Jan 13 08:08:33 2005 From: flupke at nonexistingdomain.com (flupke) Date: Thu, 13 Jan 2005 13:08:33 GMT Subject: seperating GUI from other code + reports Message-ID: Hi, i need to develop an app here which will be used to produce stats. I'm going to go with twisted pb for the client server communication. And wxPython for the GUI. Now i would want to split the GUI code from the pb code to make debugging easier amongst other things but i'm not sure how i would best implement the communication of between the GUI and the client. Do i also use pb for it? But then i would end up with the problems that some users have reported here that wxPython and pb have. This would look like this, where GUI and CLIENT are off course on the same machine. GUI pb CLIENT pb SERVER <-----------> <-----------> 1) Any thoughts about this or other methods of doing this or reason why i should not bother with this setup? 2) I will display the results of the query in a list of grid on the client. But then the users are going to want to print the results. Are there any tools that provide a way of printing queries or that provide a mechanism to build reports based on tables? The easiest way i can do it now is to make a html of the results and then opening a browser with that html page using popen. Any other ideas? Thanks, Benedict From bokr at oz.net Tue Jan 11 03:42:39 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 11 Jan 2005 08:42:39 GMT Subject: Writing huge Sets() to disk References: Message-ID: <41e38fd9.554915255@news.oz.net> On Mon, 10 Jan 2005 17:11:09 +0100, =?ISO-8859-2?Q?Martin_MOKREJ=A9?= wrote: >Hi, > I have sets.Set() objects having up to 20E20 items, What notation are you using when you write 20E20? IOW, ISTM 1E9 is a billion. So 20E20 would be 2000 billion billion. Please clarify ;-) >each is composed of up to 20 characters. Keeping >them in memory on !GB machine put's me quickly into swap. >I don't want to use dictionary approach, as I don't see a sense >to store None as a value. The items in a set are unique. > > How can I write them efficiently to disk? To be more exact, >I have 20 sets. _set1 has 1E20 keys of size 1 character. > >alphabet = ('G', 'A', 'V', 'L', 'I', 'P', 'S', 'T', 'C', 'M', 'A', 'Q', 'F', 'Y', 'W', 'K', 'R', 'H', 'D', 'E') >for aa1 in alphabet: > # l = [aa1] > #_set1.add(aa1) > for aa2 in alphabet: > # l.append(aa2) > #_set2.add(''.join(l)) >[cut] > > The reason I went for sets instead of lists is the speed, >availability of unique, common and other methods. >What would you propose as an elegant solution? >Actually, even those nested for loops take ages. :( If you will explain a little what you are doing with these set "items" perhaps someone will think of another way to represent and use your data. Regards, Bengt Richter From abkhd at earth.co.jp Sun Jan 30 17:27:30 2005 From: abkhd at earth.co.jp (A.B., Khalid) Date: 30 Jan 2005 14:27:30 -0800 Subject: pickle, cPickle, & HIGHEST_PROTOCOL Message-ID: <1107124050.160083.129630@f14g2000cwb.googlegroups.com> I wonder if someone can explain what is wrong here. I am pickling a list of dictionaries (see code attached) and unpickling it back using the HIGHEST_PROTOCOL of pickle and cPickle. I am getting an error message and trace backs if the list exceeds eight items. Whether I use pickle or cPickle does not matter, i.e., the eight number causes a problem in both modules, although the trace backs are of course dissimilar. This pickling and unpickling of the list of dictionaries worked when I stopped using the HIGHEST_PROTOCOL in both modules (pickle and cPickle), which got Python to use the ASCII format (I suppose) as I can read the pickled data. This behavior was observed in Python 2.3.4 (final), and 2.4 (final) on Win98. Any comments? Regards, Khalid # Sample program tester.py begin ! ! import pickle as pkl ! import os ! #----------------------------- ! def test_pickle(): ! fn = 'rkeys.txt' ! f = file(fn, 'r') ! lines = f.readlines() ! f.close() ! _test_list = [] ! for line in lines: ! sline = line.split(',') ! #print sline ! key, value = sline[0], sline[1].strip() ! _test_dict = {} ! _test_dict[key] = value ! _test_list.append(_test_dict) ! ! # Let's see the contents of our object ! print _test_list ! ! # Then pickle it ! f = file('pkl_' + fn, 'w') ! pkl.dump(_test_list, f, pkl.HIGHEST_PROTOCOL) ! f.close() ! ! # Empty it ! _test_list = [] ! print _test_list ! ! # Unpickling object here: ! f = file('pkl_' + fn, 'r') ! _test_list = pkl.load(f) ! f.close() ! ! # See contents after loading ! print _test_list !#----------------------------- !if __name__ == '__main__': ! test_pickle() ! !# Sample program end # Contents of file rkeys.txt (without the triple quotes): """ '1','v1' '2','v2' '3','v3' '4','v4' '5','v5' '6','v6' '7','v7' '8','v8' '9','v9' """ # Output (without the triple quotes) # Using "import pickle as pkl": """ [{"'1'": "'v1'"}, {"'2'": "'v2'"}, {"'3'": "'v3'"}, {"'4'": "'v4'"}, {"'5'": "'v5'"}, {"'6'": "'v6'"}, {"'7'": "'v7'"}, {"'8'": "'v8'"}, {"'9'": "'v9'"}] [] !Traceback (most recent call last): ! File "tester.py", line 41, in ? ! test_pickle() ! File "tester.py", line 34, in test_pickle ! _test_list = pkl.load(f) ! File "D:\PY23\PYTHON\DIST\SRC\lib\pickle.py", line 1390, in load ! return Unpickler(file).load() ! File "D:\PY23\PYTHON\DIST\SRC\lib\pickle.py", line 872, in load ! dispatch[key](self) ! File "D:\PY23\PYTHON\DIST\SRC\lib\pickle.py", line 1189, in load_binput ! i = ord(self.read(1)) !TypeError: ord() expected a character, but string of length 0 found """ # Output (without the triple quotes) # Using "import cPickle as pkl": """ [{"'1'": "'v1'"}, {"'2'": "'v2'"}, {"'3'": "'v3'"}, {"'4'": "'v4'"}, {"'5'": "'v5'"}, {"'6'": "'v6'"}, {"'7'": "'v7'"}, {"'8'": "'v8'"}, {"'9'": "'v9'"}] [] !Traceback (most recent call last): ! File "tester.py", line 41, in ? ! test_pickle() ! File "tester.py", line 34, in test_pickle ! _test_list = pkl.load(f) !EOFError """ # Output (without the triple quotes) # Using "import cPickle as pkl", or "import pickle as pkl" # but _not_ using the HIGHEST_PROTOCOL: """ [{"'1'": "'v1'"}, {"'2'": "'v2'"}, {"'3'": "'v3'"}, {"'4'": "'v4'"}, {"'5'": "'v5'"}, {"'6'": "'v6'"}, {"'7'": "'v7'"}, {"'8'": "'v8'"}, {"'9'": "'v9'"}] [] [{"'1'": "'v1'"}, {"'2'": "'v2'"}, {"'3'": "'v3'"}, {"'4'": "'v4'"}, {"'5'": "'v5'"}, {"'6'": "'v6'"}, {"'7'": "'v7'"}, {"'8'": "'v8'"}, {"'9'": "'v9'"}] """ From sam.sherlock at tiscali.co.uk Tue Jan 4 20:12:42 2005 From: sam.sherlock at tiscali.co.uk (Sam) Date: Wed, 05 Jan 2005 01:12:42 +0000 Subject: modpython, apache and windows Message-ID: <41DB3F0A.2010706@tiscali.co.uk> Hi All, I am interested in learning python since I am hearing more and more about python for use in web development I am starting out on python, with knowledge of PHP some perl my current hurdle is setting up either apache 1 or 2 with python 2.3.3 I have installed modpython fine which informed me that I need to make some configuration changes to httpd.conf I have not had it working yet, searches on the web give conflicting suggestions and so far has confused me some forums mention spyce and serving .spy files so far I one explanation worked in that a .py file was parsed but I had to set the name of the actual file within apache.conf this seems strange thanks in advance >> SS -- No virus found in this outgoing message. Checked by AVG Anti-Virus. Version: 7.0.298 / Virus Database: 265.6.7 - Release Date: 30/12/2004 From jfj at freemail.gr Thu Jan 27 22:48:35 2005 From: jfj at freemail.gr (jfj) Date: Thu, 27 Jan 2005 19:48:35 -0800 Subject: python memory blow out In-Reply-To: References: <4e4a11f805012617082ebd9b80@mail.gmail.com> Message-ID: <41F9B613.8070608@freemail.gr> Stephen Thorne wrote: > On Thu, 27 Jan 2005 09:08:59 +0800, Simon Wittber > wrote: > >>According to the above post: >> >>>a) If the allocation is > 256 bytes, call the system malloc. >>>b) If the allocation is < 256, use its own malloc implementation, which >>>allocates memory in 256 kB chunks and never releases it. >> >>I imagine this means that large memory allocations are eventually >>released back to the operating system. However, in my case, this >>appears to be not happening. > > > There was a recent patch posted to python-dev list which allows python > to release memory back to the operating system once the 256kb chunk is > no longer used. > The policy is that the memory allocated for those things is as much as the maximum number of them where needed during the program. This is "bad" in rare cases: A program which - at some point, while normally needs 10-20 integers, it peaks its requirements and allocates 10000000 integers. - which does not terminate after that peak but keeps running for a long time without ever needing again many integers. Such programs are rather rare. Moreover, the OS will happily swap out the unused int blocks after a while. A more pathetic situation would be, in the above scenario to release all the 100000000 integers except from every 1000th. Assuming those ints left are accessed frequently, the OS can't even swap out the pages! But such programs, unless intentionally constructed are, **very** rare and it's supposed to be better to have a faster python in the general case. Gerald. From me at privacy.net Sat Jan 1 10:50:05 2005 From: me at privacy.net (Mark Carter) Date: Sat, 01 Jan 2005 15:50:05 +0000 Subject: Which blog tool In-Reply-To: References: <41d6a22f$0$42579$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: <41d6c6ad$0$56207$ed2619ec@ptn-nntp-reader02.plus.net> Premshree Pillai wrote: > You can use the Blogger API to post to your Blogger account. There's a > Python interface to the API -- PyBlogger -- available here: > http://beetle.cbtlsl.com/archives/category/pyblogger Hey, it Just Works! I got the whole basic thing working in a few minutes. It was exactly what I was looking for. Thanks for the link. From dbickett at gmail.com Mon Jan 24 00:53:23 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Mon, 24 Jan 2005 00:53:23 -0500 Subject: how to write a tutorial In-Reply-To: <1d6cdae305012321452fb71ca6@mail.gmail.com> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106531824.833549.28720@c13g2000cwb.googlegroups.com> <1d6cdae305012321452fb71ca6@mail.gmail.com> Message-ID: <1d6cdae3050123215312afc095@mail.gmail.com> Daniel Bickett wrote: > [snip] > You guys are just begging for a YHBT ;-) I apologize, that should have been "we" -- I was criticizing him too. no-one-wants-to-be-a-hypocrite-ly y'rs, Daniel Bickett From pythongnome at hotmail.com Sun Jan 23 17:11:40 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Sun, 23 Jan 2005 22:11:40 GMT Subject: how to write a tutorial In-Reply-To: References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: Daniel Bickett wrote: >>Most texts in computing are written by authors to defend and showcase >>their existence against their peers. > > > When you aren't busy `showcasing' your ignorance, this is *all* i see > in everything you write. Um, maybe that was his point... From ialbert at mailblocks.com Thu Jan 6 16:18:07 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 06 Jan 2005 16:18:07 -0500 Subject: Download .jpg from web In-Reply-To: References: Message-ID: GMane Python wrote: > Using a network camera with built-in webserver The first thing that might be worth investigating is this webserver. What kind of throughput is it capable of? How does it handle repeated requests etc. Your program won't be faster than the server that provides it with the data. Istvan. From bh at intevation.de Sat Jan 29 14:48:12 2005 From: bh at intevation.de (Bernhard Herzog) Date: Sat, 29 Jan 2005 20:48:12 +0100 Subject: limited python virtual machine References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> <16891.41849.882856.527798@montanaro.dyndns.org> <1gr5th5.13asce21fjmj8tN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > OK then -- vars(type(object)) is a dict which has [[the unbound-method > equivalent of]] object.__subclasses__ at its entry for key > '__subclasses__'. Scratch 'vars' in addition to 'getattr'. And 'eval' > of course, or else building up the string 'object.__subclasses__' (in a > way the regex won't catch) then eval'ing it is easy. I dunno, maybe I'm > just being pessimistic, I guess... You can defeat the regexp without any builtin besides object: >>> eval("# coding: utf7\n" "+AG8AYgBqAGUAYwB0AC4AXwBfAHMAdQBiAGMAbABhAHMAcwBlAHMAXwBf-") >>> Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ From bokr at oz.net Wed Jan 26 05:43:53 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 26 Jan 2005 10:43:53 GMT Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> <1106669254.838248.317170@z14g2000cwz.googlegroups.com> <10vdj4s9ib19fe3@corp.supernews.com> Message-ID: <41f772b2.1858112584@news.oz.net> On Wed, 26 Jan 2005 11:55:59 -0800, jfj wrote: >Jeff Shannon wrote: > >> >> >> So, what problem is it, exactly, that you think you'd solve by making >> tuple slices a view rather than a copy? >> > >I think views are good for > 1) saving memory > 2) saving time (as you don't have to copy the elements into the new tuple) > >And they are worth it. However, (as in other cases with slicing), it is >very easy and fast to create a view for a slice with the default step >'1', while it's a PITA and totally not worth it to create a view for a >slice with non default step. I think it would be good to: > > if slice_step == 1 > create_view > else > create_new_tuple > >Actually, i think that slices with step, is a bad feature in general >and i think I will write a PEP to suggest their removal in python3k. > What's the big deal with other than 1 steps? It is just adjusting a few numbers so that you can either index the new virtual slice with an integer and return the element, in which case the index into the original tuple will be someoffset+i*somefactor once you get past the limit checks for the virtual slice. By the same token, transforming a few numbers of one virtual slice into similar numbers for a a new virtual slice of that shouldn't be rocket science. And it wouldn't have to be done more than once. Don't have time to do it now, but there are plenty around here that could, I'm sure. Regards, Bengt Richter From aleaxit at yahoo.com Wed Jan 5 08:35:38 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 5 Jan 2005 14:35:38 +0100 Subject: Cookbook 2nd ed Credits References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> Message-ID: <1gpx70u.1ug02dpsxhx39N%aleaxit@yahoo.com> Premshree Pillai wrote: > On Wed, 5 Jan 2005 08:55:39 +0100, Alex Martelli wrote: > > Premshree Pillai wrote: > > > Do contributors of less than 5 recipes get a copy too? :-? > > Of course! > > > Btw, is there a comprehensive list of ALL contributors put up anywhere? > > Not yet -- do you think I should put it up on my website? > > If you can, why not! Hmmm, essentially, because the list is *tentative* until the very last minute -- even at proofreading time it's possible, though very unlikely, that we might have to excise a recipe completely. But, as long as this is understood -- I sent both lists (first-authors only, and all-contributions) to Anand Pillai, since he asked in mail, and I gather he'll be putting them up on his site. Alex From duncan.booth at invalid.invalid Wed Jan 26 11:11:29 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 Jan 2005 16:11:29 GMT Subject: re.search - just skip it References: <1106754436.876675.144290@c13g2000cwb.googlegroups.com> Message-ID: wrote: > Input is this: > > SET1_S_W CHAR(1) NOT NULL, > SET2_S_W CHAR(1) NOT NULL, > SET3_S_W CHAR(1) NOT NULL, > SET4_S_W CHAR(1) NOT NULL, > ; > > .py says: > > import re, string, sys > s_ora = re.compile('.*S_W.*') > lines = open("y.sql").readlines() > for i in range(len(lines)): > try: > if s_ora.search(lines[i]): del lines[i] > except IndexError: > open("z.sql","w").writelines(lines) > > but output is: > > SET2_S_W CHAR(1) NOT NULL, > SET4_S_W CHAR(1) NOT NULL, > ; > > It should delete every, not every other! No, it should delete every other line since that is what happens if you use an index to iterate over a list while deleting items from the same list. Whenever you delete an item the following items shuffle down and then you increment the loop counter which skips over the next item. The fact that you got an IndexError should have been some sort of clue that your code was going to go wrong. Try one of these: iterate backwards iterate over a copy of the list but delete from the original build a new list containing only those lines you want to keep also, the regex isn't needed here, and you should always close files when finished with them. Something like this should work (untested): s_ora = 'S_W' input = open("y.sql") try: lines = [ line for line in input if s_ora in line ] finally: input.close() output = open("z.sql","w") try: output.write(str.join('', lines)) finally: output.close() From craig at postnewspapers.com.au Fri Jan 7 12:34:18 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 08 Jan 2005 01:34:18 +0800 Subject: how to extract columns like awk $1 $5 In-Reply-To: <41DEC3C4.2030103@abisen.com> References: <41DEC3C4.2030103@abisen.com> Message-ID: <1105119258.30384.54.camel@rasputin.localnet> On Sat, 2005-01-08 at 01:15, Anand S Bisen wrote: > Hi > > Is there a simple way to extract words speerated by a space in python > the way i do it in awk '{print $4 $5}' . I am sure there should be some > but i dont know it. The 'str.split' method is probably what you want: .>>> x = "The confused frog mumbled something about foxes" .>>> x.split() ['The', 'confused', 'frog', 'mumbled', 'something', 'about', 'foxes'] .>>> x.split(" ")[4:6] ['something', 'about'] so if 'x' is your string, the rough equivalent of that awk statement is: .>>> x_words = x.split() .>>> print x_words[4], x_words[5] or perhaps .>>> print "%s %s" % tuple(x.split()[4:6]) -- Craig Ringer From bulba at bulba.com Sat Jan 8 19:34:45 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 09 Jan 2005 01:34:45 +0100 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> Message-ID: <21v0u012jb2lslg0hra6t55virb31r8ta2@4ax.com> On Sat, 08 Jan 2005 08:28:12 GMT, "Roose" wrote: >I am not trying to be insulting... but unless someone would like to educate >me otherwise, the idea of an OS written in Python is almost ludicrous. As I >said, I think you might mean an OS SHELL, which would be a reasonable >(although maybe unconventional) thing to write in python. That's a crazy idea I once had - what if a user could run Python as a shell of Linux/other free U**x, and access every single subsystem and piece of data in the object-like manner? Sure, things like pipes and immediate access to files without having to open() them and the whole filesystem hierarchy would have to be added. Quite a lot of plumbing work would have to be done, but once it were done, it would be like an object operating system, everything organized nicely in predictable object hierarchies with dot access. System scripts would no longer be a mess that breaks every now and then depending on slight differences in filesystem hierarchy. Python dictionaries with their ability to quickly bind names to various objects would make it possible to keep such hierarchy stable, even with data moving around on different physical disk partitions and folders. Instead of saying: # cp /etc/postfix/main.cf /mnt/floppy the user could say e.g. .>>> copy system[config][mta] floppy or .>>> copy system.config.mta floppy In an "object system" like Python it could be reasonable to consider writing a class that would implement at least a subset of generic interface to the equivalent functionalities of various MTAs. Maybe. With traditional filesystems trying smth like that is not really reasonable, because 99% of the time it would work, but 1% of the time it would fail and that 1% would ruin the whole venture, as handling low-level OS complexity for a non-tech user has to be more reliable than that - in two cases when I installed Linux for free for someone the installation was finally deleted by those users because the desktop shortcuts to devices like floppy and CD ultimately failed to work for some reason and using 'mount -t iso9660 ...' was not an option that they would consider learning and using really. Think about all the potential! On top of clean, stable system interface a user could use map, filter and reduce functions on various system objects. Handlers for files with known structure could be written, so dot or list or dictionary access would allow manipulating data inside the files, like file[rownumber]='spam', or spreadsheet_file['A2', 100]. Or you could issue commands like browser.go('somewhere') or desktop.edit('hello.txt'). I was considering writing smth like this myself but it's way over my head re low-level OS and kernel stuff. :-( IMHO Linux problem has long been that in its lower level interface (above kernel and below GUI) is way too much like traditional UNIX. Sure someone with sysadmin experience can use it - but in my experience it's way over the head of the typical user. Trying to teach them about mknod and /dev/* hierarchy is hopeless and too hard for them. -- It's a man's life in a Python Programming Association. From premshree.pillai at gmail.com Sun Jan 30 14:38:19 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Mon, 31 Jan 2005 01:08:19 +0530 Subject: search engine In-Reply-To: <1107112770.301449.49070@c13g2000cwb.googlegroups.com> References: <1107112770.301449.49070@c13g2000cwb.googlegroups.com> Message-ID: On 30 Jan 2005 11:19:30 -0800, jlrodilla at gmail.com wrote: > hi all, i?m doing a search engine using python for the spider and php > to make a web for the search. The Database i have choosen is Just curious: is there any particular reason you want to use PHP for building the web interface? > postgreSQL. Do you think it is a good choosen? Any suggestion? > > if anybody in interested in colaborate please send an e-mail to > jlrodilla at gmail.com > > In a few weeks i will upload all the code to one domain and so i can be > able to send you information about this project. > > The idea is to build a search engine like "google", but my/our search > engine only look for tech pages, i also wants that users can select if > they want to search a web, faqs/howto, manuals/tutorials... > > Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From peter at engcorp.com Mon Jan 24 22:05:02 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jan 2005 22:05:02 -0500 Subject: smtplib bug with Windows XP In-Reply-To: <1106614880.586616.19780@f14g2000cwb.googlegroups.com> References: <1106614880.586616.19780@f14g2000cwb.googlegroups.com> Message-ID: stewart.midwinter at gmail.com wrote: > I'm having problem with a script that used to work under Win2k but is > now broken after an install of WinXP Pro. I can no longer connect to a > local mail server. Has anyone else seen this? If so, were you able to > work around it? Here's the traceback (below). The usual first step to troubleshooting such a problem is to use Telnet to connect manually. Type this "telnet 10.50.200.6 25" and see what you get. If it appears correct (it helps to know some of the SMTP protocol: you should get a "220" response here plus the host's name), type "helo blech.org" or something like that to see the response. "Help" is usually a valid command at this point. If you can't do this manually, then smtplib certainly cannot either. > Interestingly, if I > change ports to the POP port 110, I get a different error, but one that > lets me know that I can reach the server. "ping" would let you know you can reach the server as well, but using SMTP to connect to a POP3 server is perhaps a somewhat more complicated and hopeless, but interesting way to do the same thing. >>>>s = smtplib.SMTP('10.50.200.6',25) > > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Programs\Python24\Lib\smtplib.py", line 241, in __init__ > (code, msg) = self.connect(host, port) > File "C:\Programs\Python24\Lib\smtplib.py", line 303, in connect > raise socket.error, msg > socket.error: (10053, 'Software caused connection abort') Try manually, but think about these options: a firewall that has suddenly been enabled, an SMTP server that now requires authentication, some kind of proxy like what virus scanners use (though why they would intercept outgoing mail I don't know)... -Peter From steven.bethard at gmail.com Mon Jan 10 16:48:50 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 10 Jan 2005 14:48:50 -0700 Subject: [OT] Re: Old Paranoia Game in Python In-Reply-To: References: <2005010903390916807%spk00@coxnet> Message-ID: Terry Reedy wrote: > Never saw this specific game. Some suggestions on additional factoring out > of duplicate code. > > >>def next_page(this_page): >> print "\n" >> if this_page == 0: >> page = 0 >> return > > > The following elif switch can be replaced by calling a selection from a > list of functions: > > [None, page1, pag2, ... page57][this_page]() > > >> elif this_page == 1: >> page1() >> return >> elif this_page == 2: >> page2() >> return > > ... > >> elif this_page == 57: >> page57() >> return > > > Also, a chose3 function to complement your chose (chose2) function would > avoid repeating the choose-from-3 code used on multiple pages. > > Terry J. Reedy This is what I love about this list. Where else is someone going to look at 1200+ lines of code and give you useful advice?! ;) Very cool. (Thanks Terry!) While we're making suggestions, you might consider writing dice_roll as: def dice_roll(num, sides): return sum(random.randrange(sides) for _ in range(num)) + num for Python 2.4 or def dice_roll(num, sides): return sum([random.randrange(sides) for _ in range(num)]) + num for Python 2.3. You also might consider writing all the pageX methods in a class, so all your globals can be accessed through self, e.g.: class Game(object): def __init__(self): ... self.page = 1 self.computer_request = 0 ... def page2(): print ... if self.computer_request == 1: new_clone(45) else: new_clone(32) ... You could then have your class implement the iteration protocol: def __iter__(self): try: while True: self.old_page = self.page yield getattr(self, "page%i" % page) except AttributeError: raise StopIteration And then your main could look something like: def main(args): ... instructions() more() character() more() for page_func in Game(): page_func() print "-"*79 Anyway, cool stuff. Thanks for sharing! Steve From vze4rx4y at verizon.net Mon Jan 31 19:43:21 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 01 Feb 2005 00:43:21 GMT Subject: set, dict and other structures References: <1107214762.198058.55680@f14g2000cwb.googlegroups.com> Message-ID: > I'm frequently using Py2.4 sets, I find them quite useful, and I like > them, even if they seem a little slower than dicts. Glad to hear that you find them to be a useful abstraction. Since sets are internally implemented as dicts, they should have almost identical performance (net of a small difference for the time to forward the calls). > Sets also need the > same memory of dicts (can they be made to use less memory, not storing > values? Maybe this requires too much code rewriting). Yes, an alternate implementation could be written that would take less memory (by about 1/3) and be a bit faster. The approach would be to copy relevant sections of the dictionary implementation and then remove anything pertaining to dict values. If the need arises and I find the time, this will probably happen someday. In the meantime, the current implementation is rock solid and gives great performance. Have you encountered situations where a 1/3 memory savings and a slight speed improvement would have made a critical difference in a real application? > I presume such sets are like this because they are kind of dicts. If > this is true, then converting a dict to a set (that means converting > just the keys; this is often useful for a successive processing with > set operators like intersection, etc) can be a very quick operation; > but this little code shows me that this isn't true, set-ify a dict is > even slower than doing it on a list. Can this operation made faster (by > people that writes Python interpreter)? Dicts take longer than lists because dict iteration takes longer than for lists. If set-ifying a dictionary turns out to be an essential and time-critical operation, it is possible to add some special case code for this. The question is whether it is worth it. If you find the need is pressing, file a feature request explaining why it is essential. Then, I'll implement it for you. On the other hand, if this is a theoretical nice-to-have, then why clutter up the code (with pre-sizing and forcing all values to True). > I've studied the nice sets python module from Py2.3, and I am... > well... writing something similar, a (python) graph module for sparse > graphs. I've found 3 modules like that around on the Net, but I think > they can be improved (even if I'm not an expert of Python, and I know, > my code is probably quite rough/naive compared to "sets" module one...) > Graphs are complex data structures, so probably one person needs from a > graph data structure are different from other people needs, so it's > probably not easy to define a "standard" graph module fit for everyone. > Still, I think it can be useful to have a standard module to manage > them. > Do you think it be useful to add a (well made) standard module like > that? Start by posting a module outside the standard library; gathering user feedback; and, if popular, propose it for inclusion in the standard library. My guess is that there will be two issues. One is that no one implementation of graphs seems to satisfy all users. The second is that only a small fraction of Python users need for graph support (there is probably a much greater demand for combinatorics, numeric/numarray, or financial modules). If the appeal is not broad, it has little chance of making it into the standard library. Raymond Hettinger From nightmarch at gmail.com Mon Jan 24 22:23:51 2005 From: nightmarch at gmail.com (nightmarch) Date: Tue, 25 Jan 2005 11:23:51 +0800 Subject: Why can't use cursor.nextset() in adodbapi package? In-Reply-To: References: Message-ID: <31d9b15c05012419231edc7646@mail.gmail.com> Thank you Dennis! You mean I should execute many select statement like this " rec = crsr.fetchall() " ? But the result is the same, still got the error like "... 'Current provider does not support returning multiple recordsets from a single execution.'..." On Mon, 24 Jan 2005 17:00:39 GMT, Dennis Lee Bieber wrote: > On Mon, 24 Jan 2005 17:18:05 +0800, nightmarch > declaimed the following in comp.lang.python: > > > >>> sql = "select * from wjtmp" > > >>> crsr.execute(sql) > > >>> rec = crsr.fetchone() > > >>> crsr.nextset() > > > com_error: (-2147352567, '\xb7\xa2\xc9\xfa\xd2\xe2\xcd\xe2\xa1\xa3', > > (0, 'ADODB.Recordset', 'Current provider does not support returning > > multiple recordsets from a single execution.', > > 'C:\\WINNT\\HELP\\ADO210.CHM', 0, -2146825037), None) > > > > > > > > > > Why? > > > > Could it be because you don't have multiple recordsets in crsr? > > You're executing a single select statement, retrieving the > /first/ record from the result, and then trying to get a totally > different result set. > > Maybe you want the next record in the record set you already > have? crsr.fetchnext()? > > > thanks > > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < > -- > http://mail.python.org/mailman/listinfo/python-list > From apardon at forel.vub.ac.be Mon Jan 17 04:45:52 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Jan 2005 09:45:52 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> Message-ID: Op 2005-01-14, Steve Holden schreef : > Antoon Pardon wrote: > >> Op 2005-01-13, hanz schreef : >> >>>Antoon Pardon wrote: >>> >>>>So if I have a call with an expression that takes more than >>>>one line, I should assign the expression to a variable and >>>>use the variable in the call? >>> >>>Yes, that's sometimes a good practice and can clarify >>>the call. >>> >>> >>>>But wait if I do that, people will tell me how bad that it >>>>is, because it will keep a reference to the value which >>>>will prevent the garbage collector from harvesting this >>>>memory. >>> > Of course, unless that reference is in the global scope of the __main__ > module its lifetime will be transient anyway. If the reference is stored > in a function's local variable then unless its value is returned from > the function it will become available for garbage collection when the > function returns. > >>>Nobody will tell you that it's bad. >> >> >> Sorry, someone already did. If I recall correctly it >> was Alex Martelli. >> > "A foolish consistency is the hobgoblin of little minds". Rules are made > to be broken. Like only use immutables as dictionary keys. > Besides which, if you don't understand the language > environment, rules alone will do you very little good. Try to focus a > little more on principles and a little less on minutiae. And what are the difference between those two? Sometimes I get the impression that everything is a principle until one personnaly finds the need to break it. After that it is a rule. -- Antoon Pardon From limodou at gmail.com Tue Jan 18 23:31:11 2005 From: limodou at gmail.com (limodou) Date: Wed, 19 Jan 2005 12:31:11 +0800 Subject: safest way to kill a thread In-Reply-To: <1106106497.429643.307440@f14g2000cwb.googlegroups.com> References: <1106106497.429643.307440@f14g2000cwb.googlegroups.com> Message-ID: <41EDE28F.1020401@gmail.com> Using Thread's method setDaemon() before you call the start() method. Just like : t.setDaemon(True) t.start() martinnitram at excite.com wrote: > Dear all, > in python, a thread can be created by t = threading.Thread. But i > found that when the main (and the thread) program is running and user > use Crtl+C/Crtl+Z to break the program abnormally, the thread is still > running and needed to kill manually (by the pid). Is there had any > safest way to kill/exit the thread program under python (when the > thread program part is a forever loop)? > > Thank a lot > -- I love python! My Blog: http://www.donews.net/limodou From roy at panix.com Sun Jan 16 19:48:05 2005 From: roy at panix.com (Roy Smith) Date: Sun, 16 Jan 2005 19:48:05 -0500 Subject: List problems in C code ported to Python References: <3SDGd.22010$Z%.6947@fe1.texas.rr.com> Message-ID: "Paul McGuire" wrote: > "A" == 'a' is true in Python, not true in C. It could be true in C, if the string is stored in very low memory :-) From apardon at forel.vub.ac.be Fri Jan 28 10:14:12 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Jan 2005 15:14:12 GMT Subject: How to test that an exception is raised ? References: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> <41fa400b$0$2029$6c56d894@feed0.news.be.easynet.net> Message-ID: Op 2005-01-28, StepH schreef : > Thanks for you answer. > I'm new to Python (coming from C/C++). > > Do you say that it's not possible to test (using unittest) if an exception > is well raised if the tested code catch it ? > How to solve this paradoxe ? How to automaticaly test such code ? IMO you want something unittest are not designed for. Unittest are supposed to test for particular results, not for particular behaviour within. If the expected behaviour is that calling code doesn't see an exception raised, then the test passed if no exception was seen. You equally can't test which branch of an if statement was taken or which parameter was given to a helper function in order to get to the desired result. That you internally raise an exception and catches it, is an implementation detail, that normally is of no concern to the tester. -- Antoon Pardon From harold.fellermann at upf.edu Wed Jan 12 13:12:44 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Wed, 12 Jan 2005 19:12:44 +0100 Subject: Why would I get a TypeEror? In-Reply-To: References: Message-ID: <8EA8DF22-64C5-11D9-B3E0-003065FB7B26@upf.edu> On 12.01.2005, at 18:35, It's me wrote: > For this code snip: > > a=3 > .... > b=(1,len(a))[isinstance(a,(list,tuple,dict))] > > Why would I get a TypeError from the len function? because len() works only for sequence and mapping objects: >>> help(len) Help on built-in function len in module __builtin__: len(...) len(object) -> integer Return the number of items of a sequence or mapping. - harold - -- Ceci n'est pas une signature. -- From steve at holdenweb.com Sun Jan 16 12:28:56 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 16 Jan 2005 12:28:56 -0500 Subject: nntplib: abstraction of threads In-Reply-To: References: <1105840367.526347.110160@c13g2000cwb.googlegroups.com> Message-ID: <41EAA458.1020501@holdenweb.com> Werner Amann wrote: > Rakesh schrieb: > > >>What I want is to *group the messages belonging to each thread* . > > > Hello > > Why not sort with Message-ID and References? > Attention - it is a Newbie-Solution. > > import nntplib > > hamster = nntplib.NNTP('127.0.0.1', 119, 'user', 'pass') > resp, count, first, last, name = hamster.group('comp.lang.python') > resp, items = hamster.xover(first,last) > > start_dic = {} > re_dic = {} > numb = 1 > > for id,subject,author,date,message_id,references,size,lines in items: > if 'Re:' not in subject: > start_dic[subject] = (author, message_id) > else: > re_dic[numb] = (subject, author, references) > numb += 1 > > resp = hamster.quit() > > for a in start_dic: > print a > print start_dic[a][0] > for b in re_dic: > if start_dic[a][1] in re_dic[b][2]: > print '|' > print ' ->', re_dic[b][0] > print ' ', re_dic[b][1] > print > Better still, do a Google search on "mail threading algorithm", implement the algorithm described in http://www.jwz.org/doc/threading.html and post your implementation back to the newsgroup :-) regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From lbates at syscononline.com Fri Jan 28 19:45:14 2005 From: lbates at syscononline.com (Larry Bates) Date: Fri, 28 Jan 2005 18:45:14 -0600 Subject: some kind of LFU dict... In-Reply-To: <63b5e209.0501280739.3887d82@posting.google.com> References: <63b5e209.0501280739.3887d82@posting.google.com> Message-ID: Sounds like you want a database (e.g. on disk storage of keys and values that get accessed via the key). Take a look at one of the databases for storing your key/value pairs. Larry Bates Joh wrote: > Hello, > > (first i'm sorry for my bad english...) > > for a program, i need to have some kind of dictionary which will > contain a huge amount of keys and values. i have tried 'to do it > simple' using a normal dict but when available memory was exhausted, > my computer started to be really slow as it swap-ed. > > so i wondered if i can not use some kind of cache, i googled and found > information on LRU, LFU, and LFU interested me : keep only most > frequently used items inside dict (and memory) and writing others on > disk for a possible future reuse. > > here is a silly attempt to do it, it still missed some features but > before to continue i would like to have your opinions. i'm interested > in any propositions or refactorisations :) and btw i may have missed > others already/tuned/better solutions... > > best. > > --- > > import fileinput, pickle, random, shutil, sys > > class sLFU: > TMP = """%s.bak""" > """ a simple kind of Least Frequently Used container""" > def __init__(self, size, ratio, filename = None): > """ filename = a temporary file which will could be deleted""" > self.d = {} # container > self.size, self.ratio = size, ratio > self.freqs, self.fmin = {}, 0 > self.filename = filename > if self.filename: open(self.filename, 'w') > def __setitem__(self, obj, v): > self.d[obj] = v > self.freqs[obj] = self.freqs.get(obj, self.fmin) + 1 > if len(self.d) > self.size: > """ lfu = { (size / ratio) least frequently used > objects... }""" > freqs = [(f, obj) for (obj, f) in self.freqs.items()] > # maybe should i use a generator () like > # ((f, obj) for (obj, f) in self.freqs.items()) > freqs.sort() > lfu = {} > # and here enumerate(sorted(freqs)) > for i, (f, obj) in enumerate(freqs): > if i > self.size / self.ratio: > break > lfu[obj] = self.d[obj] > """ next minimal frequency will be max frequency of the > lfu > (maybe it would be better to substract this from others in > self.freqs)""" > self.fmin = f > """ and now delete theses objects...""" > for obj in lfu: > del self.freqs[obj] > del self.d[obj] > if self.filename: > """ now must save lfu to disk... > as i do not managed to do otherwise, copy file to a > tmp > file and read it line by line, updating when > necessary... > there must be plenty rooms for improvement here :(""" > shutil.copy(self.filename, self.TMP % self.filename) > fhs = open(self.TMP % self.filename) > fh = open(self.filename, 'w') > """ flag to ignore 'value' line""" > ignoreNext = False > for i, line in enumerate(fhs): > """ first copy old lfu which were already set, > updating > them if necessary...""" > if ignoreNext: > ignoreNext = False > continue > line = line.rstrip() > if i % 2 == 0: > obj = self.loads(line) > if obj not in lfu and obj in self.d: > """ obj available from memory, do not to > keep it on disk...""" > ignoreNext = True > continue > elif obj in lfu: > """ obj was available from memory, but as > a lfu, > was removed and must be updated on disk""" > fh.write("%s\n" % line) > fh.write("%s\n" % self.dumps(lfu[obj])) > del lfu[obj] > ignoreNext = True > continue > """ default behaviour : copy line...""" > fh.write("%s\n" % line) > """ from now lfu should contain only unseen lfu > objects, > add them to file...""" > fh = open(self.filename, 'a') > for obj in lfu: > fh.write("%s\n" % self.dumps(obj)) > fh.write("%s\n" % self.dumps(lfu[obj])) > def __getitem__(self, obj): > if obj in self.d: > """ from memory :)""" > return self.d[obj] > if self.filename: > """ if a filename was provided, search inside file if > such an obj is present, then return it ; else raise > IndexErrror.""" > fh = open(self.filename) > found = False > for i, line in enumerate(fh): > line = line.rstrip() > if found: > v = self.loads(line) > self.d[obj] = v > self.freqs[obj] = self.fmin + 1 > return v > if obj == self.loads(line): > found = True > raise KeyError(obj) > """ maybe class methods would have been better here, > actually i would have liked static + class... > totally arbitrary format, haved choosed to use pickle, > odd line contain 'obj' > (next) even line contain 'value' > """ > def dumps(self, s): > return pickle.dumps(s).replace("\n", "\t") > staticmethod(dumps) > def loads(self, s): > return pickle.loads(s.replace("\t", "\n")) > staticmethod(loads) > > > > lfu = sLFU(2, 2, 'slfu.txt') > lfu[1] > 8 > = {'1': > 1fd2 > 'a'} > lfu[2] = [] > lfu[3] = '3' > lfu[2] = [1,] > lfu[2] = [1,2] > lfu[4] = 4 > lfu[5] = '5' > > print "#d", len(lfu.d) > print lfu.d > print "".join(open(lfu.filename).readlines()) From jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com Sun Jan 2 10:57:43 2005 From: jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com (Miklós P) Date: Sun, 2 Jan 2005 16:57:43 +0100 Subject: Python! Is! Truly! Amazing! References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: "Erik Bethke" wrote: > Hello Everyone, > > I have to say: > > Python! Is! Truly! Amazing! > > So I started with python about a month ago and put in 24 hours across > three weekends. ... > > Truly thank you. > > -Erik > I enjoyed to read about your enthusiasm about Python you have recently discovered. :) After checking out your personal and business site, I'm sure you'll be even more pleased when Python will be an essential component in your business and, say, GoPets take on a bit of snake-like inner working. :-) Best, Mikl?s --- Jegenye 2001 Bt. Egyedi szoftverk?sz?t?s, tan?csad?s | Custom software development, consulting Magyarul: http://jegenye2001.parkhosting.com In English: http://jegenye2001.parkhosting.com/en From jerf at jerf.org Fri Jan 21 08:46:18 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 21 Jan 2005 08:46:18 -0500 Subject: Dynamic properties References: Message-ID: On Fri, 21 Jan 2005 23:27:28 +0800, Craig Ringer wrote: > The chances are that whatever you want to do with dynamically created > properties is better done with __getattr__ and __setattr__ instead. Rather than post my own comment, I'd like to highlight this, emphasize it, and underline it twice. The two other repliers I see were nice to explain how to do what you were trying to do, but you probably shouldn't do it that way. class DictWrap(object): def __init__(self, dictToWrap): self.__dict__['dictToWrap'] = dictToWrap def __getattr__(self, key): return self.__dict__['dictToWrap'][key] def __setattr__(self, key, value): self.__dict__['dictToWrap'][key] = value def __delattr__(self, key): del self.__dict__['dictToWrap'][key] Note the direct use of __dict__, which bypasses the *attr machinery. This implements a "full" dict wrap; adjust as needed. Be sure to read about *attr in the Python manual so you understand what they do. You can do more in getattr if you want, but it doesn't sound like you want much else. Python 2.3.4 (#1, Oct 26 2004, 20:13:42) [GCC 3.4.2 (Gentoo Linux 3.4.2-r2, ssp-3.4.1-1, pie-8.7.6.5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class DictWrap(object): ... def __init__(self, dictToWrap): ... self.__dict__['dictToWrap'] = dictToWrap ... def __getattr__(self, key): ... return self.__dict__['dictToWrap'][key] ... def __setattr__(self, key, value): ... self.__dict__['dictToWrap'][key] = value ... def __delattr__(self, key): ... del self.__dict__['dictToWrap'][key] ... >>> a = {'LV1': .5, 'LV10': 5, 'LV100': 50} >>> d = DictWrap(a) >>> d.LV1 0.5 >>> d.LV1 = "Hello!" >>> d.LV5 = 2.5 >>> d.__dict__ {'dictToWrap': {'LV5': 2.5, 'LV10': 5, 'LV100': 50, 'LV1': 'Hello!'}} >>> del d.LV100 >>> d.__dict__ {'dictToWrap': {'LV5': 2.5, 'LV10': 5, 'LV1': 'Hello!'}} >>> From 2004b at usenet.alexanderweb.de Wed Jan 26 11:18:59 2005 From: 2004b at usenet.alexanderweb.de (Alexander Schremmer) Date: Wed, 26 Jan 2005 17:18:59 +0100 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> Message-ID: <1a72l6umj80r6.dlg@usenet.alexanderweb.de> On Tue, 25 Jan 2005 22:08:01 +0100, I wrote: >>>> sys.safecall(func, maxcycles=1000) > could enter the safe mode and call the func. This might be even enhanced like this: >>> import sys >>> sys.safecall(func, maxcycles=1000, allowed_domains=['file-IO', 'net-IO', 'devices', 'gui'], allowed_modules=['_sre']) Every access to objects that are not in the specified domains are restricted by the interpreter. Additionally, external modules (which are expected to be not "decorated" by those security checks) have to be in the modules whitelist to work flawlessy (i.e. not generate exceptions). Any comments about this from someone who already hacked CPython? Kind regards, Alexander From sjmachin at lexicon.net Sat Jan 15 19:34:00 2005 From: sjmachin at lexicon.net (John Machin) Date: 15 Jan 2005 16:34:00 -0800 Subject: How to del item of a list in loop? In-Reply-To: References: Message-ID: <1105835640.771989.163400@f14g2000cwb.googlegroups.com> Fredrik Lundh wrote: > > lst = [i for i in lst if i != 2] > > (if you have 2.4, try replacing [] with () and see what happens) The result is a generator with a name ("lst") that's rather misleading in the context. Achieving the same result as the list comprehension, by doing lst = list(i for ... etc etc), appears to be slower. From http Sat Jan 22 12:09:38 2005 From: http (Paul Rubin) Date: 22 Jan 2005 09:09:38 -0800 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> <7xu0p9lk4h.fsf@ruckus.brouhaha.com> Message-ID: <7x8y6l8k6l.fsf@ruckus.brouhaha.com> "Andrew Koenig" writes: > In this case, I think the right solution to the problem is two-fold: > > 1) from __future__ import lexical_comprehensions > > 2) If you don't import the feature, and you write a program that depends > on a list-comprehension variable remaining in scope, the compiler > should issue a diagnostic along the lines of > > Warning: This program should be taken out and shot. It's not obvious to me how the compiler can tell. Consider: x = 3 if frob(): frobbed = True squares = [x*x for x in range(9)] if blob(): z = x Should the compiler issue a warning saying the program should be taken out and shot? With lexical comprehensions, the program is perfectly valid and sets z to 3 if blob() is true. The whole point of lexical comprhensions is to make Python safe for such programs. Without lexical comprehensions, the program still doesn't depend on the listcomp leakage if frob() and blob() aren't simultaneously true (envision "assert not frobbed" before the "z = x"). So "should be taken out and shot" is maybe a little bit extreme. From chris.cavalaria at free.fr Fri Jan 28 18:19:18 2005 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Sat, 29 Jan 2005 00:19:18 +0100 Subject: Daylight savings and getmtime References: <8b2d5523.0501281503.253269@posting.google.com> Message-ID: <35vvjmF4sbe8jU1@individual.net> Qvx wrote: > Hello, > > I'we written a simple web deployment program which scans for the > changes made to local copy of web site. Changed files are than > packaged into a zip file and deployed to web server. > > Now here's the catch. Changes are computed using (1) log file from the > last deployment and (2) local file system. Log file contains > datestamps (integers) returned from os.path.getmtime(f) function at > the time of last deployment. So i'm comparing two getmtime() values. > The problem is when Daylight saving kicks in: suddenly all local files > are reported as older than they were at the time of deployment. > > How do I compensate for this? > > Thanks, > Tvrtko Never use the local time, always use GMT ( UTC ) time instead. Since it seems os.path.getmtime already gives UTC time, onemust wonder if your OS isn't broken in some way ;) If you can't solve that problem, then use a simple md5sum of the files instead. md5sum isn't that slow to compute and it gives better results than timestanps. Or use a specialised tool like rsync which does a very good job for that. From ville at spammers.com Wed Jan 5 10:02:05 2005 From: ville at spammers.com (Ville Vainio) Date: 05 Jan 2005 17:02:05 +0200 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> Message-ID: >>>>> "Paul" == Paul Rubin writes: Paul> Ville Vainio writes: >> To me, this seems to be the job for the Fedora maintainers, not >> Python maintainers. If something essential is not in the distro >> the distro maintainers have screwed up. Paul> I can't parse that. It says two contradictory things. Paul> Sentence 2 says that if something essential is not in the Paul> (Python) distro then the (Python) distro maintainers have Paul> screwed up. Sentence 1 says it's the Fedora maintainer's Paul> job to deal with it. Huh? By "distro" I meant the Linux distribution, not the Python distribution. Distro is a customary term for a Linux distribution so I didn't qualify the word at the time. -- Ville Vainio http://tinyurl.com/2prnb From peter at engcorp.com Mon Jan 3 17:03:12 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 03 Jan 2005 17:03:12 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com><7xmzvu1ycn.fsf@ruckus.brouhaha.com><7xd5wqd14y.fsf@ruckus.brouhaha.com><7xfz1lal5d.fsf@ruckus.brouhaha.com><7xekh423b6.fsf@ruckus.brouhaha.com> <_rTBd.66275$Jk5.46@lakeread01> Message-ID: Steve Holden wrote: > Whereas the bleached bones of the failed open source projects are > visible for all to see on the SourceForge beach. It occurs to me that the value of those projects can be judged in a number of ways. One of them is in how much those involved in the projects have learned from the experience. Perhaps one rarely starts a second open source project with quite as much rabid, unthinking enthusiasm as one did the first time around, and maybe the world is a better place for it. I know that I've started many one-man projects over the years, and only slowly (I'm a little thick, you see) came to realize that while it's incredibly easy to start something, seeing it through to the end is rather more difficult. At this point, perhaps largely as a result of a new world-view inspired by the agile movement, I rarely start anything... and when I do, it's driven by a strong, recurring need, and I only do just enough to meet that need, in the simplest way I can find. (Often, that ends up not involving a computer.) -Peter From francis.girard at free.fr Fri Jan 21 10:54:52 2005 From: francis.girard at free.fr (Francis Girard) Date: Fri, 21 Jan 2005 16:54:52 +0100 Subject: need help on generator... In-Reply-To: <1106320014.19065.14.camel@bucket.localnet> References: <63b5e209.0501210558.686f5c10@posting.google.com> <1106318290.19065.11.camel@bucket.localnet> <1106320014.19065.14.camel@bucket.localnet> Message-ID: <200501211654.52900.francis.girard@free.fr> Le vendredi 21 Janvier 2005 16:06, Craig Ringer a ?crit?: > On Fri, 2005-01-21 at 22:38 +0800, Craig Ringer wrote: > > consecutive_sets = ( x[offset:offset+subset_size] > > for subset_size in xrange(2, len(x)) > > for offset in xrange(0, len(x) + 1 - subset_size) ) > > Where 'x' is list to operate on, as I should've initially noted. Sorry > for the reply-to-self. > > I did say "awful" for a reason ;-) > > -- > Craig Ringer First, I think that you mean : consecutive_sets = [ x[offset:offset+subset_size] for subset_size in xrange(2, len(x)) for offset in xrange(0, len(x) + 1 - subset_size)] (with square brackets). Second, this is not lazy anymore (like Denis S. Otkidach previous answer was) because the __whole__ list get constructed __before__ any other piece of code have a chance to execute. The type of consecutive_sets is simply a list, not a generator. I'm just trying to understand and obviously I'm missing the point. Thank you Francis Girard FRANCE From steve at holdenweb.com Mon Jan 31 15:35:57 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 15:35:57 -0500 Subject: python and gpl In-Reply-To: <804tv01vej83hm602acfoh291fobov5l4a@4ax.com> References: <7xmzuqgmv6.fsf@ruckus.brouhaha.com> <804tv01vej83hm602acfoh291fobov5l4a@4ax.com> Message-ID: <41FE96AD.5040000@holdenweb.com> Scott Robinson wrote: > On 30 Jan 2005 21:59:25 -0800, Paul Rubin > wrote: > > >>John Hunter writes: >> >>>The question is: does shipping a backend which imports a module that >>>links with GPL code make some or all of the library GPL. >> >>Literally speaking, no, not automatically, any more than driving a car >>makes you into a licensed driver if you weren't one already. But if >>you weren't licensed, then you've broken the law by driving the car. >>So your question should be: 1) is shipping that backend one of the >>things you need the GPL to license you to legally do, and 2) if so, >>does the GPL in fact give you that license? >> >>If you're asking in terms of legal enforcement, the answer is 1) maybe >>and 2) almost certainly not. I think it's better to ask in terms of >>the GPL's spirit. I would say that it's not in the GPL's spirit and >>that GPL die-hards would consider that use objectionable, though they >>might make exceptions for specific cases (so it doesn't hurt to ask). >>Some authors who use the GPL are less strict about how they interpret >>it, so again, the friendly thing to do is ask the author. >> >> * If a backend module somebackend does >> >> import somelib >> >> where somelib is a python wrapper of GPL code, is somebackend GPLd? >> >>It's GPL'd if you GPL it. If you don't GPL it, then distributing it >>it may be a GPL violation that could get you taken to court. I >>believe the FSF's view is that it is fact a violation; however, the >>courts have not yet established this. The law doesn't have a >>black-and-white boundary. It's more like a fractal. The only way to >>find out what a court will decide is to actually try a case there. >> >>Rather than try to probe how closely you can dance around the >>boundaries of the GPL, you might just ask the author of the GPL'd >>library whether what you want to do is ok with him or her. If s/he >>says no and you do it anyway, you're both inviting trouble over the >>possible infringement, and also inviting people to try to use your >>code in ways you don't like. Since the free software movement depends >>on a spirit of cooperation, I think it's best to avoid trying to press >>too hard against the boundaries of anyone's licenses. >> >>http://www.gnu.org/licenses/gpl-faq.html > > > If you read the GPL, it claims everything it can (any "work" created > using GPLed "work"). My guess is that anything that calls the code in > a way not specifically allowed by the author is going to get you into > trouble. IANAL, but from what I can remember about earlier licensing > issues, any code specific for a GPLed library (especially "import") > will get you into to trouble. Having a non-free library with an > identical API and issuing > exec("import "+sys.argv[1]) > where the user can supply sys.argv as the name of the gpl'ed library > will work (I think there is a free/non-free library out there that is > never run, but exists for exactly this condition). > > Scott Robinson > I presume the appropriate way to answer this question is to ask the Gnu, since under these circumstances the Python zen would advise "refuse the temptation to guess". So I am Cc'ing gnu at gnu.org with a request for an answer to the (apparently relatively simple) question: If a Python program imports a module licensed under the GPL, in your opinion does the Python program become a derivative work of the GPL'd software? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From bokr at oz.net Thu Jan 6 16:09:45 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 06 Jan 2005 21:09:45 GMT Subject: Other notes References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> <41DD40F1.5030301@holdenweb.com> Message-ID: <41dda7c5.167823026@news.oz.net> On Thu, 06 Jan 2005 19:24:52 GMT, Andrew Dalke wrote: >Me >>>>> (BTW, it needs to be 1 .. 12 not 1..12 because 1. will be interpreted >>>>> as the floating point value "1.0".)< > >Steve Holden: >> Indeed, but if ".." is defined as an acceptable token then there's >> nothing to stop a strict LL(1) parser from disambiguating the cases in >> question. "Token" is not the same thing as "character". > >Python's tokenizer is greedy and doesn't take part in the >lookahead. When it sees 1..12 the longest match is for "1." > But it does look ahead to recognize += (i.e., it doesn't generate two successive also-legal tokens of '+' and '=') so it seems it should be a simple fix. >>> for t in tokenize.generate_tokens(StringIO.StringIO('a=b+c; a+=2; x..y').readline):print t ... (1, 'a', (1, 0), (1, 1), 'a=b+c; a+=2; x..y') (51, '=', (1, 1), (1, 2), 'a=b+c; a+=2; x..y') (1, 'b', (1, 2), (1, 3), 'a=b+c; a+=2; x..y') (51, '+', (1, 3), (1, 4), 'a=b+c; a+=2; x..y') (1, 'c', (1, 4), (1, 5), 'a=b+c; a+=2; x..y') (51, ';', (1, 5), (1, 6), 'a=b+c; a+=2; x..y') (1, 'a', (1, 7), (1, 8), 'a=b+c; a+=2; x..y') (51, '+=', (1, 8), (1, 10), 'a=b+c; a+=2; x..y') (2, '2', (1, 10), (1, 11), 'a=b+c; a+=2; x..y') (51, ';', (1, 11), (1, 12), 'a=b+c; a+=2; x..y') (1, 'x', (1, 13), (1, 14), 'a=b+c; a+=2; x..y') (51, '.', (1, 14), (1, 15), 'a=b+c; a+=2; x..y') (51, '.', (1, 15), (1, 16), 'a=b+c; a+=2; x..y') (1, 'y', (1, 16), (1, 17), 'a=b+c; a+=2; x..y') (0, '', (2, 0), (2, 0), '') Regards, Bengt Richter From tanghaibao at gmail.com Fri Jan 7 15:37:43 2005 From: tanghaibao at gmail.com (Haibao Tang) Date: 7 Jan 2005 12:37:43 -0800 Subject: Display Function Code Body? Message-ID: <1105130263.788520.96710@f14g2000cwb.googlegroups.com> Hail Python pals! I played with the R (http://r-project.cran.org) last night to do some statistics and it has an interactive session too, and I found a feature that is quite useful. I found by actually typing a function name, the R gives you a code body output. > f1 = function(x){x*x} > f1 function(x){x*x} # more examples (you can try some) > sd function (x, na.rm = FALSE) { if (is.matrix(x)) apply(x, 2, sd, na.rm = na.rm) else if (is.vector(x)) sqrt(var(x, na.rm = na.rm)) else if (is.data.frame(x)) sapply(x, sd, na.rm = na.rm) else sqrt(var(as.vector(x), na.rm = na.rm)) } # ------------------------------------------------ While our python gives an output which is more pro but less informational. >>> def f1(x):return x*x >>> f1 What I would like to do is to write a function like disp(), when typed, it can give you the code infomation. >>> disp(f1) def f1(x): return x*x # or any shallow function code from a file >>> import calendar; disp(calendar.isleap) def isleap(year): """Return 1 for leap years, 0 for non-leap years.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) # surely the compiled function code cannot be displayed >>> disp(blabla) : internal/compiled function Can someone please point out how this can be achieved nicely. I've tried some text searching approach, too dirty I must say. Oh! Thank you ... Haibao Tang From http Mon Jan 10 19:30:21 2005 From: http (Paul Rubin) Date: 10 Jan 2005 16:30:21 -0800 Subject: Writing huge Sets() to disk References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> Message-ID: <7xmzvgren6.fsf@ruckus.brouhaha.com> Martin MOKREJ? writes: > >> I have sets.Set() objects having up to 20E20 items, > just imagine, you want to compare how many words are in English, German, > Czech, Polish disctionary. You collect words from every language and record > them in dict or Set, as you wish. > > Once you have those Set's or dict's for those 4 languages, you ask > for common words and for those unique to Polish. I have no estimates > of real-world numbers, but we might be in range of 1E6 or 1E8? > I believe in any case, huge. They'll be less than 1e6 and so not huge by the standards of today's computers. You could use ordinary dicts or sets. 1e20 is another matter. I doubt that there are any computers in the world with that much storage. How big is your dataset REALLY? > I wanted to be able to get a list of words NOT found in say Polish, > and therefore wanted to have a list of all, theoretically existing words. > In principle, I can drop this idea of having ideal, theoretical lexicon. > But have to store those real-world dictionaries anyway to hard drive. One way you could do it is by dumping all the words sequentially to disk, then sorting the resulting disk file using an O(n log n) offline algorithm. Basically data sets of this size are outside of what you can easily handle with builtin Python operations without putting some thought into algorithms and data structures. From "ribosome" I'm guessing you're doing computational biology. If you're going to be writing code for these kinds of problems on a regular basis, you probably ought to read a book or two on the topic. "CLRS" is a good choice: http://theory.lcs.mit.edu/~clr/ http://mitpress.mit.edu/algorithms/ From whereU at now.com Mon Jan 3 02:59:53 2005 From: whereU at now.com (Eric Pederson) Date: Sun, 2 Jan 2005 23:59:53 -0800 Subject: The Industry choice In-Reply-To: <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> Message-ID: <20050102235953.1631636599.whereU@now.com> Alex Martelli commented: > It's not just _foreign_ companies -- regional clustering of all kinds > of > business activities is a much more widespread phenomenon. Although I'm > not sure he was the first to research the subject, Tjalling Koopmans, > as > part of his lifework on normative economics for which he won the Nobel > Prize 30 years ago, published a crucial essay on the subject about 50 > years ago (sorry, can't recall the exact date!) focusing on > _indivisibilities_, leading for example to transportation costs, and to > increasing returns with increasing scale. Today, Paul Krugman is > probably the best-known name in this specific field (he's also a > well-known popularizer and polemist, but his specifically-scientific > work in economics has mostly remained in this field). > > > China right now)? According to standard economics it should > > not happen - what's the point of getting into this overpriced > > city if elsewhere in this country you can find just as good > > conditions for business. > > Because you can't. "Standard" economics, in the sense of what you > might > have studied in college 25 years ago if that was your major, is quite > able to account for that if you treat spatial variables as exogenous to > the model; Krugman's breakthroughs (and most following work, from what > I > can tell -- but economics is just a hobby for me, so I hardly have time > to keep up with the literature, sigh!) have to do with making them > endogenous. > > Exogenous is fine if you're looking at the decision a single firm, the > N+1 - th to set up shop in (say) a city, faces, given decisions already > taken by other N firms in the same sector. > > The firm's production processes have inputs and outputs, coming from > other firms and (generally, with the exception of the last "layer" of > retailers etc) going to other firms. Say that the main potential > buyers > for your firm's products are firms X, Y and Z, whose locations all > "happen to be" (that's the "exogenous" part) in the Q quarter of town. > So, all your competitors have their locations in or near Q, too. Where > are you going to set up your location? Rents are higher in Q than > somewhere out in the boondocks -- but being in Q has obvious > advantages: > your salespeople will be very well-placed to shuttle between X, Y, Z > and > your offices, often with your designers along so they can impress the > buyers or get their specs for competitive bidding, etc, etc. At some > points, the competition for rents in quarter Q will start driving some > experimenters elsewhere, but they may not necessarily thrive in those > other locations. If, whatever industry you're in, you can strongly > benefit from working closely with customers, then quarter Q will be > where many firms making the same products end up (supply-side > clustering). > > Now consider a new company Z set up to compete with X, Y and Z. Where > will THEY set up shop? Quarter Q has the strong advantage of offering > many experienced suppliers nearby -- and in many industries there are > benefits in working closely with suppliers, too (even just to easily > have them compete hard for your business...). So, there are easily > appreciated exogenous models to explain demand-side clustering, too. > > That's how you end up with a Holliwood, a Silicon Valley, a Milan (for > high-quality fashion and industrial design), even, say, on a lesser > scale, a Valenza Po or an Arezzo for jewelry. Ancient European cities > offer a zillion examples, with streets and quarters named after the > trades or professions that were most clustered there -- of course, > there > are many other auxiliary factors related to the fact that people often > _like_ to associate with others of the same trade (according to Adam > Smith, generally to plot some damage to the general public;-), but > supply-side and demand-side, at least for a simpler exogenous model, > are > plenty. > > Say that it's the 18th century (after the corporations' power to stop > "foreign" competition from nearby towns had basically waned), you're a > hat-maker from Firenze, and for whatever reason you need to move > yourself and your business to Bologna. If all the best hat-makers' > workshops and shops are clustered around Piazza dell'Orologio, where > are > YOU going to set up shop? Rents in that piazza are high, BUT - that's > where people who want to buy new hats will come strolling to look at > the > displays, compare prices, and generally shop. That's close to where > felt-makers are, since they sell to other hat-makers. Should your > business soon flourish, so you'll need to hire a worker, that's where > you can soon meet all the local workers, relaxing with a glass of wine > at the local osteria after work, and start getting acquainted with > everybody, etc, etc... Right, and distribution in general is "clumpy"; i.e. one doesn't find the spatial distribution of people to be uniform (unless at saturation!) I'm decades behind on economics research, but I remember modeling clustering based on mass and distance (the gravity model). On a decision making basis there seems to be an aspect of it that is binary: (0) either give in to gravity and gain shared advantage as part of a massive object, or (1) choose an alternate "location" far enough away not to be much affected by the force of the massive objects, and try to build "mass" there. I suspect Python is a (1) in that regard, but I may be wrong. Gravity as a model of technology adoption appeals to me as I've been thinking about cosmology a fair bit, and I have grave suspicions that much of the universe's dark (and green) matter is in Redmond. Eric Pederson http://www.songzilla.blogspot.com ::::::::::::::::::::::::::::::::::: domainNot="@something.com" domainIs=domainNot.replace("s","z") ePrefix="".join([chr(ord(x)+1) for x in "do"]) mailMeAt=ePrefix+domainIs ::::::::::::::::::::::::::::::::::: From bingham at cenix-bioscience.com Wed Jan 19 03:06:37 2005 From: bingham at cenix-bioscience.com (Aaron Bingham) Date: Wed, 19 Jan 2005 09:06:37 +0100 Subject: Fuzzy matching of postal addresses In-Reply-To: <$aq2IQPQ8X7BFwRy@at-andros.demon.co.uk> References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> <$aq2IQPQ8X7BFwRy@at-andros.demon.co.uk> Message-ID: <41EE150D.5050001@cenix-bioscience.com> Andrew McLean wrote: > Thanks for all the suggestions. There were some really useful pointers. > > A few random points: [snip] > 4. You need to be careful doing an endswith search. It was actually my > first approach to the house name issue. The problem is you end up > matching "12 Acacia Avenue, ..." with "2 Acacia Avenue, ...". Is that really a problem? That looks like a likely typo to me. I guess it depends on your data set. In my case, the addresses were scattered all over the place, with relatively few in a given city, so the likelyhood of two addresses on the same street in the same town was very low. We /wanted/ to check for this kind of 'duplication'. Note that endswith will not deal with 'Avenue' vs. 'Ave.', but I supose a normalization phase could take care of this for you. The Monge algorithm I pointed you to takes care of this pretty nicely. -- -------------------------------------------------------------------- Aaron Bingham Application Developer Cenix BioScience GmbH -------------------------------------------------------------------- From nick at craig-wood.com Thu Jan 27 04:30:01 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 27 Jan 2005 09:30:01 GMT Subject: Classical FP problem in python : Hamming problem References: <63b5e209.0501210558.686f5c10@posting.google.com> <6PKdnVpD-4f3CGvcRVn-gQ@comcast.com> Message-ID: Francis Girard wrote: > Thank you Nick and Steven for the idea of a more generic imerge. You are welcome :-) [It came to me while walking the children to school!] [snip] > class IteratorDeiterator: > def __init__(self, iterator): > self._iterator = iterator.__iter__() > self._firstVal = None ## Avoid consuming if not requested from outside > ## Works only if iterator itself can't return None You can use a sentinel here if you want to avoid the "can't return None" limitation. For a sentinel you need an object your iterator couldn't possibly return. You can make one up, eg self._sentinel = object() self._firstVal = self._sentinel Or you could use self (but I'm not 100% sure that your recursive functions wouldn't return it!) > def __iter__(self): return self > > def next(self): > valReturn = self._firstVal > if valReturn is None: and if valReturn is self._sentinel: > valReturn = self._iterator.next() > self._firstVal = None self._firstVal = self._sentinel etc.. [snip more code] Thanks for some more examples of fp-style code. I find it hard to get my head round so its been good exercise! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From steve at holdenweb.com Sat Jan 1 11:42:16 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Jan 2005 11:42:16 -0500 Subject: what is lambda used for in real code? In-Reply-To: References: Message-ID: Adam DePrince wrote: [...] > > In sort, we must preserve the ability to create an anonymous function > simply because we can do so for every other object type, and functions > are not special enough to permit this special case. > And you'd create an anonymous type how, exactly? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From donn at u.washington.edu Wed Jan 12 14:51:32 2005 From: donn at u.washington.edu (Donn Cave) Date: Wed, 12 Jan 2005 11:51:32 -0800 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <10u5fu3o7v4h9e3@corp.supernews.com> <10u8e65lju3atbd@corp.supernews.com> Message-ID: In article , Jacek Generowicz wrote: > Donn Cave writes: > > > List incomprehensions do not parse well in my eyes. > > Are you familiar with the Haskell syntax for list comprehensions? > > For example: > > http://www.zvon.org/other/haskell/Outputsyntax/listQcomprehension_reference.h I haven't used it more than once or twice in the modest amount of Haskell code I've written, but I've seen it a few times. > Does their striking similarity to mathematical set notation help at > all ? Not a bit. If it's any more obvious than the Python version, I suppose it's the | -- my parser sees [a|b] on the first pass. But it isn't like I ever made any real effort to get comfortable with Python list comprehensions. I was just relaying my (lack of) intuitive grasp of them, compared to map and lambda. Donn Cave, donn at u.washington.edu From aleaxit at yahoo.com Sun Jan 2 18:14:48 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 3 Jan 2005 00:14:48 +0100 Subject: ? about file() and open() References: <1104706607.022890.314500@c13g2000cwb.googlegroups.com> Message-ID: <1gpsduc.bbh4xyw3ymg6N%aleaxit@yahoo.com> Sean wrote: > Was wondering if there was any difference between these two functions. Not today: >>> open is file True they're two names for the same object. Which isn't a function, btw: >>> type(open) the object, as you see, is a type (besides calling it to instantiate it, you might inherit from it, etc). > I have read some text that said file() wasn't introduced until 2.2 and > that it was synonymous with open(). Does this mean that I should be > using file() where I used open() before? According to Guido, you should keep _calling_ 'open' -- that's the name to which a factory function to be called may be bound in the future if and when a good way is found to return filelike objects of some other type depending on circumstances (e.g., one day it might become possible to open some kinds of URL that way). You should use 'file' when you're subclassing, or in other situations where you want to be sure you're naming a type, not a function (few good cases come to mind, but maybe isinstance is a possible case, although likely not _good_...;-). Alex From jzgoda at gazeta.usun.pl Tue Jan 25 17:03:04 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Tue, 25 Jan 2005 23:03:04 +0100 Subject: python without OO In-Reply-To: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: Davor wrote: > Is it possible to write purely procedural code in Python, or the OO > constructs in both language and supporting libraries have got so > embedded that it's impossible to avoid them? Sure, but you will got problem with libraries. Some of them are in fact frameworks and need some subclassing or other OO fluff. > Also, is anyone aware of > any scripting language that could be considered as "Python minus OO > stuff"? (As you can see I'm completely new to Python and initially > believed it's a nice&simple scripting language before seeing all this > OO stuff that was added in over time) Icon, the language for OO haters. May I ask why you do you hate OO so much? -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From honor2003 at yahoo.com Tue Jan 4 00:50:52 2005 From: honor2003 at yahoo.com (john) Date: 3 Jan 2005 21:50:52 -0800 Subject: FS: PC Doctor Message-ID: <1104817852.587703.310920@c13g2000cwb.googlegroups.com> Bought from http://www.PCbeginner.com two weeks ago. Now my computer got fixed and I do not need it any more. Asking $15 only. I will ship to you by first class mail. Email: honor2003 at yahoo.com From zslist at gmail.com Thu Jan 6 19:05:07 2005 From: zslist at gmail.com (zslist at gmail.com) Date: 6 Jan 2005 16:05:07 -0800 Subject: python reading/writing ms-project files? Message-ID: <1105056307.322989.54930@z14g2000cwz.googlegroups.com> any existing or pointers on how to do this? thanks. From bokr at oz.net Mon Jan 24 02:30:32 2005 From: bokr at oz.net (Bengt Richter) Date: Mon, 24 Jan 2005 07:30:32 GMT Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) References: <41f325b5.1576259210@news.oz.net> <6I2dnYLoXdcTmGncRVn-vw@comcast.com> Message-ID: <41f490e8.1669238027@news.oz.net> On Sun, 23 Jan 2005 13:14:10 -0700, Steven Bethard wrote: >Bengt Richter wrote: >> On Sat, 22 Jan 2005 16:22:33 +1000, Nick Coghlan wrote: >> >> [Steven Bethard] >>>> > If you really want locals that don't contribute to arguments, I'd be >>>> > much happier with something like a decorator, e.g.[1]: >>>> > >>>> > @with_consts(i=1, deftime=time.ctime()) >>>> > def foo(x, y=123, *args, **kw): >>>> > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime >>>> > >>>> > Then you don't have to mix parameter declarations with locals >>>> > definitions. [...] [Nick Coghlan] >>>Raymond's constant binding decorator is probably a good model for how to do it: >>>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 >>> >> >> [Bengt Richter] >> I thought so too. I modified it to accept **presets as a keyword argument >> and generate constants and assignments from its values matching assignment names >> when the rhs was __frompresets__, e.g., >> >> >>> from makeconstpre import make_constants as pre >> >>> import time >> >>> @pre(verbose=True, deftime=time.ctime(), a=1, b=2, c=3, pi=__import__('math').pi) >> ... def foo(): >> ... deftime = __frompresets__ >> ... b, a = __frompresets__ >> ... c = __frompresets__ >> ... pi = __frompresets__ >> ... return locals() >> ... >> __frompresets__ : deftime --> Sat Jan 22 20:18:09 2005 >> __frompresets__ : ('b', 'a') --> (2, 1) >> __frompresets__ : c --> 3 >> __frompresets__ : pi --> 3.14159265359 >> locals --> > [Steven Bethard] >Hmm... Having to state > deftime = __frompresets__ >when you've already stated > deftime=time.ctime() >seems a little redundant to me... > Yeah, but as a quick hack, it made the byte code twiddling all changing byte codes in-place. I didn't want to verify that byte code wouldn't need relocation fixups if I inserted something, (unless of course within a suite with branches or loops) but hopefully it's easily so at the beginning. BTW, unlike default arguments, varname = __frompresets__ will work anywhere in the code, (for the current decorator version) and the generated byte code will have a load of an appropriate constant (the same one if the same name is being assigned). This would be tricky to get right if done in a hidden just-in-time manner only in branches that used the values, but hidden initialization of the whole presets set at the beginning should be relatively easy if there are no relocation problems. So, e.g., for >>> presets = dict(a=1, b=2, deftime=__import__('time').ctime()) in the decorator args, the next version will act as if the decorated function had the source code >>> print '%s = __frompresets__' % ', '.join(sorted(presets)) a, b, deftime = __frompresets__ for the current version, except that it will be hidden. Regards, Bengt Richter From ian at kirbyfooty.com Sun Jan 2 17:12:04 2005 From: ian at kirbyfooty.com (ian at kirbyfooty.com) Date: 2 Jan 2005 14:12:04 -0800 Subject: ctypes NULL pointers; was: Python To Send Emails Via Outlook Express In-Reply-To: References: Message-ID: <1104703924.410611.35820@c13g2000cwb.googlegroups.com> Thanks again Lenard!! From craig at postnewspapers.com.au Sat Jan 8 00:40:40 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 08 Jan 2005 13:40:40 +0800 Subject: Help uninstalling/installing Python 2.4 In-Reply-To: References: Message-ID: <1105162839.31717.21.camel@rasputin.localnet> On Sat, 2005-01-08 at 08:08, Baggs wrote: > Tk calls did not work, the output from Python when running a program > stated that I probably did not have TK installed. I got and installed > TK 8.4 and the problem persisted (I know I should have written down the > exact error, but I didn't... but the story gets worse!) You probably didn't have the -devel packages for Tcl and Tk installed, so Python would've decided you didn't have Tk and not built tkinter support. Chances are if you install the devel packages and recompile Python, it'll work fine. > when I re-installed I still have > problems.. everything installs ok, but now I get the following errors > with Python... > > bash: /usr/bin/python: No such file or directory Is that when you run a script, or when you type 'python' in your shell? If the former, make sure you write your scripts with a #! like this: #!/usr/bin/env python not #!/usr/bin/python That way, the right python will get run so long as it's on your path - it doesn't have to be in /usr/bin. If the error is when typing 'python' on the command line, ensure you have no aliases for the name 'python' hanging around ('alias python' to find out). Also check what is actually being run with 'which python' and see if it's a wrapper script that calls /usr/bin/python. > when I go to /usr/local/bin and type ./python I get > > Python 2.4 (#6, Jan 7 2005, 18:44:57) > [GCC 3.4.1 (Mandrakelinux 10.1 3.4.1-4mdk)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > Traceback (most recent call last): > File "/etc/pythonrc.py", line 2, in ? > import readline > ImportError: No module named readline > > I think some paths are screwed up.. can someone take pity on me and give > me a hand. I'd say that'll be the same as with Tkinter - you probably didn't have the GNU readline development headers installed, so Python disabled readline support when it was compiled. That's just a guess, but seems pretty likely. -- Craig Ringer From fumanchu at amor.org Wed Jan 26 01:46:34 2005 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 25 Jan 2005 22:46:34 -0800 Subject: I want update one record using ADO,but I can't ,why? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339829C@exchange.hqamor.amorhq.net> nightmarch wrote: > Sorry, I mean this code line " rs.Supports( wc.constants.adUpdate ) " > got False result, So I can't update one record,i.e. I can't execute > this code "rs.Fields.Item(0).Value = 11". > > And , if code is written like this: > > ## conn.Open(connStr ) > rs.Open( tblName, conn, wc.constants.adOpenKeyset, > wc.constants.adLockOptimistic ) > > rs.Fields.Item(0).Value = 11 > s.Update() > ##>code------------------------- > > I got error msg like following: > > ## self._oleobj_.Invoke(*(args + (value,) + defArgs)) > com_error: (-2147352567, '\xb7\xa2\xc9\xfa\xd2\xe2\xcd\xe2\xa1\xa3', > (0, 'ADODB.Field', 'Current Recordset does not support updating. This > may be a limitation of the provider, or of the selected locktype.', > 'C:\\WINNT\\HELP\\ADO210.CHM', 0, -2146825037), None) > ##>errorMsg---------------------------- Well, without knowing your entire Oracle setup, I'm not sure how far one can get. My only thought is to try a full SELECT statement instead of just the tablename, and preface the tablename with the schema, something like: "select * from %s.%s;" % (schema, tblName) It's possible the trailing semicolon is important to close the statement. The next thing to check would be permissions. Robert Brewer MIS Amor Ministries fumanchu at amor.org From mgarrett at garrett-technologies.com Wed Jan 26 23:53:02 2005 From: mgarrett at garrett-technologies.com (mcg) Date: 26 Jan 2005 20:53:02 -0800 Subject: String Fomat Conversion Message-ID: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> Investigating python day 1: Data in file: x y 1 2 3 4 5 6 Want to read file into an array of pairs. in c: scanf("%d %d",&x,&y)---store x y in array, loop. How do I do this in python?? In the actual application, the pairs are floating pt i.e. -1.003 From itsme at yahoo.com Tue Jan 11 23:22:00 2005 From: itsme at yahoo.com (It's me) Date: Wed, 12 Jan 2005 04:22:00 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: "Robert Kern" wrote in message news:cs1mp9$sg9$1 at news1.ucsd.edu... > > That's *it*. So, how would you overload an operator to do: With native complex support: def twice(a): return 2*a print twice(3+4j), twice(2), twice("abc") Let's presume for a moment that complex is *not* a native data type in Python. How would we implement the above - cleanly? From rnd at onego.ru Fri Jan 7 01:59:24 2005 From: rnd at onego.ru (Roman Suzi) Date: Fri, 7 Jan 2005 09:59:24 +0300 (MSK) Subject: Python evolution: Unease In-Reply-To: <7xd5wh7qdf.fsf@ruckus.brouhaha.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41dcf582.122188317@news.oz.net> <7xd5wh7qdf.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 6 Jan 2005, Paul Rubin wrote: >software when I buy a new computer, or at least a new hard drive. I >don't try to migrate system or configuration files. I just install >the OS distro from scratch and migrate my user files. > >> There are several parts to those frustrations. But you are presuming >> that they would have been solved for you and put on a DVD with all >> dependency problems resolved. Ok, let's assume that. In that case, >> an installation stub module could just as well have the solution built >> into it as to what versions etc are needed to make the module work. I do not like the idea of having stubs. Once I had an experience working with CPAN (I tried to install SpamAssassin and it required some specific modules.) "Magic" install shell, provided by Perl, upgraded half the Perl distro, including newer version of Perl! So, I do like Python distutils better. it is not a major problem to install something even if it required something else. Of course, this depends on the package authors. >How can it work just as well, when it requires a high-speed internet >connection which I might not have? And why is "just as well" good >enough, given how inconvenient and error-prone it is, compared with >just installing from a DVD once and for all? To have any attraction >what ever, the installation stub scheme (for me at least) has to work >"an order of magnitude better", not "just as well", as a one-time >complete install. > >> To bring a large collection into version-alignment ISTM you need a version >> freeze across too many libraries of different kinds with different >> development schedules and resources to make it reliable. > >One part of the problem is excessive version dependence between >package X and package Y. That's why I think there should be more >integration within packages, i.e. the Python distro should include a >lot more modules that you currently have to download from other >places. > >> I realize this problem has been "solved" with various RPM and >> app-loading methods, but I think python could wrap its solution >> nicely. I don't think distutils and setup.py is easy enough to >> create (at least I have been somewhat frustrated in using it >> effectively), though it deals with a lot of what has to be done. > >Since all these schemes have failed whenever they've been tried, all I >can think is that it's a harder problem than it sounds. I have installed many packages with Distutils, and usually there were no problems. If there were, they were no greater than installing some devel library and/or adding an include directory. So, Distutils, IMHO, are successful. Yes, probably there could be a no-brainer script to run install directly from zip and/or tar.gz/bz2 file, but I usually check md5, pgp sigs and look inside anyway before running something. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From eric_brunel at despammed.com Mon Jan 3 10:23:21 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 03 Jan 2005 16:23:21 +0100 Subject: Tkinter zoom box In-Reply-To: References: Message-ID: <41d96195$0$4122$8fcfb975@news.wanadoo.fr> Philippe C. Martin wrote: > Hi, > > I have the following convern: I have Tkinter applications that require a zoom > box, and have had the following behavior without changing a line of code: > > 1) Mandrake 10.0/KDE 3.2/Python 2.3: no zoom box > 2) Mandrake 10.0/KDE 3.2/Python 2.4: zoom box shows > 3) Mandrake 10.1/KDE 3.3/Python 2.4: no zoom box > 4) Mandrake 10.1/Gnome 2.6/Python 2.4: zoom box shows > > I know that sounds strange, but I am fairly certain this is what happened. > > Is there a way to _force_ that zoom box ? What do you call a "zoom box"? There's no widget with this name in "regular" Tkinter widgets, so it must be built with some other one... Which one is it? A button, a menubutton, or what else? If you had some (simple) code showing the problem, that would also help a lot to understand what's going on... -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From guettli at thomas-guettler.de Mon Jan 10 08:24:41 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Mon, 10 Jan 2005 14:24:41 +0100 Subject: Powerful CGI libraries for Python? References: Message-ID: Am Mon, 10 Jan 2005 10:11:16 +0800 schrieb sam: > Hi, > > I m looking for a CGI libraries just like perl's CGI.pm for Python. > From google, I found quite a few of CGI libraries already written for > python. But I haven't had experience to try any of them in Python. > > Can anyone share your Python CGI experience with me? Which library is > better in terms of functionality and stability? Hi, in the standard library there is cgi and cgitb. If you just want to write a small cgi script, both modules should be all you need. I found quixote simple and easy to learn. Quixote 1.x is quite stable. The version I use is more then six months old, and there is no need to update. Take a look at: http://www.python.org/cgi-bin/moinmoin/WebProgramming Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From steve at holdenweb.com Wed Jan 12 15:42:58 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 12 Jan 2005 15:42:58 -0500 Subject: Newbie: Pythonwin In-Reply-To: References: Message-ID: <41E58BD2.2030102@holdenweb.com> Brent W. Hughes wrote: > 1) I'm running a program within Pythonwin. It's taking too long and I want > to stop/kill it. What do I do (other than ctrl-alt-del)? > When PythonWin is running it puts an icon in the system tray. You can right-mouse on this icon and select "Break into running code". > 2) I'm running a long program and I want to minimize it to let it continue > to run in the background while I do something else in the foreground. I try > clicking on Pythonwin's minimize box but it doesn't respond until the Python > program finally quits Then it minimizes! Any way I can do what I want > here? > Sorry, I think you'll need to ask Mark Hammond to have PythonWin pump events more aggressively or some such. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From ashot at removethismolsoft.com Sat Jan 15 19:23:26 2005 From: ashot at removethismolsoft.com (Ashot) Date: Sat, 15 Jan 2005 16:23:26 -0800 Subject: video analysis with python Message-ID: Hi, I need to write a video analysis tool which extracts statistics from microsocope video. Essentially what I need is to translate the video data into numerical matrices. I have been using Python for the past 1.5 years anytime I could for absolutely everything, because it has every library imaginable... Alas, I can not find a library for decoding video/using codecs. The only solution I have been able to come up with is to create an image sequence and load those in with PIL, however this is not really feasible as the images are too large (nor is it proffessional). Is there a library or project that I have missed, or is there a way to incorporate something like vfw.lib directly? If there isn't I think this would be a pretty large whole in Python's arsenal. Thanks in advance for any help. -- Ashot Petrosian University of Texas at Austin, Computer Sciences From Serge.Orlov at gmail.com Fri Jan 14 14:46:57 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 14 Jan 2005 11:46:57 -0800 Subject: Why 'r' mode anyway? (was: Re: Pickled text file causing ValueError (dos/unix issue)) References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> <41e80785$0$6203$e4fe514c@news.xs4all.nl> Message-ID: <1105732017.740111.135650@f14g2000cwb.googlegroups.com> Irmen de Jong wrote: > Tim Peters wrote: > > > Yes: regardless of platform, always open files used for pickles in > > binary mode. That is, pass "rb" to open() when reading a pickle file, > > and "wb" to open() when writing a pickle file. Then your pickle files > > will work unchanged on all platforms. The same is true of files > > containing binary data of any kind (and despite that pickle protocol 0 > > was called "text mode" for years, it's still binary data). > > I've been wondering why there even is the choice between binary mode > and text mode. Why can't we just do away with the 'text mode' ? We can't because characters and bytes are not the same things. But I believe what you're really complaining about is that "t" mode sometimes mysteriously corrupts data if processed by the code that expects binary files. In Python 3.0 it will be fixed because file.read will have to return different objects: bytes for "b" mode, str for "t" mode. It would be great if file type was split into binfile and textfile, removing need for cryptic "b" and "t" modes but I'm afraid that's too much of a change even for Python 3.0 Serge. From zombiehunter at gmail.com Mon Jan 24 08:43:14 2005 From: zombiehunter at gmail.com (zombiehunter at gmail.com) Date: 24 Jan 2005 05:43:14 -0800 Subject: short programming projects for kids In-Reply-To: References: <1106332638.595750.150590@c13g2000cwb.googlegroups.com> Message-ID: <1106574194.187150.112570@c13g2000cwb.googlegroups.com> I was just about to suggest Livewires. I'm a programming newb (35 yrs old ) haha- and I'm finding the lIvewires course pretty helpful, even though it's geared for teens. I suppose my brain works on that functional level. :) And a book that's great for beginner's (know you probably don't want to buy books but just wanted to throw this info out there in case it helps somehow) is Python Programming for the Absolute Beginner by Michael Dawson. I'm working through that too and it's wonderful. It had many fairly simple to implement programs (lots of them simple games) that build on each other in a very easily comprehended, step-by-step manner. Hope htis helps- From x2164 at mailcity.com Sun Jan 30 22:52:55 2005 From: x2164 at mailcity.com (x2164 at mailcity.com) Date: 31 Jan 2005 03:52:55 GMT Subject: test_socket.py failure References: <41FD4F53.2040507@holdenweb.com> Message-ID: Steve Holden wrote: > x2164 at mailcity.com wrote: > > hi all, > > > > Linux 2.4.28 > > Glibc 2.2.5 > > gcc 2.95.3 > > > > > > I'm new to Python. > > > > I've compiled Python 2.4 from tar file. > > > > When running 'make test' i'm getting a failure > > in test_socket. > > > > Running './python Lib/test/test_socket.py' yields: > > > > > > ====================================================================== > > ERROR: testGetServBy (__main__.GeneralModuleTests) > > ---------------------------------------------------------------------- > > Traceback (most recent call last): > > File "Lib/test/test_socket.py", line 330, in testGetServBy > > port2 = socket.getservbyname(service) > > error: service/proto not found > > > > ---------------------------------------------------------------------- > > Ran 58 tests in 3.826s > > > > > > > > The value of 'service' was "daytime". > > > > After much hand wringing, editing, and use of 'print' > > statements i commented out line 330, > > '# port2 = socket.getservbyname(service)' and replaced it > > with the line 'port2 = port'. > > > > Running './python Lib/test/test_socket.py' now yields: > > > > > > testGetServBy (__main__.GeneralModuleTests) ... ok > > . > > . > > . > > ---------------------------------------------------------------------- > > Ran 58 tests in 5.181s > > > > OK > > > > > > Located the code for 'socket_getservbyname' in > > 'Modules/socketmodule.c' where the call to the glibc > > function 'getservbyname' is made: > > > > Py_BEGIN_ALLOW_THREADS > > sp = getservbyname(name, proto); > > Py_END_ALLOW_THREADS > > if (sp == NULL) { > > PyErr_SetString(socket_error, "service/proto not found"); > > return NULL; > > } > > > > > > The only call of socket.getservbyname that failed was when > > it was passed the single argument. Since the error message > > "service/proto not found" seems to only be generated upon > > failure of gibc's 'getservbyname' could it be that > > 'PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto)' > > generates values for 'name' and/or 'proto' that cause the > > failure? > > > > My search for prior reports of failure at line 330 found > > a mention of problems at line 331. > > > > Well, at any rate, if someone could point me down the > > correct path on this i would appreciate it. > > > Compiling from source requires you to indicate the features that you > want compiled in. Without thread support, sockets din't work, so it > looks like you need to configure threads in. IIRC you do this by editing > the Modules.? file. > regards > Steve hi Steve, Here's a cut down version of the compilation line for socketmodule.c which contains the 'socket_getservbyname' code: gcc -pthread -DNDEBUG ... -c /usr/src/Python-2.4/Modules/socketmodule.c -o build/temp.linux-i686-2.4/socketmodule.o Is '-pthread' the type of thread i need? I'm still curious why only the call with one argument to 'socket.getservbyname' fails while the two other calls which pass two arguments don't fail. Any ideas? pete jordan x2164 at mailcity com -- ............ From steven.bethard at gmail.com Fri Jan 7 15:12:58 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Jan 2005 13:12:58 -0700 Subject: switching an instance variable between a property and a normal value Message-ID: I'd like to be able to have an instance variable that can sometimes be accessed as a property, and sometimes as a regular value, e.g. something like: py> class C(object): ... def usevalue(self, x): ... self.x = x ... def usefunc(self, func, *args, **kwds): ... self._func, self._args, self._kwds = func, args, kwds ... self.x = C._x ... def _get(self): ... return self._func(*self._args, **self._kwds) ... _x = property(_get) ... py> c = C() py> c.usevalue(4) py> c.x 4 py> c.usefunc(list) py> c.x # I'd like this to print [] Of course, the code above doesn't do what I want because C._x is a property object, so the assignment to self.x in usefunc just adds another name for that property object. If I use self._x (or getattr(self, '_x'), etc.) then self._func only gets called that one time: py> class C(object): ... def usevalue(self, x): ... self.x = x ... def usefunc(self, func, *args, **kwds): ... self._func, self._args, self._kwds = func, args, kwds ... self.x = self._x ... def _get(self): ... return self._func(*self._args, **self._kwds) ... _x = property(_get) ... py> c = C() py> c.usefunc(list) py> c.x is c.x # I'd like this to be False True Is there any way to get the kind of behavior I'm looking for? That is, is there any way to make self.x use the property magic only some of the time? Steve P.S. Yes, I know I could make both access paths run through the property magic, with code that looks something like: py> class C(object): ... _undefined = object ... def __init__(self): ... self._value, self._func = C._undefined, C._undefined ... def usevalue(self, x): ... self._value = x ... self._func = C._undefined ... def usefunc(self, func, *args, **kwds): ... self._func, self._args, self._kwds = func, args, kwds ... self._value = C._undefined ... def _get(self): ... if self._value is not C._undefined: ... return self._value ... if self._func is not C._undefined: ... return self._func(*self._args, **self._kwds) ... raise AttributeError('x') ... x = property(_get) ... py> c = C() py> c.usevalue(4) py> c.x 4 py> c.usefunc(list) py> c.x is c.x False This code is kinda complicated though because I have to make sure that only one of self._func and self._value is defined at any given time. From paul at subsignal.org Thu Jan 27 08:11:01 2005 From: paul at subsignal.org (paul koelle) Date: Thu, 27 Jan 2005 14:11:01 +0100 Subject: subprocess.Popen() redirecting to TKinter or WXPython textwidget??? In-Reply-To: <41f811fe$0$148$3a628fcd@reader1.nntp.hccnet.nl> References: <41f80b1b$0$148$3a628fcd@reader1.nntp.hccnet.nl> <1106775371.049857.36360@z14g2000cwz.googlegroups.com> <41f811fe$0$148$3a628fcd@reader1.nntp.hccnet.nl> Message-ID: <35s44aF4qo76cU1@individual.net> Ivo Woltring wrote: > The output of mencoder is not readable with readlines (i tried it) because > after the initial informational lines You don't get lines anymore (you get a > linefeed but no newline) > The prints are all on the same line (like a status line) > something like > Pos: 3,1s 96f ( 0%) 42fps Trem: 0min 0mb A-V:0,038 [171:63] Have you tried popen3 with stdout and stderr? hth Paul From steve at holdenweb.com Wed Jan 19 08:58:10 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Jan 2005 08:58:10 -0500 Subject: generator expressions: performance anomaly? In-Reply-To: <7xhdlejenm.fsf@ruckus.brouhaha.com> References: <377Hd.77904$Jk5.30235@lakeread01> <41ED1C0F.4030800@holdenweb.com> <7xhdlejenm.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steve Holden writes: > >>You probably already know that sensible compiled language systems have >>used constant folding since time immemorial, but Python has always >>eschewed it. That's what comes of being a pragmatist's language: if >>such optimizations really are required the programmer is expected to >>perform them. > > > You mean the lack is deliberate? I just figured it was an artifact of > the implementation and that PyPy had some reasonable chance of fixing it. No, it's not been deliberately omitted, it's just not a development priority. Pragmatic Python programmers are prepared to do the folding themselves in the (exceptionally rare) cases where it has a significant effect on performance. PyPy may or may not fix it. And, of course, a dynamic language has rather less ability to take advantage of more advanced optimizations since it's much harder to guarantee functional behavior for any given subexpression. Once side effects rear their ugly heads all bets are off. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From cold_fusion at fastmail.fm Wed Jan 5 16:40:07 2005 From: cold_fusion at fastmail.fm (Avi Berkovich) Date: Wed, 05 Jan 2005 23:40:07 +0200 Subject: Reaching the real world In-Reply-To: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> References: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> Message-ID: <41dc5ef2$1@news.012.net.il> Hey, If you want to do something simple, you can use your parallel port to control other circuitry. I've made an extension module before for DLPortIO which is a free lib for doing port IO in win2k/xp. I have to dig it out of my hdds/discs if you want it, but it's really easy to make with pyrex anyway. Avi. From steven.bethard at gmail.com Tue Jan 4 10:20:34 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 04 Jan 2005 15:20:34 GMT Subject: Lambda as declarative idiom (was RE: what is lambda used for in real code?) In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> Message-ID: <6vyCd.617042$wV.607079@attbi_s54> Roman Suzi wrote: > On Mon, 3 Jan 2005, Steven Bethard wrote: > > >>Roman Suzi wrote: >> >>>I wish lambdas will not be deprecated in Python but the key to that is >>>dropping the keyword (lambda). If anybody could think of a better syntax for >>>lambdas _with_ arguments, we could develop PEP 312 further. >> >>Some suggestions from recent lambda threads (I only considered the ones >>that keep lambda as an expression): > > Wow! Is there any wiki-page these could be put on? It's now on: http://www.python.org/moin/AlternateLambdaSyntax and I added Bengt Richter's and your recent suggestions. Steve From mefjr75 at hotmail.com Tue Jan 25 22:36:30 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 25 Jan 2005 19:36:30 -0800 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> Message-ID: <1106710590.312881.222520@c13g2000cwb.googlegroups.com> Davor, I was gonna let it go but .... I never was good at shutin up ;) The greatest strength a manager can have is delegation. And with that add the ability to best use the resources available . It seems you are telling me that : 1) You do not understand most programming concepts 2) You are not willing to learn. 3) You might not have the skill set to manage developers What does it all mean? Stop telling your programmers how to program! Seriously NOW. If you managed a group of doctors would you tell them that they could only use techniques that *YOU* understood, even if the were STANDARD and well known by others? That brings me to the other point , you have mentioned design patterns, did YOU read GOF Design Patterns? It seems to me that if you were to spend a week with the book you could grasp at least the gist of the major patterns.They are pretty simple and quite informative. You should at least speak the lingo of the field you manage in. If your guys occasionally do something and you feel lost, that is a sign you are normal. Oh yea and don't confuse programming idioms of various language with design patterns. Start cultivating a talent for setting clear goals and clear objectives , learn how to manage people and have better communication (that is two way) with your developers. Your job is to be a manager , so __manage__ your team , have the overview have the design concept have the long road in mind and then at the same time listen to your team and do what it takes to smooth the rough edges and move the project forward, don't fiddle the details unless needed. Set goals not details unless they are real restrictions. Life is full of real restrictions and so are most projects so avoid getting into the unrealistic and unreasonable. Let your talent make you look good and help them do it. This advice holds true for every field I can think of. Ignorance can be remedied with a book , but apathy sometimes needs a swift kick in the ass. Hope you do well, M.E.Farmer From mcturra2000 at yahoo.co.uk Tue Jan 4 05:34:36 2005 From: mcturra2000 at yahoo.co.uk (Mark Carter) Date: Tue, 04 Jan 2005 10:34:36 +0000 Subject: How can engineers not understand source-code control? In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> <41d8417e$0$14596$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: <41da713a$0$610$ed2619ec@ptn-nntp-reader03.plus.net> > Cameron Laird wrote: > >> I've seen the infatuation for Excel (and so on) for years, True story: when I began working for my current employer, there was a guy there doing some work with a spreadsheet. He was given two weeks to perform the task. It was a loss-leader to get some real work from the client. There already existed a spreadsheet, which did financial projections. It used VBA fairly extensively, and his task was to adapt it to remove the VBA code. This means converting things like functions into equivalent cell formulae. The rationale behind this is that VBA is too hard for most people to understand, whereas formulae are easier to understand. Conditionals look really confusing in formulae, and I don't know how he coped with loops. And then, of course, you have to replicate them to every cell that requires them. Can you imagine that? Is this very the definition of madness, or what? The whole thing was a gigantic spreadsheet (I can't remember, it was either 9Mb or 90Mb in size), and kept crashing every few minutes. Utter utter insanity. Whenever he went back the client, she demanded improvements. We had effectively told her that she could have whatever whe wanted. And oh, it would only take 2 weeks. The managers never pulled the plug on the project. Apparently, our guy sat in on a conversation that the client had with a potential contractor who would replace the spreadsheet. His first question was, surprise surprise, "why on earth did you try to do it that way?" The thing is, our guy was scheduled to be booted out the door because he was in a business area that was being discontinued by us, so from my employer's point-of-view, I guess that all this lunacy actually made sense. From fredrik at pythonware.com Tue Jan 18 02:19:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 18 Jan 2005 08:19:02 +0100 Subject: Problem parsing namespaces with xml.dom.minidom References: <41eca38d@clear.net.nz> Message-ID: Mike McGavin wrote: > I'm not terribly experienced with XML in general, so it's possible that I'm just incorrectly > interpreting how things are supposed to work to begin with. If this is the case, please accept my > apologies, but I'd like any suggestions for how I should be doing it. I'd really just like to be > able to parse an XML document into a DOM, and then be able to pull out elements relative to their > namespaces. is the DOM API an absolute requirement? From peter at engcorp.com Tue Jan 18 11:04:01 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Jan 2005 11:04:01 -0500 Subject: Advice to a Junior in High School? In-Reply-To: <1106034944.793262.19950@z14g2000cwz.googlegroups.com> References: <1106034944.793262.19950@z14g2000cwz.googlegroups.com> Message-ID: collegebabe2004 wrote: > I would suggest taking Japanese because you will have to work with them > eventually if you do decide to choose compsci as your proffesion. Over what time frame should I expect this requirement to become critical? I'd like to know so I can reserve a spot in the next Japanese course in the area, if you think it's really urgent. Also, should I plan on adopting various aspects of the Japanese culture as well, or will a mastery of the language be sufficient? -Peter From peter at engcorp.com Sat Jan 8 12:38:18 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Jan 2005 12:38:18 -0500 Subject: sorting on keys in a list of dicts In-Reply-To: References: <10tr9ejf05pv660@corp.supernews.com> Message-ID: Nick Coghlan wrote: > Stability in sorting is a property not to be sneezed at - it means > switching to sorting by a second key gives the effect of "sort by key 1, > then by key 2", whereas that doesn't hold with an unstable sort Assuming "key 1" refers to the first key, and "key 2" to the second key, then I believe you meant "gives the effect of 'sort by key 2 then by key 1'". In other words, if you have a stable sort algorithm and do one sort operation using key 2, then a second sort operation using key 1, it's the same as doing a single sort with the key combination "key 1, key 2", not the other way around. -Peter From flamesrock at gmail.com Sun Jan 2 23:54:20 2005 From: flamesrock at gmail.com (flamesrock) Date: 2 Jan 2005 20:54:20 -0800 Subject: XML: Better way to accomplish this? Message-ID: <1104728060.417168.277780@c13g2000cwb.googlegroups.com> Hi, I'm working on creating an xml structure like the following, as effiecienty and elegantly as possible using minidom preferably: # # # # 0 # # # 0 # # # 0 # # # 0 # # # # # # # # # # 0 # # # 0 # # # 0 # # # # # # # # # # 0 # # # 0 # # # 0 # # # # # # # # # # 0 # # # 0 # # # 0 # # # # # (left out) The following code accomplishes that, but being a newb to xml..I'm not sure if this can be done a better (I'd like to stick with dom due to the nature of this app): (left textnode parts like mayor, cityname out to keep code concise for now) # from xml.dom.minidom import parseString # #create a new document # scoreXML = parseString(u''.encode('UTF-8')) # art = scoreXML.documentElement # # #create a total population, cities and some city elements # population = scoreXML.createElementNS(None,u'population') # cities = scoreXML.createElementNS(None,u'cities') # city1 = scoreXML.createElementNS(None,u'city1') # city2 = scoreXML.createElementNS(None,u'city2') # city3 = scoreXML.createElementNS(None,u'city3 and so on') # # #add it under the region element # art.appendChild(population) # art.appendChild(cities) # # # create a total element with a population number inside # # and do this for all RCI numbers # population.appendChild(scoreXML.createElementNS(None,u'total')) # total = scoreXML.createTextNode(u'0') # population.firstChild.appendChild(total) # #will get RCI with seperate function # RCI = [scoreXML.createTextNode(u'0'), # scoreXML.createTextNode(u'0'), # scoreXML.createTextNode(u'0')] #[r,c,i] # for populationElement in [u'R',u'C',u'I']: # population.appendChild(scoreXML.createElementNS(None,populationElement)) # population.lastChild.appendChild(RCI[0]) # RCI.pop(0) # # #add the elements underneath city # allcities = [city1,city2,city3] # for city in allcities: # cities.appendChild(city) # # for cityattribute in [u'cityname',u'mayor',u'morelater']: # city.appendChild(scoreXML.createElementNS(None,cityattribute)) # # citypopulation = scoreXML.createElementNS(None,u'citypopulation') # city.appendChild(citypopulation) # #will get RCI with seperate function # RCI = [scoreXML.createTextNode(u'0'), # scoreXML.createTextNode(u'0'), # scoreXML.createTextNode(u'0')] #[r,c,i] # # for populationElement in [u'R',u'C',u'I']: #>>>>>>>>>>citypopulation.appendChild(scoreXML.createElementNS(None,populationElement)) # citypopulation.lastChild.appendChild(RCI[0]) # RCI.pop(0) # #write the result # print scoreXML.toprettyxml() Any ideas? -thanks in advance From erikbethke at gmail.com Thu Jan 20 09:58:57 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 20 Jan 2005 06:58:57 -0800 Subject: ElementTree cannot parse UTF-8 Unicode? In-Reply-To: References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> <1106230846.455765.7310@c13g2000cwb.googlegroups.com> Message-ID: <1106233137.588111.216480@z14g2000cwz.googlegroups.com> Woo-hoo! Everything is working now! Thank you everyone! The TWO problems I had: 1) I needed to save my XML file in the first place with this code: f = codecs.open(paths[0], 'w', 'utf8') 2) I needed to download the UNICODE version of wxPython, duh. So why are there non-UNICODE versions of wxPython??? To save memory or something??? Thank you all! Best! -Erik From michael_r_campbell at att.net Fri Jan 28 13:33:19 2005 From: michael_r_campbell at att.net (mike) Date: 28 Jan 2005 10:33:19 -0800 Subject: py.dll for version 2.2.1 (Windows) Message-ID: <1106937199.667357.42040@z14g2000cwz.googlegroups.com> Just recently, my virus checker detected what it called a Trojan Horse in the py.dll file in the python22 folder. Installation is version 2.2.1 and I think that it came installed when I bought the PC in October 2002. Does anyone know where I can get a copy of the py.dll file from version 2.2.1 for Windows (XP) ? I looked at www.python.org and do not see a py.dll file in the self-installation or .tgz versions of 2.2.1 that are posted. Thanks ! Mike From emami at knmi.nl Tue Jan 4 05:00:34 2005 From: emami at knmi.nl (Nader Emami) Date: Tue, 04 Jan 2005 11:00:34 +0100 Subject: csh to Python Message-ID: Hello, I am new in Python world, and would like to begin with translate a csh file to a python script. Could somebody give me an advise (documentation or web-site) where I can do that. with regards, Nader From Serge.Orlov at gmail.com Tue Jan 11 18:57:52 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 11 Jan 2005 15:57:52 -0800 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <41e41633$1@nntp0.pdx.net> <41e458a9$0$7090$8fcfb975@news.wanadoo.fr> Message-ID: <1105487872.494278.128510@f14g2000cwb.googlegroups.com> Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle. wrote: > Hi ! > > >>> It is a least-common-denominator argument, not a "this is better" > argument. > > I understand, but I have a feeling of attempt at hegemony. Is english > language really least-common-denominator for a russian who writes into > cyrillic, or not anglophone chinese? I don't know about Chinese but English *is* the least common denominator for native Russian software developers, there are a lot of reasons for that: - to switch between Russian keyboard layout and English keyboard you need to press a switch key or usually even two keys (at the same time). Since language syntax and library calls are in English you have to switch often. Very often you forget what is the current keyboard layout and start typing in wrong one and you have to delete the garbage, hit switch key and type it again. If it happens ten times every ten minutes it will drive you crazy. - Most of native Russian developers graduated from universities or institutes. They attended hundreds of hours of math and physics classes. All these classes use latin notation. - Any serious local sw development job application mentions "Technical English" as requirement. It means you're expected to read technical documents in English. - At the same time majority of native Russians developers do not speak English very well and they feel they need more English practice. Using English identifiers is a chance to practice while you work. - The amount of useful information in English is much greater than in Russian, thanks to Internet. Surprised? :) Serge. From bokr at oz.net Sun Jan 9 16:50:51 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 09 Jan 2005 21:50:51 GMT Subject: time module precision References: <1105268967.629064.154850@c13g2000cwb.googlegroups.com> Message-ID: <41e1a171.428347721@news.oz.net> On 9 Jan 2005 03:09:27 -0800, janeaustine50 at hotmail.com wrote: [...] > >What I want to do is waiting(not busy-delaying) for a few tens to >hundreds of microseconds in some threads. The closet solution I got is >using windows QueryPerformanceCounter (in Python, time.clock) with busy >looping checking if we have past the target time. However, that makes >the cpu usage upto almost 100%. > >So the problem (waiting tens to hundreds of us without busy looping) >still remains... > Microseconds is tough if you are going to give up control to a scheduling/dispatching mechanism that works in milliseconds (e.g. 10ms normal slice on NT4), and where badly written interrupt handling may cause significant latency hiccups. There's a reason CD burners come with big buffers. One question is if you are waiting for an event that causes and interrupt, or if you are guaranteeing a delay to give something a chance to happen (e.g. like some pysical process like a sound echo) so you can read a sensor interface at an appropriate time after starting some process, or whether you're waiting for an event that originates in another thread running under ordinary scheduling constraints. If you want close time control under windows, you may have to write driver-level software and/or raise priorities to real-time levels and make sure those things don't run very long before blocking. I suspect that multimedia support stuff in windows might be useful for quasi-real-time stuff, but I haven't used it. (I just seem to remember reading something about that in the MSDN docs, but I am not sure. And too lazy to go back and look ;-) Regards, Bengt Richter From fuzzyman at gmail.com Tue Jan 4 09:55:40 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 Jan 2005 06:55:40 -0800 Subject: Reaching the real world Message-ID: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> I have a friend who would like to move and program lights and other electric/electro-mechanical devices by computer. I would like to help - and needless to say Python would be an ideal language for the 'programmers interface'. What I'd like is an electronic interface that connects to several relays and a python extension module to switch on and off the relays. I've had a quick google and can't see anything too similar to what I want. pyro (python robotics) seems to require expensive (relatively) robotic equipment. Does anyone know anything *similar* to what I have in mind, or have alternative suggestions ? Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From google-groups at slippytoad.com Thu Jan 13 19:51:37 2005 From: google-groups at slippytoad.com (Nick Atkins) Date: 13 Jan 2005 16:51:37 -0800 Subject: Pygtk: How to remove title bar from a window In-Reply-To: References: <1105653476.254139.58810@f14g2000cwb.googlegroups.com> Message-ID: <1105663897.698607.17720@z14g2000cwz.googlegroups.com> Thanks for the reply Diez. I'm not sure I can draw a border on its own with pyGTK but admittedly I am not yet an expert. I have the following minimal test program which opens a window and I cannot get it to draw a window with no title bar, just a border: #!/usr/bin/env python import pygtk pygtk.require('2.0') import gtk if __name__ == "__main__": # create a popup w = gtk.Window() w.set_size_request(100, 100) w.set_decorated(False) w.set_has_frame(False) w.set_border_width(10) w.show() gtk.main() I tried removing the set_decorated and set_has_frame lines and changing them to True but I either get a complete title-bar window or nothing at all. Any ideas? Thanks. From craig at postnewspapers.com.au Mon Jan 10 18:17:51 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Tue, 11 Jan 2005 07:17:51 +0800 Subject: C structure in the Python extension In-Reply-To: References: Message-ID: <1105399071.3938.1.camel@albert.localnet> Dave win wrote: >Howdy: > When I was writting interface functions of the extending python, I >meet a question. As I using the "PyArg_ParseTuple(args,arg_type,...)" >function call, if I wanna use the personal defined argument, such as the >C structure which I made. How to make it? > >static PyObject* Call_V_ABSUB(PyObject *self, PyObject* args){ > myStruct FU; > myStruct result; > if(!PyArg_ParseTuple(args,"O&",&FU)) return NULL; > ^^^^^^^ > How to modify here??? > V_ABSUB(FU); > > return Py_BuildValue("i",result); >} > > You can't, really. Python code can't work with C structs directly, so it can't pass you one. I have used one utterly hideous hack to do this when prototyping code in the past, but that was before I knew about PyCObject. PyCObject is also pretty evil if abused, but nowhere NEAR on the scale of what I was doing. Can you say passing pointers around as Python longs? Can't bring yourself to say it? Don't blame you. My only defense was that it was quick hack prototype code, and that the Python/C API for making classes is too painful to use when quickly prototyping things. To do what you want, you could encapsulate a pointer to the struct in a PyCObject, then pass that around. Your Python code will just see a PyCObject with no attributes or methods; it can't do anything to it except pass it to other Python code (and delete it, but that'll result in a memory leak if the PyCObject holds the only pointer to the struct). Your C code can extract the pointer to the struct and work with that. DO NOT do this if the Python code just deleting the PyCObject could ever discard the last pointer to the struct, as you'll leak the struct. A much BETTER option is probably to rewrite myStruct to be a Python type ("class") implemented in C, and provide it with both a C and Python API. This isn't too hard, though the Python/C API does make creating types a bit cumbersome. (Most of this seems to be because you're playing pretend-we-have-objects in C, rather than issues specific to the Python/C API). -- Craig Ringer From craig at postnewspapers.com.au Sat Jan 22 04:46:15 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 22 Jan 2005 17:46:15 +0800 Subject: need help on need help on generator... In-Reply-To: <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> Message-ID: <1106387175.4103.16.camel@albert.localnet> On Sat, 2005-01-22 at 10:10 +0100, Alex Martelli wrote: > The answer for the current implementation, BTW, is "in between" -- some > buffering, but bounded consumption of memory -- but whether that tidbit > of pragmatics is part of the file specs, heh, that's anything but clear > (just as for other important tidbits of Python pragmatics, such as the > facts that list.sort is wickedly fast, 'x in alist' isn't, 'x in adict' > IS...). A particularly great example when it comes to unexpected buffering effects is the file iterator. Take code that reads a header from a file using an (implicit) iterator, then tries to read() the rest of the file. Taking the example of reading an RFC822-like message into a list of headers and a body blob: .>>> inpath = '/tmp/msg.eml' .>>> infile = open(inpath) .>>> for line in infile: .... if not line.strip(): .... break .... headers.append(tuple(line.split(':',1))) .>>> body = infile.read() (By the way, if you ever implement this yourself for real, you should probably be hurt - use the 'email' or 'rfc822' modules instead. For one thing, reinventing the wheel is rarely a good idea. For another, the above code is horrid - in particular it doesn't handle malformed headers at all, isn't big on readability/comments, etc.) If you run the above code on a saved email message, you'd expect 'body' to contain the body of the message, right? Nope. The iterator created from the file when you use it in that for loop does internal read-ahead for efficiency, and has already read in the entire file or at least a chunk more of it than you've read out of the iterator. It doesn't attempt to hide this from the programmer, so the file position marker is further into the file (possibly at the end on a smaller file) than you'd expect given the data you've actually read in your program. I'd be interested to know if there's a better solution to this than: .>>> inpath = '/tmp/msg.eml' .>>> infile = open(inpath) .>>> initer = iter(infile) .>>> headers = [] .>>> for line in initer: .... if not line.strip(): .... break .... headers.append(tuple(line.split(':',1))) .>>> data = ''.join(x for x in initer) because that seems like a pretty ugly hack (and please ignore the variable names). Perhaps a way to get the file to seek back to the point last read from the iterator when the iterator is destroyed? -- Craig Ringer From fredrik at pythonware.com Thu Jan 20 02:21:13 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jan 2005 08:21:13 +0100 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> Message-ID: Timothy Fitz wrote: > While I agree that the Zen of Python is an amazingly concise list of > truisms, I do not see any meaning in: > > Flat is better than nested. Python's not Pascal. From x2164 at mailcity.com Sun Jan 30 08:35:27 2005 From: x2164 at mailcity.com (x2164 at mailcity.com) Date: 30 Jan 2005 13:35:27 GMT Subject: test_socket.py failure Message-ID: hi all, Linux 2.4.28 Glibc 2.2.5 gcc 2.95.3 I'm new to Python. I've compiled Python 2.4 from tar file. When running 'make test' i'm getting a failure in test_socket. Running './python Lib/test/test_socket.py' yields: ====================================================================== ERROR: testGetServBy (__main__.GeneralModuleTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "Lib/test/test_socket.py", line 330, in testGetServBy port2 = socket.getservbyname(service) error: service/proto not found ---------------------------------------------------------------------- Ran 58 tests in 3.826s The value of 'service' was "daytime". After much hand wringing, editing, and use of 'print' statements i commented out line 330, '# port2 = socket.getservbyname(service)' and replaced it with the line 'port2 = port'. Running './python Lib/test/test_socket.py' now yields: testGetServBy (__main__.GeneralModuleTests) ... ok . . . ---------------------------------------------------------------------- Ran 58 tests in 5.181s OK Located the code for 'socket_getservbyname' in 'Modules/socketmodule.c' where the call to the glibc function 'getservbyname' is made: Py_BEGIN_ALLOW_THREADS sp = getservbyname(name, proto); Py_END_ALLOW_THREADS if (sp == NULL) { PyErr_SetString(socket_error, "service/proto not found"); return NULL; } The only call of socket.getservbyname that failed was when it was passed the single argument. Since the error message "service/proto not found" seems to only be generated upon failure of gibc's 'getservbyname' could it be that 'PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto)' generates values for 'name' and/or 'proto' that cause the failure? My search for prior reports of failure at line 330 found a mention of problems at line 331. Well, at any rate, if someone could point me down the correct path on this i would appreciate it. pete jordan x2164 -> mailcity.com -> equals at symbol -- ............ From john at grulic.org.ar Tue Jan 18 09:22:13 2005 From: john at grulic.org.ar (John Lenton) Date: Tue, 18 Jan 2005 11:22:13 -0300 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: <20050118142213.GB26210@grulic.org.ar> On Mon, Jan 17, 2005 at 03:20:01PM +0000, Antoon Pardon wrote: > Op 2005-01-17, John Lenton schreef : > > > > knowledgeable and experienced users know when to ignore the rules. > > Then why seems there to be so few acknowledgement that these rules > may indeed be broken by users. My experience is that anyone who suggests > so runs the risk of being branded a (python) heretic. First you learn the basics, then you think you're knowledgeable and experienced, then you learn the rules, then you become one with the rules, and then you may break them. Most people suggesting these things haven't gotten past step #3. Using Craig's parallel to C's goto, every and all newbie using gotos should be lambasted: even if the use might be correct for the problem they are trying to solve, the reasons for its correctness are far too complex for them to grasp. But really, in practically any system, the rules are generalizations, and they exist because the particulars are too delicate to trust the unexperienced. The small print is unprintable. He dicho. -- John Lenton (john at grulic.org.ar) -- Random fortune: Yo siempre ser? el futuro Nobel. Debe ser una tradici?n escandinava. -- Jorge Luis Borges. (1899-1986) Escritor argentino. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From steven.bethard at gmail.com Thu Jan 13 14:30:10 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 13 Jan 2005 12:30:10 -0700 Subject: Refactoring; arbitrary expression in lists In-Reply-To: References: Message-ID: BJ?rn Lindqvist wrote: >> # do other non-extension-related tests here >> if basename.find( "Makefile" ) != -1: >> return "text/x-makefile" > > > I believe this can be nicelier written as: > > if "Makefile" in basename: > +1 for "nicelier" as VOTW (Vocabulation of the week) =) Steve From fredrik at pythonware.com Sat Jan 15 07:54:05 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 15 Jan 2005 13:54:05 +0100 Subject: How to del item of a list in loop? References: Message-ID: "skull" wrote: > It makes a copy operation! so? in python, shallow copies are cheap. > here is a faster and 'ugly' solution: faster? did you try it, or are you combining a C++ mindset with an urge to do premature optimizations? (hint: it's slower) if you care about performance, you shouldn't use "remove", btw. building a new list is more efficient, especially if you use a list comprehension: lst = [i for i in lst if i != 2] (if you have 2.4, try replacing [] with () and see what happens) From bulba at bulba.com Wed Jan 5 14:08:42 2005 From: bulba at bulba.com (Bulba!) Date: Wed, 05 Jan 2005 20:08:42 +0100 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <16859.16548.249527.30210@montanaro.dyndns.org> <864d37090501050117761a32e6@mail.gmail.com> Message-ID: On Wed, 5 Jan 2005 07:37:25 -0600, Skip Montanaro wrote: > > Terry> Numarray has a record array type. If there is not one publicly > Terry> available, perhaps you could write a CSV file to record-array > Terry> slurper and contribute it to the Recipes site or maybe even the > Terry> CSV module. > >> > >> -1 on putting such a beast into the CSV module, especially if, as it > >> seems, it would rely on something outside the core. > > Carlos> Although I see your point, in the long term it will be required. > Carlos> Assuming that Numarray will, at some point in the future, be > Carlos> included in the stdlib... why not give these people some help, > Carlos> easing the integration? > >I'm not sure they really need my help. I've never needed Numarray (or >Numeric) in my own work. I've never needed numeric stuff either. I just need to do things like: .>>> table.sort(column_name) # that obviously would sort rows of table by the values of column column_name or .>>> unique = table.unique(column_name) # that would yield such a subset of all the rows that would contain unique values from column column_name or .>>> table1.union(table2 [,drop_missing_columns | ,fill_missing_with_None]) or .>>> common = table1.intersection(table2, column_name [, unique | , redundant]) # that would yield all the rows that have the same values in column_name in both table1 and table2; if optional keyword "unique" were given, those could e.g. be only rows from table1, when the "redundant" keyword were specified, that could be a union of common rows from table1 and table2 or .>>> complement = table.complement(complement_function) # where complement function could be anything, like (!cellvalue) or string.upper; that obviously would run the complement_function on every cell in table (obviously, this could also be implemented as map(table, complement_function) ) Now suppose a programmer could write a custom complement function that detects all the irregularly distributed "anomalous" data points (be it whatever, missing surnames from personnel records or values from a physical experiments that are below some threshold) in this table and returns, say, a list of tuples that are coordinates of those data points. Getting it from a specific table would be a matter of one instruction! Yes, I know, it can be written by hand. But by this line of logic why bother learning VHLL and not just stay with C? >If it's deemed useful I'm sure someone from that >community could whip something out in a few minutes. The concepts >represented by the csv module are a lot shallower than those represented by >Numarray. True, and I may scratch enough time together to learn all the necessary stuff (I'm not even half done in learning Python) to write it myself. That is not the point, however: the biggest boost and one of the main points of getting into Python, at least for me, but I'm sure this is also motivation for quite a lot of other people, is precisely the ease of exploiting capabilities of data structures like dictionaries and lists, which when coupled with this data structure's object-style .method are simply very convenient and fast. This is where IMHO Python excels among the VHLL languages. I'm about to post reworked version of my program that doesn't use a _single_ traditional loop to do all the data transformations I need (I just still need to solve some problems there / polish it). This is not just about that damn CSV file that I already have the way I wanted it and sent it to customer, this is about _terse and clear_ manipulations of rich data structures in Python. Why not extend them with flexible tables / matrices / arrays that would work in as "Pythonic" ways as dictionaries and lists already do? If Pythoners say a=['A'], it's only logical to say a.append('B'). :-) -- It's a man's life in a Python Programming Association. From ola.natvig at infosense.no Tue Jan 18 08:21:18 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Tue, 18 Jan 2005 14:21:18 +0100 Subject: generator expressions: performance anomaly? In-Reply-To: <354gj7F4etgn8U1@individual.net> References: <377Hd.77904$Jk5.30235@lakeread01> <354gj7F4etgn8U1@individual.net> Message-ID: Diez B. Roggisch wrote: >> lst = list(genexp) >> tpl = tuple(genexp) >> >> >>Since in such cases the object is build in memory any way, I don't >>think it would be a problem of having them prebuilt in memory, or am >>I missing something? > > > Yes. Consider this: > > lst = list(time.time() for i in xrange(10)) > tpl = tuple(time.time() for i in xrange(10)) > > Would it be a bad solution to make that a list or tuple of ten time.time() calls, you could also restrict what theese prebuilding sequenses could contain, or perhaps try to prebuild them, and then fail if it's impossible. -- -------------------------------------- Ola Natvig infoSense AS / development From Scott.Daniels at Acm.Org Wed Jan 12 15:14:43 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 12 Jan 2005 12:14:43 -0800 Subject: Iteration over two sequences In-Reply-To: <1gq9z5q.1x7si1us4kgmcN%news+0409@henrikholm.com> References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> <1105549514.563799.307030@z14g2000cwz.googlegroups.com> <1gq9z5q.1x7si1us4kgmcN%news+0409@henrikholm.com> Message-ID: <41e58244$1@nntp0.pdx.net> Henrik Holm wrote: > John Lenton wrote: > > >>>def dotproduct(a, b): >>> psum = 0 >>> for i in range(len(a)): >>> psum += a[i]*b[i] >>> return psum >> >>for this particular example, the most pythonic way is to do nothing at >>all, or, if you must call it dotproduct, >> >>>>>from Numeric import dot as dotproduct > > > Downloading, installing, and getting to know numerical modules for > Python is mext on my list :). However, I was under the impression that > Numarray is preferred to Numeric -- is that correct? Are these two > competing packages? (Hopefully this is not flame war bait...) > Numarray is the future, Numeric is the "past", but in the present Numeric is better (and more mature) at some stuff than Numarray. Learning both is not much harder than learning one, actually (they share a lot). --Scott David Daniels Scott.Daniels at Acm.Org From ialbert at mailblocks.com Mon Jan 17 11:11:55 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 17 Jan 2005 11:11:55 -0500 Subject: pychecker - sets.Set need to be overridden In-Reply-To: <1105978024.706237.304360@c13g2000cwb.googlegroups.com> References: <1105978024.706237.304360@c13g2000cwb.googlegroups.com> Message-ID: wittempj at hotmail.com wrote: > <__main__.Foo instance at 0x00C578A0> Set([]) > on 2.4. on WinXP. What environment do you run in? I'm running it on cygwin, but still don't get it, why the warning? Istvan. From steve at holdenweb.com Sat Jan 1 11:51:40 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Jan 2005 11:51:40 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <1104511661.928284.10200@z14g2000cwz.googlegroups.com> Message-ID: <5CABd.65441$Jk5.59430@lakeread01> Cameron Laird wrote: > In article <1104511661.928284.10200 at z14g2000cwz.googlegroups.com>, > wrote: > >>Bulba wrote: >> >>>OK, so what projects and why would you consider >>>Python: >>>1. "clearly unsuitable" >> >>Large-scale scientific computing projects, such as numerical weather >>prediction, where performance is critical. Python could be used as the >>"glue" but not the "guts", where Fortran 95 and C++ are more >>appropriate. In my tests, some posted here, there has been a > > . > . > . > I feel like growling that it's clearly a mistake for large-scale > scientific computing projects not to leverage dynamic languages, > at least in part. Yes, I've seen projects that would have been > disasters if done entirely in Python. I've also seen many, many > large-scale scientific projects that soaked up far more resources > than they should have because they limited themselves to C++ or > Fortran. > > I argue that it's a false opposition to categorize projects in > terms of use of single languages. Many projects are MUCH better > off with a mix of Python and Fortran, say (and probably SQL and > JavaScript and ...), and it's pernicious to accomodate the > managerial conceit that One Language will suffice. Indeed it's sensible to choose language based on the nature of the task to be performed, to avoid "language-blindness" and to build systems in mixed languages. Unfortunately the hierarchy of power in most modern commercial and academic organizations is such that large-scale efforts will be nominally run by single individuals, and since those individuals typically can dispense favors and determine who advances within the organization it's often unwise *not* to accommodate the managerial conceit it career advancement is one's primary goal. which-is-why-i-run-my-own-business-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From lbates at syscononline.com Mon Jan 31 15:19:23 2005 From: lbates at syscononline.com (Larry Bates) Date: Mon, 31 Jan 2005 14:19:23 -0600 Subject: barchart for webpage needed In-Reply-To: References: Message-ID: dimitri pater wrote: > Hello, > > I am looking for a Python tool to create graphs and charts on a > webpage. Chartdirector is too expensive for me. A simple script for > creating a barchart should be sufficient as a starting point. > > Thanks! > Dimitri ReportLab's Graphics module is free and works quite well for me. www.reportlab.org Larry Bates From martin at v.loewis.de Sun Jan 30 03:46:51 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 30 Jan 2005 09:46:51 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xsm4j1wbe.fsf@ruckus.brouhaha.com> References: <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> <7xacqsbfk2.fsf@ruckus.brouhaha.com> <41fbcb11$0$12030$9b622d9e@news.freenet.de> <7xsm4j1wbe.fsf@ruckus.brouhaha.com> Message-ID: <41fc9eec$0$25945$9b622d9e@news.freenet.de> Paul Rubin wrote: > Oh, ok. Earlier you said you wanted user feedback before you could > conclude that there was reason to want an AES module at all. I believe I never said that. I said that I wanted user feedback to determine whether *this* AES module (where this is either your from-scratch implementation, or any other specific implementation contributed) is desirable. > Hmm, this is very very interesting. I am highly confident that all > the purely technical questions (i.e. everything about the API and the > code quality, etc.) can converge to a consensus-acceptable solution > without much hassle. I had thought there were insurmountable > obstacles of a nontechnical nature, mainly caused by legal issues, and > that these are beyond any influence that I might have by writing or > releasing anything. These obstacles are indeed real. But I believe they are not unsurmountable. For example, there is the valid complaint that, in order to export the code from SF, we need to follow U.S. export laws. 10 years ago, these would have been unsurmountable. Today, it is still somewhat painful to comply with these laws, but this is what the PSF is for, which can fill out the forms necessary to allow exporting this code from the U.S.A. Regards, Martin From elephantum at dezcom.mephi.ru Sun Jan 9 06:05:31 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 14:05:31 +0300 Subject: python3: 'where' keyword In-Reply-To: <7xk6qnzd3d.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> Message-ID: <34chfrF490f8aU1@individual.net> Paul Rubin wrote: > You mean I can't say > > # compute sqrt(2) + sqrt(3) > x = (sqrt(a) where: > a = 2.) \ > + sqrt (a) where: > a = 3. No, I'd prefer to not embed 'where' into expression. From t-meyer at ihug.co.nz Wed Jan 26 21:52:54 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Thu, 27 Jan 2005 15:52:54 +1300 Subject: Which is faster? In-Reply-To: Message-ID: > Any idea which of the following is faster? > > 'a/b/c/'[:-1] > > or > > 'a/b/c/'.rstrip('/') > > Thanks in advance. > > P.S. I could time it but I thought of trying my luck here > first, in case someone knows already, and of course the reason. Timing it is almost no work, though: >>> import timeit >>> timeit.Timer("'a/b/c/'[:-1]").timeit() 0.23856551600831949 >>> timeit.Timer("'a/b/c/'.rstrip('/')").timeit() 0.74258655778876914 The obvious reason for the former to be faster (although I haven't checked to see whether it's true) is because the latter checks for a specific character, whereas the former just snips it off whatever it is. =Tony.Meyer From phr at localhost.localdomain Mon Jan 24 15:25:18 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Mon, 24 Jan 2005 20:25:18 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <1106564799.011057.181280@c13g2000cwb.googlegroups.com> Message-ID: "Fuzzyman" writes: > I also feel the lack of a standard cryptography module in the core... > even a *basic* one. At least rotor provided that, before it was deprecated. Rotor was insecure and really shouldn't have been used. If you need crypto in pure Python, try this: http://www.nightsong.com/phr/crypto/p3.py It's a nonstandard algorithm, but so was rotor. Its security should be much better than rotor's, and its speed should be tolerable for most purposes. From tim.peters at gmail.com Fri Jan 14 18:20:57 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 14 Jan 2005 18:20:57 -0500 Subject: oddities in the datetime module In-Reply-To: <41e84175$0$258$edfadb0f@dread12.news.tele.dk> References: <41e79a1a$0$264$edfadb0f@dread12.news.tele.dk> <41e84175$0$258$edfadb0f@dread12.news.tele.dk> Message-ID: <1f7befae050114152031a6f13f@mail.gmail.com> [Max M] > ... > First of, it should be possible to easily convert between the > datetime objects. Why? All the conversions people asked for when the module was being designed were implemented. > And eg. the date object doesn't have a datetime() method. Which > it could easily have. But not a *sensible* one. If you only have a date (or time), what's a conversion to datetime supposed to do about the "missing values"? Guess? No good. > Neither does time. They could have. But I don't think that > is the way to solve it. datetime.datetime objects have .date() and .time() methods, returning the obvious datetime.date and datetime.time slices of the datetime.datetime. The class constructor datetime.combine() goes in the other direction, building a datetime.datetime object by combining a datetime.date and a datetime.time. > It is a problem if you make a subclass of datetime. Often you > will ned to make datetime arithmetics with the new class. > > Like: datetime_subclass_1 + datetime_subclass_2 > > The result of that is a plain datetime If your subclass doesn't override __add__, yes. > In that case you will rather want your own subclass returned. While possible, that's not necessarily so of all subclasses. > But subclasses of datetime returns datetime objects. Not the > subclass. That depends on whether the subclass overrides __add__, and if so, the code in its __add__ method. > So to do an add of your own objects you must convert the output > to your own class "manually" > > class my_datetime(datetime): > > def __add__(self, other): > result = datetime.__add__(self, other) > return my_datetime(result.timetuple()[:6]) > > datetime(), time() etc. methods will not help with this. Well, it's unclear where you think you need help there. If that's what you want your subclass __add__ to do, you've already done it, right? It could save tedium to give your subclass a class constructor, e.g., from_datetime(), and then code __add__ as def __add__(self, other): return my_datetime.from_datetime(datetime.__add__(self, other)) Whether the implementation wants to use timetuple() depends on what the subclass wants to do; for example, a subclass that intends to support a notion of time zone needs more than just that. From beliavsky at aol.com Thu Jan 20 21:21:16 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 20 Jan 2005 18:21:16 -0800 Subject: problems with duplicating and slicing an array References: Message-ID: <1106274076.241474.245030@f14g2000cwb.googlegroups.com> Yun Mao wrote: >I have some questions when I'm using python numeric: >1. When I do v = u[:, :], it seems u and v still point to the same >memory. e.g. When I do v[1,1]=0, u[1,1] will be zero out as well. >What's the right way to duplicate an array? Now I have to do v = >dot(u, identity(N)), which is kind of silly. You can use v = 1*u or v = u.copy() to get the type of copy you want. >2. Is there a way to do Matlab style slicing? Use the take function. The output of the following code from Numeric import array,take a = array([1,2]) b = a c = 1*a d = a.copy() a[0] = 3 print b print c print d print take(a,[1,0,1]) is [3 2] [1 2] [1 2] [2 3 2] From a at b.c Sat Jan 22 14:18:57 2005 From: a at b.c (Doug Holton) Date: Sat, 22 Jan 2005 13:18:57 -0600 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> Message-ID: <46ednYMe9-q4Om_cRVn-tQ@comcast.com> Fredrik Lundh wrote: > A.M. Kuchling wrote: > > >>IMHO that's a bit extreme. Specifications are written to be detailed, so >>consequently they're torture to read. Seen the ReStructured Text spec >>lately? > > > I've read many specs; YAML (both the spec and the format) is easily > among the worst ten-or-so specs I've ever seen. What do you expect? YAML is designed for humans to use, XML is not. YAML also hasn't had the backing and huge community behind it like XML. XML sucks for people to have to write in, but is straightforward to parse. The consequence is hordes of invalid XML files, leading to necessary hacks like the mark pilgrim's universal rss parser. YAML flips the problem around, making it harder perhaps to implement a universal parser, but better for the end-user who has to actually use it. More people need to work on improving the YAML spec and implementing better YAML parsers. We've got too many XML parsers as it is. From steve at holdenweb.com Fri Jan 21 09:37:28 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Jan 2005 09:37:28 -0500 Subject: PyCon Preliminary Program Announced! In-Reply-To: References: <20050121000607.DE1261E4010@bag.python.org> <41F061C3.3000802@gmail.com> <1f7befae0501201952139c57a8@mail.gmail.com> Message-ID: <41F113A8.8020908@holdenweb.com> Timothy Fitz wrote: >>I don't care much for "parallel tracks" myself, because I want to hear >>basically everything. But we had more proposals of higher quality >>this year than ever before, so it came down to scheduling more talks >>in parallel than ever before too, or rejecting perfectly good >>proposals. > > > Will there be recordings of any of these presentations? There are > quite a few times when I want to be at all three tracks at the same > time. There are currently loose plans to have each session recorded. This will, however, require massive volunteer effort which so far nobody has offered to coordinate, so unless someone steps up to the plate with a sound plan to ensure that at least the initial capture takes place this may remain a pipe dream (there are limits to the chairman's powers that he is starting to treat as actual rather than theoretical ;-) What's actually required? Someone needs to start a resource, with a copy of the schedule ( and a Wiki page might do, its source can be lifted directly from the Wiki source of http://www.python.org/moin/PyConDC2005/Schedule) that allows volunteers to sign up to record specific sessions. We also need a release form that speakers can sign to allow the recording to take place and for it to be published under a suitable Creative Commons license. We need advice on file formats and software for Linux, Windows and Mac (plus any other platforms that may be used): experience says that apparently it's possible to make acceptable recordings with an external microphone such as a lapel mike from the front of the room, without involving the University. If someone wants to liaise about electronic feeds I'll certainly facilitate interaction with GWU as long as the cost is acceptable (zero would be best). Finally we need someone coordinating at the conference to make sure this all happens, that the release forms are collected, and that the sound files are made available - probably on www.python.org. This is a /community conference/, guys. I *know* the Python community can collectively take this task and eat it for breakfast, but please don't believe it will happen as a result of a few newsgroup posts saying what a nice idea it would be. Things don't happen that way, and I have the grey hairs to prove it. Please, make this happen! regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From tdelaney at avaya.com Sun Jan 30 18:02:12 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 31 Jan 2005 10:02:12 +1100 Subject: Pystone benchmark: Win vs. Linux (again) Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE025202F1@au3010avexu1.global.avaya.com> Franco Fiorese wrote: > * Windows XP Pro: 16566.7 pystones/second > * Linux (kernel 2.6.9 NPTL): 12346.2 pystones/second First of all, realise that pystone is not meant to be a general-purpose benchmarking program. It test a specific, *small* subset of the functionality available in Python. It's also not meant to be able to compare across machines, etc. It's highly susceptible to cache effects and various other things. If you include parrotbench you will get a better view of things, but it's also not designed for comparisons across machines. Tim Delaney From http Thu Jan 6 17:16:13 2005 From: http (Paul Rubin) Date: 06 Jan 2005 14:16:13 -0800 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> Message-ID: <7xzmzmurte.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > Yes, apart from libraries and similar cases (frameworks etc), it's no > doubt rare for closed-source "end-user packages" to be sold with > licenses that include source and allow you to "do anything with it". > > However, allowing customization (at least for internal use within the > customer organization), while rare, is far from unheard of. There's no obstacle to doing that with GPL'd software either. From bulba at bulba.com Tue Jan 4 14:06:57 2005 From: bulba at bulba.com (Bulba!) Date: Tue, 04 Jan 2005 20:06:57 +0100 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> Message-ID: On Tue, 4 Jan 2005 11:15:54 +0100, aleaxit at yahoo.com (Alex Martelli) wrote: >Also, you keep talking about "the core python team" on the basis, it >would appear, of reading one document by Guido. Have you bothered doing >a MINIMUM of homework, such as, looking at > http://www.amk.ca/diary/archives/cat_python.html >and specifically AMK's entry for September 30? This complaint about "syntax cruft" is really weird, as while browsing through the old and new docs I got the impression that Python hasn't really changed so much as just added new, and mostly well-chosen features. What's not to like in sets for instance?! However, I do have to concede that Python as environment still has a way to go - not the language features are missing, but better _standard_ IDE and debugger. E.g. Pythonwin debugger sometimes simply dies on me, I have no idea why. This is not to criticize the great work that you guys are doing and the results of which we get FOR FREE (something in principle I don't believe), but merely to indicate that Python has grown and so did the expectations. People tend to get spoilt: they expect to find in a free product the gazillion of VS-like features. :-) As we say here, "appetite tends to grow as you eat". E.g. right now I would kill for a standard, built-in matrix type that would be as flexible as lists and dictionaries are in Python, so that I could slurp the whole CSV file or some other table in one instruction into a matrix that could accomodate data types likes strings and floats (just like dictionaries do - just, say, declare, "column 1 of matrix contains strings, and please convert the values in column 2 into floats"), and then easily do some fancy matrix transformations. Clean and expressive syntax plus flexibility of lists and dictionaries are the main reasons I got into Python. Where else could I do smth as neat as writing a CSV header with: DictWriterInstance.writerow(dict(zip(titles,titles))) Note I didn't have to do any operations myself: all that was necessary for me as a programmer was to figure out how to connect the Lego pieces together. We need more of this sort of expressive power in a standard library and built-in types. This is the subconscious power of attraction in Python I think. :-) I'm not a language designer. I don't know how to get there. I just would love to see more of that around. To summarize, it's not the language that is would be nice to develop further. Those are: - more of the rich, flexible data types - more extensive standard debugger - possibly standard IDE with more features that are typically found in commercial products No, really, guys, great thanks for all that work. -- Real world is perfectly indifferent to lies that are the foundation of leftist "thinking". From rnd at onego.ru Wed Jan 12 12:03:53 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 12 Jan 2005 20:03:53 +0300 (MSK) Subject: java 5 could like python? In-Reply-To: References: Message-ID: On Wed, 12 Jan 2005, vegetax wrote: >-No naming convention. The speech of "it fits in my head" is no longer valid >when i use a lot of functionality,modules,classes in a large proyect. >For example if i remember a function i want ie:get attribute, i dont >remember if the module implementer coded it as >getAttribute,GetAttribute,get_attribute, then i have to go and check the >doc, every time,which is a waste of time. Or yes, I hate those 'get' too. Why not to use just obj.attribute instead? Otherwise, the pluralism present in Python, makes me feel more at home. >-library Organization,we have modules that can have 20 classes(I imagine >that is because of the commodity of having all in one file) which makes >reading the doc horribly painfull and is very hard to find the stuff >coupled with the "pool" of modules that is the python installation >directory,all throwed away at the installation directory without a >categorization. Probably some Really Large Corporation could add Python Standard Library Enterprise Edition and win big. >-Is python library half object oriented? half functional oriented? I can Right now it change its orientation to iterator/generators... I image a nice box with Python 3 in it, where there will be no more inconsistencies with naming, etc. >understand that python allows some functional programing components when >they are necesary,but there are libraries that totaly ignore object >orientation which makes them problematic to use.for example,Whats with the >os.path module and files? why do i have to say os.path.getfilesize(f.name) >all the time? why cant i say f.size? Why does urlparse returns a tuple of 7 >items instead of an URL object? why there isnt an URL object? and so on.. This reminds me of attributes vs. tags debate of how to structure XML. size(f) or f.size() - that is the question >I havent figured out a way to overcome those factors,the delaying and lost >of focus that is having to check the docs all the time,every 5 seconds and >having to make object oriented wrapers for several libraries or having to >go and read the source code to know what the heck a function returns or >what are its arguments makes coding unpleasant an very slow , i often have >15 pydocs windows open at the same time. What should i do? Do not use windows. Sit for an evening add read all the docs. Coding will becaome much faster. >-Realying on ides is imposible due to python dinamic nature,very litle(next >to nothing) assistance can be espected from them. Class browsing and auto-completion are probably the only features I sometime miss. But otherwise what IDEs are for? >-Memorazing all the function names,parameters,return values,conventions of >the modules i use doesnt look like a good solution. But it is a must: how do you communicate if you do not nother to remember words? >Join it with poor and outdated documention and we have a very unpleasant >standard library. >class C{ > public void func(){ > print("hello world"); // instead of System.out.println("hello world"); Probably print statement will not make it into Python 3.0. Very sad. > print(run("ls /tmp")); > } >} > >Same for almost all python builtin functions. > >Also there is the generics support and so on.. > >But for some reason i dont know,the switch back feels wrong =( ,would it be >posible to imitate python's behavior with the new java features and some >hacks? would be worth the effort? If not what can i do to use efficiently >python modules and libraries? I recall, i didnt had this problem when doing >small applications with a small set of modules. > >Sorry for my bad english. That is it. I hate English. It has sooo much exceptions to remember! Esperanto is much cleaner language. UN should drop all it's official languages and use Esperanto instead. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From steven.bethard at gmail.com Sun Jan 23 15:14:10 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 23 Jan 2005 13:14:10 -0700 Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) In-Reply-To: <41f325b5.1576259210@news.oz.net> References: <41f325b5.1576259210@news.oz.net> Message-ID: <6I2dnYLoXdcTmGncRVn-vw@comcast.com> Bengt Richter wrote: > On Sat, 22 Jan 2005 16:22:33 +1000, Nick Coghlan wrote: > > >>Steven Bethard wrote: >> >>>I wrote: >>> > If you really want locals that don't contribute to arguments, I'd be >>> > much happier with something like a decorator, e.g.[1]: >>> > >>> > @with_consts(i=1, deftime=time.ctime()) >>> > def foo(x, y=123, *args, **kw): >>> > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime >>> > >>> > Then you don't have to mix parameter declarations with locals >>> > definitions. >>> > >>> > Steve >>> > >>> > [1] I have no idea how implementable such a decorator would be. I'd >>> > just like to see function constants declared separate from arguments >>> > since they mean such different things. >>> >>>I played around with this, and I think it's basically implementable: >> >>Raymond's constant binding decorator is probably a good model for how to do it: >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 >> > > > I thought so too. I modified it to accept **presets as a keyword argument > and generate constants and assignments from its values matching assignment names > when the rhs was __frompresets__, e.g., > > >>> from makeconstpre import make_constants as pre > >>> import time > >>> @pre(verbose=True, deftime=time.ctime(), a=1, b=2, c=3, pi=__import__('math').pi) > ... def foo(): > ... deftime = __frompresets__ > ... b, a = __frompresets__ > ... c = __frompresets__ > ... pi = __frompresets__ > ... return locals() > ... > __frompresets__ : deftime --> Sat Jan 22 20:18:09 2005 > __frompresets__ : ('b', 'a') --> (2, 1) > __frompresets__ : c --> 3 > __frompresets__ : pi --> 3.14159265359 > locals --> Hmm... Having to state deftime = __frompresets__ when you've already stated deftime=time.ctime() seems a little redundant to me... Steve From FBatista at uniFON.com.ar Wed Jan 5 14:58:47 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 5 Jan 2005 16:58:47 -0300 Subject: Python evolution: Unease Message-ID: [Daniel Bowett] #- Contribute to where on Sourceforge??? Which domentation are #- we talking #- about in general? Suppose you're reading Python documentation. Don't know, for example, os.remove(). There you find that a particular parragraph is difficult to understand. You say "Hey, this could be better written", so you write i a more pedagogic way. After that you go to SF, Python project (http://sourceforge.net/projects/python), and go to Bugs. There, if you are logged in SF, you will see a "Submit new" link. You click on it and you'll see a form to fill. Select some fields (specially bug group in "Documentation") and in "Detailed Description:" you put something like "This particular sentence was difficult to read. Attaching a new way to write it". Of course, then attach the file of your text (if it's short enough you can put it directly in that field). Of course, if you write any NEW documentation about something that is not documented at all, or find some more serious issues with the docs (for example, bad argument count in a function) you can follow the same steps. . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From grahamd at dscpl.com.au Thu Jan 6 05:10:11 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 6 Jan 2005 02:10:11 -0800 Subject: Contributor's List References: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> Message-ID: <1105006211.527899.318740@c13g2000cwb.googlegroups.com> Anand wrote: > A list of contributors to Python Cookbook (Second Edition) is available > at the following links. Original list courtesy Alex Martelli. > > Since the book is not yet in print, the lists are still tentative > because of potential last minute editing changes. > > List of first authors > o http://harvestman.freezope.org/cookbook/credau.html > > List of all authors > o http://harvestman.freezope.org/cookbook/creds.html Is this mean't to only cover additional entries which were added in the 2nd edition, or is it also mean't to encompass entries which were carried over from the 1st edition as well. If it is both, then the editing must have been quite cut throat as I dropped from 3 entries in the 1st edition to 0 in the 2nd edition. I can sort of understand if the intent was to get rid of entries which referenced packages which weren't regarded as mainstream. I guess it is only 14 years of work down the drain. ;-( From steve at holdenweb.com Mon Jan 17 09:45:51 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 09:45:51 -0500 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Antoon Pardon wrote: > Op 2005-01-17, Steve Holden schreef : > >>Antoon Pardon wrote: >> >> >>>Op 2005-01-17, Steve Holden schreef : >>> >>> >>>>Antoon Pardon wrote: >>>>[...] >>>> >>>> >>>>>>"A foolish consistency is the hobgoblin of little minds". Rules are made >>>>>>to be broken. >>>>> >>>>> >>>>>Like only use immutables as dictionary keys. >>>>> >>>> >>>>Fair enough, but don;t go advising newbies to do this. >>> >>> >>>How about something like this. >>> >>>Because of the extra precautions one has to take when >>>using mutables as hash keys, we advise newbies >>>to stick with immutable keys until they have gathered >>>enough knowledge and experience to adequatly weight >>>the pro and cons of a mutable key solution against >>>an immutable key solution. >>> >> >>There you go with the minutiae again. How about: >> >>"Don't use mutables as hash keys"? > > > That sounds too dogmatic to my ears. I also find it > too selective. The problem with mutables as dictionary > keys is not specific to dictionaries. Everywhere you > have mutables in a container, it is possible that > mutating the object in the container will cause > problem. Heck even using mutables as arguments can > cause trouble. Why else the specific advice against > > def foo(p = []) > > type of arguments. So should we adopt the principles: > > Don't use mutables in containers > > Don't use mutables as default values for parameters > > Don't use mutables as arguments. > > Don't assign one mutable to an other. > > > I don't see a big difference between these principles > and the hash key principle, so in the end may be we > should just stick with the more general principle: > > Don't use mutables! > > > and be done with it. > http://redwing.hutman.net/~mreed/warriorshtm/tirelessrebutter.htm regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From jacek.generowicz at cern.ch Thu Jan 13 08:13:28 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 13 Jan 2005 14:13:28 +0100 Subject: from __future__ import decorators References: Message-ID: Peter Otten <__peter__ at web.de> writes: > Have a look at Bill Mill's redecorate utility: > > http://llimllib.f2o.org/files/redecorate.py Heh, this is exactly the sort of thing I wanted do avoid writing, as it would be difficult to get right. Looks like it's author has similar feelings. However, it could well be the most pragmatic solution in my case. Thanks. From chris.cavalaria at free.fr Sun Jan 16 09:25:57 2005 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Sun, 16 Jan 2005 15:25:57 +0100 Subject: Newbie inheritance question. References: Message-ID: <41ea7975$0$6635$626a14ce@news.free.fr> bwobbones wrote: > Hi all, > > I'm a java programmer struggling to come to terms with python - bear > with me! > > I'm trying to subclass a class, and I want to be able to see it's > attributes also. Here are my classes: > > two.py > ***************************** > from one import one > > class two(one): > def __init__(self): > print "two" > > def printTestVar(self): > print "testVar: " + str(self.testVar) > ***************************** You simply forgot to call the parent __init__. You have to do that explicitely in Python. From lbates at syscononline.com Wed Jan 26 17:49:51 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 26 Jan 2005 16:49:51 -0600 Subject: exclude binary files from os.walk In-Reply-To: References: <41f8167b$0$8648$a1866201@visi.com> Message-ID: There's no definitive way of telling a file is "non-ascii". Bytes in a binary file define perfectly good ascii characters. Windows depends on file extensions to try to keep track of the "type" of data in a file, but that isn't foolproof. I can rename a plain ascii file with a .EXE extension. We could be of more help, if you would take the time to explain a little about what you are trying to do. Larry Bates rbt wrote: > Grant Edwards wrote: > >> On 2005-01-26, rbt wrote: >> >> >>> Is there an easy way to exclude binary files (I'm working on >>> Windows XP) from the file list returned by os.walk()? >> >> >> >> Sure, assuming you can provide a rigorous definition of 'binary >> files'. :) > > > non-ascii From peter at engcorp.com Sat Jan 29 22:57:34 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 29 Jan 2005 22:57:34 -0500 Subject: cx_freeze error In-Reply-To: <1107054796.999110.18380@c13g2000cwb.googlegroups.com> References: <1107048210.548048.152870@z14g2000cwz.googlegroups.com> <1107054796.999110.18380@c13g2000cwb.googlegroups.com> Message-ID: zyqnews at 163.net wrote: > There is no any module like "re.py", I just compiled the hello.py it > has only one line: > print "hello!" Interesting. Just to confirm, could you try this? Run Python, and at the interactive prompt, type the following: >>> import re >>> re.compile >>> re.__file__ (path to file re.pyc) If you get an AttributeError after the second line, then the result of the third line (re.__file__) will tell you where this "re" module is that doesn't have a compile() function like it should have. Either there's an "re" kicking around that shouldn't be there, or cx_freeze is doing something weird... at least, those are the only theories that come to mind. -Peter From fireeagle at comcast.net Thu Jan 27 01:58:35 2005 From: fireeagle at comcast.net (fireeagle) Date: Wed, 26 Jan 2005 22:58:35 -0800 Subject: (no subject) Message-ID: <20050127065832.49BCA1E4004@bag.python.org> Subscribe -------------- next part -------------- An HTML attachment was scrubbed... URL: From binux.lists at gmail.com Thu Jan 6 03:57:40 2005 From: binux.lists at gmail.com (Binu K S) Date: Thu, 6 Jan 2005 14:27:40 +0530 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: References: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> <003801c4f3b9$af17fa20$0800a8c0@vishnu> <2b7d8b42050105232546083758@mail.gmail.com> Message-ID: <2b7d8b420501060057270f1878@mail.gmail.com> On Thu, 6 Jan 2005 13:17:11 +0530, Gurpreet Sachdeva wrote: > On Thu, 6 Jan 2005 12:55:22 +0530, Binu K S wrote: > >>>The file's current position moves as you write into it. > I concure and have figured out the solution BUT while reading from the > file from the position where the file handler is, should return > "Null/Blank/Anything in this world" BUT should not write into the > file... > The information written was that in the Buffer of the handler... Does > that mean reading a file will actually release the buffer by throwing > the contents in the file??? > I'm sorry, I didn't get what you trying to say here. Where do you see a read altering the file? An example might help. > Please Comment... > > >>>You normally wouldn't read from the file that you are writing into. > > May be applicable in handling logs... Sometimes after opening a file you read the contents of a file and then append to it. I haven't seen writing to a file and then going back to see what was written. > > Regards, > Garry > From martin at v.loewis.de Wed Jan 12 03:12:43 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 12 Jan 2005 09:12:43 +0100 Subject: Wide Unicode build for Windows available somewhere? In-Reply-To: <1105485536.966610.76570@z14g2000cwz.googlegroups.com> References: <1105485536.966610.76570@z14g2000cwz.googlegroups.com> Message-ID: <41e4dbf8$0$30343$9b622d9e@news.freenet.de> cwittern at yahoo.com wrote: > I am trying to locate a windows binary of a recent python (2.4 > preferred, but not essential) with support for Unicode characters > with values greater than 0x10000. I have tested the python.org > binaries and those from Activestate, both give me a traceback on > unichr(0x10000) and tell me its a "narrow" build. Wide unicode is currently not supported on Windows. A number of internal APIs (in particular for the registry, and for the "mbcs" codec) assume that sizeof(Py_UNICODE) is 2. Contributions are welcome. Even with that fixed, Pythonwin would still need a major rework to support wide Unicode. Regards, Martin From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 13:48:46 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?ISO-8859-15?Q?Martin_MOKREJ=A6?=) Date: Mon, 10 Jan 2005 19:48:46 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <1105381712.3588.15.camel@localhost.localdomain> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> Message-ID: <41E2CE0E.5000704@ribosome.natur.cuni.cz> Adam DePrince wrote: > On Mon, 2005-01-10 at 11:11, Martin MOKREJ? wrote: > >>Hi, >> I have sets.Set() objects having up to 20E20 items, >>each is composed of up to 20 characters. Keeping >>them in memory on !GB machine put's me quickly into swap. >>I don't want to use dictionary approach, as I don't see a sense >>to store None as a value. The items in a set are unique. > > > Lets be realistic. Your house is on fire and you are remodeling the > basement. > > Assuming you are on a 64 bit machine with full 64 bit addressing, your > absolute upper limit on the size of a set is 2^64, or > 18446744073709551616 byte. Your real upper limit is at least an order > of magnitude smaller. > > You are asking us how to store 20E20, or 2000000000000000000000, items > in a Set. That is still an order of magnitude greater than the number > of *bits* you can address. Your desktop might not be able to enumerate > all of these strings in your lifetime, much less index and store them. > > We might as well be discussing the number of angles that can sit on the > head of a pin. Any discussion of a list vs Set/dict is a small micro > optimization matter dwarfed by the fact that there don't exist machines > to hold this data. The consideration of Set vs. dict is an even less > important matter of syntactic sugar. > > To me, it sounds like you are taking an AI class and trying to deal with > a small search space by brute force. First, stop banging your head > against the wall algorithmically. Nobody lost their job for saying NP > != P. Then tell us what you are tring to do; perhaps there is a better > way, perhaps the problem is unsolvable and there is a heuristic that > will satisfy your needs. Hi Adam, just imagine, you want to compare how many words are in English, German, Czech, Polish disctionary. You collect words from every language and record them in dict or Set, as you wish. Once you have those Set's or dict's for those 4 languages, you ask for common words and for those unique to Polish. I have no estimates of real-world numbers, but we might be in range of 1E6 or 1E8? I believe in any case, huge. My concern is actually purely scientific, not really related to analysis of these 4 languages, but I believe it describes my intent quite well. I wanted to be able to get a list of words NOT found in say Polish, and therefore wanted to have a list of all, theoretically existing words. In principle, I can drop this idea of having ideal, theoretical lexicon. But have to store those real-world dictionaries anyway to hard drive. Martin From bokr at oz.net Fri Jan 14 17:29:01 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 14 Jan 2005 22:29:01 GMT Subject: Octal notation: severe deprecation References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> <39ednWfqlrgB6HvcRVn-iA@powergate.ca> <41e6f606.777680996@news.oz.net> <34qjvcF4dkctuU2@individual.net> Message-ID: <41e83e05.861647303@news.oz.net> On Fri, 14 Jan 2005 20:13:48 +0100, Reinhold Birkenfeld wrote: >Bengt Richter wrote: >> On Thu, 13 Jan 2005 08:18:25 -0500, Peter Hansen wrote: >> >>>and-google at doxdesk.com wrote: >>>> In Mythical Future Python I would like to be able to use any base in >>>> integer literals, which would be better. Example random syntax: >>>> >>>> flags= 2x00011010101001 >>>> umask= 8x664 >>>> answer= 10x42 >>>> addr= 16x0E800004 # 16x == 0x >>>> gunk= 36x8H6Z9A0X >>> >>>I think I kinda like this idea. Allowing arbitrary values, >>>however, would probably be pointless, as there are very >>>few bases in common enough use that a language should make >>>it easy to write literals in any of them. So I think "36x" >>>is silly, and would suggest limiting this to 2, 8, 10, and >>>16. At the very least, a range of 2-16 should be used. >>>(It would be cute but pointless to allow 1x000000000. :-) >>> >> My concern is negative numbers when you are interested in the >> bits of a typical twos-complement number. (BTW, please don't tell me >> that's platform-specific hardware oriented stuff: Two's complement is >> a fine abstraction for interpreting a bit vector, which is another >> fine abstraction ;-) >> >> One way to do it consistently is to have a sign digit as the first >> digit after the x, which is either 0 or base-1 -- e.g., +3 and -3 would be >> >> 2x011 2x101 >> 8x03 8x75 >> 16x03 16xfd >> 10x03 10x97 > >Why not just -2x11? IMHO, Py2.4 does not produce negative values out of >hex or oct literals any longer, so your proposal would be inconsistent. > Inconsistent with what? This is a new based-literal representation, not the old hex or octal representation. It is separate and self-consistent, and can live along side the old. The fact that there is no longer a way to represent negative numbers with traditional octal or hex is due to getting away from the platform-dependent assumptions that bit 31 was a sign bit of a 32-bit two-s complement machine represenentation. That was a good thing to get away from. But it means you now have to write a unary minus expression for negative numbers, not a self-contained literal. Re your question, -2x11 is the same as -(2x11) so you have to decide what you want 2x11 to mean. If it means +3, we are back to the original problem of having no way to see any of the 111111111111....101 or ffff....fd of a -3 ;-) (Except of course by '%02x'%(-0x3&0xff) -- ick) I am not proposing a change to the new Py2.4 positive-only hex and octal literals. I just want to be able to write literals for both positive and negative numbers as self-contained literals (not expressions) without a '-' sign, and have the representation be a readable representation of typical twos-complement representation. You can't do that with -0x3, because (though the expression equals -3) it doesn't show the information about the bits that you get with 16xfd or 2x101. Note that -16xfd == 16x03 and -2x101 == 2x011 and -16x03 == 16xfd and -2x011 == 2x101. The '-' sign is not part of the literal. Regards, Bengt Richter From a at b.c Thu Jan 6 21:34:31 2005 From: a at b.c (Doug Holton) Date: Thu, 06 Jan 2005 20:34:31 -0600 Subject: Embedding a restricted python interpreter In-Reply-To: References: Message-ID: Rolf Magnus wrote: > Hi, > > I would like to embed a python interpreter within a program, but since that > program would be able to automatically download scripts from the internet, > I'd like to run those in a restricted environment, which basically means > that I want to allow only a specific set of modules to be used by the > scripts, so that it wouldn't be possible for them to remove files from the > hard drive, kill processes or do other nasty stuff. > Is there any way to do that with the standard python interpreter? Hi, there is a page on this topic here: http://www.python.org/moin/SandboxedPython The short answer is that it is not possible to do this with the CPython, but you can run sandboxed code on other virtual machines, such as Java's JVM with Jython, or .NET/Mono's CLR with Boo or IronPython. In the future it may also be possible to do this with PyPy or Parrot. From wuwei23 at gmail.com Mon Jan 24 02:09:07 2005 From: wuwei23 at gmail.com (alex23) Date: 23 Jan 2005 23:09:07 -0800 Subject: how to write a tutorial In-Reply-To: References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106531824.833549.28720@c13g2000cwb.googlegroups.com> Message-ID: <1106549330.444901.170110@f14g2000cwb.googlegroups.com> Daniel Bickett wrote: > You guys are just begging for a YHBT ;-) Point taken :) I've noticed very few people even acknowledge his posts at all; I'll follow the group lead and do the same. Cheers! - alex23 From __peter__ at web.de Thu Jan 27 03:17:33 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Jan 2005 09:17:33 +0100 Subject: Which is faster? References: <1106793602.782397.61260@z14g2000cwz.googlegroups.com> Message-ID: Aggelos I. Orfanakos wrote: > Any idea which of the following is faster? > > 'a/b/c/'[:-1] > > or > > 'a/b/c/'.rstrip('/') Don't ask for the speed, decide whether you want to transform "a/b/c" --> "a/b/c" "a/b/c//" --> "a/b/c" or "a/b/c" --> "a/b/" "a/b/c//" --> "a/b/c/" That is much more important. Peter From rkern at ucsd.edu Fri Jan 7 22:06:31 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 07 Jan 2005 19:06:31 -0800 Subject: Python evolution: Unease In-Reply-To: <41deb485$1@nntp0.pdx.net> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com><7x652che6z.fsf@ruckus.brouhaha.com><7x4qhw859p.fsf@ruckus.brouhaha.com><7xk6qrnbum.fsf@ruckus.brouhaha.com><41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41deb485$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > If you can wait, the plan for MacEnthon (Python 2.4 on Mac) looks great: Actually, just packages for 2.3 (or 2.3.x for Tiger) as of right now. When someone else packages up 2.4 nicely, I'll start making packages for that, too. > http://www.scipy.org/wikis/featurerequests/MacEnthon > > I seem to remember discussion about synchronizing with the windows 2.4 > version to have essentially the same list. They probably won't be synchronized too much. My additions to the list are primarily for the people I need to support within my organization. Or my own personal sense of whimsy. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From fuzzyman at gmail.com Wed Jan 5 07:13:18 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jan 2005 04:13:18 -0800 Subject: is python more popular than coldfusion? In-Reply-To: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1104927198.542009.208630@z14g2000cwz.googlegroups.com> Definitely ! Fuzzy http://www.voidspace.org.uk/python/index.shtml From fredrik at pythonware.com Thu Jan 13 14:15:20 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 13 Jan 2005 20:15:20 +0100 Subject: sorted (WAS: lambda) References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com><7x7jmh1eek.fsf@ruckus.brouhaha.com> <7xpt09xizb.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >> Note that sorted is a builtin function, not a method of a list >> object. > > Oh, same difference. I thought it was a method because I'm not using > 2.4 yet. The result is the same nope. sorted works on any kind of sequence, including forward-only iterators. sorted(open(filename)) works just fine, for example. > other than that having it as a function instead of a method is another > inconsistency to remember I suspect that you don't really understand how sequences and iterators work in Python... From ionel.mc at gmail.com Sun Jan 9 10:07:53 2005 From: ionel.mc at gmail.com (ionel) Date: Sun, 9 Jan 2005 17:07:53 +0200 Subject: raw sockets ? i need a python sniffer Message-ID: on windows xp well i got pylibpcap-0.4 but i can't compile it :( i got python 2.4, visual studio 2003 when i run "setup.py build" i get this: C:\Python24\lib\distutils\dist.py:222: UserWarning: 'licence' distribution optio n is deprecated; use 'license' warnings.warn(msg) running build running build_py running build_ext building 'pcapcmodule' extension Traceback (most recent call last): File "d:\_PRO\__11\lib\pylibpcap-0.4\pylibpcap-0.4\setup.py", line 104, in ? cmdclass = {'clean': pcapclean, 'build_ext':pcap_build_ext}, File "C:\Python24\lib\distutils\core.py", line 149, in setup dist.run_commands() File "C:\Python24\lib\distutils\dist.py", line 946, in run_commands self.run_command(cmd) File "C:\Python24\lib\distutils\dist.py", line 966, in run_command cmd_obj.run() File "C:\Python24\lib\distutils\command\build.py", line 112, in run self.run_command(cmd_name) File "C:\Python24\lib\distutils\cmd.py", line 333, in run_command self.distribution.run_command(command) File "C:\Python24\lib\distutils\dist.py", line 966, in run_command cmd_obj.run() File "C:\Python24\lib\distutils\command\build_ext.py", line 279, in run self.build_extensions() File "C:\Python24\lib\distutils\command\build_ext.py", line 405, in build_exte nsions self.build_extension(ext) File "C:\Python24\lib\distutils\command\build_ext.py", line 442, in build_exte nsion sources = self.swig_sources(sources, ext) TypeError: swig_sources() takes exactly 2 arguments (3 given) any help please? :) -- ionel. From sjmachin at lexicon.net Wed Jan 12 19:34:04 2005 From: sjmachin at lexicon.net (John Machin) Date: 12 Jan 2005 16:34:04 -0800 Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: <1105576444.510743.93120@f14g2000cwb.googlegroups.com> Chris Lasher wrote: > Hello, > I have a rather large (100+ MB) FASTA file from which I need to > access records in a random order. The FASTA format is a standard format > for storing molecular biological sequences. Each record contains a > header line for describing the sequence that begins with a '>' > (right-angle bracket) followed by lines that contain the actual > sequence data. Three example FASTA records are below: > > >CW127_A01 > TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG > TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA > GCATTAAACAT [snip] > Since the file I'm working with contains tens of thousands of these > records, I believe I need to find a way to hash this file such that I > can retrieve the respective sequence more quickly than I could by > parsing through the file request-by-request. However, I'm very new to > Python and am still very low on the learning curve for programming and > algorithms in general; while I'm certain there are ubiquitous > algorithms for this type of problem, I don't know what they are or > where to look for them. So I turn to the gurus and accost you for help > once again. :-) If you could help me figure out how to code a solution > that won't be a resource whore, I'd be _very_ grateful. (I'd prefer to > keep it in Python only, even though I know interaction with a > relational database would provide the fastest method--the group I'm > trying to write this for does not have access to a RDBMS.) > Thanks very much in advance, > Chris Before you get too carried away, how often do you want to do this and how grunty is the box you will be running on? Will the data be on a server? If the server is on a WAN or at the other end of a radio link between buildings, you definitely need an index so that you can access the data randomly! By way of example, to read all of a 157MB file into memory from a local (i.e. not networked) disk using readlines() takes less than 4 seconds on a 1.4Ghz Athlon processor (see below). The average new corporate desktop box is about twice as fast as that. Note that Windows Task Manager showed 100% CPU utilisation for both read() and readlines(). My guess is that you don't need anything much fancier than the effbot's index method -- which by now you have probably found works straight out of the box and is more than fast enough for your needs. BTW, you need to clarify "don't have access to an RDBMS" ... surely this can only be due to someone stopping them from installing good free software freely available on the Internet. HTH, John C:\junk>python -m timeit -n 1 -r 6 "print len(file('bigfile.csv').read())" 157581595 157581595 157581595 157581595 157581595 157581595 1 loops, best of 6: 3.3e+006 usec per loop C:\junk>python -m timeit -n 1 -r 6 "print len(file('bigfile.csv').readlines())" 1118870 1118870 1118870 1118870 1118870 1118870 1 loops, best of 6: 3.57e+006 usec per loop From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 20:11:53 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?windows-1252?Q?Martin_MOKREJ=8A?=) Date: Tue, 11 Jan 2005 02:11:53 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <7xis64ree5.fsf@ruckus.brouhaha.com> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <7xmzvgren6.fsf@ruckus.brouhaha.com> <7xis64ree5.fsf@ruckus.brouhaha.com> Message-ID: <41E327D9.4000202@ribosome.natur.cuni.cz> Paul Rubin wrote: > Paul Rubin writes: > >>handle with builtin Python operations without putting some thought >>into algorithms and data structures. From "ribosome" I'm guessing >>you're doing computational biology. If you're going to be writing Well, trying sort of ... Not much successfull so far. ;) >>code for these kinds of problems on a regular basis, you probably >>ought to read a book or two on the topic. "CLRS" is a good choice: >> >> http://theory.lcs.mit.edu/~clr/ >> http://mitpress.mit.edu/algorithms/ > > > Correction to unclarity: I meant a book on the topic of algorithms and > data structures (e.g. CLRS). Since you're presumably already a > biologist, I wouldn't presume to suggest that you read a book on > biology ;-). Yes, I'm. I still don't get what that acronym CLRS stands for ... :( From simon.brunning at gmail.com Fri Jan 21 07:37:46 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 21 Jan 2005 12:37:46 +0000 Subject: map in Python In-Reply-To: <1106310327.213874.305660@f14g2000cwb.googlegroups.com> References: <1106310327.213874.305660@f14g2000cwb.googlegroups.com> Message-ID: <8c7f10c605012104373199e615@mail.gmail.com> On 21 Jan 2005 04:25:27 -0800, Stu wrote: > I have recently switched over to Python from Perl. I want to do > something like this in Python: > > @test = ("a1", "a2", "a3"); > map {s/[a-z]//g} @test; > print @test; > > However, I take it there is no equivalent to $_ in Python. But in that > case how does map pass the elements of a sequence to a function? I > tried the following, but it doesn't work because the interpreter > complains about a missing third argument to re.sub. > > import re > test = ["a1", "a2", "a3"] > map(re.sub("[a-z]", ""), test) > print test This what you want? >>> import re >>> test = ["a1", "a2", "a3"] >>> test = [re.sub("[a-z]", "", item) for item in test] >>> test ['1', '2', '3'] -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From bkc at Murkworks.com Mon Jan 17 16:22:19 2005 From: bkc at Murkworks.com (Brad Clements) Date: Mon, 17 Jan 2005 16:22:19 -0500 Subject: Scriptomatic 2.0 References: <41eab05f$0$25799$8fcfb975@news.wanadoo.fr> Message-ID: If you stick an 's' into the URI, so it's https:// you'll get a certificate warning from FireFox. Looks like MS is running a self-signed certificate on www.microsoft.com weird. really -- Novell DeveloperNet Sysop #5 _ "Do Re Mi chel La Si Do" wrote in message news:41eab05f$0$25799$8fcfb975 at news.wanadoo.fr... > Hi ! > > Scriptomatic 2.0 can, now, to generate scripts in Python. > > Download : > > http://www.microsoft.com/downloads/thankyou.aspx?FamilyID=09dfc342-648b-4119-b7eb-783b0f7d1178&displaylang=en > > > Note : scriptomatic is a generator of WMI's scripts, for Windows, (and > compatibles WBEM). > > > > Good night > -- > Michel Claveau > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From mauriceling at acm.org Wed Jan 5 00:43:46 2005 From: mauriceling at acm.org (Maurice LING) Date: Wed, 05 Jan 2005 05:43:46 GMT Subject: Embedding a restricted python interpreter In-Reply-To: References: Message-ID: <41db7e8f$1@news.unimelb.edu.au> Rolf Magnus wrote: > Hi, > > I would like to embed a python interpreter within a program, but since that > program would be able to automatically download scripts from the internet, > I'd like to run those in a restricted environment, which basically means > that I want to allow only a specific set of modules to be used by the > scripts, so that it wouldn't be possible for them to remove files from the > hard drive, kill processes or do other nasty stuff. > Is there any way to do that with the standard python interpreter? > I won't really count on that. In my opinions, which may be wrong, Python is not constructed to work in a sandbox like Java. Java does it by subjecting all classes that it loads through a security manager. What you seems to want is a Python to have Java applet-typed of restrictions. You can try to use 'exec' to run your scripts in a constructed environment. For example, global = {} local = {} ... your stuffs .... statement = [] # to hold the script to run for line in statement: exec statement in global, local global and local are the global and local namespaces respectively. Although it had been explained to me before but I can't recall the details of how it works. In gist, you may be able to craft a global and local environment for your script to run in. I do not know if it is possible to disable or override 'import'...... maurice From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 18:05:02 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?UTF-8?B?TWFydGluIE1PS1JFSsWg?=) Date: Tue, 11 Jan 2005 00:05:02 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <41e2f24d$1@nntp0.pdx.net> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <41e2f24d$1@nntp0.pdx.net> Message-ID: <41E30A1E.2000000@ribosome.natur.cuni.cz> Dear Scott, thatnk you for you excellent email. I also thought about using some zip() function to compress the strings first before using them as keys in a dict. But I don't think I can use one-way hashes, as I need to reconstruct the string later. I have to study hard to get an idea what the proposed code really does. Scott David Daniels wrote: > Tim Peters wrote: > >> [Martin MOKREJ?] >> >>> just imagine, you want to compare how many words are in English, German, >>> Czech, Polish disctionary. You collect words from every language and >>> record >>> them in dict or Set, as you wish. >> >> >> Call the set of all English words E; G, C, and P similarly. >> >>> Once you have those Set's or dict's for those 4 languages, you ask >>> for common words >> >> >> This Python expression then gives the set of words common to all 4: >> E & G & C & P >> >>> and for those unique to Polish. >> >> P - E - G - C > > > One attack is to define a hash to get sizes smaller. Suppose you find > your word sets are 10**8 large, and you find you need to deal with sets > of size 10**6. Then if you define a hash that produces an integer below > 100, you'll find: > E & G & C & P == Union(E_k & G_k & C_k & P_k) for k in range(100) > P - E - G - C == Union(P_k - E_k - G_k - C_k) for k in range(100) > where X_k = [v for v in X if somehash(v) == k] I don't understand here what would be the result from the hashing function. :( Can you clarify this please in more detail? P is the largest dictionary in this example, or was it shifted by one to the right? > This means, you can separate the calculation into much smaller buckets, > and combine the buckets back at the end (without any comparison on the > combining operations). Yes. > > For calculating these two expressions, you can dump values out to a > file per hash per language, sort and dupe-elim the contents of the > various files (maybe dupe-elim on the way out). Then hash-by-hash, > you can calculate parts of the results by combining iterators like > inboth and leftonly below on iterators producing words from files. > > > def dupelim(iterable): > source = iter(iterable) > former = source.next() # Raises StopIteration if empty > yield former > for element in source: > if element != former: > yield element > former = element > > def inboth(left, right): > '''Take ordered iterables and yield matching cases.''' > lsource = iter(left) > lhead = lsource.next() # May StopIteration (and we're done) > rsource = iter(right) > for rhead in rsource: > while lhead < rhead: > lhead = lsource.next() > if lhead == rhead: > yield lhead > lhead = lsource.next() > > def leftonly(left, right): > '''Take ordered iterables and yield matching cases.''' > lsource = iter(left) > rsource = iter(right) > try: > rhead = rsource.next() > except StopIteration: # empty right side. > for lhead in lsource: > yield lhead > else: > for lhead in lsource: > try: > while rhead < lhead: > rhead = rsource.next() > if lhead < rhead: > yield lhead > except StopIteration: # Ran out of right side. > yield lhead > for lhead in lsource: > yield lhead > break Aaaah, so the functions just walk one line in left, one line in right, if values don't match the value in left is unique, it walks again one line in left and checks if it already matches the value in riught file in the last position, and so on untill it find same value in the right file? So, it doesn't scan the file on right n-times, but only once? Yes, nice thing. Then I really don't need an index and finally I really believe flatfiles will do just fine. > >> Real-word dictionaries shouldn't be a problem. I recommend you store >> each as a plain text file, one word per line. Then, e.g., to convert >> that into a set of words, do >> >> f = open('EnglishWords.txt') >> set_of_English_words = set(f) >> f.close() >> >> You'll have a trailing newline character in each word, but that >> doesn't really matter. >> >> Note that if you sort the word-per-line text files first, the Unix >> `comm` utility can be used to perform intersection and difference on a >> pair at a time with virtually no memory burden (and regardless of file >> size). > > In fact, once you've sorted these files, you can use the iterators > above to combine those sorted files. > > For example: > > Ponly = open('polishonly.txt', 'w') > every = open('every.txt', 'w') > for hashcode in range(100): > English = open('english_%s.txt' % hashcode) --------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^ this is some kind of eval? > German = open('german_%s.txt' % hashcode) > Czech = open('czech_%s.txt' % hashcode) > Polish = open('polish_%s.txt' % hashcode) > for unmatched in leftonly(leftonly(leftonly(dupelim(Polish), > dupelim(English)), dupelim(German)), dupelim(Czech)): > Ponly.write(unmatched) > English.seek(0) > German.seek(0) > Czech.seek(0) > Polish.seek(0) > for matched in inboth(inboth(dupelim(Polish), dupelim(English)), > inboth(dupelim(German), dupelim(Czech))): > every.write(matched) > English.close() > German.close() > Czech.close() > Polish.close() > Ponly.close() > every.close() > > > --Scott David Daniels > Scott.Daniels at Acm.Org From jurgenex at hotmail.com Mon Jan 17 19:48:44 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Tue, 18 Jan 2005 00:48:44 GMT Subject: [perl-python] 20050117, filter, map References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> Message-ID: Abigail wrote: > Steven Bethard (steven.bethard at gmail.com) wrote on MMMMCLVII September > $$ Is there any chance you could post these all as part of the same > thread? > > Just killfile him, and stop replying. Remember, don't feed the trolls. True, except that he spreads lies about Perl and really bad code all over the place. If you don't tell people about how awful his skills are then they may actually mistake his incompetency for flaws in Perl. jue From ianb at colorstudy.com Wed Jan 26 00:55:21 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Tue, 25 Jan 2005 23:55:21 -0600 Subject: [ANN] SQLObject 0.6.1 Message-ID: <41F730C9.2040104@colorstudy.com> SQLObject 0.6.1 --------------- Version 0.6.1 is a bug fix release for 0.6. Most of the work on this release has been thanks to the contributions of Oleg Broytmann. Thanks Oleg! A brief list of changes: * All class methods take a connection argument. * "DISTINCT" option for select results. * Connection objects have a new module attribute, to get access to the connection's exceptions. * New UnicodeCol() for encoding and decoding values from the database. * Added Indexing (patch from Jeremy Fitzhardinge). * Database connections explicitly closed, instead of just letting them be garbage collected. * selectBy can take be called with instances instead of only IDs for foreign key columns. * DBMConnection was removed (it's been broken a long time). What Is SQLObject? ------------------ SQLObject is an Object-Relational Mapper. Basically it makes your database rows feel like (relatively) normal Python objects: Tables are classes, rows are instances, columns are attributes. SQLObject both allows you to define your classes in Python, and SQLObject will create the tables on your behalf, or SQLObject may use database reflection to dynamically create a class given a table name. SQLObject portably supports a variety of database backends: MySQL, PostgreSQL, SQLite, Firebird, MaxDB/SAPDB, and SyBase. SQLObject is being used in a variety of external projects: ezSQLObject, sqlo for Zope 3, and Subway (a Ruby on Rails clone), among others. Where Is SQLObject? ------------------- Website: http://sqlobject.org News: http://sqlobject.org/docs/News.html#sqlobject-0-6-1 Documentation: http://sqlobject.org/docs/SQLObject.html Subversion repository: http://svn.colorstudy.com/trunk/SQLObject Mailing list: http://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://dir.gmane.org/gmane.comp.python.sqlobject Download: http://prdownloads.sourceforge.net/sqlobject/SQLObject-0.6.1.tar.gz?download -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From bulba at bulba.com Sun Jan 2 12:15:56 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 02 Jan 2005 18:15:56 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: On Sat, 01 Jan 2005 15:08:01 -0500, Steve Holden wrote: >> There is the stability issue you mention... but also probably the fear >> issue. If you choose a solution from a major company -- then it fails for >> some reason or they drop the product -- it's their fault -- you've got an >> automatic fall guy. On the other hand, an open source solution or >> otherwise less accepted solution ... it will probably be consider >> your fault by the organization. It's a rational decision to avoid >> personal risk when you don't get much reward for choosing something >> different. >You are ignoring the fact that with the open source solution you do at >least have the option of hiring bright programmers to support the >framework which has now become moribund, Theoretically. Because even though the source code is available and free (like in beer as well as in speech) the work of programmers isn't cheap. This "free software" (not so much OSS) notion "but you can hire programmers to fix it" doesn't really happen in practice, at least not frequently: because this company/guy remains ALONE with this technology, the costs are unacceptable. It's a case of "marginal cost" (cost of making yet another copy) becoming equals to the costs of a project: that is extraordinarily expensive software. If this software gets sold or copied by the millions, the marginal costs is going down to zero, like it is the case with Linux. Imagine NOT being a technology company (say, Sun or IBM or Borland) and trying to hire programmers to fix you the kernel of this operating system. >whereas when a company goes >bust there's no guarantee the software IP will ever be extricated from >the resulting mess. There is a good _chance_ here: money. Somebody has poured a lot of money into this thing. It's not going to get dropped bc of that. >So I'm not sure I'd agree with "rational" there, though "comprehensible" >might be harder to argue with. It depends on definition of "rational", on definition of your or company's goals and on the definitions of the situations that are the context. >Avoidance of blame is way too large a motivator in large organizations, >and it leads to many forms of sub-optimal decision making. This might be of interest to some people: http://www.pkarchive.org/new/DefectiveInvestors.html -- It's a man's life in a Python Programming Association. From apardon at forel.vub.ac.be Thu Jan 20 07:19:11 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Jan 2005 12:19:11 GMT Subject: Freezing a mutable (was Re: lambda) References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> <41ed8c13.1209309354@news.oz.net> Message-ID: Op 2005-01-20, Nick Coghlan schreef : > Antoon Pardon wrote: >> Interesting idea. But I think you are wrong when you say that two lists >> that compare equal at the time they are frozen, will get the same >> dictionary entry. The problem is an object must compare equal to >> the key in the dictionary to get at the same entry. So if you freeze >> a list and its copy but then mutate them differently, they no longer >> are equal and so wont get you at the same entry. > > The trick is that the result of the freezing operation is cached until such time > as you explicitly unfreeze the object. I missed that you would use it with the idiom: dct[x.frozen()] I have two problems with this approach. 1) It doesn't work when you get your keys via the keys/items methods. 2) This is rather minor, but a user could still unfreeze untimely -- Antoon Pardon From alanmk at hotmail.com Sun Jan 23 07:23:27 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 23 Jan 2005 12:23:27 +0000 Subject: Textual markup languages (was Re: What YAML engine do you use?) In-Reply-To: References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> Message-ID: [Effbot] > ReST and YAML share the same deep flaw: both formats are marketed > as simple, readable formats, and at a first glance, they look simple and read- > able -- but in reality, they're messy as hell, and chances are that the thing > you're looking at doesn't really mean what you think it means (unless you're > the official ReST/YAML parser implementation). experienced designers > know how to avoid that; the ReST/YAML designers don't even understand > why they should. I'm looking for a good textual markup language at the moment, for capturing web and similar textual content. I don't want to use XML for this particular usage, because this content will be entered through a web interface, and I don't want to force users through multiple rounds of submit/check-syntax/generate-error-report/re-submit in order to enter their content. I have no strong feelings about YAML: If I want to structured data, e.g. lists, dictionaries, etc, I just use python. However, I'm torn on whether to use ReST for textual content. On the one hand, it's looks pretty comprehensive and solidly implemented. But OTOH, I'm concerned about complexity: I don't want to commit to ReST if it's going to become a lot of hard work or highly-inefficient when I really need to use it "in anger". From what I've seen, pretty much every textual markup targetted for web content, e.g. wiki markup, seems to have grown/evolved organically, meaning that it is either underpowered or overpowered, full of special cases, doesn't have a meaningful object model, etc. So, I'm hoping that the learned folks here might be able to give me some pointers to a markup language that has the following characteristics 1. Is straightforward for non-technical users to use, i.e. can be (mostly) explained in a two to three page document which is comprehensible to anyone who has ever used a simple word-processor or text-editor. 2. Allows a wide variety of content semantics to be represented, e.g. headings, footnotes, sub/superscript, links, etc, etc. 3. Has a complete (but preferably lightweight) object model into which documents can be loaded, for transformation to other languages. 4. Is speed and memory efficient. 5. Obviously, has a solid python implementation. Most useful would be a pointer to a good comparison/review page which compares multiple markup languages, in terms of the above requirements. If I can't find such a markup language, then I might instead end up using a WYSIWYG editing component that gives the user a GUI and generates (x)html. htmlArea: http://www.htmlarea.com/ Editlet: http://www.editlet.com/ But I'd prefer a markup solution. TIA for any pointers. regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From ajsiegel at optonline.com Sun Jan 30 07:51:08 2005 From: ajsiegel at optonline.com (Arthur) Date: Sun, 30 Jan 2005 07:51:08 -0500 Subject: The next Xah-lee post contest References: Message-ID: On Sat, 29 Jan 2005 15:41:00 +0100, PA wrote: > >On Jan 29, 2005, at 15:32, rbt wrote: > >> Unix donkey! You not elegant. You have poor design. >> Sloppy Perl monkey! You be lazy! You code very very bad. >> >> Xah know all! > >Follow The True Path, follow The Xah Way To Enlightenment: > >"The Unix Pestilence" >http://www.xahlee.org/UnixResource_dir/freebooks.html > >Cheers Not sure how Xah got himself into all this. When I actually read the substance of Xah's articles like the one referenced above, and ignore the stuff in Red, I don't find it all that bizarre - or uninformative. He links to substantive resources. He has postive things to say about lots of things, including Python. Guess I am prejudiced by the fact that I have always enjoyed his plane curve pages, and after David Eppsteins Geometry Junkyard and a few others, consider it one of the more interesting web resources in respect to geometry. I knew of him for this, well before I knew of him as the Usenet character he is. Wish he would do himself the favor of better separating he various "interests". One can google on "plane curves", and the first hit will be Xah's site. I certainly find it interesting and well done. On the other hand, if one goes by way of his home page, one is greeted first with a vitriolic message expressing a sentiment not all that uncommon but not very relevant to the substance of much of what is to be found at the site. Oh well. Art From fredrik at pythonware.com Sun Jan 23 13:33:58 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 19:33:58 +0100 Subject: What is print? A function? References: <200501231835.07310.frans.englich@telia.com> Message-ID: Frans Englich wrote: > I find this a nice solution. The most practical would be if it was possible to > do this with print, of course. But print won't budge. you can disable print, though: class dev_null: def write(self, text): pass sys.stdout = dev_null() or pipe all print requests to a debug stream: if my_debug_flag: debug = sys.stdout else: debug = dev_null() print >>debug, "hello" print >>debug, "the value is", value > Is it possible to create own statements, such that it would be possible to do: > > printDebug "test" no. From caseyhHAMMER_TIME at istar.ca Wed Jan 26 23:11:57 2005 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Thu, 27 Jan 2005 04:11:57 GMT Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: "The object-oriented programming paradigm has an undeserved reputation as being complicated; most of the complexity of languages such as C++ and Java has nothing to do with their object orientation but comes instead from the type declarations and the mechanisms to work around them. This is a prime example of how Scheme's approach of removing restrictions compares with the "piling feature on top of feature" needed in other languages, such as the C++ template mechanism." "Handbook of Programming Languages, Volume IV: Functional and Logic Programming Languages" Peter H. Salus, editor 1998 page 63 Similarly, now, Java's generics! -- Regards, Casey From jbperez808 at wahoo.com Wed Jan 12 04:54:49 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Wed, 12 Jan 2005 17:54:49 +0800 Subject: Another look at language comparisons In-Reply-To: <41e00ac1$0$265$edfadb0f@dread12.news.tele.dk> References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> <1105188426.955508.263030@c13g2000cwb.googlegroups.com> <41e00ac1$0$265$edfadb0f@dread12.news.tele.dk> Message-ID: <34kaf5F4ag9k6U1@individual.net> Max M wrote: > Jan Dries wrote: > >> beliavsky at aol.com wrote: >> And there is hope for Python, as Guido has recently been seen with a >> beard :-) >> http://www.tbray.org/ongoing/When/200x/2004/12/08/-big/IMG_3061.jpg > > > LOL, he is working on linux, isn't he? > > So it was about bloody time. Guido Van Rossum is now working on linux?? From xah at xahlee.org Sun Jan 23 04:28:28 2005 From: xah at xahlee.org (Xah Lee) Date: 23 Jan 2005 01:28:28 -0800 Subject: how to write a tutorial In-Reply-To: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> Message-ID: <1106472508.591411.40140@c13g2000cwb.googlegroups.com> adding to my previosu comment... In the Python tutorial: http://python.org/doc/2.3.4/tut/node11.html the beginning two paragraphs should be deleted. Nobody gives a shit except a few smug academicians where the author wrote it for pleasing himself. For 99% of readers, it is incomprehensible and irrelevant. the first paragraph of 9.1 "A Word About Terminology" is epitome of masturbation. The entire 9.1 is not necessary. Large part of 9.2 "Python Scopes and Name Spaces" is again masturbatory. -- Most texts in computing are written by authors to defend and showcase their existence against their peers. In a tutorial, nobody cares how the language compared to x y and z, or what technicality is it all about, or some humorous snippet of history only funny to the author himself. Particularly for texts in a tutorial context, you want to write it as simple as possible covering the most useful basic functionalities and concepts, and self-contained. Not showcasing your knowledge of history of languages or your linguistic lineage byways. For example this chapter 9 on Objects, it is not difficult to write it without making a show of lingoes. One simply write what is of Python, without thinking about relation to xyz languages or the "computer science" establishment and their ways of thinkings of namespaces and scopes and dynamic and statics and inheritances ... fucking bags of shit. Also, in the computing industry, documentations and tutorials often lacks examples. Especially important in tutorials. Be fewer in words, more in examples. (for example, unix man pages are full of arcane abstract syntax specifications and inner-working technicalities while most don't contain a single example of usage that is much needed.) also, this does not mean beginning to write for dummies as the highly successful series of "xyz for Dummies" books. These are successful because the corpus of textbook writers are all inclined and habituated to chalk up to jargons and intellectualization on the accounts of their own esteem and careers. Dummy books are moronic because they assumed the general readers are morons. PS Another illustrative case is the official Java Tutorial. Python tutorial is to the point on the whole. The Java Tutorial is completely asinine. Chalking up to rocket sciences every chance with unhelpful and misleading drivel. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From godoy at ieee.org Wed Jan 19 11:25:31 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Wed, 19 Jan 2005 14:25:31 -0200 Subject: Accessing MDB files on Windows References: <1635068.ZTfiooUzB4@strongwill.g2ctech> Message-ID: <4262806.PViGKJWPeZ@strongwill.g2ctech> Larry Bates, Quarta 19 Janeiro 2005 14:01, wrote: > I'm assuming the application will be run on Windows. You're right. It will be run on Windows. I discarded some other platform due to the difficulty of supporting this file format. > You can use ODBC or DAO. > > An DAO solution that I wrote (and use) can be found > at: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303349 Thanks! I'm looking at it. > For ODBC you would just use the standard library module. Thanks. I'll be trying the DAO first. -- Godoy. From ncoghlan at iinet.net.au Mon Jan 10 05:26:23 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 10 Jan 2005 20:26:23 +1000 Subject: python3: accessing the result of 'if' In-Reply-To: References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> <1105236383.521393.40680@c13g2000cwb.googlegroups.com> Message-ID: <41E2584F.3050808@iinet.net.au> Steve Holden wrote: > Excuse me, these are supposed to be IMPROVEMENTS to Python? I think it's more messing around before coming to the conclusion that, of the many things that 'where' helps with, this sure as hell ain't one of them :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From andrea.gavana at agip.it Fri Jan 14 05:44:39 2005 From: andrea.gavana at agip.it (andrea.gavana at agip.it) Date: Fri, 14 Jan 2005 11:44:39 +0100 Subject: Threading Or Other Suggestions?!? Message-ID: Hello NG, I have a wxPython application that does a lot of things. One of them, in particular, I have doubts on how to implement it. Essentially, this part of my application calls an external executable (an oil reservoir simulator). What I would like to do, is to give the user the possibility to run more than 1 simulation at the same time. This means: 1) Writing the executable "data file" needed by the simulator 2) Run the executable file (and wait until completion) 3) Examine the simulation results For this, I was thinking about threads... does anyone have other/better suggestion(s)? Does anyone see any difficulty/memory problems in using threads? Thanks to you all for every suggestion. Andrea. ------------------------------------------------------------------------------------------------------------------------------------------ Message for the recipient only, if received in error, please notify the sender and read http://www.eni.it/disclaimer/ From bulba at bulba.com Wed Jan 5 21:11:59 2005 From: bulba at bulba.com (Bulba!) Date: Thu, 06 Jan 2005 03:11:59 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> <1gpwrh7.b7z8qtablx7gN%aleaxit@yahoo.com> Message-ID: On Wed, 5 Jan 2005 11:19:56 +0100, aleaxit at yahoo.com (Alex Martelli) wrote: >Say that the city has ten hat shops of the same quality. One is in >Piazza dell'Unita`, all the way to the Northern border of the city. One >is in Piazza Saragozza, all the way to the Southern border. The other >eight are in Piazza dell'Orologio, smack in the middle of downtown. >Each shop offers hats taken from the same random distribution: we can >say that a normal curve measuring the utility function for the customer >(some function of price, quality, looks, fit, ...), with identical >average and variance, represents the best hat available today from a >given shop from the POV of a given customer. >Say that a customer has one day to shop for their new hat, and the >locations are too far apart for a customer to visit more than one >location within that day. If a customer chooses to visit the one >southern shop, or the one northern shop, the customer expects to be >presented with the choice of hat from said normal curve. If the >customer goes downtown, they expect a choice which overall lies along a >DIFFERENT curve -- the best-of-eight samples from the normal curve. >Sorry I can't model that analytically, but both intuitively and from any >little simulation (easy to code in Python) you can see the customer's >expectations are much better if they choose the location where they can >do more comparison shopping! Obviously. I completely agree with you that is how it works _in a model_, if reality were similar to that model. What I doubt is that _in practice_ simple costs associated with physical distance are so overwhelming. Maybe they used to be in the past. I keep asking: what exactly is the premium to customer to go to that place? what is the cost? Suppose in your example the customer has to get in the car in order to get to the hat shop anyway. And when he gets to that quarter of the city, he finds no parking place. And we know that even highly paid people tend to spend seemingly irrationally much time driving around in order to find the free place because they find the thought of having to pay little money to pay for parking so disgusting. >Note that I'm not saying there are no forces pushing against clustering: >of course there are, varying by industry etc. But they're easy to >overstate. True, true... What I'm getting at is that "repelling forces" can also be easy to understate and "pulling forces" can be easy to overstate. >Consider the highly skilled worker who has a choice: they >can stay in some crowded cluster, say Silicon Valley, and keep facing >congestion, high rents, etc, for high salaries and great opportunities >to keep hopping to the highest bidder; or, they can accept an offer at a >lower salary in some more isolated area, say a minor cluster such as >Austin, Tx, and get less congestion, cheaper housing, etc, although also >less opportunity to keep enhancing their careers. I personally know a developer who worked in Orange County, absolutely loved the place and refused to leave for years even though it consumed almost half of his wage in rent. Then, one day, when he called me (we like to have long talks over the phone), he said "screw it, I truly hate to leave, but I'm not going to suffer that rent anymore". Now he claims that due to other factors California is going down the drain and educated people and businesses escape that state. Apparently some stronger "repelling force" has overcome the pulling clustering forces. > Which kind of worker >will tend to pick which of the two? Somebody who thinks they may be >past the peak of their career, and won't get many more lucrative offers >in the future anywa, might be more tempted by (say) Austin, while >somebody who's keenly competitive and on a sharp upwards path may keep >braving the congestion for the (to them) attractive lures and challenges >of Silicon Valley. Not if the state has had rollling black-outs, which puts the production on automated semiconductor line in danger, because backup generators have not been designed to operate for such a long black-out. You see, I'm not disagreeing with you that your model applies _where it applies_. I only disagree that it applies in face of stronger forces. Now what kind of forces is dominant in most frequent scenarios would have to be worked out in tedious empirical research I think. Which I haven't done, because learning some economics is just a hobby to me. >Of course there are a zillion other factors, but in >as much as we're talking about factors strictly related to clustering, >this is the bias, and therefore (in an Akerlovian model) this is the >message which tends to be sent by such choices. This I agree with. >But there are other transaction costs, mostly connected to the need for >face-to-face interaction as being the most effective form. I've worked >for a SW development firm which tried to coordinate development >distributed across many locations via cheap video-based teleconferences >spanning timezones from California all the way to India; I've done way >more than my share of telecommuting and airport- and plane-hopping for >development projects geographically distributed and/or mostly located >far from the customers and/or other stakeholders; I know whereof I >speak... Oh I do not mean smth so extreme. >I remember glancing at some costly booklet called something like "Poland >Infrastructure Report" back when an employer was considering setting up >a branch office somewhere in Poland (selling and customizing SW for the >mechanical industry), and back then issues such as internet and other >telecom access, easy availability of top graduates, ease for expatriates >from Italy to live in the place for a while knowing only English and >Italian, at most German and French, and not Polish or Russian, closeness >to good international airports and other good transportation, closeness >to partner firms and potential customers' decision-makers, all appeared >to point to Warsaw, if I recall correctly. Mechanical engineers with >some programming experience or viceversa, good translators, and good >salespeople with connections in the mechanical industry, are not as >ultra-specialized as all that, after all. Most sales offices in Warsaw do not employ esp. educated people in my impression. OTOH, the carmaking facilities nowadays require more much more know-how and specialized workforce than a sales office does. Or at least that was my impression when I worked at the construction machine manufacturer in Berlin. Capital investments per worker in auto industries are reportedly very high. Simple physical tasks are done largely by machines, like this 100 million Deutschmark costing laser-cutting installation that I've seen there, where a pile of iron bars is pulled in at one end and the pile of ready components is spitted out of the other end (unlike typical thermal cutting, laser has the advantage of not destroying the metal structure adjacent to the cut, so the parts of the machines subject to high-stress are oft produced this way). Oh, and by the way that installation doesn't get used much. Somebody at the office didn't check carefully enough the energy prices before ordering it and later someone discovered that off-site specialized cutting firms that take advantage of energy available at low prices at special times in other countries can get it produced cheaper. Moving it elsewhere or selling is not an option, since it is a specially constructed, low, 50-meters long hall that stands inside the huge manufacturing hall of the company. 100 million DM (when 1 DM was worth some half of Euro back then) down the drain. When the company was in rather bad financial situation (later I've learned it was finally bought out by Americans). Oh well. No big deal. I was utterly shocked. Having grown up in Soviet times I have been used to seeing precious resources wasted by organizations as if resources were growing on trees, but smth like this?! In a shining ideal country of Germany?! Unthinkable. >The firm I was working for had a consensus decision-making process (even >I was involved) and managers (and other employees) and stockholders were >mostly the same people -- it wasn't all that large a firm at the time. >Nobody needed to practice risk avoidance. Again, you may have had good luck. Where I worked (including some places in Germany and UK) it was almost the only factor that seemed to matter to people - they'd do ANYTHING not to take a risky decision, to "pass the buck", not to stick their necks out, not to declare doing some work that involved challenges. Though maybe that is just my impression - such issues as interpreting behavior of another human being are contrived and tend to be heavily "filtered" in a subjective filters. Policemen for instance place little value in witnesses of events, because the testimonies tend to be made up of so much disinformation and personal sentiments rather than perceiving what really happened. If that happens re simple events, it is probably much worse re interpretations of another person's motives. >The infrastructure advantages >of Warsaw vs other locations loomed HUGELY large, judging of course from >some consultants' reports purchased for the purpose -- I'd be skeptical of such reports - I don't know about situation from the beginning of 1990s, where this partially may have been the case; however, back then pretty much all of the country has had lousy infrastructure, and today, many bigger cities have comparatively good infrastructure. Workers - here's the difference. Warsaw has been a big "vacuum cleaner" for talented people from all over the country. This may have been a factor. >it may look >different to people living in the place, although I'd like to get a >second opinion from Warsaw's Chamber of Commerce since you appear to >have a very specific individual bone to pick (and I can sympathize: even >though Milan may be the economically correct choice for foreign >investors, I'd never want to LIVE there myself, being a Bolognese... but >I must admit that Milan's infrastructure, connections, location, etc, >etc, may in several cases drive a rational decision to set up there). It's not so much individual as the fact that 80% of foreign investments in this country (in terms of amounts of money invested) are made in Warsaw. While Warsaw REALLY does not have so much better infrastructure. There's the same problem with Russia: similar fraction of foreign investments take place in Moscow, which drives real estate prices there to simply insane levels. Even though other big cities, e.g. Saint-Petersburg has 4.5 million inhabitants and lots of educated people there, too. I doubt that foreign investments in more developed countries are so concentrated in capital cities. Can your clustering model really explain this difference? IOW, I do not claim that your model has zero relevance to real world. I only think that there may be other, fundamental and stronger factors that overwhelm the "clustering forces". There is another factor in this game: govt is a big customer and stability and consistency of legal acts as well as transparency in this country leave much to be desired with, to put it lightly. So the companies HAVE TO be close to the centers of power, just to have its property secure. In this way it is most definitely rational decision to invest in Warsaw even thought the office space there is more expensive than in London (at least that was the case several years ago). > Not all corporations do that: in this country Coca-Cola has made >> their big "green field" investment almost in the middle of nowhere >> in this country. GM, Volkswagen, FIAT, and most of other carmakers >> have made similar decisions. Doesn't seem like those were bad business >> decisions for them. >If their needs were for cheap land for greenfield factories, and cheap >workers for said factories, then they were acting under very different >forces than a midsize company looking to set up a mostly-sales branch >office, not an industrial factory. True. I grant that. >> The cluster I've seen - an IT "corporate area" in Dublin, >> Ireland - was specifically created not due to "natural clustering", >> but due to govt policy of tax breaks and preparing good >> infrastructure in this place rather than some inter-business and >> inter-customer dependencies, since e.g. Microsoft (where the company >> sent me for training) neither is able to get all the workers it needs >> just from this city, nor it sells mostly to local customers, but it >> sells all over Europe. >That's addressing only the issue of endogenous vs exogenous original >causes for clustering. Many attempts to create clusters artificially >have happened ever since the economical advantages of clusters were >discussed in the literature, together with the crucial point that WHERE >the cluster originally happens is in most cases almost random, it's >self-reinforcing once it's properly underway. Note that a lot of deliberate or half-deliberate attempts to create clusters have failed: "content industry" in NY, there was a failed attempt to create high-tech IT/telecom cluster in southern France, etc. "Jumpstarting" the cluster should be easy if this model applied, after which it should develop in a self-reinforcing manner. So why deliberate attempts fail so frequently, while clusters appear in other, unforeseen locations? >Most such attempts have >failed, because governments' powers aren't unlimited; Dublin is a good >example of this strategy succeeding. I'm not sure if this is correlation, but not causation; perhaps except in a wider sense, like creating other good reasons for foreign companies to invest in Ireland at all. I see the "clustering" forces as a sort of derived factor: first, there are fundamental issues that make the company set up in that place or not - see it as "mass" in a physical analogy. Inter-dependency issues, or "gravity" in a physical analogy, comes only later. I do not claim that they can't have the influence at all, by no means. I'm just skeptical of claims if they are of primary importance. >No matter WHY the good infrastructure is there, the tax breaks, the >thriving community of high-tech workers, etc, a firm deciding where to >set up may perfectly well find it rational to have all of these >advantages overwhelm the issues of rents, congestion, competition for >good workers. In other words, my disagreement with your thesis that, >because the government lowered taxes, taking advantage of that is NOT in >the best interests of a firm's stockholders, is now maximal: I find your >thesis not just wrong, but by now outright silly. Huh? Of course it is in the interest of the company and stockholders and they will most likely do it! The point here is much more subtle: what I mean is that this cluster has been created not so much by "gravity" and "repulsion" forces as simple rational choice unrelated to inter-dependency issues - so companies clustering in that place is definitely a rational choice, given that Dublin is 2 million people city in a 5 million people country, they simply won't find workers elsewhere; however, I'd hold this correlation as just correlation (with exception of simple ability of finding most educated workers) and not necessarily causation. That those were _other_ economic factors - like Irish being highly educated, speaking English, and living in a relatively inexpensive member country of EU - as the decisive factors of that decision and not necessarily the typical clustering factors like "being close to your customers". Speaking in such terms, maybe Ireland as a whole country has been such a "cluster", but then again, is such a cluster result of "interdependency" issues or more fundamental factors, such as historical circumstances, govt decisions, political stability, secure property rights, corruption, etc? If the latter, I'd argue that "clustering" in Ireland is a correlation, not causation. >> To me, the issue of manager having to face their superiors >> asking him a question - "why on Earth have you decided >> to locate our branch in the middle of nowhere in this country? >> Why not in capital city? Can't you look at the map? Read some >> stats how many inhabitants this city has and what is the >> income level there?" is overwhelming: it would take long >> time to explain for this manager who e.g. may have already >You are wrong, because the same decisions get rationally made by >sole-owner sole-manager companies where these considerations cannot >apply. Deciding where to site an imporant branch is a BIG decision: of >course it takes a long time, *DUH*, and all sorts of factors are taken >into consideration. Then you have had a good luck of interacting with much, much more reasonable managers than I have had. And that includes some managers in some big multinationals, and not just in this country. Sure, many managers I've seen were careful, insightful and wanted to understand this issue well before making the decision; but I have met equally many decisionmakers who tended to be rash, careless and too quick in their judgments, and really not prone to reconsidering their opinion if the new evidence came in. Sometimes I was scared silly to see how carelessly the important decisions were made, because I knew I may have to live with the consequences. >> got his hands dirty in this industry in that country to know >> that say, there's little revenue increase to be gained in >> locating the facility in capital city, the needed workers are >> actually hard to find there, etc. >So all of these factors are folded into a huge pile of reports in >companies where such decisions are at all likely to be challenged later, >and sign-off on the folders is carefully obtained for cover-up purposes. >If the local development agencies of the "middles of nowhere in that >country" don't do their job, including showering managers planning such >decisions with supporting materials, that's a bad sign: maybe due to >cultural influences foreign capital, professionals, and managers are NOT >welcome there as they would be in a relative metropolis, for example. That was not a factor here really. Most of that has to do with the fact that regional and local branches of govt are exceptionally clueless and lazy (and corrupt), at least when compared to govt in capital city. However, I've observed that they're learning, esp. in the north to north-western part of the country. The East, as usual, is a no-man's-land. It's also the poorest part. >> To me, this is much like decision whether do much of >> development in Python or MS VS / VB. "But everybody's >> using VisualStudio / VB" is a simple and compelling argument: >> "so many people can't be wrong", while explanations that >> going Python may actually be better decision in this context >> requires long and complex explanations and managers oft can >> not even be bothered to read executive summaries. >The issue of parallels or otherwise is by now totally secondary, to me, >to the main issue that I find your approach to explaining regional >clustering problems across industries totally, irredeemably, and >horribly WRONG. So, I'm not going to make the post even longer by even >trying to address this part. Few, besides the two of us, can be left >reading by now, and clearly our disagreements on economics are so total >that it's unlikely we can get anywhere by our discussions anyway. I prefer to think that those are contrived issues and we rather had some disagreements. As usual, when you leave the trivia, and start on more complicated issues, it's not simple anymore. >> I feel econ models frequently are elegantly designed >> abstractions of elegantly designed problems; the problem >> is how close those are to the real-world problems. At >> the end of the day, it's "human action" that gets all >> of that implemented. I've seen too much resources >> going down the drain in completely idiotic projects >> and decisions to believe managers are rational beings. >When you claim managers are acting rationally (if selfishly) to avoid >risk to themselves, you can't then justify this claim by adding that >they aren't rational at all. But that was my attempt of (poor) sarcasm actually... I did not mean that literally. Sorry for that. >Economics does cover, in its modern form, >both issues of agency problems (misalignment of incentives between agent >and owner) AND ones of "bounded rationality" (all the way from >asymmetric information, to transaction costs relating to acquiring and >processing information). Trying to throw economics overboard because >you can't be bothered to understand it is a kind of behavior that >reminds me closely of the "leftists" you excoriate in your signature. I forgot to change this sig when switching to here from political ng, sorry.. It's just a sig but still OT given the nature of the group. Re "throwing the economics overboard" - perish the thought! I don't know why you came to this conclusion, perhaps I did not indicate clearly enough I meant the last paragraph in an ironic way. On the contrary, I have the impression that I belong to the small minority of people who consider economics as science. Au contraire, people oft perceive me as believing too much in relevance of economics! That doesn't mean I have to seee _particular economic model_ as relevant. The history of economics is scattered with such examples, like Phillips curve or Bowley's law (my favorite book by Mark Blaug, "Methodology of Economics", worth a ton of gold, quotes a long litany of such broken models). There's nothing wrong in principle about it: science is about falsification (or at least Karl Popper told us so). I'm just wary of what I see as excessive stressing one factor (like physical proximity) over other, possibly neglected factors. -- It's a man's life in a Python Programming Association. From tim.golden at viacom-outdoor.co.uk Sat Jan 8 14:36:57 2005 From: tim.golden at viacom-outdoor.co.uk (Tim G) Date: 8 Jan 2005 11:36:57 -0800 Subject: Installing IPython on win2k In-Reply-To: References: Message-ID: <1105213017.820231.67050@c13g2000cwb.googlegroups.com> Dave Merrill wrote: > Hi, I'm new to python, and ipython, but not to programming, having trouble > getting ipython installed on windows 2000, python 233. Any help would be > much appreciated; I'm sure I'm being some basic flavor of dense... First of all, rest assured that it does work (and quite easily) so welcome to Python and iPython and I hope the going's a bit smoother as you go along. > Then downloaded ipython-0.6.6.zip and unzipped it. When I double-click > setup.py, I get only a brief wait cursor; nothing else happens, and > importing ipython as a test fails. First of all, ipython isn't really an import into python; you run it and it runs python (if you understand me). So when you've installed it, I think it puts an item on your start menu. On linux, it puts an executable ipython onto your path. I've just downloaded and run the setup.py, and it does create a Start Menu item which will start iPython. Look out for that and see if it does the business. > Both files in the scripts dir, ipython and pycolor, have no filename > extension, which seems odd to my newbie eye. I tried renaming them to .py, > still no difference. This is a unixism. Some unix types decry the use of file extensions because the information the extension gives -- which executable program to use -- is already embedded in the first line of a file. > > My apologies for this basic question, and my no doubt ignorant flailing > about. Very much looking forward to getting this working. > > Thanks, > > Dave Merrill Good luck and happy hunting TJG From rff_rff at remove-yahoo.it Sun Jan 2 09:02:43 2005 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Sun, 02 Jan 2005 14:02:43 GMT Subject: Continuations Based Web Framework - Seaside. In-Reply-To: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> Message-ID: <7aTBd.11928$H%6.521997@twister1.libero.it> Mike Thompson ha scritto: > > 'Seaside' is a Smalltalk framework for what might be called "Modal Web > Development" or "Synchronous Web Programming", or even "Continuation > Based Web Apps". > > http://www.beta4.com/seaside2/ > > Very sexy it looks too. And it seems to be generating a lot of interest > - Ruby and Java variants have already sprung up: > > http://rubyforge.org/projects/borges/ > http://lakeshore.sourceforge.net/ actually, there are also implementations in Scheme, Common Lisp (UnCommonWeb) and Cocoon-FLOW has similar concepts. And somewhere (I think on the portland pattern repository) I recall reading that Viaweb (aka "the first web app") was written in CPS. Also notice that the Wee project in ruby is more advanced that Borges. > I googled for the python spin-off but didn't find one. Closest I found > was Imposter (http://csoki.ki.iif.hu/~vitezg/impostor/) which looks like > an earlier, partially failed attempt to do what Seaside now seems to be > delivering. I think "independent" more than earlier, it seem many people are reinventing this from time to time. Anyway, I just wanted to point out that IIRC something on this lines appeared recently in the nevow svn tree, maybe you can take a look. From steven.bethard at gmail.com Fri Jan 7 15:49:15 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Jan 2005 13:49:15 -0700 Subject: Display Function Code Body? In-Reply-To: <1105130263.788520.96710@f14g2000cwb.googlegroups.com> References: <1105130263.788520.96710@f14g2000cwb.googlegroups.com> Message-ID: Haibao Tang wrote: > What I would like to do is to write a function like disp(), when typed, > it can give you the code infomation. Check the docs entitled "Retrieving source code": http://docs.python.org/lib/inspect-source.html Depending on what you want, you may be able to use inspect.getsource: py> import inspect py> import string py> print inspect.getsource(string.split) def split(s, sep=None, maxsplit=-1): """split(s [,sep [,maxsplit]]) -> list of strings Return a list of the words in the string s, using sep as the delimiter string. If maxsplit is given, splits at no more than maxsplit places (resulting in at most maxsplit+1 words). If sep is not specified or is None, any whitespace string is a separator. (split and splitfields are synonymous) """ return s.split(sep, maxsplit) However, this won't work for functions you've defined interactively I don't think. On the other hand, if you defined them interactively, you can just scroll up. ;) Steve From ncoghlan at iinet.net.au Sat Jan 29 03:14:39 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 29 Jan 2005 18:14:39 +1000 Subject: Who should security issues be reported to? In-Reply-To: <7xu0p0yin0.fsf@ruckus.brouhaha.com> References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <7xu0p0yin0.fsf@ruckus.brouhaha.com> Message-ID: <41FB45EF.2010409@iinet.net.au> Paul Rubin wrote: >>More significantly, any security problem is likely to be with a >>specific function or object that has been implemented in C. > > > False; the Cookie module example we talked about was caused by an > unforeseen interaction between pure Python modules (Cookie and pickle). Fair cop on the C thing, but that example otherwise illustrates my point perfectly. Unpickling untrusted data is just as dangerous as evaluating or executing untrusted data. This is *still* dangerous, because there *is no patch* to fix the problem. There are only documentation changes to highlight the security risks associated with unpickling, and Deprecation Warnings on the Cookie classes which use this unsafe feature. So, the only effective mechanism is to get the word out to Python *users* that the feature is unsafe, and should be used with care, which basically requires telling the world about the problem. Any time Python has a problem of this sort, there is going to be at least one solution, and only possibly two: 1. Avoid the feature that represents a security risk 2. Eliminate the security risk in a maintenance update. The first solution applies regardless of whether the security risk is inherent in Python's design or not. Some obvious examples (given above) relate to execution of untrusted code. The second solution applies only to bugs in the CPython implementation and extension modules. And often, tweaking the application's Python code to avoid the dangerous features is going to be faster (and safer) than changing over to a new Python version. By keeping the process public, and clearly identifying the problematic features, application developers can immediately start working on protecting themselves, in parallel with the CPython developers (possibly) working on a new maintenance release. To go with the 72 hours + 8 example you gave - what if you could work around the broken feature in 6? I suspect we'll have to agree to disagree on this point. Where we can agree is that I certainly wouldn't be unhappy if SF had a feature like Bugzilla's security flag. Regards, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From peter at engcorp.com Fri Jan 14 23:25:21 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 14 Jan 2005 23:25:21 -0500 Subject: Com port interrupts again In-Reply-To: <154gu09bghnq674s2nqot9si6d50igueq7@4ax.com> References: <154gu09bghnq674s2nqot9si6d50igueq7@4ax.com> Message-ID: engsol wrote: > I didn't fully think through my application before posting my > question. Async com port routines to handle com port interrups > only work well if one has access to the low level operating > system. In that case the receive buffer interrupt would cause > a jump to an interrupt service routine.. I don't believe that > Python provides that capabilty directly. The solution then would > be to write a C extention? Maybe, but I doubt that you can or would really want to do this with modern operating systems anyway. With DOS, and similar primitive things, glomming onto an interrupt or hooking yourself into the interrupt table was pretty easy. I don't think either Windows or Linux is structured such that you just "write a C extension" to intercept interrupts. Instead, you must write relatively complicated drivers which have to be loaded at system startup (more or less) and be tied into the kernel at a relatively low level. Think "rocket science", at least in comparison to writing a simple C extension. :-) > The suggestions offered by respondents to my original post > were almost all of a "Use threads, and poll as needed" flavor. > You're right...I need to learn threads as applied to com ports. At least on Windows, I'm fairly sure you can configure the read timeouts so that you get behaviour on reads that for all intents and purposes is about as good as an interrupt, without the difficulties inherent in that approach, but provided you are willing to dedicate a thread to the task. On Linux, it's possible the read timeouts capabilities are a little less flexible (but I've only just barely glanced at this area), but as I recall you were on Windows anyway. BTW, another post pointed you to USPP. As far as I know, it hasn't been updated recently and, while I can't say how it compares to PySerial, I believe it's fair to say at this point in time that PySerial is the _de facto_ standard way to do serial port stuff in Python. If it doesn't do what you need, it's probably a good idea to at least point that out in its mailing list so that it can be improved. -Peter From dbickett at gmail.com Mon Jan 24 00:45:08 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Mon, 24 Jan 2005 00:45:08 -0500 Subject: how to write a tutorial In-Reply-To: References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106531824.833549.28720@c13g2000cwb.googlegroups.com> Message-ID: <1d6cdae305012321452fb71ca6@mail.gmail.com> Chris Mattern wrote: > alex23 wrote: > > > Having read your comments on women, > > I hadn't looked at that part of his site until now. I can only say: > gah. Haven't seen something like that since Dave Sim's infamous > "Tangent" essay. It's painfully obvious that it is all for the sole purpose of negative attention. You guys are just begging for a YHBT ;-) Daniel Bickett From skip at pobox.com Fri Jan 28 15:09:46 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 28 Jan 2005 14:09:46 -0600 Subject: some kind of LFU dict... In-Reply-To: <63b5e209.0501280739.3887d82@posting.google.com> References: <63b5e209.0501280739.3887d82@posting.google.com> Message-ID: <16890.39946.399821.436142@montanaro.dyndns.org> Joh> so i wondered if i can not use some kind of cache, i googled and Joh> found information on LRU, LFU, and LFU interested me : keep only Joh> most frequently used items inside dict (and memory) and writing Joh> others on disk for a possible future reuse. I have a Cache class that you might subclass to provide different behavior: http://www.musi-cal.com/~skip/python/Cache.py What it does now is throw out keys that match the desired criteria. You could subclass it to stuff those items in a DB file (probably using the anydbm module) and read them from the DB file if an attempt to access a key in the cache fails. Skip From rakesh_usenet at yahoo.com Mon Jan 17 03:20:24 2005 From: rakesh_usenet at yahoo.com (Rakesh) Date: 17 Jan 2005 00:20:24 -0800 Subject: nntplib: abstraction of threads In-Reply-To: <41EAA458.1020501@holdenweb.com> References: <1105840367.526347.110160@c13g2000cwb.googlegroups.com> <41EAA458.1020501@holdenweb.com> Message-ID: <1105950024.112707.286290@z14g2000cwz.googlegroups.com> Steve Holden wrote: > Werner Amann wrote: > > > Rakesh schrieb: > > > > > >>What I want is to *group the messages belonging to each thread* . > > > > > > Hello > > > > Why not sort with Message-ID and References? > > Attention - it is a Newbie-Solution. > > > > import nntplib > > > > hamster = nntplib.NNTP('127.0.0.1', 119, 'user', 'pass') > > resp, count, first, last, name = hamster.group('comp.lang.python') > > resp, items = hamster.xover(first,last) > > > > start_dic = {} > > re_dic = {} > > numb = 1 > > > > for id,subject,author,date,message_id,references,size,lines in items: > > if 'Re:' not in subject: > > start_dic[subject] = (author, message_id) > > else: > > re_dic[numb] = (subject, author, references) > > numb += 1 > > > > resp = hamster.quit() > > > > for a in start_dic: > > print a > > print start_dic[a][0] > > for b in re_dic: > > if start_dic[a][1] in re_dic[b][2]: > > print '|' > > print ' ->', re_dic[b][0] > > print ' ', re_dic[b][1] > > print > > > Better still, do a Google search on "mail threading algorithm", > implement the algorithm described in > > http://www.jwz.org/doc/threading.html Thanks a lot for the link. > > and post your implementation back to the newsgroup :-) Sure I would. I would definitely do the same. I am a python newbie and am reading nntp spec (rfc) right now. Once I get a working version I would definitely post the same. From peter at engcorp.com Wed Jan 5 15:14:33 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 05 Jan 2005 15:14:33 -0500 Subject: OT: spacing of code in Google Groups In-Reply-To: References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> Message-ID: Jacek Generowicz wrote: > Peter Hansen writes: >>Grant Edwards wrote: >> >>>I always rather liked line numbers (a-la 'can -n'). That also >>>makes discussion of the code easier: >> >>That, unfortunately, is somewhat harder to remove without >>using a regular expression... > > You mean to say that your editor does not have rectangle operations ? > :-) I wouldn't know.** I try quite hard to limit the features that I have to learn and remember to a very, very small list. Why the heck would I ever have to do "rectangle operations" on a regular basis? ;-) -Peter ** I'm using Scite; it probably has it. It has quite a few features -- far more than I'll ever use. Remarkable how simple an editor could be and still be effective... for some people. From fredrik at pythonware.com Mon Jan 31 14:19:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 31 Jan 2005 20:19:02 +0100 Subject: Relocatable binary installs.... References: <1107195180.462949.222980@z14g2000cwz.googlegroups.com> <41FE7F26.1090209@holdenweb.com> Message-ID: Steve Holden wrote: >>>Is there a way to make a relocateable python binary... that is... a >>>python installation that won't care where it is on the machine... and >>>won't care if it gets put somewhere else besides / ? >> >> >> the standard CPython interpreter is 100% "relocatable". If you think >> it isn't, you have to be a bit more specific. >> > Is it possible that you are using "relocatable" in the standard sense of "code can be located > anywhere in physical memory", where the OP is using the same term to mean "can live anywhere in > the filestore"? nope. > I suspect the problem the OP is seeing is because the --prefix configuration parameter will cause > an interpreter to look in a specific place for standard libraries. Clearly if you "relocate" the > libraries to another directory entirely then an interpreter without any further nouse (and no > symbolic links to help it) is going to crap out badly. clearly? [fredrik at brain build] mv python2.3 /tmp [fredrik at brain build] mkdir /tmp/lib [fredrik at brain build] mv lib /tmp/lib/python2.3 [fredrik at brain build] cd /tmp [fredrik at brain tmp]$ ./python2.3 >>> import sys >>> sys.prefix '/tmp' >>> sys.path ['', '/tmp/lib/python23.zip', '/tmp/lib/python2.3', ...] >>> [fredrik at brain tmp]$ mkdir spam [fredrik at brain tmp]$ mv python2.3 spam [fredrik at brain tmp]$ mv lib spam [fredrik at brain tmp]$ cd spam/ [fredrik at brain spam]$ ./python2.3 >>> import sys >>> sys.prefix '/tmp/spam' >>> sys.path ['', '/tmp/spam/lib/python23.zip', '/tmp/spam/lib/python2.3', ...] >>> [fredrik at brain spam]$ mkdir bin [fredrik at brain spam]$ mv python2.3 bin [fredrik at brain spam]$ bin/python2.3 >>> import sys >>> sys.prefix '/tmp/spam' >>> [fredrik at brain spam]$ cd bin [fredrik at brain bin]$ ./python2.3 >>> import sys >>> sys.prefix '/tmp/spam' [fredrik at brain fredrik]$ export PATH=/tmp/spam/bin:$PATH [fredrik at brain bin]$ cd [fredrik at brain fredrik]$ python2.3 >>> import sys >>> sys.prefix '/tmp/spam' >>> and so on... From fuzzyman at gmail.com Tue Jan 25 04:02:45 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Jan 2005 01:02:45 -0800 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: Message-ID: <1106643765.733317.27440@f14g2000cwb.googlegroups.com> An implementation of the core language semantics - without any modules or file operations would be dead useful. It could replace some of the function of the long dead rexec modules as well as support projects like this. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From hat at se-126.se.wtb.tue.nl Tue Jan 4 11:03:17 2005 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Tue, 4 Jan 2005 16:03:17 +0000 (UTC) Subject: Parallelization with Python: which, where, how? References: Message-ID: On Mon, 20 Dec 2004 14:03:09 +0100, Mathias wrote: > Can someone recommend a parallelization approach? Are there examples or > documentation? Has someone got experience with stability and efficiency? If you think a light-weight approach of distributing work and collecting the output afterwards (using ssh/rsh) fits your problem, send me an email. Albert -- Unlike popular belief, the .doc format is not an open publically available format. From joshway_without_spam at myway.com Wed Jan 12 17:23:30 2005 From: joshway_without_spam at myway.com (JCM) Date: Wed, 12 Jan 2005 22:23:30 +0000 (UTC) Subject: reference or pointer to some object? References: Message-ID: Torsten Mohr wrote: ... > I still wonder why a concept like "references" was not > implemented in Python. I think it is (even if small) > an overhead to wrap an object in a list or a dictionary. > Isn't it possible to extend Python in a way to use > real references? Or isn't that regarded as necessary? Some think it's unwise. The ability to modify local variables in your caller's scope can lead to messiness, especially if the modifiability isn't evident to the caller (eg. via C's "&"). From rkern at ucsd.edu Mon Jan 3 21:02:27 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 03 Jan 2005 18:02:27 -0800 Subject: Howto Extract PNG from binary file @ 0x80? In-Reply-To: <1104802606.806575.178870@c13g2000cwb.googlegroups.com> References: <1102753727.706459.105920@f14g2000cwb.googlegroups.com> <1104797038.407042.32580@z14g2000cwz.googlegroups.com> <1104802606.806575.178870@c13g2000cwb.googlegroups.com> Message-ID: Don't seek to position 97. Seek to 96. You're off by one. That's why there's the test for the header (which you removed). Files (and Python strings for that matter) are 0-indexed. The first character is 0, the second 1, and so on. If you want the 97th character, you have to seek to position 96. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From phil at riverbankcomputing.co.uk Fri Jan 28 08:47:21 2005 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Fri, 28 Jan 2005 13:47:21 -0000 (GMT) Subject: example needed: sip + Qt In-Reply-To: References: Message-ID: <39688.82.68.80.137.1106920041.squirrel@82.68.80.137> > Hi, > > can someone provide me with a running example for subclassing QWidget (or > something similarly simple) in C++ and then creating SIP (4.x+) bindings > for in for Python (2.3+)? > > I am looking for something I can start of with and work my way towards > more > complicated stuff (with Qt). > > The QLabel example in the SIP reference manual yields syntax errors for > me. What syntax errors? If there is a documentation bug then I'll fix it. Phil From apardon at forel.vub.ac.be Fri Jan 14 04:55:06 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Jan 2005 09:55:06 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-01-14, Fredrik Lundh schreef : > Paul Rubin wrote: > >>> > Huh? Expressions are not statements except when they're "expression >>> > statements"? What kind of expression is not an expression statement? >>> >>> any expression that is used in a content that is not an expression statement, >>> of course. >> >> Come on, that is vacuous. The claim was "expressions are not >> statements". But it turns out that expressions ARE statements. > > no, expressions CAN BE USED as statements. that doesn't mean > that they ARE statements, unless you're applying belgian logic. No I am applying set logic. Any string that is in the set of valid expressions is also in the set of valid statements. Like any animal that is in the set of dogs is also in the set of mamals. -- Antoon Pardon From philippecmartin at sbcglobal.net Wed Jan 5 09:14:44 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Wed, 05 Jan 2005 15:14:44 +0100 Subject: smtp question - using email module Message-ID: <1104934484.6869.13.camel@localhost> Thank you all for your help - an yes! the email module is _very_ nice. Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From bulba at bulba.com Thu Jan 6 20:13:28 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 02:13:28 +0100 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <10trej2fl8dip65@corp.supernews.com> Message-ID: <7lmrt0tf6lgdj70klbsti1r8uougm4tf9n@4ax.com> On Thu, 06 Jan 2005 14:27:55 -0800, Jeff Shannon wrote: >>>That's generally the goal of the Free Software Foundation: they think >>>all users should have the freedom to modify and/or distribute your code. >> >> You have the freedom of having to wash my car then. ;-) >A more accurate analogy would be, "You're free to borrow my car, but >if you do, you must wash it and refill the gas tank before you return it." That analogy is an equivalent of LGPL. Not GPL. GPL in analogy would require you to donate whatever you created thanks to studying the construction of that car in the meantime. And yes, again, sure that is what the borrower agreed to do, sure that NOT using it at all does not result in such obligations, and again - that is not the point. >Note that the so-called 'viral' nature of GPL code only applies to >*modifications you make* to the GPL software. The *only* way in which >your code can be 'infected' by the GPL is if you copy GPL source. >Given the standard usage of closed-source software, you never even >have access to the source. Which means that standard closed-source software does not impose itself on your software - except those detestable cases where Stefan Axelsson pointed out, it prevents you from developing smth similar if you agreed to such a pre-condition in EULA of this thing. It would appear that such a software attempts to economically lock the user in using the only binary in the world that implements this functionality; and FSF attempts to economically, indirectly lock the developers - and indirectly users - in "being pressured to give away" on the rationale of sharing being so good for everyone. Now, this may not be what they INTENDED - but from my viewpoint it seems like that is the RESULT. Not only I see this as unfair, but also as counter-effective in getting more of people into both using and developing software with publicly available source code ("free software" guys tend to get hot under the collar when they hear "open source"). Trying to bully people into this thing _for their own good_ tends to have the effect opposite to the intended. You achieve more by showing positive attitude rather than via conspiracy theories and paranoia. It is also this mostly friendly and relaxed aspect of Python community that I like so much. Again, agreeing / not agreeing and resulting use / walking away _are not the issue_. I don't see MS defended like "well if you don't like whatever MS does, just don't use their software, so shut up about whatever licenses MS actually has and about whatever it does!". >If you use GPL software in the same way >that you use closed-source software, then the GPL cannot 'infect' >anything you do. True, but that abstracts from source code issues, doesn't it? >The 'infective' nature of the GPL *only* comes when you make use of >the *extra* privelidges that open source grants. Those extra privileges are the only way of _building_ large software systems, isn't it? So I would define it as "normal". Yes, closed-source is sort of "crippled" in this regard. >So yes, those extra >privelidges come with a price (which is that you share what you've >done); but if you don't want to pay that price, you have the choice of >not using those privelidges. This does not, in any way, prevent you >from using GPL'ed software as a user. Obviously; but while what you wrote is true, it is not the crux of the problem. >(Problems may come if someone licenses a library under the GPL; that's >what the LGPL was invented for. But the issue here is not that the >GPL is bad, it's that the author used the wrong form of it.) >Personally, I'm not a big fan of the GPL. I'm much more likely to use >BSD-ish licenses than [L]GPL. Personally, I think that LGPL in abstract sense does make sense: if you use and modify this thing, you should return back the _modified_ part - and this should apply regardless whether you keep it in private or not, release in binary or in source to anybody. However, it's definitely safer and since it also FEELS more benign, BSD-like licenses are probably more productive in terms of motivating people to cooperate, so I agree with you on that point. > But it still bugs me to see the GPL >misrepresented as some plot to steal the effort of hardworking >programmers -- it is, instead, an attempt to *encourage* hardworking >programmers to share in a public commons, by ensuring that what's >donated to the commons remains in the commons. OK, a quick sanity check: does Python not remain "in the commons" because some people use it in closed-source applications? I would say that ALL of software released under GPL, LGPL or other free / open source licenses remains in the commons. All of the controversies seem to be about the derived works, don't they? -- It's a man's life in a Python Programming Association. From Prikryl at skil.cz Thu Jan 20 03:36:08 2005 From: Prikryl at skil.cz (Petr Prikryl) Date: Thu, 20 Jan 2005 09:36:08 +0100 Subject: list item's position Message-ID: > On Wed, 19 Jan 2005 22:04:44 -0500, Bob Smith wrote: > > [...] how to find an element's numeric value (0,1,2,3...) > > in the list. Here's an example of what I'm doing: > > > > for bar in bars: > > if 'str_1' in bar and 'str_2' in bar: > > print bar > > > > This finds the right bar, but not its list position. The reason I need > > to find its value is so I can remove every element in the list before it > > so that the bar I found somewhere in the list becomes element 0... does > > that make sense? I have borrowed the bars list example from "Bill Mill"s solutions and here are the two solutions... bars = ['str', 'foobaz', 'barbaz', 'foobar'] # Solution 1: The enumerate(). for idx, bar in enumerate(bars): if 'bar' in bar and 'baz' in bar: break bars_sliced = bars[idx:] print bars_sliced # Solution 2: Low level approach, testing and removing combined. In situ. while bars: # some prefer len(bars) > 0, which is less magical, IMHO bar = bars.pop(0) # get and remove the first element if 'bar' in bar and 'baz' in bar: bars.insert(0, bar) # insert the tested back break # and finish print bars The result is ['barbaz', 'foobar'] in both cases. Petr -- Petr Prikryl (prikrylp at skil dot cz) From drewp at bigasterisk.com Mon Jan 3 13:14:13 2005 From: drewp at bigasterisk.com (drewp at bigasterisk.com) Date: 3 Jan 2005 10:14:13 -0800 Subject: Is Python good for graphics? In-Reply-To: <10s1bdaj7gbin8e@corp.supernews.com> References: <10s1bdaj7gbin8e@corp.supernews.com> Message-ID: <1104776053.962423.112510@f14g2000cwb.googlegroups.com> Esmail Bonakdarian wrote: > > Basically, I would like to be able to create some basic animations > where I can help visualize various sorting algorithms (for instance > http://ciips.ee.uwa.edu.au/~morris/Year2/PLDS210/sorting.html#insert_anim) > or graph searches (coloring nodes as each gets visited). (Something > like this: http://cs.smith.edu/~thiebaut/java/graph/Welcome.html) For the sorting algorithms, at least, check out Demo/tkinter/guido/sortvisu.py in the standard distribution. I'd recommend Tk for all the other demos you described, too. From pythongnome at hotmail.com Fri Jan 14 08:06:17 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Fri, 14 Jan 2005 13:06:17 GMT Subject: porting C code In-Reply-To: <0NidnetRONZTgHrcRVn-oQ@powergate.ca> References: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> <0NidnetRONZTgHrcRVn-oQ@powergate.ca> Message-ID: Peter Hansen wrote: > Lucas Raab wrote: > >> I have the statement: "typedef unsigned long int word32" and later >> on: "word32 b[3]" referencing the third bit of the integer. > > > If that's really exactly what you have, then you actually have > something defining an array of three unsigned long integers > named "b". And even if you didn't have precisely "word32 b[3]", > but merely a "b[3]" reference somewhere, it would be referencing > the third element of an array called "b", which is possibly a byte, > maybe a long, but definitely not a bit. > > Maybe showing it as code rather than inline in your text > would avoid the possibility of confusion. > > -Peter Sorry, the third "byte" is what I meant. As for code samples, I hope the following will work: typedef unsigned long int word32 ; void mu(word32 *a) { int i ; word32 b[3] ; b[0] = b[1] = b[2] = 0 ; for( i=0 ; i<32 ; i++ ) { b[0] <<= 1 ; b[1] <<= 1 ; b[2] <<= 1 ; if(a[0]&1) b[2] |= 1 ; if(a[1]&1) b[1] |= 1 ; if(a[2]&1) b[0] |= 1 ; a[0] >>= 1 ; a[1] >>= 1 ; a[2] >>= 1 ; } a[0] = b[0] ; a[1] = b[1] ; a[2] = b[2] ; } The "a[#]" and "b[#]" are the parts that are giving me trouble. From klachemin at comcast.net Sun Jan 23 09:04:26 2005 From: klachemin at comcast.net (Kamilche) Date: 23 Jan 2005 06:04:26 -0800 Subject: Reload Tricks In-Reply-To: <1gqsb7j.1tbzcqn1f431kdN%aleaxit@yahoo.com> References: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> <1gqsb7j.1tbzcqn1f431kdN%aleaxit@yahoo.com> Message-ID: <1106489066.098048.212390@z14g2000cwz.googlegroups.com> Well, I look forward to seeing the new version. I have the old version of the Python cookbook, it was very useful! From aleaxit at yahoo.com Mon Jan 31 08:16:38 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 31 Jan 2005 14:16:38 +0100 Subject: how do i create such a thing? References: <7vGdnTsopcKl-GDcRVn-rw@comcast.com> Message-ID: <1gr9b2q.1dlgnok1ayt2zsN%aleaxit@yahoo.com> Steven Bethard wrote: > Of if you only want to deal with the case where the attribute doesn't > exist, you can use getattr, which gets called when the attribute can't > be found anywhere else: > > py> class DefaultAttr(object): > ... def __init__(self, default): > ... self.default = default > ... def __getattr__(self, name): > ... return self.default > ... > py> x = DefaultAttr(99) > py> x.a > 99 > py> x.a = 10 > py> x.a > 10 This is a good approach, but it's fragile regarding specialnames. >>> class DefaultAttr(object): ... def __init__(self, default): self.default = default ... def __getattr__(self, name): return self.default ... >>> import copy >>> copy.copy(DefaultAttr(99)) Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.4/copy.py", line 87, in copy rv = reductor(2) TypeError: 'int' object is not callable There are many more, worse example for classic classes, but even in newstyle classes you must consider that once in a while a system routine will try a getattr(someinst, '__aspecialname__', None) or the like -- and your class is making its instances claim to have ANY special name that may be introspected for in this way. This can be a pernicious lie, since your class in fact has no idea whatsoever what that specialname and the corresponding value might be for. It's HIGHLY advisable to have your __getattr__ methods raise AttributeError for any requested name that starts and ends with double underscores, possibly with some specific and specifically designed exceptions. Alex From hgk at et.uni-magdeburg.de Mon Jan 17 06:18:35 2005 From: hgk at et.uni-magdeburg.de (Hans Georg Krauthaeuser) Date: Mon, 17 Jan 2005 12:18:35 +0100 Subject: platform independent kbhit() Message-ID: Hey all, this is probably a FAQ, but I didn't found the answer... I use msvcrt.kbhit() to check for a user keyboard event on windows. But now, I would prefer to make the module independent from the platform used. I already know that I can use curses (on linux/unix) or Tkinter. Also, I found this http://my.execpc.com/~geezer/software/kbhit.c C source that has a kbhit() and a getch() for linux/unix that I can SWIG to python. Are there other (more simple, pure python, true platform independent) possibilities? Best regards Hans Georg Krauthaeuser -- www.uni-magdeburg.de/krauthae From http Tue Jan 11 12:30:12 2005 From: http (Paul Rubin) Date: 11 Jan 2005 09:30:12 -0800 Subject: Time script help sought! References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> Message-ID: <7x4qhn7u1n.fsf@ruckus.brouhaha.com> "kpp9c" writes: > These are analog tapes that were digitized (on to CD or a digital tape) > that have now been exported as individual files that are meant to be > part of an on-line audio archive. ... > I was hoping and > praying that some one here was feeling generous and show me the way... Is this online archive going to be accessible by the public for free? What's in the archive? If you're asking for volunteer labor it's generally appropriate to say precisely what that the labor is for. From ralobao at gmail.com Thu Jan 6 16:47:22 2005 From: ralobao at gmail.com (ralobao at gmail.com) Date: 6 Jan 2005 13:47:22 -0800 Subject: Download .jpg from web In-Reply-To: References: Message-ID: <1105048042.103907.158870@f14g2000cwb.googlegroups.com> You could try using: urlllib.urlretrieve ...it may be faster. From fredrik at pythonware.com Fri Jan 28 07:00:03 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 28 Jan 2005 13:00:03 +0100 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> <41FA22DA.2090402@iinet.net.au> Message-ID: Nick Coghlan wrote: >> I'm sorry, but this isn't really good enough. If Open Source wants to >> say that they are better than these proprietary companies, they need >> to deal with these sorts of things more professionally and establish >> decent channels of communications for dealing with it. > > Is that the sound of a volunteer I hear? > > All you have to do is put your hand up, and the problem will be solved. If not you, who? oh, please. this is a security issue. it needs a little more coordination than an ordinary bug report. From exarkun at divmod.com Sat Jan 8 10:44:53 2005 From: exarkun at divmod.com (Jp Calderone) Date: Sat, 08 Jan 2005 15:44:53 GMT Subject: "A Fundamental Turn Toward Concurrency in Software" In-Reply-To: Message-ID: <20050108154453.32125.797079096.divmod.quotient.2429@ohm> On Sat, 08 Jan 2005 14:22:30 GMT, Lee Harr wrote: >>> [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that the > >> continous CPU performance gain we've seen is finally over. And that future > >> gain would primary be in the area of software concurrency taking advantage > >> hyperthreading and multicore architectures. > >> > > > Well, yes. However, it's not as bad as it looks. I've spent a good part > > of my professional life with multiprocessors (IBM mainframes) and > > I have yet to write a multi-thread program for performance reasons. > > All of those systems ran multiple programs, not single programs > > that had to take advantage of the multiprocessor environment. > > Your typical desktop is no different. My current system has 42 > > processes running, and I'd be willing to bet that the vast majority > > of them aren't multi-threaded. > > > > Exactly. If every one of your processes had its own 2 Ghz processor > running nothing else, I think you would be pretty happy. Your OS > had better be well-written to deal with concurrent access to > memory and disks, but I think for general application development > there will be huge speed boosts with little need for new > programming paradigms. Not likely. How often do you run 4 processes that are all bottlenecked on CPU? It's not a common usage pattern. If you have 16 CPUs, and 15 of them are running mostly idle processes and that *one* process you'd wish would hurry the heck up and finish has the 16th pegged at 100% usage, you are not a happy camper. For the case where you do have a lot of competing unrelated processes, no doubt SMP is a big win automatically, but there will still need to be language innovations to make it easier to develop software which can benefit from the additional hardware for the more common case of individual CPU hungry processes. Jp From martin at v.loewis.de Sun Jan 23 18:24:59 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 24 Jan 2005 00:24:59 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> Message-ID: <41f4324a$0$1547$9b622d9e@news.freenet.de> Paul Rubin wrote: > If he understood how Python is actually used, he'd understand that any > C module is a lot more useful in the core than out of it. This is non-sense. I have been distributing C modules outside the core for quite some time now, and I found that the modules are quite useful. distutils makes it really easy for anybody to use them. > There are already tons of > 3rd party crypto modules outside the core, and the module I was > writing wouldn't add anything useful to those. Why do you think these are not part of the core? It's not because they contain crypto code, or because they had been rejected. They are primarily not included in Python because they have not been contributed to Python, yet. If they were contributed, a number of things still would need to be considered, e.g. what is the size of the code, including libraries, is the contributor really the author, is the code likely going to be maintained, and so on. However, it never got that far. > Where does Frederik get > off lecturing me about wanting to get a module into the core, when > Guido had invited me to do precisely that with that very module? I know that *I* am very opposed to any contribution of a larger module that has not seen any real users, yet. So if the module was primarily written to be included in the core, I would initially reject it for that very reason. After one year or so in its life, and a recognizable user base, inclusion can be considered. > I did release a replacement for the rotor module that's written in > Python, which means it's reasonably useable without being in the core. > However, while its security should be ok, to provide reasonable > performance it had to use a nonstandard algorithm and therefore isn't > good for interoperating with anything. To be both acceptably fast and > interoperable with other applications, a C module is needed. I fail to see the problem you seem to have with C modules. They are very easy to use if written properly. Regards, Martin From andre.roberge at gmail.com Sat Jan 22 19:04:50 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 22 Jan 2005 16:04:50 -0800 Subject: finding name of instances created In-Reply-To: References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> Message-ID: <1106438690.420574.247510@f14g2000cwb.googlegroups.com> Steven Bethard wrote: > If you have access to the user module's text, something like this might > be a nicer solution: > > py> class Robot(object): > ... def __init__(self): > ... self.name = None > ... def move(self): > ... print "robot %r moved" % self.name > ... > py> class RobotDict(dict): > ... def __setitem__(self, name, value): > ... if isinstance(value, Robot): > ... value.name = name > ... super(RobotDict, self).__setitem__(name, value) > ... > py> user_code = """\ > ... alex = Robot() > ... anna = Robot() > ... alex.move() > ... anna.move()""" > py> robot_dict = RobotDict() > py> robot_dict['Robot'] = Robot > py> exec user_code in robot_dict > robot 'alex' moved > robot 'anna' moved > > Note that I provide a specialized dict in which to exec the user code -- > this allows me to override __setitem__ to add the appropriate attribute > to the Robot as necessary. > I have tried this exact example (using Python 2.3 if it makes any difference) and what I got was: robot None moved robot None moved I checked what I wrote, used cut & paste on your code, removing the leading "junk", tried it again ... to no avail. :-( Andr? From wittempj at hotmail.com Mon Jan 3 10:22:14 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 3 Jan 2005 07:22:14 -0800 Subject: removing comments form a file In-Reply-To: <5b617$41d956df$53e8229a$22273@freeler.nl> References: <5b617$41d956df$53e8229a$22273@freeler.nl> Message-ID: <1104765734.888089.279470@f14g2000cwb.googlegroups.com> You cold do something like this: >>> import re >>> commentpattern = re.compile('.*(?=//)|.*(?!//)') >>> stringwithcomment = 'Blah di blah // some comment' >>> match = commentpattern.match(stringwithcomment) >>> match.group() 'Blah di blah ' >>> stringwithoutcomment = 'Blah di blah' >>> match = commentpattern.match(stringwithoutcomment) >>> match.group() 'Blah di blah' >>> blankline = '\n' >>> match = commentpattern.match(blankline) >>> match.group() '' >>> and put this in a loop where you iterate over your file. Martin (The Netherlands, Amsterdam, bij Diemen) Noud Aldenhoven wrote: > Hello everyone, > > I was wondering how to remove comments away form a file. > So that's why I made this script. > > =============================== > #!/usr/bin/env python > > import sys > import string > import time > > helptext = "usage: python rmcomment [oldfile] [newfile] [comment]" > > def rmcomment(oldfile, newfile, comment): > oldfile = open(oldfile, 'r') > newfile = open(newfile, 'w') > ccount = 0 > lcount = 0 > for line in oldfile.readlines(): > splitline = string.split(line) > pstest = 0 > fileline = "" > for word in splitline: > if word[:2] == comment: > pstest = -1 > ccount += 1 > pass > elif pstest == -1: > pass > else: > fileline += word + " " > if len(fileline) == 0: > pass > else: > newfile.write(fileline + "\n") > lcount += 1 > print "Done... in %s seconds\nRemoved comment from %s lines\nWrote % > lines to %s" % (time.time()-start , ccount, lcount, newfile) > raw_input("Push the enter button to quit>") > > if __name__ == "__main__": > if sys.argv[1] == "-h" or sys.argv[1] == "-help": > print helptext > else: > start = time.time() > oldfile = sys.argv[1] > newfile = sys.argv[2] > comment = sys.argv[3] > rmcomment(oldfile, newfile, comment) > > > ======================================== > > This script works fine with standard text files. An example is this one: > > example.txt: > > Hello Fuckin' World //how are you doing today > //I think it delete this sentence and the next sentence too! > > But this one not! #Even not this comment > > end example.txt > > If I use my script, named rmcomment.py I get this: > > jwaixs at linux:~/programmeren/python/rmcomment$ cat example.txt > Hello Fuckin' World //how are you doing today > //I think it delete this sentence and the next sentence too! > > But this one not! #Even not this comment's > jwaixs at linux:~/programmeren/python/rmcomment$ python rmcomment.py > example.txt newexample.txt // > Done... in 0.00104999542236 seconds > Removed comment from 2 lines > Wrote 2nes to > Push the enter button to quit> > jwaixs at linux:~/programmeren/python/rmcomment$ cat newexample.txt > Hello Fuckin' World > But this one not! #Even not this comment > jwaixs at linux:~/programmeren/python/rmcomment$ > > works fine... but here's my problem. If I use rmcomment.py also the > whitelines will be removed. And I don't want that to happen. Here's another > example: > > jwaixs at linux:~/programmeren/python/rmcomment$ cat otherexample.txt > //This shows what whitelines are doing here > left from me is a nice white line tabs > and here left are at least 3 white line tabs > > //and ofcourse, comments will be deleted > jwaixs at linux:~/programmeren/python/rmcomment$ python rmcomment.py > otherexample.txt newotherexample.txt // > Done... in 0.0011351108551 seconds > Removed comment form 2 lines > Wrote 2nes to > Push the enter button to quit> > jwaixs at linux:~/programmeren/python/rmcomment$ cat newotherexample.txt > left from me is a nice white line tabs > and here left are at least 3 white line tabs > jwaixs at linux:~/programmeren/python/rmcomment$ > > My beautiful whitelines are gone! And I don't want that! > I've thaught how to fix this for a time, but I can't make it on my own. Too > less programming experiance, I'm afraid. > Could someone help me with this problem? Or fix the script or give a hint or > something? > > Thank you at least for reading this post, > > Noud Aldenhoven > The Netherlands (In de beurt bij Nijmegen, voor de nieuwschierigen) > > ps. Yes, I'm a Dyslextion and can't write correct english. I'm sorry for > that. From ajikoe at gmail.com Wed Jan 26 15:00:51 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 26 Jan 2005 12:00:51 -0800 Subject: access private field in python 2.4 In-Reply-To: <4prkc2-ini.ln1@pluto.i.infosense.no> References: <1106754371.637295.82160@z14g2000cwz.googlegroups.com> <4prkc2-ini.ln1@pluto.i.infosense.no> Message-ID: <1106769651.371856.107960@f14g2000cwb.googlegroups.com> Hello, if we want to access the private member of object we use the classname, it doesn't make sense. For example: I have class A: class A: def __init__(self, i): self.__i = i; pass __i = 0 a = A(22); b = A(33); How can I get field i in object a and how can I get field i in object b? Beside I try to call: print _A__i #fail this create error Please help. Pujo Aji From fumanchu at amor.org Tue Jan 25 13:25:00 2005 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 25 Jan 2005 10:25:00 -0800 Subject: I want update one record using ADO,but I can't ,why? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398297@exchange.hqamor.amorhq.net> nightmarch wrote: > I want update one record ,but I can't ,why? > > code like following: > > ##------------------------------------------------- > import win32com.client as wc > > def main(): > conn = wc.Dispatch(r'ADODB.Connection') > rs = wc.Dispatch(r'ADODB.Recordset') > connStr = "Provider=MSDAORA.1;Password=jmpower;User > ID=jmpower;Data Source=jmgis_agps3;Persist Security Info=True" > tblName = r'wjtmp' > > conn.Open(connStr ) > > rs.Open( tblName, conn, wc.constants.adOpenKeyset, > wc.constants.adLockOptimistic ) > > if rs.Supports( wc.constants.adUpdate ): > rs.Fields.Item(0).Value = 11 > rs.Update() > else: > print "recordset can't update" > > rs.Close() > conn.Close() > > if __name__ == '__main__': > main() > ##------------------------------------------------- You almost give us enough information to help out ,but you don't quite ,why? What happens when you run the above? Is there any output? Error message? Does your update affect the membership of the record in the keyset? http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/ htm/mdconkeysetcursors.asp Why are you using keysets at all? Robert Brewer MIS Amor Ministries fumanchu at amor.org From martin at v.loewis.de Thu Jan 27 18:16:10 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 28 Jan 2005 00:16:10 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: <41f97630$0$11586$9b622d9e@news.freenet.de> phr at localhost.localdomain wrote: > I don't see why you can't make up your mind enough to issue simple > statements like "the Python lib should have a module that does > so-and-so I can say that assuming I know what so-and-so is. For the specific case of AES, I would say "I don't think the Python lib necessarily needs to have an AES module, but I would not object if it had one" (the latter part in consideration of consequences that inclusion of crypto code might have). > and it should meet such-and-such requirements I can only say such things if I know such-and-such in detail to specify requirements. For the specific case of AES, I don't know enough about it to specify requirements. I will have to trust others (and by that, I mean *multiple* others) > so if > someone submits one that meets the requirements and passes code review > and testing and doesn't have unexpected issues or otherwise fail to > meet reasonable expectations, we'll use it". Because I cannot specify requirements, I cannot make such a promise. In addition, for any new module, there is one primary requirement for acceptance that cannot be fulfilled in code quality: the contributor should promise to support the module in a foreseeable future (i.e. a couple of years). > Again, we're talking about straightforward modules whose basic > interface needs are obvious. You are talking about such a thing. I don't know enough about the functionality to specify what an obvious interface is, or to recognize one if I see it. > I don't know what OMG is, but there is no IETF requirement that any > implementations be available in any particular language. See RFC 2026, section 4.1.2. Two independent implementations are required for the document to advance to draft (!) standard. > However, the result of my not writing an AES module is that Python > doesn't have an AES module. That's not true. PyCrypto does have AES support. >>No, it's three steps >>1. decide that you want to do it >>2. do it >>3. decide whether you are pleased with the result, and only >> use it if you are >> >>IOW, there should not be a blanket guarantee to use it after step 1. > > > But, it's completely normal to say before step 1 that "if the result > of step 2 does so-and-so, then I'll be pleased in step 3", That's what I'm saying: If you distribute the module to users for a year, and users express interest and support for your choice of API, I'll support inclusion of the module. "do it" involves more than just writing the code. > You and > Frederik seem to think there's something inappropriate or > self-inflated about wanting that expectation before committing to do a > pile of work that's primarily for other people's benefit. It's very easy. If you are primarily do it for other people's benefit, and if you don't find any satisfaction in the process of doing it - THEN DON'T. I really mean that; this is how free software works. People *volunteer* to do things. If they don't volunteer - that's perfectly fine. > I think > your stated attitude is completely bizarre, that you can't really > believe anything so silly, so you're really just acting bureaucratic, > looking for excuses to say no instead of yes to worthwhile proposals. As I said above - for the specific feature in question, I don't care enough for the feature itself. Python will be just as useful to me with the feature as it is without. What I do care about is the effort that I will need to continue maintaining Python. I don't want to have to maintain an ill-designed, buggy module with no active maintainer, and I don't want to tell people that I had to rip the module out just because it doesn't work at all. Regards, Martin From kbk at shore.net Sat Jan 29 14:10:30 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Sat, 29 Jan 2005 14:10:30 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200501291910.j0TJAUhi007769@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 280 open ( +7) / 2747 closed ( +1) / 3027 total ( +8) Bugs : 803 open ( +6) / 4799 closed (+10) / 5602 total (+16) RFE : 167 open ( +1) / 141 closed ( +0) / 308 total ( +1) New / Reopened Patches ______________________ tarfile.ExFileObject iterators (2005-01-23) http://python.org/sf/1107973 opened by Mitch Chapman Allow slicing of any iterator by default (2005-01-24) http://python.org/sf/1108272 opened by Nick Coghlan fix .split() separator doc, update .rsplit() docs (2005-01-24) CLOSED http://python.org/sf/1108303 opened by Wummel type conversion methods and subclasses (2005-01-25) http://python.org/sf/1109424 opened by Walter D?rwald distutils dry-run breaks when attempting to bytecompile (2005-01-26) http://python.org/sf/1109658 opened by Anthony Baxter patch for idlelib (2005-01-26) http://python.org/sf/1110205 opened by sowjanya patch for gzip.GzipFile.flush() (2005-01-26) http://python.org/sf/1110248 opened by David Schnepper HEAD/PUT/DELETE support for urllib2.py (2005-01-28) http://python.org/sf/1111653 opened by Terrel Shumway Patches Closed ______________ fix .split() maxsplit doc, update .rsplit() docs (2005-01-24) http://python.org/sf/1108303 closed by rhettinger New / Reopened Bugs ___________________ "\0" not listed as a valid escape in the lang reference (2005-01-24) CLOSED http://python.org/sf/1108060 opened by Andrew Bennetts broken link in tkinter docs (2005-01-24) http://python.org/sf/1108490 opened by Ilya Sandler Cookie.py produces invalid code (2005-01-25) http://python.org/sf/1108948 opened by Simon Dahlbacka idle freezes when run over ssh (2005-01-25) http://python.org/sf/1108992 opened by Mark Poolman Time module missing from latest module index (2005-01-25) http://python.org/sf/1109523 opened by Skip Montanaro Need some setup.py sanity (2005-01-25) http://python.org/sf/1109602 opened by Skip Montanaro distutils argument parsing is bogus (2005-01-26) http://python.org/sf/1109659 opened by Anthony Baxter bdist_wininst ignores build_lib from build command (2005-01-26) http://python.org/sf/1109963 opened by Anthony Tuininga Cannot ./configure on FC3 with gcc 3.4.2 (2005-01-26) CLOSED http://python.org/sf/1110007 opened by Paul Watson recursion core dumps (2005-01-26) http://python.org/sf/1110055 opened by Jacob Engelbrecht gzip.GzipFile.flush() does not flush all internal buffers (2005-01-26) http://python.org/sf/1110242 opened by David Schnepper os.environ.update doesn't work (2005-01-27) CLOSED http://python.org/sf/1110478 opened by June Kim list comprehension scope (2005-01-27) CLOSED http://python.org/sf/1110705 opened by Simon Dahlbacka RLock logging mispells "success" (2005-01-27) CLOSED http://python.org/sf/1110998 opened by Matthew Bogosian csv reader barfs encountering quote when quote_none is set (2005-01-27) http://python.org/sf/1111100 opened by washington irving tkSimpleDialog broken on MacOS X (Aqua Tk) (2005-01-27) http://python.org/sf/1111130 opened by Russell Owen Bugs Closed ___________ bug with idle's stdout when executing load_source (2005-01-20) http://python.org/sf/1105950 closed by kbk "\0" not listed as a valid escape in the lang reference (2005-01-23) http://python.org/sf/1108060 closed by tim_one Undocumented implicit strip() in split(None) string method (2005-01-19) http://python.org/sf/1105286 closed by rhettinger split() takes no keyword arguments (2005-01-21) http://python.org/sf/1106694 closed by rhettinger Cannot ./configure on FC3 with gcc 3.4.2 (2005-01-26) http://python.org/sf/1110007 closed by loewis os.environ.update doesn't work (2005-01-27) http://python.org/sf/1110478 closed by loewis Scripts started with CGIHTTPServer: missing cgi environment (2005-01-11) http://python.org/sf/1100235 closed by loewis list comprehension scope (2005-01-27) http://python.org/sf/1110705 closed by rhettinger RLock logging mispells "success" (2005-01-27) http://python.org/sf/1110998 closed by bcannon README of 2.4 source download says 2.4a3 (2005-01-20) http://python.org/sf/1106057 closed by loewis New / Reopened RFE __________________ 'attrmap' function, attrmap(x)['attname'] = x.attname (2005-01-26) http://python.org/sf/1110010 opened by Gregory Smith From jnc at ecs.soton.ac.uk Mon Jan 10 09:14:24 2005 From: jnc at ecs.soton.ac.uk (John Carter) Date: Mon, 10 Jan 2005 14:14:24 +0000 Subject: Using ICL to compile C extensions References: <1104815892.984903.182190@f14g2000cwb.googlegroups.com> Message-ID: On 3 Jan 2005 21:18:13 -0800, dayzman at hotmail.com wrote: >Hi, > >Does anyone know how I can use "icl" (Intel C++) to compile C >extensions? I'm on Windows, and my Python is compiled using VS7.1 >(binary distribution). Right now, when I run setup.py install, it uses >cl.exe (MSVC++ Toolkit 2003), and I would like to use icl because >MSVC++ 2003 does not support C99. >Any help will be much appreciated. > >Cheers, >Michael I've not tried to do it using distutils yet, but when I was building extension modules with my own make files and nmake all I had to do was chance cl to icl and use the correct linker. You can tune the performance playing with switches, but I got a factor 3 improvement on a DCT type algorithm with out of the box settings. I can send you an example makefile if you want John Carter jnc at ecs.soton.ac.uk From reinhold-birkenfeld-nospam at wolke7.net Sat Jan 1 15:26:24 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 01 Jan 2005 21:26:24 +0100 Subject: Looping using iterators with fractional values In-Reply-To: <1104609929.888351.8870@c13g2000cwb.googlegroups.com> References: <1104609929.888351.8870@c13g2000cwb.googlegroups.com> Message-ID: <33ofbhF40asveU1@individual.net> drife wrote: > Hello, > > Making the transition from Perl to Python, and have a > question about constructing a loop that uses an iterator > of type float. How does one do this in Python? > > In Perl this construct quite easy: > > for (my $i=0.25; $i<=2.25; $i+=0.25) { > printf "%9.2f\n", $i; > } <=Py2.3: for i in [x/4.0 for x in xrange(1, 10)]: print "%9.2f" % i Py2.4: for i in (x/4.0 for x in xrange(1, 20)): print "%9.2f" % i Reinhold From aleaxit at yahoo.com Tue Jan 4 11:15:53 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 4 Jan 2005 17:15:53 +0100 Subject: Cookbook 2nd ed Credits (was Re: The Industry choice) References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> Message-ID: <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> wrote: > But then I have THREE published recipes!! > Does that mean that I get three free copies of the cookbook ? ;-) ...ti piacerebbe eh...?-) Sorry, "one each", even though you have _five_ credits. For the curious, here's the roster of most credited contributors (remember, significant comments we merged into other's recipes also count!-)...: 1: 42 u'Alex Martelli' 2: 26 u'Raymond Hettinger' 3: 25 u'Luther Blissett' 4: 22 u'Peter Cogolo' 5: 10 u'John Nielsen' 6: 10 u'Anna Martelli Ravenscroft' 7: 8 u'J\x9frgen Hermann' 8: 7 u'Scott David Daniels' 9: 7 u'Chris Perkins' 10: 6 u'S\x8ebastien Keim' 11: 6 u'Paul Prescod' 12: 6 u'Noah Spurrier' 13: 6 u'Jeff Bauer' 14: 6 u'Holger Krekel' 15: 6 u'Danny Yoo' 16: 6 u'Brent Burley' 17: 5 u'Paul Moore' 18: 5 u'Michele Simionato' 19: 5 u'Mark Nenadov' 20: 5 u'David Eppstein' 21: 5 u'Brian Quinlan' If you wished to count only _authored_ recipes (but that's a bit misleading, since in several recipes-as-published there is a merge of two or three separately submitted and accepted recipes, and here I'm counting only the first-listed-author per published-recipe...): 1: 25 u'Luther Blissett' 2: 21 u'Alex Martelli' 3: 9 u'John Nielsen' 4: 8 u'Raymond Hettinger' 5: 8 u'J\x9frgen Hermann' 6: 6 u'S\x8ebastien Keim' 7: 6 u'Peter Cogolo' 8: 6 u'Anna Martelli Ravenscroft' 9: 5 u'Scott David Daniels' 10: 5 u'Paul Prescod' 11: 5 u'Michele Simionato' 12: 5 u'Mark Nenadov' 13: 5 u'Jeff Bauer' 14: 5 u'Brent Burley' ...but each still gets ONE free copy...!-) Alex From marklists at mceahern.com Sat Jan 15 19:02:33 2005 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 15 Jan 2005 18:02:33 -0600 Subject: deleting from tarfile In-Reply-To: References: Message-ID: <41E9AF19.1020702@mceahern.com> Uwe Mayer wrote: >Hi, > >is it possible to delete a file from a tar-archive using the tarfile module? > >Thanks >Uwe > > It doesn't appear so. A workaround, of course, is to create a new file with the subset of files from the old file: #!/usr/bin/env python import tarfile import os def removeFile(filename, nameToDelete): """Remove nameToDelete from tarfile filename.""" prefix, ext = os.path.splitext(filename) newFilename = '%(prefix)s-modified%(ext)s' % locals() original = tarfile.open(filename) modified = tarfile.open(newFilename, 'w') for info in original.getmembers(): if info.name == nameToDelete: continue extracted = original.extractfile(info) if not extracted: continue modified.addfile(info, extracted) original.close() modified.close() // m From rbt at athop1.ath.vt.edu Wed Jan 26 17:43:33 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Wed, 26 Jan 2005 17:43:33 -0500 Subject: MSI Difficulties In-Reply-To: <1106775563.795954.50420@z14g2000cwz.googlegroups.com> References: <1106775563.795954.50420@z14g2000cwz.googlegroups.com> Message-ID: brolewis wrote: > I am trying to deploy Python onto a number of laptops and have been > trying to take advantage of Python 2.4's MSI installer. I have tried > using the following commands to install, but to no avail: > > msiexec /i python-2.4.msi /qb ALLUSERS=1 > -- and -- > msiexec /i python-2.4.msi /qb ALLUSERS=1 ADDLOCAL=ALL > > However both of these commands fail to update the Windows path to > include C:\Python24 and as such creates problems for me when trying to > actually use Python. How can I rectify this situation? Is there a > command I am missing? Do I need to manually update the Path, and if so, > is there a programatic way I can do this? Thanks in advance > I've always manually updated the path... but I suppose there may be a way to do this automatically during install or programatically (bat file or py script afterwards). Perhaps someone more knowledgeable can answer these questions? Best of luck! From alexs at advfn.com Thu Jan 13 07:56:38 2005 From: alexs at advfn.com (Alex Stapleton) Date: Thu, 13 Jan 2005 12:56:38 -0000 Subject: Debian says "Warning! you are running an untested version of Python." on 2.3 Message-ID: Whenever I run python I get "Warning! you are running an untested version of Python." prepended to the start of any output on stdout. This is with Debian and python 2.3 (running the debian 2.1 and 2.2 binaries doesn't have this effect) Does anyone have any idea how to stop this or have even seen it before? Google says Your search - "you are running an untested version" - did not match any documents :( From tundra at tundraware.com Sun Jan 23 13:58:20 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 23 Jan 2005 13:58:20 EST Subject: Insanity In-Reply-To: References: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> <3sfcc2-b6v1.ln1@eskimo.tundraware.com> Message-ID: Fredrik Lundh wrote: > Tim Daneliuk wrote: > > >>Thanks - very helpful. One followup - your re works as advertised. But >>if I use: r'\[PROMPT:[^]].*\]' it seems not to. the '.*' instead of just '*' >>it matches the entire string ... > > > it's not "just '*'", it's "[^]]*". it's the "^]" set (anything but ]) that's repeated. > > "[^]].*\]" means match a single non-] character, and then match as many > characters as you possibly can, as long as the next character is a ]. > > "[^]]*\]" means match as many non-] characters as possible, plus a single ]. Got it - 'Makes perfect sense too > > >>which seems counterintutive to me. > > > then you need to study RE:s a bit more. > > (hint: an RE isn't a template, it's a language description, and the RE engine > is designed to answer the question "does this string belong to this language" > (for match) or "is there any substring in this string that belongs to this > language" (for search) as quickly as possible. things like match locations > etc are side effects). Yes, I understand this. But your clarification is most helpful. Thanks! ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From hcslmf at texlife.com Sat Jan 8 16:48:23 2005 From: hcslmf at texlife.com (brolewis) Date: 8 Jan 2005 13:48:23 -0800 Subject: Python Installation In-Reply-To: <1105220812.579690.292260@c13g2000cwb.googlegroups.com> References: <1105220812.579690.292260@c13g2000cwb.googlegroups.com> Message-ID: <1105220903.772101.298500@c13g2000cwb.googlegroups.com> For what its worth, I am running Windows XP Pro on all of these machines. From michele.simionato at gmail.com Thu Jan 27 03:24:23 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 27 Jan 2005 00:24:23 -0800 Subject: python without OO In-Reply-To: <1106694083.199064.240680@f14g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> Message-ID: <1106814263.835719.181360@z14g2000cwz.googlegroups.com> Davor wrote: > Thanks, > > I do not hate OO - I just do not need it for the project size I'm > dealing with - and the project will eventually become open-source and > have additional developers - so I would prefer that we all stick to > "simple procedural" stuff rather than having to deal with a developer > that will be convincing me that his 50 layers inheritance hierarchy is > good since it exists in some weird pattern that he saw somewhere on > some Java design patterns discussion board :-) and other "proper" OO > design issues... Once I opted for C++ in a very small project and > believed everyone will stick with C subset + better type checking > offered through C++ - but I simply could not manage to keep them off > using OO stuff which was just making program more complicated than it > should have been. (note, I am not an experienced developer, nor the > others I'll be working with (even though some think they are:-)), so I > prefer preemptively dealing with issue of everyone showing off their OO > design skills) > I think Davor is making an important point here: Python has grown in the last 14 years, and it is no more the simple scripting language it used to be. In particular, it evolved a lot of OOP "cruft" (static/classmethods, properties, the __new__ method, super, the new MRO, descriptors,metaclasses, etc.) and there is more than a learning curve issue coming with the added complexity. Davor is right: even if you do not want to use it, the stuff is *there* and somebody in your team will. So definitely there is an audience of programmers that just do not have an use for all the sophistication and actually are penalized by it. There is not much than can be done at the Python level. But I would see with interest a Python spinoff geared towards simplicity. Few months ago there was the Prothon proposal (by all means a terrible proposal) but the goal that motivated it (simplification, trying to remove classes) was in my opinion worthwhile. Now, *how* to remove (or simplify) classes is not at all clear to me, not I am convinced that prototypes are the right way to go, but still I feel that there is something wrong with inheritance. Maybe protocols are the solution, who knows? But in any case I think it is important to keep searching for semplicity. I do not believe Python is the definitive language, and it is probabily possible to introduce something better. It is just that nothing of the kind appeared until now, but I keep watching at the horizon ;) Michele Simionato From steve at holdenweb.com Wed Jan 19 12:17:59 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Jan 2005 12:17:59 -0500 Subject: Has apparent 2.4b1 bug been fixed? flatten in Lib\compiler\ast.py overloads 'list' name In-Reply-To: References: <41ede67e.1232456679@news.oz.net> Message-ID: Larry Bates wrote: > You have name clashing between Python's built in list function > and the variable called list that you pass into the function. > Change the passed in variable name to something else. > I believe Bengt was merely seeking confirmation that this was indeed a bug in a distributed library (which he then provided himself by finding a bug report). Hence his use of the phrase "overloads 'list' name" in the subject line! regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From sp1d3rx at gmail.com Tue Jan 11 14:21:06 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 11 Jan 2005 11:21:06 -0800 Subject: Time script help sought! In-Reply-To: <1105470872.613166.187800@f14g2000cwb.googlegroups.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> Message-ID: <1105471266.880133.318470@c13g2000cwb.googlegroups.com> Gosh Mark you must be a friggin genius or something. I can't even begin to read your code. Anyways, I think mine is easier to understand. My program has all the functions (save a couple) that you would need for your project. It's an exercise for you to copy and paste what you want where you want it and to form a basic program structure out of it. some of my comments spilled on to the next line (thanks google!) so you will have to clean it up a bit. From craig at postnewspapers.com.au Fri Jan 7 00:58:45 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 07 Jan 2005 13:58:45 +0800 Subject: curses is not imported under Linux (and Python 2.4) In-Reply-To: <41dd65bd.785984171@news.compuserve.de> References: <41dd65bd.785984171@news.compuserve.de> Message-ID: <1105077525.28776.71.camel@rasputin.localnet> On Fri, 2005-01-07 at 00:38, Konrad Koller wrote: > import curses > produces the ImportError: No module named _curses > ("from _curses import *" in line 15 in __init__.py) > Of course imp.find_module ("_curses") reports the same error. > How can I make use of the curses package for writing a Python script > with curses? What Linux distro? Is the Python version you're running one you compiled, one that shipped with the distro, or a 3rd party RPM? At a guess, I'd say you compiled it yourself and you don't have the ncurses development packages (providing the ncurses header files and static libs) installed. -- Craig Ringer From bvande at po-box.mcgill.ca Wed Jan 26 14:53:04 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed, 26 Jan 2005 14:53:04 -0500 Subject: how to write a tutorial In-Reply-To: References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106723545.429728.308620@f14g2000cwb.googlegroups.com> Message-ID: <41F7F520.8040706@po-box.mcgill.ca> Terry Reedy said unto the world upon 2005-01-26 14:08: > Xah the arrogant wrote, among other things, > However, there are several errors in the above that would mislead a Python > learner. I advise any such to ignore Xah's writings. > > Terry J. Reedy Hi all, here's a thought: There isn't any doubt that these 'tutorials' are generally unwelcome and unhelpful. Numerous people have kindly taken the time to flag some of the problems. So much so that any competent google of the archives would quickly reveal the group consensus on their instructional merit. I submit that continued corrections and advice of this sort are counter-productive. I understand the good intentions behind the corrections. (Indeed, my own level of Python-fu is such that it is possible that I might have been mislead the 'tutorials' without these corrections; I thus appreciate the correctors' efforts.) But, such corrections are troll-food and make it unlikely that the 'game' of posting such tutorials will soon loose its magical power to amuse the OP. They all but ensure that there will be more such 'tutorials' to correct. Could we try to ignore them in the hopes that without the light of attention they will wither, meanwhile trusting the many extant reviews and google to do their work? (In case it isn't obvious: none of this is intended as a criticism of Terry or any of the others who have been 'fighting the good fight'; I just think a change of strategy might be in order.) Best to all Brian vdB From fredrik at pythonware.com Mon Jan 24 11:09:06 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 17:09:06 +0100 Subject: Right place for third party modules (here: fixedpoint) References: <35kj2iF4n6sokU1@news.dfncis.de> Message-ID: >> I suppose fixedpoint is no package as described in the tutorial and so "site-packages" might not >> be the right place for it. > > site-packages sure works on my windows xp / python 2.4 configuration. ah, forget what I said. you need to put the fixedpoint.py *file* under site-packages, not the entire directory. as that "python -v -v" would have told you: > more out ... # trying C:\python24\lib\site-packages\fixedpoint.pyd # trying C:\python24\lib\site-packages\fixedpoint.dll # trying C:\python24\lib\site-packages\fixedpoint.py # trying C:\python24\lib\site-packages\fixedpoint.pyw # trying C:\python24\lib\site-packages\fixedpoint.pyc Traceback (most recent call last): File "", line 1, in ? ImportError: No module named fixedpoint ... From elephantum at dezcom.mephi.ru Tue Jan 11 05:38:25 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Tue, 11 Jan 2005 13:38:25 +0300 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <34frdmF42p2jrU1@individual.net> Message-ID: <34hol1F4ajrmmU1@individual.net> > So of the four keywords suggested so far ('where', 'with', 'in', > 'using'), I'd currently vote for 'using' with 'where' a fairly close > second. My vote goes to 'using' because it has a fairly clear meaning > ('execute the statement using this extra information'), and doesn't have > the conflicting external baggage that 'where' does. I should agree with you =) Though I love "with" for historical reasons and addiction to functional languages "using" is not that bad and I do not mind using it. =) From jdhunter at ace.bsd.uchicago.edu Fri Jan 28 14:47:13 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 28 Jan 2005 13:47:13 -0600 Subject: Installing Numeric with ATLAS and LAPACK In-Reply-To: <1106940704.164253.134630@c13g2000cwb.googlegroups.com> ("drife"'s message of "28 Jan 2005 11:31:44 -0800") References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> <1106940704.164253.134630@c13g2000cwb.googlegroups.com> Message-ID: >>>>> "drife" == drife writes: drife> Thanks John. Those are the steps I followed, and to no drife> avail. Make sure you get a clean build by rm -rf ing the build dir before you build again. Then capture the output of your build to a file. When you say "to no avail" what do you mean -- that the calculation was slower. If you still have troubles, post again to the numpy-discussion list listing what you did and the output of the build process. Good luck! JDH From case.nelson at gmail.com Wed Jan 12 00:02:48 2005 From: case.nelson at gmail.com (snoe) Date: 11 Jan 2005 21:02:48 -0800 Subject: Help Optimizing Word Search In-Reply-To: <1105492347.701890.124830@f14g2000cwb.googlegroups.com> References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> <1105492347.701890.124830@f14g2000cwb.googlegroups.com> Message-ID: <1105506168.801091.282350@z14g2000cwz.googlegroups.com> First of all thank you very much for the reply. I hope I'm not too verbose here, just hope that if someone else runs into a similar problem they can find an answer here. > This appears to be a Computer Science 101 Data Structures and > Algorithms question, not a Python question, but here's an answer > anyway Heh, it's been awhile since I took data structures 101 but I asked here after reading about python generators, and although I can't quite get my head around them, I have a sense that they could help me check all mutations (is this the right word?) of the candidate strings. Thanks for the ideas on finding matches, I will have to try the bit filter out to see if its faster. The trie works similar to this in that it will return a 3 if the substring is not in the dictionary so that you don't have to check any superset of the mutation. Although to clarify, the reason I posted was mostly for help on my weak wildcard algorithm. > If "aa" is in your dictionary, what queries would retrieve it? Any query that contains either "a" and "a" or "a" and "?" or "?" and "?". So some examples would be: "aa", "a?", "aba", "baa", "bbbaba", "b?b?", "bab?", "?abbbbb" etc... > Searching with wild cards: your example of query == "??" seems to yield > all two-letter words. I'd like to see what you expect for "a?", "?a", > "ab?", and "aa?" before suggesting how to tackle wild cards. > Reverse-engineering requirements out of other folks' code is not > something I do for fun :-) My apologies, in my haste my example of what query == "??" yields was unclear. Every list of candidate letters should yield every unique (if possible) mutation, of length 1 to len(candidate). Heh, exactly what each of those strings would yield is pretty much the root of my problem: ?? yields (the order of the results dont matter): a, b, c, d, e, f, ..., x, y, z, aa, ab, ac, ..., ax, ay, az, ba, bb, bc, ..., ya, yb, yc, ..., yx, yy, yz, za, zb, zc, ..., zx, zy, zz a? yields a, b, c, d, ..., x, y, z, aa, ab, ac, ..., ax, ay, az, ba, ca, da, ..., xa, ya, za ?a yields same as a? ab? yields a, b, c, d, ..., x, y, z, aa, ab, ac, ..., ax, ay, az, ba, bb, bc, ..., bx, by, bz, ca, cb, da, db, ea, eb, ..., xa, xb, ya, yb, za, zb, aba, abb, abc, abd, ..., abx, aby, abz, baa, bab, bac, ..., bax, bay, baz, aab, acb, adb, ..., axb, ayb, azb, bba, bca, bda, ... bxa, bya, bza, cba, dba, eba, xba, yba, zba HTH, basically every possible string out of the given pool of up to 10 letters. Ok writing these out just gave me an idea on how I could try and write this another way. Ok done. Wow, this program actually ran much much slower than my original 135 seconds vs 9 seconds!! I'm not sure if I made a huge mistake or if it's because in the original I can stop searching superset-candidates if the candidate is not a substring of a dictionary word (in the same way the mask would reject impossible mutations). This produces the correct mutations however (although not unique as I wrote out above): -- begin code -- !def getmutations(pool): ! ! for i, letter in enumerate(pool): ! pool2 = pool[:] ! pool2.pop(i) ! ! for mutation in getmutations(pool2): ! if letter != '?': ! yield letter + mutation ! else: ! for c in alpha: ! yield c + mutation ! ! yield "" !letters = list('abae?s?') !s = time.time() !output = open('words.log','w') !for candidate in getmutations(letters): ! # Check if word is valid ! result = mytrie.query(candidate) ! ! # Found a word, add it to the database ! if result == 1: ! words[candidate] = 1 ! !print time.time() - s --- end code --- From mirko-lists at zeibig.net Tue Jan 4 04:40:54 2005 From: mirko-lists at zeibig.net (Mirko Zeibig) Date: Tue, 04 Jan 2005 10:40:54 +0100 Subject: python 3000 and removal of builtin callable Message-ID: <33v6l6F40l7hqU1@individual.net> Hello everybody, I recently stumbled across the proposal of removing `callable` in Python 3000 (http://python.org/peps/pep-3000.html) catching an exception instead, maybe something like this: --- snip --- [mize at lxmize mize]$ python2.3 Python 2.3.3 (#1, Apr 6 2004, 01:47:39) [GCC 3.3.3 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> i = 5 >>> i() Traceback (most recent call last): File "", line 1, in ? TypeError: 'int' object is not callable >>> --- snap --- This is not an option for e.g. IDEs as some functions might actually do something when called ;-) and I like `callable` for introspection. Other ways would be to check for the `__call__` attribute or use several methods of the `inspect`-Module, both of which are not better than `callable` IMHO. Regards Mirko -- Insert a sig please. From mnations at gmail.com Tue Jan 18 17:21:37 2005 From: mnations at gmail.com (Mudcat) Date: 18 Jan 2005 14:21:37 -0800 Subject: How to fill available screen size then scroll Message-ID: <1106086897.788340.267550@f14g2000cwb.googlegroups.com> Hi all, I am writing a gui that expands depending on the number of interefaces a user decides to use with Win 2k, Tkinter, and Pmw. So with normal use the gui window will expand to the screen size and then clip without scrolling. If I use Pmw.ScrolledFrame, the clipping frame is set based on the size of the first child frame and never expands to fill the screen. It just expands the size of the inside frame inside the clipping frame. I need a tweener solution. I need the gui to expand until it reaches the width of the available viewing screen. THEN the scroll bar kicks in with a clipping frame the width of the screen to allow the user to see as many interfaces as possible. Does anyone know how to do this? Thanks ahead of time, Marc From ncoghlan at iinet.net.au Sat Jan 22 00:59:05 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 22 Jan 2005 15:59:05 +1000 Subject: Print a string in binary format In-Reply-To: <41f1b14a.1480920561@news.oz.net> References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> <41f1b14a.1480920561@news.oz.net> Message-ID: <41F1EBA9.5010903@iinet.net.au> Bengt Richter wrote: > On Sat, 22 Jan 2005 00:45:19 +1000, Nick Coghlan wrote: >>Here's an interesting twiddle, though (there's probably already something along >>these lines in the cookbook): > > Looks like you also played with this problem, after Alex posted a request for alternative > one-liner solutions to a question on an Italian newsgroup last October? ("show_base" reminded me > of "number_in_base") > > http://groups-beta.google.com/groups?hl=en&lr=&q=number_in_base&qt_s=Search+Groups See, I knew I wouldn't be the first one to think of it :) I stole some ideas from that thread to add to the new version down below (I did not, however, try to make the function expressible as a one-liner, since, after the function has been defined, *using* it is a one-liner!) > Hm, learn something every day ;-) > It didn't occur to me that a string multiplied by a negative number would default > nicely to the same result as multiplying by zero. Where'd I learn that trick?. . . oh, that's right, Facundo used it when working out the string representation for Decimal. It certainly makes padding to a desired minimum field width pretty easy. > Of course, this is the prefixed-sign and absolute value representation, > which is no good if you are using base 2, 8, or 16 to get an idea of > underlying bits in a negative two-s complement representation. Dealing with negative numbers isn't really needed for printing a string as binary , since ord() returns only positive results. However, we should be able to add complement formatting fairly easily: Py> def show_base(val, base, min_digits=1, complement=False, ... digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"): ... if base > len(digits): raise ValueError("Not enough digits for base") ... negative = val < 0 ... val = abs(val) ... if complement: ... sign = "" ... max = base**min_digits ... if (val >= max) or (not negative and val == max): ... raise ValueError("Value out of range for complemented format") ... if negative: ... val = (max - val) ... else: ... sign = "-" * negative ... val_digits = [] ... while val: ... val, digit = divmod(val, base) ... val_digits.append(digits[digit]) ... result = "".join(reversed(val_digits)) ... return sign + ("0" * (min_digits - len(result))) + result ... Py> show_base(10, 2) '1010' Py> show_base(-10, 2) '-1010' Py> show_base(10, 2, 8) '00001010' Py> show_base(-10, 2, 8) '-00001010' Py> show_base(10, 2, 8, complement=True) '00001010' Py> show_base(-10, 2, 8, complement=True) '11110110' Py> show_base(10, 16, 2, complement=True) '0A' Py> show_base(-10, 16, 2, complement=True) 'F6' Py> show_base(127, 16, 2, complement=True) '7F' Py> show_base(-127, 16, 2, complement=True) '81' Py> show_base(255, 16, 2, complement=True) 'FF' Py> show_base(-255, 16, 2, complement=True) '01' Py> show_base(256, 16, 2, complement=True) Traceback (most recent call last): File "", line 1, in ? File "", line 10, in show_base ValueError: Value out of range for complemented format Py> show_base(-256, 16, 2, complement=True) '00' Py> Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ncoghlan at iinet.net.au Fri Jan 14 22:44:47 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 15 Jan 2005 13:44:47 +1000 Subject: import keyword behaviour - performance impact if used multiple times? In-Reply-To: <1105721512.379401.266490@c13g2000cwb.googlegroups.com> References: <41a87cd9$0$25779$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <1105721512.379401.266490@c13g2000cwb.googlegroups.com> Message-ID: <41E891AF.8010900@iinet.net.au> neophyte wrote: > Nick Coghlan wrote: > >> > Is >> > this something to do with system modules being singletons? >> >>They aren't singletons in the GoF design pattern sense. However, > > Python's import > >>machinery operates in such a way that it takes effort to get multiple > > version of > >>the same module into memory at the same time (it *can* be done, but > > you have to > >>work at it). > > Given that this is exactly what I want, how can you do it? > If you just want to reload an existing module, use the builtin "reload" function. Getting multiple versions of a module into sys.modules at the same time isn't something I've ever actually wanted to do, but the following will do it: Py> import sys Py> sys.modules["sys1"] = sys Py> del sys.modules["sys"] Py> import sys Py> import sys1 Py> sys is sys1 False However: 1. Doing this at all is probably a bad idea (since you may end up duplicating objects that are meant to be unique within the process, and any C-extension code will still be shared between the multiple versions of the module) 2. Doing it to 'sys' like I just did is an even worse idea, since you *definitely* end up doing 1 :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From news at NOwillmcguganSPAM.com Wed Jan 26 11:21:59 2005 From: news at NOwillmcguganSPAM.com (Will McGugan) Date: Wed, 26 Jan 2005 16:21:59 +0000 Subject: Help With Python In-Reply-To: References: Message-ID: <41f7c3a7$0$7777$db0fefd9@news.zen.co.uk> Judi Keplar wrote: > I am currently taking a course to learn Python and was looking for > some help. I need to write a Python statement to print a comma- > separated repetition of the word, "Spam", written 511 times ("Spam, > Spam, ? Spam"). > > Can anybody help me get started? I am completely new to programming! > > Thanks in advance! >>> print "Spam, " * 510 + "Spam" Will McGugan From jdhunter at ace.bsd.uchicago.edu Fri Jan 28 13:59:11 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 28 Jan 2005 12:59:11 -0600 Subject: handling xls with pyuno Message-ID: Does anyone have any example scripts using the OpenOffince python-bridge module pyuno to load xls, extract the data, and/or save to another format such as xsc or csv. Thanks, JDH From fb at frank-buss.de Fri Jan 21 10:03:45 2005 From: fb at frank-buss.de (Frank Buss) Date: Fri, 21 Jan 2005 15:03:45 +0000 (UTC) Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <0n7Id.135415$Xk.80179@pd7tw3no> Message-ID: drewc wrote: > What does this have to do with Lisp? (i'm in c.l.l). he is a troll, but one who confess this fact: http://www.xahlee.org/Netiquette_dir/troll.html -- Frank Bu?, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From salvafg at terra.es Sat Jan 29 14:52:34 2005 From: salvafg at terra.es (Salvador Fandino) Date: Sat, 29 Jan 2005 19:52:34 GMT Subject: ASPy package Message-ID: <6QRKd.53675$A7.97046@telenews.teleline.es> Hello, I have been trying to download ASPy (an old jython package implementing ASP pages support) from the Internet but it is not available anymore from its home page. Does anybody have it and could link it in some public place? Best Regards - Salvador From deetsNOSPAM at web.de Sun Jan 23 07:06:50 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 23 Jan 2005 13:06:50 +0100 Subject: debugging xmlrpc servers References: <1106442233.305138.24790@f14g2000cwb.googlegroups.com> Message-ID: I have difficulties understanding your probelem - is your own method giving you trouble (and the 'exceptions.ValueError:too many values to unpack') error or is it the remote debugger? Or do you simply not understand the error message itself. The error itself is raised in cases like this: a,b,c = (1,2,3,4) Now to see where that sort of statement fails, it would help if you'd give us the actual code for your result-method. -- Regards, Diez B. Roggisch From aleaxit at yahoo.com Sat Jan 15 14:56:54 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 15 Jan 2005 20:56:54 +0100 Subject: hash patent by AltNet; Python is prior art? References: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> Message-ID: <1gqg78x.1pugljnc5awhmN%aleaxit@yahoo.com> GerritM wrote: > How can this type of fundamental knowledge be patented? I am afraid this is > again an example of a total failure of the current patent system. As a European citizen, you have a chance to make a difference to software patentability in Europe -- think globally, act locally. The Netherlands are a crucial country in the ongoing battle against software patents. Get active! -- we have won major battles over the last 4+ years and we'll need to win quite a few more to break the back of this ugly beast forever. A future where the US and other major SW development countries such as India have saddled themselves with this absurdity, and Europe has freed itself of it, is THE best competitive hope to make Europe into the hotbed of software development and IT innovation in the next generation. Personally, I'm neither patriotic nor competitive, so I'd rather look forward to a world entirely free of this blight -- but hey, where I can make a difference is HERE, so, HERE is where I act. Alex From craig at postnewspapers.com.au Fri Jan 7 00:43:29 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 07 Jan 2005 13:43:29 +0800 Subject: Python C Object Comparison In-Reply-To: <41DD1428.1030503@esi-india.com> References: <41DD1428.1030503@esi-india.com> Message-ID: <1105076609.28776.56.camel@rasputin.localnet> On Thu, 2005-01-06 at 18:34, Anand K Rayudu wrote: > Here is my python code > > import myModule > > a=myModule.myAPI1("1") > b=myModule.myAPI2("name") > > # basically both above functions return same C pointer. > # so i want to compare > if(a==b): print "They are same" > else : print "They are different" > > python always prints they are different, > I guess this is because in python layer we create PythonCObject for > every C pointer, and that is how it is exposed to python. Though both > the APIs are returning the same C pointer, they are different instances > of PythonCObject. That sounds likely to me. > So i guess that is the reason comparison is failing. > How ever is it possible to make python to compare actual C pointer, > rather than the PythonCObject Pointer. You might be able to subclass PyCObject and work with your subclassed version (that adds a __eq__ method). In the end, though, I don't think that's the right path to proceed down. My understanding is that CObjects are for passing pointers through Python code in a safe way. I don't think they're really intended for uses where the Python code is actually working with the objects, only pass them around as opaque objects. If you want to actually work with the objects you're passing around, I'd think about implementing my own type that better fits the API my extension module wants to present to Python code. I'm using PyCObjects as a temporary ugly hack in an embedded app I'm working on... but it's seriously ugly. What I should do, and will soon do now that I've tested the concept of what I'm doing and it works, is move all my functions into a class and make the class own and manage the C++ object (and pointer to it) that it owns. Perhaps that's a better solution for you too? If you want any opinions from folks here about the best way to solve your problem, you'll probably need to explain a bit more of your problem - like what your extension module is doing that makes it have to pass PyCObjects around and get Python code to work with them. -- Craig Ringer From sp1d3rx at gmail.com Fri Jan 14 17:22:24 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 14 Jan 2005 14:22:24 -0800 Subject: win32net help In-Reply-To: References: Message-ID: <1105741344.058696.161980@z14g2000cwz.googlegroups.com> Have you tried using UDP instead of TCP? Also, it is common practice to choose a random port over 1024 for opening a connection to a remote server. From tjreedy at udel.edu Sun Jan 2 21:52:04 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Jan 2005 21:52:04 -0500 Subject: Calling Function Without Parentheses! References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> Message-ID: "Kamilche" wrote in message news:1104715584.407505.190910 at f14g2000cwb.googlegroups.com... > What a debug nightmare! I just spent HOURS running my script through > the debugger, sprinkling in log statements, and the like, tracking down > my problem. Did you try PyChecker? (Don't know if > I called a function without the ending parentheses. Which means you didn't call, and that was your problem ;-) In Python, the (...) pair in the appropriate context (where an operator is expected) *is* the infix/postfix call operator. It is equivalent to the call or gosub prefix in some other languages. The call operator works with any callable, not just function objects. >I sure do WISH Python would trap it when I try to do the following: trap = raise an exception? nooooh. > MyFunc > instead of: > MyFunc() In Python, non-keyword names resolve at runtime to the objects they are then bound to. This simple, uniform rule is, to me, part of the beauty of Python. There are lots of times that one wants to refer to a callable without calling it. Indeed, because Python separates referring to an object from calling the object, it can and does have a broader notion of 'callable' than other languages. This includes the option of making instances of any user class callable (by including a __call__ method). Terry J. Reedy From agriff at tin.it Mon Jan 10 02:31:02 2005 From: agriff at tin.it (Andrea Griffini) Date: Mon, 10 Jan 2005 07:31:02 GMT Subject: Speed revisited References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> <1105237556.402188.126980@c13g2000cwb.googlegroups.com> <1105303172.147395.63580@c13g2000cwb.googlegroups.com> <36c3u0tpbg6f98ta6cm4fkj2kn0dkv624m@4ax.com> <1105315414.432202.249470@c13g2000cwb.googlegroups.com> Message-ID: On 9 Jan 2005 16:03:34 -0800, "John Machin" wrote: >My wild guess: Not a common use case. Double-ended queue is a special >purpose structure. > >Note that the OP could have implemented the 3-tape update simulation >efficiently by reading backwards i.e. del alist[-1] Note that I was just trying to say that it's not obvious that list insertion at the first element is O(n); because there are "less naive" implementation that can do better. For a lower level language O(n) is probably what 99% of programmers indeed would expect, but for a VHLL like python this is IMO not the case. I remember when a few years ago working with PowerBuilder (a RAD environment for client-server applications) to my great surprise I found that even adding at the end of a list was O(n) in that language... where is the line ? After all "smart" reallocation is still a tradeoff (extra "wasted" space traded for diminshed copying) ... Andrea From mike at lookdirect.com.au Mon Jan 31 17:42:11 2005 From: mike at lookdirect.com.au (mike) Date: 31 Jan 2005 14:42:11 -0800 Subject: Microsoft Visual C++ and pyton In-Reply-To: References: <1107126726.533325.104300@z14g2000cwz.googlegroups.com> Message-ID: <1107211331.830565.238150@c13g2000cwb.googlegroups.com> Thanks Chris.. I was also advised to build the python core (pythoncore.vcproj) with my C++ program. By that way I would not have to load the python core anymore during runtime. Is this a good approach? I am currently using VC++ 7 and python 2.4. - mike Christopher De Vries wrote: > On Sun, Jan 30, 2005 at 03:12:06PM -0800, mike wrote: > > I am new with python. Is it possible to have an MFC application and > > develop some module using python? what are the steps in doing this? can > > anybody give me a url or some documentation for this.. thanks.. > > It is possible to embed python in a C or C++ application, enabling you to call > python functions from C. I would recommend reading "Extending and Embedding the > Python Interpreter" at http://docs.python.org/ext/ext.html for more > information. If you are currently using Visual C++ 6.0, either stick with > Python 2.3 or read this: http://www.vrplumber.com/programming/mstoolkit/ to > learn how to build extensions for python 2.4 with the free VC++ toolkit > compiler. If you are already using version 7 of the Microsoft C++ compiler then > you should have no problems with Python 2.4. > > I usually do not embed the interpreter, but I have written some extension > modules... well, I should say I have used SWIG (http://www.swig.org/) to create > wrappers around some C libraries. For information (read: rants) on extending > versus embedding see http://twistedmatrix.com/users/glyph/rant/extendit.html > and http://c2.com/cgi/wiki?EmbedVsExtend . > > You can also use win32 python extensions to make your module available through > COM, but I don't know anything about that. > > Chris From ncoghlan at iinet.net.au Tue Jan 4 05:46:55 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 04 Jan 2005 20:46:55 +1000 Subject: why does UserDict.DictMixin use keys instead of __iter__? In-Reply-To: References: Message-ID: <41DA741F.5050406@iinet.net.au> Steven Bethard wrote: > Sorry if this is a repost -- it didn't appear for me the first time. > > > So I was looking at the Language Reference's discussion about emulating > container types[1], and nowhere in it does it mention that .keys() is > part of the container protocol. Because of this, I would assume that to > use UserDict.DictMixin correctly, a class would only need to define > __getitem__, __setitem__, __delitem__ and __iter__. So why does > UserDict.DictMixin require keys() to be defined? Because it's a DictMixin, not a ContainerMixin? .keys() is definitely part of the standard dictionary interface, and not something the mixin can derive from the generic container methods. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From exarkun at divmod.com Thu Jan 6 09:09:00 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 06 Jan 2005 14:09:00 GMT Subject: get the IP address of a host In-Reply-To: Message-ID: <20050106140900.25734.752673503.divmod.quotient.3700@ohm> On Thu, 06 Jan 2005 14:35:16 +0100, J Berends wrote: > > From several approached I came up with the following code: > > def getipaddr(hostname='default'): > """Given a hostname, perform a standard (forward) lookup and return > a list of IP addresses for that host.""" > if hostname == 'default': > hostname = socket.gethostname() > ips = socket.gethostbyname_ex(hostname)[2] > ips = [i for i in ips if i.split('.')[0] != '127'] > if len(ips) != 0: > # check if we have succes in determining outside IP > ip = ips[0] > elif len(ips) == 0 and hostname == socket.gethostname(): > # when we want to determine local IP and did not have succes > # with gethostbyname_ex then we would like to connect to say... > > # google.com and determine the local ip address bound to the > # local socket. > try: > s = socket.socket() > s.connect(('google.com', 80)) > print ('___ connecting to internet to determine local ip') > ip = s.getsockname()[0] s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('1.2.3.4', 56)) ip = s.getsockname()[0] > del s > except: > print ('*** cannot connect to internet in order to \ > determine outside IP address') > raise Exception > if len(ip) != 0: > return ip > else: > print ('*** unable to determine outside IP address') > raise Exception > > It returns the IP address with which it connects to the world (not lo), > might be a pvt LAN address or an internet routed IP. Depend on where the > host is. > > I hate the google trick actually, so any suggestions to something better > is always welcome. Jp From francis.girard at free.fr Fri Jan 21 11:16:28 2005 From: francis.girard at free.fr (Francis Girard) Date: Fri, 21 Jan 2005 17:16:28 +0100 Subject: need help on need help on generator... In-Reply-To: <1106322141.19065.42.camel@bucket.localnet> References: <63b5e209.0501210558.686f5c10@posting.google.com> <200501211605.40696.francis.girard@free.fr> <1106322141.19065.42.camel@bucket.localnet> Message-ID: <200501211716.28459.francis.girard@free.fr> Really, thank you Craig Ringer for your great answer. > I'm afraid I can't help you with that. I tend to take the view that side > effects in lazily executed code are a bad plan, and use lazy execution > for things where there is no reason to care when the code is executed. I completly agree with this. But this is much more true in theory than in practice. In practice you might end up with big big memory usage with lazy constructs as the "system" has to store intermediate results (the execution context in the case of Python). These kinds of phenomena happen all the time in a language like Haskell -- at least for a beginner like me -- if you don't pay attention to it ; and this makes the language a lot more difficult to master. Thus you have to keep an eye on performance even though, in FP, you shoould just have to "declare" your intentions and let the system manage the execution path. > http://gnosis.cx/publish/programming/metaclass_1.html > http://gnosis.cx/publish/programming/metaclass_2.html Thank you, I'll read that. Francis Girard FRANCE Le vendredi 21 Janvier 2005 16:42, Craig Ringer a ?crit?: > On Fri, 2005-01-21 at 16:05 +0100, Francis Girard wrote: > > I recently read David Mertz (IBM DeveloperWorks) about generators and > > got excited about using lazy constructs in my Python programming. > > Speaking of totally great articles, and indirectly to lazyness (though > not lazyily evaluated constructs), I was really impressed by this > fantastic article on metaclasses: > > http://gnosis.cx/publish/programming/metaclass_1.html > http://gnosis.cx/publish/programming/metaclass_2.html > > which shows that they're really just not that hard. That saved me an > IMMENSE amount of utterly tedious coding just recently. > > > But besides the fact that generators are either produced with the new > > "yield" reserved word or by defining the __new__ method in a class > > definition, I don't know much about them. > > They can also be created with a generator expression under Python 2.4. A > generator expression works much like a list comprehension, but returns a > generator instead of a list, and is evaluated lazily. (It also doesn't > pollute the outside namespace with its working variables). > > >>> print [ x for x in range(1,10)] > > [1, 2, 3, 4, 5, 6, 7, 8, 9] > > >>> print ( x for x in xrange(1,10) ) > > > > >>> print list(( x for x in xrange(1,10) )) > > [1, 2, 3, 4, 5, 6, 7, 8, 9] > > Not the use of xrange above for efficiency in the generator expressions. > These examples are trivial and pointless, but hopefully get the point > across. > > > In particular, I don't know what Python constructs does generate a > > generator. > > As far as I know, functions that use yield, and generator expressions. I > was unaware of the ability to create them using a class with a __new__ > method, and need to check that out - I can imagine situations in which > it might be rather handy. > > I'm not sure how many Python built-in functions and library modules > return generators for things. > > > I know this is now the case for reading lines in a file or with the > > new "iterator" package. But what else ? Does Craig Ringer answer mean > > that list comprehensions are lazy ? > > Nope, but generator expressions are, and they're pretty similar. > > > Where can I find a comprehensive list of all the lazy constructions > > built in Python ? (I think that to easily distinguish lazy from strict > > constructs is an absolute programmer need -- otherwise you always end > > up wondering when is it that code is actually executed like in > > Haskell). > > I'm afraid I can't help you with that. I tend to take the view that side > effects in lazily executed code are a bad plan, and use lazy execution > for things where there is no reason to care when the code is executed. > > -- > Craig Ringer From steve at holdenweb.com Fri Jan 14 17:22:20 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 17:22:20 -0500 Subject: (objects as) mutable dictionary keys In-Reply-To: References: Message-ID: Antoon Pardon wrote: > Op 2005-01-14, Peter Maas schreef : > >>I have summarized the discussion about the usability of lists (and >>and other mutable types) as dictionary keys and put it into the >>Python wiki.URL: http://www.python.org/moin/DictionaryKeys. >> >>This summary might be used as a reference should the 'mutable >>dictionary keys' issue come up again in c.l.py. >> > > I had a look and I think you should correct the followingr: > > Dictionary lookup with mutable types like lists is a source of > unpleasant surprises for the programmer and therefore impossible in > Python. > Better, perhaps, to say: Dictionary lookup with mutable types like lists can be a source of unpleasant surprises for the programmer and therefore not recommended in Python. > > It is not impossible in Python. It may be discouraged but it is not > impossible since I have already done so. > If I discouraged you from shooting yourself in the foot would you do that too? some-people-just-won't-be-told-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From a at a.invalid Thu Jan 27 03:32:37 2005 From: a at a.invalid (Timo Virkkala) Date: Thu, 27 Jan 2005 08:32:37 GMT Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> Message-ID: Davor wrote: > Timo Virkkala wrote: >> This guy has got to be a troll. No other way to understand. > > not really - it was not my intention at all - but it seems people get > upset whenever this OO stuff is mentioned - and what I did not expect at > all at this forum as I believed Python people should not be so OO > hardcore (seems not all as quite a few have indicated in their > replies)... Nevertheless, I think the discussion has several quite good > points! Yes, sorry about that. I posted too soon. After posting I read more of your posts and realized that you really mean it, so I tried to cancel my message, but apparently it got through (news message canceling has never been that reliable..). I believe that if you take the time to do some Python programming, you can find out that OO, when used correctly, is not the huge monster your previous languages had led you to believe it is. In Python, you can use just the right amount of OO to make things easier and more sensible, without complicating things with huge inheritance trees and unnecessary polymorphism. Again, sorry about my premature judgement. -- Timo Virkkala From __peter__ at web.de Fri Jan 28 04:33:30 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Jan 2005 10:33:30 +0100 Subject: get list of member variables from list of class References: Message-ID: Oliver Eichler wrote: > what will be the fastest solution to following problem > > class a: > def __init__(self): > self.varA = 0 > self.varB = 0 > s.o. ... > > > listA = [a]*10 > > > varA = [] > varB = [] > > for l in listA: > varA.append(l.varA) > varB.append(l.varB) > s.o. ... > > > I could think of: > [varA.append(l.varA) for l in listA] > [varB.append(l.varB) for l in listA] > s.o. ... > > But is this faster? After all I have to iterate over listA several times. > > Any better solutions? A different approach, a "virtual list" could even be faster if client code must access only a fraction of the items in the virtual list. If you are lucky, you never have to iterate over the complete list. >>> class A: ... def __init__(self, a): ... self.a = a ... def __repr__(self): ... return "A(%r)" % self.a ... >>> items = map(A, range(10)) >>> items [A(0), A(1), A(2), A(3), A(4), A(5), A(6), A(7), A(8), A(9)] >>> class List: ... def __init__(self, items, getter): ... self.items = items ... self.getter = getter ... def __getitem__(self, index): ... return self.getter(self.items[index]) ... def __iter__(self): ... return imap(self.getter, self.items) ... >>> from operator import attrgetter >>> from itertools import imap >>> items_a = List(items, attrgetter("a")) >>> items_a <__main__.List instance at 0x402ae2cc> >>> items_a[2] 2 >>> list(items_a) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> items[2] = A(42) >>> items [A(0), A(1), A(42), A(3), A(4), A(5), A(6), A(7), A(8), A(9)] >>> items_a[2] 42 Peter From steve at holdenweb.com Mon Jan 17 06:32:10 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 06:32:10 -0500 Subject: [perl-python] 20050117, filter, map In-Reply-To: References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> Message-ID: <41EBA23A.2010005@holdenweb.com> Erik Max Francis wrote: > Steven Bethard wrote: > >> Is there any chance you could post these all as part of the same >> thread? That would be really nice for those of us who aren't >> interested -- then we could just ignore the thread... > You are looking for evidence of cluefulness where it seems unlikely to ever appear. > > Or, better yet, not posting it at all. He's got his mailing list, what > does he need to post it here for? > As I may have mentioned before, egotism can be the only possible reason. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From kent3737 at yahoo.com Thu Jan 20 15:23:01 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Thu, 20 Jan 2005 15:23:01 -0500 Subject: Overloading ctor doesn't work? In-Reply-To: References: <35ab8oF4idc25U1@individual.net> <41effd30$1_1@newspeer2.tds.net> Message-ID: <41f010b5$1_1@newspeer2.tds.net> Paul McGuire wrote: > "Kent Johnson" wrote in message > news:41effd30$1_1 at newspeer2.tds.net... > >>>Martin H?cker wrote: >>> >>> >>>>Hi there, >>>> >>>>I just tried to run this code and failed miserably - though I dunno >>>>why. Could any of you please enlighten me why this doesn't work? >> >>Here is a simpler test case. I'm mystified too: >> >>from datetime import datetime >> >>class time (datetime): >> def __init__(self, hours=0, minutes=0, seconds=0, microseconds=0): >> datetime.__init__(self, 2001, 10, 31, hours, minutes, seconds, > > microseconds) > >>print time(1,2,3,4) # => 0001-02-03 04:00:00 >>print time() # => TypeError: function takes at least 3 arguments (0 > > given) > >> >>What happens to the default arguments to time.__init__? What happens to > > the 2001, 10, 31 arguments > >>to datetime.__init__? >> >>I would expect the output to be >>2001-10-31 01:02:03.000004 >>2001-10-31 00:00:00.000000 >> >>Kent > > > I can't explain this behavior, but this version does work (uses > datetime.combine instead of ctor) > > -- Paul > > > from datetime import datetime, date as dt_date, time as dt_time > > class time_d (datetime): > def __new__(cls, *args): > # default to no microseconds > if len(args)==3: > args = args + (0,) > if len(args)==4: > tmpdate = datetime.today() > h, mi, s, ms = args > return datetime.combine(tmpdate, dt_time(h,mi,s,ms)) > elif len(args)==7: > y,m,d,h,mi,s,ms = args > return datetime.combine(dt_date(y,m,d), dt_time(h,mi,s,ms)) > else: > raise TypeError, "wrong number of args" > > print time_d(2001,10,31,1,2,3,4) > print time_d(1,2,3,4) > print time_d(1,2,3) Ah, right. The light turns on... datetime is immutable so overriding the constructor doesn't change the constructed object. You have to override __new__ instead. http://www.python.org/2.2.1/descrintro.html#__new__ This works: from datetime import datetime class time (datetime): def __new__(cls, hours=0, minutes=0, seconds=0, microseconds=0): return datetime.__new__(cls, 2001, 10, 31, hours, minutes, seconds, microseconds) print time(1,2,3,4) # => 2001-10-31 01:02:03.000004 print time() # => 2001-10-31 00:00:00 Kent > > > From sam.wun at authtec.com Mon Jan 24 01:26:58 2005 From: sam.wun at authtec.com (sam) Date: Mon, 24 Jan 2005 14:26:58 +0800 Subject: compile python to binary In-Reply-To: References: <1d6cdae3050123080242bf8994@mail.gmail.com> Message-ID: <41F49532.5040307@authtec.com> Fredrik Lundh wrote: > Daniel Bickett wrote: > > >>I believe Sam was talking about "frozen" python scripts using tools >>such as py2exe: > > > oh, you mean that "python compiler" didn't mean "the python compiler". > > here are links to some more tools, btw: > > http://effbot.org/zone/python-compile.htm > Thanks for the link. It is what I exactly looking for. Thanks Sam > > > > From marc_a_poulin at yahoo.com Fri Jan 28 19:04:48 2005 From: marc_a_poulin at yahoo.com (Marc Poulin) Date: Fri, 28 Jan 2005 17:04:48 -0700 Subject: Where can I find sample "beginner" programs to study? References: <_6CdnWIOB8AaA2fcRVn-rg@speakeasy.net> Message-ID: <41fad2f9$0$206$75868355@news.frii.net> Todd_Calhoun wrote: > I'm trying to learn Python (and programming), and I'm wondering if there > are any places where I can find small, simple programs to study. > > Thanks. Look at http://www.livewires.org.uk/python/ Good projects and tutorials for beginners. From get at bent.com Wed Jan 26 02:59:35 2005 From: get at bent.com (nobody) Date: Wed, 26 Jan 2005 17:59:35 +1000 Subject: MySQLdb References: Message-ID: <1106726373.519886@chloe.intranet> > How many indices? Just the primary key (id). From benn at cenix-bioscience.com Thu Jan 20 05:55:11 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Thu, 20 Jan 2005 11:55:11 +0100 Subject: [Fwd: Re: Oddity is shutil.copyfileobj] Message-ID: <41EF8E0F.2070401@cenix-bioscience.com> -------------- next part -------------- An embedded message was scrubbed... From: Neil Benn Subject: Re: Oddity is shutil.copyfileobj Date: Thu, 20 Jan 2005 11:41:40 +0100 Size: 2267 URL: From firstname.lastname at iki.fi-spam Wed Jan 12 09:03:07 2005 From: firstname.lastname at iki.fi-spam (Simo Melenius) Date: 12 Jan 2005 16:03:07 +0200 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <1105509379.301556.178130@z14g2000cwz.googlegroups.com> Message-ID: <87wtui4uec.fsf@sme.intra.citec.fi> michele.simionato at gmail.com writes: > This is a bizarre idea if you want to make Python run faster. It is > not so bizarre if what you want is to have access to Python from > Lisp/Scheme in the same sense Jython has access to Java. And it sounds very nice if you prefer writing Lisp code (or resort to it if needed) and run it on a cross-platform environment that's available almost everywhere, and access a large standard library of modern utilities. br, S From steven.bethard at gmail.com Wed Jan 26 12:46:45 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 10:46:45 -0700 Subject: inherit without calling parent class constructor? In-Reply-To: References: Message-ID: Christian Dieterich wrote: > Hi, > > I need to create many instances of a class D that inherits from a class > B. Since the constructor of B is expensive I'd like to execute it only > if it's really unavoidable. Below is an example and two workarounds, but > I feel they are not really good solutions. Does somebody have any ideas > how to inherit the data attributes and the methods of a class without > calling it's constructor over and over again? > > Thank, > > Christian > > Here's the "proper" example: > > class B: > def __init__(self, length): > size = self.method(length) > self.size = size > def __str__(self): > return 'object size = ' + str(self.size) > def method(self, length): > print 'some expensive calculation' > return length > > class D(B): > def __init__(self, length): > B.__init__(self, length) > self.value = 1 > > if __name__ == "__main__": > obj = D(7) > obj = D(7) I'm confused as to how you can tell when it's avoidable... Do you mean you don't want to call 'method' if you don't have to? Could you make size a property, e.g. class B(object): def __init__(self, length): self._length = length def _get_size(self): print 'some expensive calculation' return self._length size = property(fget=_get_size) class D(B): def __init__(self, length): super(B, self).__init__(length) self.value = 1 if __name__ == "__main__": obj = D(7) obj = D(7) Then 'size' won't be calculated until you actually use it. If 'size' is only to be calculated once, you might also look at Scott David Daniels's lazy property recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/363602 Steve From ug at algonet.se Tue Jan 25 03:26:50 2005 From: ug at algonet.se (=?ISO-8859-1?Q?Ulf_G=F6ransson?=) Date: Tue, 25 Jan 2005 09:26:50 +0100 Subject: Open Folder in Desktop In-Reply-To: <1106635751.661619.253930@c13g2000cwb.googlegroups.com> References: <1106635751.661619.253930@c13g2000cwb.googlegroups.com> Message-ID: Kamilche wrote: > Is there a command you can execute in Python that will open a window on > the desktop, such as 'My Documents'? Kind of like 'system', but for > folder names, not just programs. I'm running on Windows 2000. Maybe this is good enough? os.system("explorer " + folder_path) /ug From strombrg at dcs.nac.uci.edu Mon Jan 3 16:23:23 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Mon, 03 Jan 2005 13:23:23 -0800 Subject: Zope newsgroups? Need help with POSKeyError References: <41d5e51d$0$4095$afc38c87@news.optusnet.com.au> Message-ID: On Sat, 01 Jan 2005 10:47:41 +1100, richard wrote: > Bob Horvath wrote: >> I have a Zope/Plone combination that I have been having POSKeyErrors >> with for a while now. Are there any newsgroups that deal with Zope? > > No, but there is a mailing list - see zope.org > > Also, try google searching for POSKeyError. > > > Richard You could also see if the zeop mailing list is gatewayed to nntp on gmane. They have a huge number of FLOSS development mailing lists on that nntp server. Google should be able to find it easily. From fredrik at pythonware.com Sun Jan 23 13:39:52 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 19:39:52 +0100 Subject: on the way to find pi! References: <20050123182847.74790.qmail@web61009.mail.yahoo.com> Message-ID: Ali Polatel wrote: > I found a code which calculates pi with an interesting algorithm the programme code is below: > [code snipped] > This code gives the number in an unusual format like "3.1415'None'" it has > a number part and a string part. are you sure? $ python pi.py How many digits? :5 3.1415 $ python pi.py How many digits? :10 3.141592653 $ python pi.py How many digits? :20 3.1415926535897932384 > Any idea how to seperate this 'None' from the number and make it a real > normal number on which I can do operations like +1 -1 or like that :) what's the point of that? the math module already contains pi with as many decimals as you can put in a Python float: $ python >>> pi = 3.1415926535897932384 >>> pi 3.1415926535897931 >>> import math >>> math.pi 3.1415926535897931 >>> pi = math.pi True From fredrik at pythonware.com Tue Jan 25 20:10:44 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Jan 2005 02:10:44 +0100 Subject: string.atoi and string.atol broken? References: Message-ID: Mike Moum wrote: > s.atoi('4',3) should result in 11 > > s.atoi('13',4) should result in 31 > > s.atoi('12',4) should result in 30 > > s.atoi('8',4) is legitimate, but it generates an error. > > Is this a bug, or am I missing something obvious? the function's named "atoi", not "atoitoa". From brian.bird at securetrading.com Wed Jan 5 04:21:41 2005 From: brian.bird at securetrading.com (brian.bird at securetrading.com) Date: 5 Jan 2005 01:21:41 -0800 Subject: Keyword arguments - strange behaviour? References: <1103622331.247762.161750@f14g2000cwb.googlegroups.com> <1103637176.450940.243500@c13g2000cwb.googlegroups.com> <1103640442.940168.246130@c13g2000cwb.googlegroups.com> <1103801690.093414.72370@f14g2000cwb.googlegroups.com> <1gpal5s.crzm5p1oal62zN%aleaxit@yahoo.com> Message-ID: <1104916901.552008.195950@z14g2000cwz.googlegroups.com> Thanks. In case anyone else is looking, the recipe is at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303440 (which also shows how to make it work with python2.3 and below since they don't support decorators) Brian From foo.bar at freesurf.ch.invalid Sat Jan 1 14:39:50 2005 From: foo.bar at freesurf.ch.invalid (Thomas Rast) Date: Sat, 01 Jan 2005 20:39:50 +0100 Subject: Python equivalent of script(1) References: <1104607982.132310.181560@c13g2000cwb.googlegroups.com> Message-ID: <87d5wprla1.fsf@thomas.local> cepl at surfbest.net writes: > I would love to have a record of all what I've done, so I can edit > this record into final script. You can save the current input history with >>> import readline >>> readline.write_history_file("python.log") If you want to log your whole session, including output, try using the 'screen' utility. HTH - Thomas -- If you want to reply by mail, substitute my first and last name for 'foo' and 'bar', respectively, and remove '.invalid'. From ovazquez at gmail.SPAM.com Sun Jan 23 07:12:56 2005 From: ovazquez at gmail.SPAM.com (Orlando Vazquez) Date: Sun, 23 Jan 2005 12:12:56 GMT Subject: re Insanity In-Reply-To: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> References: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> Message-ID: Tim Daneliuk wrote: > For some reason, I am having the hardest time doing something that should > be obvious. (Note time of posting ;) > > Given an arbitrary string, I want to find each individual instance of > text in the form: "[PROMPT:optional text]" > > I tried this: > > y=re.compile(r'\[PROMPT:.*\]') > > Which works fine when the text is exactly "[PROMPT:whatever]" but > does not match on: > > "something [PROMPT:foo] something [PROMPT:bar] something ..." > > The overall goal is to identify the beginning and end of each [PROMPT...] > string in the line. > > Ideas anyone? If I understand correctly, this is what you are trying to achieve: >>> import re >>> temp = "something [PROMPT:foo] something [PROMPT:bar] something ..." >>> prompt_re = re.compile(r"\[PROMPT:.*?\]") >>> prompt_re.findall(temp) ['[PROMPT:foo]', '[PROMPT:bar]'] >>> HTH, -- Orlando From pedro.werneck at terra.com.br Sun Jan 30 17:49:01 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Sun, 30 Jan 2005 20:49:01 -0200 Subject: is this sort method the same as the one in python 2.4 In-Reply-To: References: Message-ID: <20050130204901.69a7ef73.pedro.werneck@terra.com.br> What about this ? # if sys.version_info >= (2,4): def sorted(iterable, *args, **kwds): seq = list(iterable) seq.sort(*args, **kwds) return seq # It worked against the TestSorted in lib/test/test_builtins.py On Sun, 30 Jan 2005 08:30:17 +0100 "Fredrik Lundh" wrote: > Raymond Hettinger wrote: > > >> I'm trying to emulate the sorted() method introduced in python 2.4. The > >> only difference is that it takes a sequence as one of its arguments > >> rather than being a method of the sequence class. Does my method do the > >> same as the sorted()? > > > > Almost. This is closer to the mark: > > > > def sorted(iterable, cmp=None, key=None, reverse=False): > > "return a sorted copy of its input" > > if sys.version_info >= (2,4): > > return sorted(iterable, cmp, key, reverse) > > with your code > > print sorted([1, 2, 3]) > > gives me a traceback that ends with > > File "test.py", line 6, in sorted > return sorted(iterable, cmp, key, reverse) > File "test.py", line 6, in sorted > return sorted(iterable, cmp, key, reverse) > File "test.py", line 6, in sorted > return sorted(iterable, cmp, key, reverse) > File "test.py", line 5, in sorted > if sys.version_info >= (2,4): > RuntimeError: maximum recursion depth exceeded in cmp > > the recursion isn't really that hard to explain, but the runtime error doesn't > really seem right... > > ::: > > to fix the recursion, move the if-statement so you only define the function > if needed: > > if sys.version_info < (2,4): > def sorted(...): > .... > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From jacek.generowicz at cern.ch Tue Jan 4 10:02:16 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 04 Jan 2005 16:02:16 +0100 Subject: Optional Static Typing References: <1103795375.843649.286620@c13g2000cwb.googlegroups.com> <1103895045.561695.293330@c13g2000cwb.googlegroups.com> <41cc686a$1@nntp0.pdx.net> <1103992000.641659.48940@z14g2000cwz.googlegroups.com> <10t0fkn2kng8803@corp.supernews.com> <1gpgws6.11jticrb4ah8mN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > I've always liked the (theoretical) idea that assertions (including of > course contracts) could be used as axioms used to optimize generated > code, rather than (necessarily) as a runtime burden. E.g. (and I don't > know of any implementation of this concept, mind you), inferring (e.g. > from such assertions) that x>=0, and that y<0, the compiler could simply > cut away a branch of dead code guarded by "if x warning, in this case;-)... A few months ago, a troll challenged the denizens of comp.lang.lisp to write a Lisp implementation of some some code which he posted in C++, which would be competitive in terms of speed with his C++ version. The c.l.lers duly obliged, and, IIRC, it so happened that the improvement that made the Lisp version overtake the C++ one was the declaration of some variable to be of type "floating point number in the range 0 to two Pi". Of course, in CL type declarations are not contracts, but promises to the compiler ... but it's still an examlpe of a situation where more specific type information allowed the compiler to produce more efficient code, in practice. From fredrik at pythonware.com Mon Jan 24 16:43:38 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 22:43:38 +0100 Subject: Looking for Form Feeds References: <41F5696D.9030100@novasyshealth.com> Message-ID: Greg Lindstrom wrote: > I have a file generated by an HP-9000 running Unix containing form feeds signified by ^M^L. I am > trying to scan for the linefeed to signal certain processing to be performed but can not get the > regex to "see" it. Suppose I read my input line into a variable named "input" > > The following does not seem to work... > input = input_file.readline() > if re.match('\f', input): print 'Found a formfeed!' > else: print 'No linefeed!' hint: >>> line = "\r\f" >>> re.match("\f", line) (nothing) >>> re.search("\f", line) <_sre.SRE_Match object at 0x00B380C8> >>> re.match("\r\f", line) <_sre.SRE_Match object at 0x00B38988> in this case, it's probably better to use the "in" operator: if "\f" in line: print "found a line feed" From chris.stromberger at gmail.com Thu Jan 27 13:06:39 2005 From: chris.stromberger at gmail.com (chris) Date: 27 Jan 2005 10:06:39 -0800 Subject: urllib and proxy References: Message-ID: <1106849199.450771.314960@f14g2000cwb.googlegroups.com> This was helpful. After reading this, I realized you can also just add this atop whatever script imports urllib. Just add after "import urllib": # Disable proxy use. urllib.getproxies = lambda x = None: {} -Chris http://www.fetidcascade.com/ From pedro.werneck at terra.com.br Thu Jan 27 18:55:06 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Thu, 27 Jan 2005 21:55:06 -0200 Subject: tkinter socket client ? In-Reply-To: References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> <1106311130.446259.30710@f14g2000cwb.googlegroups.com> <1106318469.311179.126140@c13g2000cwb.googlegroups.com> <1106319270.932204.180590@c13g2000cwb.googlegroups.com> <1106659122.977876.234250@z14g2000cwz.googlegroups.com> Message-ID: <20050127215506.18ba5a76.pedro.werneck@terra.com.br> On Tue, 25 Jan 2005 13:44:32 +0000 Martin Franklin wrote: > > thanks for this info - I had to abandon the createfilehandler() method > > as it is not supported in windows and the GUI "might" be used there at > > some time ... Take a look here: http://www.pythonbrasil.com.br/moin.cgi/MonitorandoSocketsComTkinter From JoshuaACohen at gmail.com Mon Jan 31 15:10:41 2005 From: JoshuaACohen at gmail.com (Josh) Date: 31 Jan 2005 12:10:41 -0800 Subject: Handling MySQL connection Message-ID: <1107202241.789216.224920@c13g2000cwb.googlegroups.com> Hi, First off, I am a newbie to Python and so far I must say that we're getting along pretty well. My schooling was is C/C++, but have been writing code in, dare I say it, VB, for the past 4 years. Here is the problem I have run across. I am using SPE w/WXGlade to setup the GUI, so it handled the initial formatting of my python code as two seperate classes, one for the APP and one for the Frame. I'll be the first to admit I haven't gotten a good grasp on how things should flow within a python program. Anyway, what I have done is created a few functions using the DEF statement to handle the action of the widgets. Part of the program is accessing a MySQL database. Once a button is pushed, part of it's function is to open the database, check to see if a value exists, and then close the connection. Running this locally on my PC, which is also where MySQL resides, returns results instantly. The flow is a) Open a connection to the database b) Execute a simple Select statement to verify the field c) Close the connection. All done within a single DEF This works fine and dandy on my Windows 2000 PC that is also acting as the MySQL server, but when I transfer the program to a Linux box running Fedora, there is a very noticable lag when this action takes place. So my thought is rather than connecting to the database, fetching the data, then closing out the connection every time, it may be a better idea to connect to the database upon starting the program, leaving the connection open, making the transactions as needed, and then closing the connection upon leaving the program. Doing this, however, has proved to be a little more difficult than I thought, and I'm sure it's just because of my lack of knowledge of Python. So I put the question out, how do I accomplish this? Do I need some sort of Global(such an evil word) object to work off of? In the Def __init__ I would like to open the connection eg: connection = MySQLdb.connect(host="localhost", user="root", passwd="blah", db="data") In a Sepeate Function I would like to make the transactions on it. eg: cursor = connection.cursor() cursor.execute( "SELECT * FROM tags WHERE tags.tag_no = %s" %temp_tag ) self.data = cursor.fetchall() cursor.close() Finally in another Function I would like to be able to close the connection eg: connection.close() All of these Def's would fall under the same Frame class. Am I going about this incorrectly? Thanks for your help and patience. Josh From aurora00 at gmail.com Fri Jan 7 16:35:46 2005 From: aurora00 at gmail.com (aurora) Date: Fri, 07 Jan 2005 13:35:46 -0800 Subject: "A Fundamental Turn Toward Concurrency in Software" Message-ID: Hello! Just gone though an article via Slashdot titled "The Free Lunch Is Over: A Fundamental Turn Toward Concurrency in Software" [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that the continous CPU performance gain we've seen is finally over. And that future gain would primary be in the area of software concurrency taking advantage hyperthreading and multicore architectures. Perhaps something the Python interpreter team can ponder. From ian at cottee.org Tue Jan 4 21:49:37 2005 From: ian at cottee.org (Ian J Cottee) Date: Wed, 05 Jan 2005 11:49:37 +0900 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com><7xmzvu1ycn.fsf@ruckus.brouhaha.com><7xd5wqd14y.fsf@ruckus.brouhaha.com><7xfz1lal5d.fsf@ruckus.brouhaha.com><7xekh423b6.fsf@ruckus.brouhaha.com> <_rTBd.66275$Jk5.46@lakeread01> Message-ID: <171sa2-t79.ln1@suse.zobbo.org> Peter Hansen wrote: > I know that I've started many one-man projects over the years, > and only slowly (I'm a little thick, you see) came to realize > that while it's incredibly easy to start something, seeing it > through to the end is rather more difficult. > > At this point, perhaps largely as a result of a new world-view > inspired by the agile movement, I rarely start anything... > and when I do, it's driven by a strong, recurring need, and I > only do just enough to meet that need, in the simplest way > I can find. (Often, that ends up not involving a computer.) So here we are, in our wisdom. Never starting anything grandiose for fear of failure :). Personally I'm trying to get back some of that old stupidity but I'm very thick :) Ian From apardon at forel.vub.ac.be Fri Jan 14 10:41:44 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Jan 2005 15:41:44 GMT Subject: (objects as) mutable dictionary keys References: Message-ID: Op 2005-01-14, Peter Maas schreef : > I have summarized the discussion about the usability of lists (and > and other mutable types) as dictionary keys and put it into the > Python wiki.URL: http://www.python.org/moin/DictionaryKeys. > > This summary might be used as a reference should the 'mutable > dictionary keys' issue come up again in c.l.py. > I had a look and I think you should correct the followingr: Dictionary lookup with mutable types like lists is a source of unpleasant surprises for the programmer and therefore impossible in Python. It is not impossible in Python. It may be discouraged but it is not impossible since I have already done so. -- Antoon Pardon From cdieterich at geosci.uchicago.edu Wed Jan 26 12:29:48 2005 From: cdieterich at geosci.uchicago.edu (Christian Dieterich) Date: Wed, 26 Jan 2005 11:29:48 -0600 Subject: inherit without calling parent class constructor? Message-ID: Hi, I need to create many instances of a class D that inherits from a class B. Since the constructor of B is expensive I'd like to execute it only if it's really unavoidable. Below is an example and two workarounds, but I feel they are not really good solutions. Does somebody have any ideas how to inherit the data attributes and the methods of a class without calling it's constructor over and over again? Thank, Christian Here's the "proper" example: class B: def __init__(self, length): size = self.method(length) self.size = size def __str__(self): return 'object size = ' + str(self.size) def method(self, length): print 'some expensive calculation' return length class D(B): def __init__(self, length): B.__init__(self, length) self.value = 1 if __name__ == "__main__": obj = D(7) obj = D(7) Here's a workaround: class B: def __init__(self, length): size = self.method(length) self.size = size def __str__(self): return 'object size = ' + str(self.size) def method(self, length): print 'some expensive calculation' return length class D(B): def __init__(self, object): for key, value in object.__dict__.iteritems(): setattr(self, key, value) self.value = 1 if __name__ == "__main__": tmp = B(7) obj = D(tmp) obj = D(tmp) Here's another workaround: Bsize = 0 class B: def __init__(self, length): size = self.method(length) self.size = size global Bsize Bsize = self.size def __str__(self): return 'object size = ' + str(self.size) def method(self, length): print 'some expensive calculation' return length class D(B): def __init__(self, length): self.size = Bsize self.value = 1 if __name__ == "__main__": B(7) obj = D(9) obj = D(9) From apardon at forel.vub.ac.be Mon Jan 24 06:31:29 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Jan 2005 11:31:29 GMT Subject: Wrapping functions in modules or packages. Message-ID: I'm writing some utilty functions for use with gtk. But in order to use them correctly I have to know whether they are called in the gtk-thread or an other. So my idea was to wrap the gtk.main function so that it would registrate the thread_id that called it. So I was thinking about doing something like the following. import gtk import thread _gtkmain = gtk.main def main(): global _gtkthread _gtk_thread = thread.get_ident() _gtkmain() gtk.main = main Is this acceptable? Are there better ways to do things like this? From annaraven at gmail.com Fri Jan 7 06:54:50 2005 From: annaraven at gmail.com (Anna) Date: 7 Jan 2005 03:54:50 -0800 Subject: Securing a future for anonymous functions in Python References: Message-ID: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> Okay, I tried to post this previously but ran into the new Google groups system which appears to have sent my original response into the ether... Oops. Trying again. Alan Gauld wrote: > On Thu, 30 Dec 2004 23:28:46 +1000, Nick Coghlan > wrote: > > > GvR has commented that he want to get rid of the lambda keyword for Python 3.0. > > Getting rid of lambda seems like a worthy goal, > > Can I ask what the objection to lambda is? > 1) Is it the syntax? > 2) Is it the limitation to a single expression? > 3) Is it the word itself? > > I can sympathise with 1 and 2 but the 3rd seems strange since a > lambda is a well defined name for an anonymous function used in > several programming languages and originating in lambda calculus > in math. Lambda therefore seems like a pefectly good name to > choose. > > So why not retain the name lambda but extend or change the syntax > to make it more capable rather than invent a wholly new syntax > for lambdas? > > Slightly confused, but since I only have time to read these > groups regularly when I'm at home I have probably missed the bulk > of the discussion over the years. > > Alan G. > Author of the Learn to Program website > http://www.freenetpages.co.uk/hp/alan.gauld Hi Alan: Having taken some calculus (derivatives, limits, some integrals) but never even heard of lambda calculus, to me, lambda means absolutely NOTHING. Less than nothing. Actually, in my encounters with others code in Python (including reading near 1000 recipes for the recent edition of the Cookbook), what I've discovered is that what lambda mostly means to me is: "I don't wanna write clear, elegant Python - I wanna write fancy, clever, obfuscated code, and lambda lets me do that!" I've seen maybe 1 case in 10 where lambda appears, to me, to allow clearer, cleaner code than defining a function. Most cases-it's an ugly, incomprehensible hack. So, if people really need anonymous functions in Python (and apparently, they do), then at least lets get a word that actually *means* something. Every other word in Python has an obvious meaning. lambda doesn't. So, I guess I don't like the word itself - any more than I like how it's (mostly) used. Anna Martelli Ravenscroft From fuzzyman at voidspace.org.uk Wed Jan 12 04:47:49 2005 From: fuzzyman at voidspace.org.uk (Fuzzyman) Date: Wed, 12 Jan 2005 09:47:49 +0000 Subject: PyCrypto 2.0, pysco 1.4 - Windows Binaries for 2.4 Message-ID: <41E4F245.5060709@voidspace.org.uk> The location of the prebuilt windows installer for PyCypto 2.0 (for python 2.4) has changed. Apologies for any confusion, this is because of a website reorganisation at Voidspace. The new location is : http://www.voidspace.org.uk/python/modules.shtml#pycrypto There is also a prebuilt windows installer for psyco 1.4 (for python 2.4). This is because there isn't yet a prebuilt binary available from sourceforge. http://www.voidspace.org.uk/python/modules.shtml#psyco Both built using the free, Microsoft, optimizing compiler. Following instructions from : http://www.vrplumber.com/programming/mstoolkit/index.html Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From this at is.invalid Tue Jan 18 08:23:24 2005 From: this at is.invalid (John Field) Date: 18 Jan 2005 13:23:24 GMT Subject: [wxpython] exclude files in a wx.FileDialog? Message-ID: <41ed0dcc$0$73526$abc4f4c3@news.wanadoo.nl> Hello, Is it possible to exclude certain files in a wx.FileDialog, so that the user won't see them and can't select them with the mouse in de File open window? I was thinking of somehow extending the class FileDialog(Dialog) in the wx module _windows.py to a subclass, but I'm not sure how to do that (if feasible). cheers From ram at forefront-tech.No.Lunch.meat.com Wed Jan 12 18:47:13 2005 From: ram at forefront-tech.No.Lunch.meat.com (Rick Morrison) Date: Wed, 12 Jan 2005 23:47:13 GMT Subject: dict.updated References: Message-ID: <5GiFd.8571$Vj3.3354@newssvr17.news.prodigy.com> I could live with creating a new dict, sure (although it seems wasteful). I realize that something like this probably doesn't stand a chance of ever making it into the std library for what might be called "philosophical" reasons. I just want it for me (my personal philosophy runs more to the pragmatic -- well at least for coding). I suppose the in-place version would be more along the lines of: >>> def updated(d, updates): ... d.update(updates) ... return d ... >>> [updated(d, {'c':3}) for d in [{'a':1, 'b':2}, {'x':10, 'y':'11'}]] [{'a': 1, 'c': 3, 'b': 2}, {'y': '11', 'x': 10, 'c': 3}] But I'd like to put the "updated" method on the "dict" object, which is what I can't seem to figure out. Yeah I know that's "bad", but to my mind so is polluting the global namespace with the "updated" function. -- Or maybe I'm just lazy and picked up too many bad habits from Javascript. Rick "Steven Bethard" wrote in message news:dvKdnWal2sVXAXjcRVn-2g at comcast.com... > Rick Morrison wrote: > > Would there be any way to add a method to all dict objects that operated > > like the .update() method, but also returned a reference to the updated > > dict? > > Are you looking for updated() to parallel sorted(), where sorted() > returns a *new* list? I doubt you'll be able to rally much support for > a method that changes an object and returns a reference to it -- check > the archives to see these kind of things getting rejected over and over. > > Could you do something like: > > py> import itertools > py> d1 = dict(a=1, b=2) > py> d2 = dict(c=3, d=4) > py> d3 = dict(itertools.chain(d1.iteritems(), d2.iteritems())) > py> d3 > {'a': 1, 'c': 3, 'b': 2, 'd': 4} > > Steve From rccharles at my-deja.com Fri Jan 28 13:50:57 2005 From: rccharles at my-deja.com (Robert) Date: Fri, 28 Jan 2005 13:50:57 -0500 Subject: installing tkiner Message-ID: I am trying to use tkinter on macos 10.2.6. I am not having any luck. I have tried this. python python2.4 after downloading downloaded TclTkAquaBI-8.4.6.1-Jaguar.dmg and installed python2.4 could not find tkiniter downloaded macpython 2.3.3 macphyton find tkinter but got an application exception. I was under the impression that macpython included tkinter, so I manually deleted TclTkAquaBI the best I could. macpython could not find tkinter. In the packages section of macpython, I saw... ('no', '_tkinter-2.3-binary', 'Enables Tkinter GUI building with Python.') Please advise. Robert From benn at cenix-bioscience.com Wed Jan 26 06:01:47 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Wed, 26 Jan 2005 12:01:47 +0100 Subject: python without OO In-Reply-To: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <41F7789B.7070702@cenix-bioscience.com> Davor wrote: >Is it possible to write purely procedural code in Python, or the OO >constructs in both language and supporting libraries have got so >embedded that it's impossible to avoid them? Also, is anyone aware of >any scripting language that could be considered as "Python minus OO >stuff"? (As you can see I'm completely new to Python and initially >believed it's a nice&simple scripting language before seeing all this >OO stuff that was added in over time) >Thanks, >Davor > > > Hello, Yes you can, that is a benefit and flaw of python in that you can mix up procedural and OO code, it allows for simple solutions - however it also allows for you to create all kinds of havoc. IMHO, there would have to be a very very small task to require procedural code. Especially if the code is gonna be open sourced (and presumably built upon) you will benefit from a proper design so that it can be developed and moved on in the future. One other thing, if your developers are proposing deep inheritance trees in _any_ language then they are designing incorrectly. In none of the languages I code in would I design a deep inheritance tree, the deep inheritance tree is a fault of the designer not the language (for example Java does not force you to design deep inheritance trees!) - 90% of the time. I say this because you do need to be aware of the 'mythical python wand' which will turn you from a bad programmer into a good programmer simply by typing 'class Klass(object):'. Rather than reading a GOF book, I'd pick up an introduction to OO programming book to take a refresher course - you thank yourself!! Language without OO at all - what about Logo - drive that little tortoise around!! Cheers, Neil From bearophileHUGS at lycos.com Sun Jan 16 10:55:10 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 16 Jan 2005 07:55:10 -0800 Subject: generator expressions: performance anomaly? References: <1105854381.117059.59940@c13g2000cwb.googlegroups.com> Message-ID: <1105890910.933744.143580@z14g2000cwz.googlegroups.com> Nick Coghlan: >There's a similar performance glitch associated with constructing a tuple from a generator expression (with vanilla 2.4, detouring via list is actually faster) You look right: .from time import clock .print "[x for x in l], list(x for x in l), aux = list(x for x in l); tuple(aux), tuple(x for x in l):" .for np in range(13, 21): . n = 1*2**np . print "n:", n, " s:", . l = xrange(n) . t1 = clock() . [x for x in l] . t2 = clock() . print round(t2-t1,3), . . t1 = clock() . list(x for x in l) . t2 = clock() . print round(t2-t1,3), . . t1 = clock() . aux = list(x for x in l) . tuple(aux) . t2 = clock() . print round(t2-t1,3), . . #l = tuple(l) useless . t1 = clock() . tuple(x for x in l) . t2 = clock() . print round(t2-t1,3) Output: [x for x in l], list(x for x in l), aux = list(x for x in l); tuple(aux), tuple(x for x in l): n: 8192 s: 0.01 0.007 0.01 0.013 n: 16384 s: 0.024 0.019 0.021 0.032 n: 32768 s: 0.054 0.042 0.049 0.113 n: 65536 s: 0.111 0.078 0.101 0.088 n: 131072 s: 0.196 0.155 0.183 0.177 n: 262144 s: 0.436 0.385 0.429 1.832 n: 524288 s: 0.921 0.744 0.877 8.271 n: 1048576 s: 1.86 1.546 1.866 33.154 The timings for tuple(x for x in l) seem to grow as len(n)**2. Bear hugs, Bearophile From peter at engcorp.com Thu Jan 13 16:49:59 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 16:49:59 -0500 Subject: News Reader In-Reply-To: References: Message-ID: Robert Kern wrote: > Robert Kern wrote: >> Daniel Bowett wrote: >>> Is anyone reading this list through thunderbird as news? If so - how >>> did you set it up? >> >> I subscribed to comp.lang.python under my USENET news server account. > > I guess I should add that that's all I did. There's nothing special to > set up. Having to add the news server by first selecting "File->New->Account" might qualify as important enough to mention too. ;-) -Peter From fuzzyman at gmail.com Mon Jan 17 04:24:45 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 17 Jan 2005 01:24:45 -0800 Subject: how to stop google from messing Python code In-Reply-To: References: <1105620098.878376.110250@z14g2000cwz.googlegroups.com> <1105704548.146263.229220@f14g2000cwb.googlegroups.com> Message-ID: <1105953885.661245.27570@c13g2000cwb.googlegroups.com> Fredrik Lundh wrote: > Fuzzyman wrote: > > > I guess that most people use google to post to newsgroups is that they > > don't have nntp access. Telling htem to use a newsreader is facetious > > and unhelpful. > > if you have internet access, you have NNTP access. gmane.org provides access > to more than 6,500 mailing lists via NNTP, including all relevant Python forums. > Not if you're behind a censoring proxy that blocks everything except http. This is a situation many people find themselves in. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml > From john at grulic.org.ar Thu Jan 13 19:06:27 2005 From: john at grulic.org.ar (John Lenton) Date: Thu, 13 Jan 2005 21:06:27 -0300 Subject: directory bug on linux; workaround? In-Reply-To: References: Message-ID: <20050114000627.GB3727@grulic.org.ar> On Thu, Jan 13, 2005 at 12:07:04PM -0800, Russell E. Owen wrote: > I stumbled across a really strange bug involving directories on linux. > > os.path.exists(path) can return 0 even after os.path.mkdir(path) > succeeds (well after; this isn't a timing issue). > > For the first file, the directory did not exist, so my code created the > directory (successfully) using os.path.mkdir(path). The next file > failed because os.path.exists(path) returned false, so my code tried to > create the directory again, which failed with "directory exists". > > It seems that the path was to a "fat" file partition and included a > directory name that was all uppercase. The directory was created, but > using lowercase. I'm not yet sure the version of python. > > The workaround for now is to not use fat file partitions. But I was > wondering if anyone had a better option? the bug is because os.path is assuming posix semantics, which fat doesn't have. Not using fat sounds like the best idea to me, but I'm probably strongly biased against that piece of crap. -- John Lenton (john at grulic.org.ar) -- Random fortune: A fox is a wolf who sends flowers. -- Ruth Weston -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From ncoghlan at iinet.net.au Thu Jan 6 07:11:22 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 06 Jan 2005 22:11:22 +1000 Subject: Python evolution: Unease In-Reply-To: <864d3709050106020568bd8b8e@mail.gmail.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> <1104982313.217034.308760@z14g2000cwz.googlegroups.com> <864d3709050106020568bd8b8e@mail.gmail.com> Message-ID: <41DD2AEA.2020301@iinet.net.au> Carlos Ribeiro wrote: > Couldn't a better document-writing interface be implemented? Such as: http://www.python.org/moin/Documentation Or AMK's annotatable docs: http://pydoc.amk.ca/frame.html Something like that? > The docs are great, but it took me some time to find them out after > searching inside Python docs. This is not a minor issue IMHO. Actually, this is a fair point - I work on isolated machines a lot (i.e. no net access), which means I can't get to any of these handy things. It would be nice if at least some of these things could be bundled with the CPython interpreter and linked to from the main documentation (rather than from the sidebar menu on the webpage). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From none.by.e-mail Wed Jan 5 23:49:21 2005 From: none.by.e-mail (Mike Thompson) Date: Thu, 06 Jan 2005 15:49:21 +1100 Subject: Python evolution: Unease In-Reply-To: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> References: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> Message-ID: <41dcc35a$0$3872$afc38c87@news.optusnet.com.au> Alex Martelli wrote: > Carlos Ribeiro wrote: > ... > >>>- IDE: Better than what? Than IDLE? Than Eclipse? Than SPE? Than Pythonwin? >> >>I would like to seee Eric3, with some polish & opensourced on Win >>(which means solving the Qt licensing problem). Perhaps someone could >>convince Trolltech to release a special Qt Win version just for it >>(Eric3). Eclipse is also an interesting approach. > > > I love eric3, but if you're an eclipse fan, look at enthought's > "envisage" IDE -- it seems to me that it has superb promise. > I've tried both the SciPy and Enthought WWW sites and I can't find much on "Envisage". At SciPy.org there is one set of powerpoint slides on it but nothing more. Is it available for download somewhere? -- Mike From nelson at monkey.org Sun Jan 23 16:35:33 2005 From: nelson at monkey.org (Nelson Minar) Date: Sun, 23 Jan 2005 21:35:33 GMT Subject: What is print? A function? References: Message-ID: Frans Englich writes: > The reason I thinks about this is I need to implement a debug print for my > program; very simple, a function/print statement that conditionally prints > its message whether a bool is true. Not overly complex. As several folks have said, print is a statement, and Python doesn't really let you add statements to the language. You said you wanted to build a simple debugging function, so maybe this doesn't fit the bill, but for bigger pieces of code Python has a nice logging library. It's something like log4j or java.util.logging. http://www.python.org/doc/2.4/lib/module-logging.html From aleaxit at yahoo.com Sat Jan 22 18:06:51 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 23 Jan 2005 00:06:51 +0100 Subject: debugging process References: Message-ID: <1gqtexi.wxk0qn1oh6obbN%aleaxit@yahoo.com> wrote: ... > I think that this must have something to do with python expecting > itself to by in a TTY? Can anyone give any idea of where I should be > going with this? http://pexpect.sourceforge.net/ Alex From tjreedy at udel.edu Mon Jan 3 14:56:34 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 3 Jan 2005 14:56:34 -0500 Subject: emulating an and operator in regular expressions References: <1104750397.26918.1.camel@rasputin.localnet> Message-ID: "Craig Ringer" wrote in message news:1104750397.26918.1.camel at rasputin.localnet... > On Mon, 2005-01-03 at 08:52, Ross La Haye wrote: >> How can an and operator be emulated in regular expressions in Python? Regular expressions are designed to define and detect repetition and alternatives. These are easily implemented with finite state machines. REs not meant for conjunction. 'And' can be done but, as I remember, only messily and slowly. The demonstration I once read was definitely theoretical, not practical. Python was designed for and logic (among everything else). If you want practical code, use it. if match1 and match2: do whatever. Terry J. Reedy From qhfgva at gmail.com Mon Jan 17 16:08:50 2005 From: qhfgva at gmail.com (Dustin Lee) Date: Mon, 17 Jan 2005 14:08:50 -0700 Subject: python execution path Message-ID: I'm wondering if there is a way to get python to show each line as it is executed, sort of like sh -x does for shell programs. Seems like this would be a nice debugging aid. dustin From fredrik at pythonware.com Sun Jan 23 10:29:38 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 16:29:38 +0100 Subject: ANN: cElementTree 0.9.8 (january 23, 2005) Message-ID: effbot.org proudly presents release 0.9.8 of the cElementTree library, a fast and very efficient implementation of the ElementTree API, for Python 2.1 and later. On typical documents, it's 15-20 times faster than the Python version of ElementTree, and uses 2-5 times less memory. Here are some benchmark figures, using a number of popular XML tool- kits to parse a 3405k document-style XML file from disk: library memory time ------------------------------------------------------------ amara 20300k 6.4s minidom (python 2.4) 53000k 1.4s ElementTree 1.2.4 14500k 1.1s cDomlette 20500k 0.54s pyRXPU 10850k 0.175s libxml2 16000k 0.098s cElementTree 0.9 4900k 0.047s ------------------------------------------------------------ readlines (read as utf-8) 8850k 0.093s readlines (read as ascii) 5050k 0.032s ------------------------------------------------------------ This release also includes a new "iterparse" mechanism, which can be used to process the tree as it is being built. While not quite as fast as a full parse, it's over 4 times faster than Python's standard SAX interface, and even a bit faster than sgmlop. The library is available as C source code, and as Windows installers for all recent Python versions. Get your copy here: http://effbot.org/downloads#celementtree The cElementTree module uses some support functions from the standard ElementTree library, and will not work properly without it. If you haven't installed it already, you can get it from: http://effbot.org/downloads#elementtree enjoy /F "effbot.org -- not knowing how Python is used since 1995" From elephantum at dezcom.mephi.ru Sun Jan 16 07:04:53 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 16 Jan 2005 15:04:53 +0300 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> <41e6dc9b.771173178@news.oz.net> Message-ID: <34v3j5F49hm3uU1@individual.net> Nick Coghlan wrote: > # Anonymous functions > use res: > def f(x): > d = {} > exec x in d > return d > in: > res = [f(i) for i in executable] as for me, I found construction "use :" unobvious and confusing. Also there is great possibility to forget some of variables names. I think that syntax where: is more obvious. (and we already have defined semantics for it) we have two problems, that we try to solve 1) create method to nest scopes 2) create method to reverse execution order for better readability "using:" solves both at once. but your "use ... in ..." syntax shows, that you want to be able to solve 1) independently i.e. create nested scope without reversing execution order. so, I can suggest one more keyword "do:", which will create nested scope, just as "def f(): ... ; f()" do (and that could be just syntaxic sugar for it. so "use ... in ..." would look the following way: do: res = [f(i) for i in executable] #some more equations here using: def f(x): d = {} exec x in d return d that seems good for me. of course if you want to return something from the nest scope you must show that variable is from parent scope. // while writing that I realized that it's too complex to be implemented in python in that way. consider it as some type of brainstorming. From sjmachin at lexicon.net Tue Jan 4 05:55:52 2005 From: sjmachin at lexicon.net (John Machin) Date: 4 Jan 2005 02:55:52 -0800 Subject: why does UserDict.DictMixin use keys instead of __iter__? In-Reply-To: References: Message-ID: <1104836152.639270.196200@z14g2000cwz.googlegroups.com> Steven Bethard wrote: > Sorry if this is a repost -- it didn't appear for me the first time. > > > So I was looking at the Language Reference's discussion about emulating > container types[1], and nowhere in it does it mention that .keys() is > part of the container protocol. I don't see any reference to a "container protocol". What I do see is (1) """It is also recommended that mappings provide the methods keys(), ...""" (2) """The UserDict module provides a DictMixin class to help create those methods from a base set of __getitem__(), __setitem__(), __delitem__(), and keys(). """ > Because of this, I would assume that to > use UserDict.DictMixin correctly, a class would only need to define > __getitem__, __setitem__, __delitem__ and __iter__. So I can't see why would you assume that, given that the docs say in effect "you supply get/set/del + keys as the building blocks, the DictMixin class will provide the remainder". This message is reinforced in the docs for UserDict itself. > So why does > UserDict.DictMixin require keys() to be defined? Because it was a reasonable, documented, design? In any case, isn't UserDict past history? Why are you mucking about with it? From steven.bethard at gmail.com Fri Jan 21 19:46:46 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 17:46:46 -0700 Subject: finding name of instances created In-Reply-To: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> Message-ID: Andr? wrote: > Given the statement > >>>a = public_class() > > I would like to generate > >>>my_dict['a'] = private_class() > > so that one could write > >>>a.apparently_simple_method() > > and that, behind the scene, I could translate that as > >>>my_dict['a'].not_so_simple_method() > > as well as do things like > >>>for name in my_dict: >>> do_stuff(name) Why can't you just make public_class a factory, alias the method in PrivateClass and access the names through locals()? py> class PrivateClass(object): ... def not_so_simple_method(self): ... print "not so simple" ... apparently_simple_method = not_so_simple_method ... py> def public_class(): ... return PrivateClass() ... py> a = public_class() py> a.apparently_simple_method() not so simple py> # add 'name' and 'value' to locals() before iteration starts py> name, value = None, None py> for name, value in locals().iteritems(): ... if isinstance(value, PrivateClass): ... print name, value ... a <__main__.PrivateClass object at 0x01146D50> Steve From kartic.krishnamurthy at gmail.com Wed Jan 26 11:26:29 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 26 Jan 2005 08:26:29 -0800 Subject: Help With Python In-Reply-To: References: Message-ID: <1106756789.257980.256610@z14g2000cwz.googlegroups.com> Py>>> print "Spam, " * 115 Spam, Spam, Spam, Spam, Spam, ................. Spam, Multiplies (repeats) the string 115 times. To eliminate the last ", " (that is, a comma followed by space), you can do it using the slice notation and say: Py>>> print ("Spam, " * 115) [:-2] Spam, Spam, Spam, Spam, Spam, ................., Spam The [:-2] means that you asking Python to print everything from the beginning to the last but two characters of the string. You can also write this as [0:-2] [or [0:length_of_spam - 2] where length_of_spam = len("Spam, " * 115)] Since you are starting off, please read and follow the tuturial that available with your Python installation or on the Python.org site at http://docs.python.org/tut/tut.html Thank you, --Kartic From fredrik at pythonware.com Sat Jan 22 13:08:15 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 19:08:15 +0100 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com><41EE24F7.7030303@jessikat.fsnet.co.uk><7x1xchlpqv.fsf@ruckus.brouhaha.com><41efeb82$0$27807$9b622d9e@news.freenet.de><41f1a70b$0$25959$9b622d9e@news.freenet.de><7xbrbiqdhk.fsf@ruckus.brouhaha.com><7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > 2. "Would anyone except me have any use for this?" shows a lack of > understanding of how Python is used. Some users (call them > "application users" or AU's) use Python to run Python applications for > whatever purpose. Some other users (call them "developers") use > Python to develop applications that are intended to be run by AU's. "lack of understanding of how Python is used" wonderful. I'm going to make a poster of your post, and put it on my office wall. From http Sat Jan 22 07:50:30 2005 From: http (Paul Rubin) Date: 22 Jan 2005 04:50:30 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> Message-ID: <7xllalljah.fsf@ruckus.brouhaha.com> Nick Craig-Wood writes: > > No, unfortunately; the python-dev consensus was that encryption raised > > export control issues, and the existing rotor module is now on its way to > > being removed. > > I'm sure thats wrong now-a-days. Here are some examples of open > source software with strong crypto There's tons of such examples, but python-dev apparently reached consensus that the Python maintainers were less willing than the maintainers of those other packages to deal with those issues. You're right that this specifically says export control. I'm now thinking I saw some other messages, again from knowledgeable posters, saying that there was a bigger concern that including crypto in the distribution could make trouble for users in countries where having crypto at all was restricted. I'll see if I can find those. Martin, do you know more about this? I remember being disappointed about the decisions since I had done some work on a new block cipher API and I had wanted to submit an implementation to the distro. But when I heard there was no hope of including it, I stopped working on it. If there's an interest in it again, I can do some more with it. From rowen at cesmail.net Thu Jan 13 15:07:04 2005 From: rowen at cesmail.net (Russell E. Owen) Date: Thu, 13 Jan 2005 12:07:04 -0800 Subject: directory bug on linux; workaround? Message-ID: I stumbled across a really strange bug involving directories on linux. os.path.exists(path) can return 0 even after os.path.mkdir(path) succeeds (well after; this isn't a timing issue). For the first file, the directory did not exist, so my code created the directory (successfully) using os.path.mkdir(path). The next file failed because os.path.exists(path) returned false, so my code tried to create the directory again, which failed with "directory exists". It seems that the path was to a "fat" file partition and included a directory name that was all uppercase. The directory was created, but using lowercase. I'm not yet sure the version of python. The workaround for now is to not use fat file partitions. But I was wondering if anyone had a better option? -- Russell From sylvain.pasquet at gmail.com Wed Jan 26 09:16:50 2005 From: sylvain.pasquet at gmail.com (Tsubasa[Hokage]) Date: 26 Jan 2005 06:16:50 -0800 Subject: Freeze with wxpython on python 2.3 or python 2.4 on Win32 with Thread Message-ID: <549f320e.0501260616.7bc89f75@posting.google.com> first problem: With Idle environnement under Win32, all freeze after with bunch of code: #!/usr/bin/python import threading,time class T (threading.Thread) : def __init__(self,_a,_b) : threading.Thread.__init__(self) self.a = _a self.b = _b def run(self) : print "T(%d,%d)"%(self.a,self.b) time.sleep(3) print "T(%d,%d)=>%d"%(self.a,self.b,self.a+self.b) return self.a+self.b t = T(3,5) t.start() All freeze when sleep command are execute. Second part of this problem, I have a GUI in wxpython, when I create new thread i can't write new data in widget like a multibox when i am in a thread :( but i can retrieve data ( GetValue works but SetValue freeze ). Thanks From PPNTWIMBXFFC at spammotel.com Wed Jan 26 10:10:37 2005 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Wed, 26 Jan 2005 16:10:37 +0100 Subject: fast list lookup References: <3e96ebd7.0501260641.159e007f@posting.google.com> <8c7f10c60501260648c4a7c9a@mail.gmail.com> Message-ID: >> what is the fastest way to determine whether list l (with >> len(l)>30000) contains a certain element? Either a sorted list (in conjunction with the bisect-module) or a dictionary is your friend... Regards, Marco From as006d4848 at blueyonder.co.uk Mon Jan 24 00:15:07 2005 From: as006d4848 at blueyonder.co.uk (Philip Smith) Date: Mon, 24 Jan 2005 05:15:07 GMT Subject: Help with Threading Message-ID: Hi I am fairly new to Python threading and my needs are simple(!) I want to establish a number of threads each of which work on the same computationally intensive problem in different ways. I am using the thread module rather than the threading module. My problem is I can't see how (when one thread completes) to ensure that the other threads terminate immediately. Appreciate some simple advice Phil From helm.volker at gmx.de Tue Jan 4 15:10:33 2005 From: helm.volker at gmx.de (Volker Helm) Date: Tue, 04 Jan 2005 21:10:33 +0100 Subject: cxOracle for python 2.4 Message-ID: <340bheF44qhdtU1@individual.net> Hi there, does anybody knows where I can get the DB interface cx_Oracle for Python 2.4 with win32. On http://www.computronix.com/utilities.shtml exists only the version for Python 2.3. I would try to compile it myself, if I had a compiler and would know how to use it ;-) Thanks in advance, Volker From news at outbacklinux.com Wed Jan 12 06:25:43 2005 From: news at outbacklinux.com (Adrian Casey) Date: Wed, 12 Jan 2005 20:55:43 +0930 Subject: Command line and GUI tools : need a single threading solution References: <41e26e79@duster.adelaide.on.net> <34f9lfF4af717U1@individual.net> <41e38d8c@duster.adelaide.on.net> Message-ID: <41e50937@duster.adelaide.on.net> Adrian Casey wrote: > Diez B. Roggisch wrote: > >>> I'm thinking it may be possible to modify the command line tools to use >>> qt >>> threads instead of native python threads. Is this the way to go? Are >>> there other options? >> >> Why don't you use python threads in qt - I do so and so far it didn't >> make any troubles for me. And I would strongly advise against using >> qthreads with your commandline-tools, as these then would only run on >> machines where pyqt is installed - which opens a small part of >> "dependency hell" for your users. >> > I have a QThread which polls a queue object via queue.get(). The command > line tools spawn a number of threads each of which writes its output to > this queue using queue.put(). As soon as the gui gets something off the > queue, it creates a QCustomEvent and sets the data property with the data > read from the queue. My application has a customEvent() method which > reads the data item from the customEvent and processes it accordingly. > > The odd thing is, I have a non-threaded version of the command line tools > which work 100% with the gui. The multi-threaded version of the command > line tools all work OK at the console - just not with the gui. > > I will try your suggestion and replace my QCustomEvent mechanism with a > plain python queue. I tried replacing the QThread part with native python threads and, although it worked for a few minutes, I started to see XWindow errors and my application would then crash. On Phil Thompson's advice, I updated PyQt and sip. The problem appears to be fixed. Adrian. From aweinstein at vtr.net Tue Jan 4 18:40:50 2005 From: aweinstein at vtr.net (Alejandro Weinstein) Date: Tue, 04 Jan 2005 21:40:50 -0200 Subject: Reaching the real world In-Reply-To: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> Message-ID: <41DB0D62.559.2C107E@localhost> On 4 Jan 2005 at 6:55, Fuzzyman wrote: > What I'd like is an electronic interface that connects to several > relays and a python extension module to switch on and off the relays. > I've had a quick google and can't see anything too similar to what I > want. pyro (python robotics) seems to require expensive (relatively) > robotic equipment. Look at pyParallel (http://pyserial.sourceforge.net/pyparallel.html) to control the parallel port. From the parallel port you can control external devices. Please note that you will need to add a transistor to control a relay. There is also pySerial, (http://pyserial.sourceforge.net/) to control the serial port. If you know how to use a microcontroller (AVR, PIC, 8031, etc) you can communicate with it through the sereial port, and let the micro control the "real world". Regards, Alejandro. From timr at probo.com Tue Jan 25 03:18:44 2005 From: timr at probo.com (Tim Roberts) Date: Tue, 25 Jan 2005 00:18:44 -0800 Subject: is there better 32 clock() timing? References: Message-ID: Ray Schumacher wrote: > >I have a need for a time.clock() with >0.000016 second (16us) accuracy. >The sleep() (on Python 2.3, Win32, at least) has a .001s limit. > >Are they lower/better on other's platforms? You need to be careful about describing what you're seeing here. It is not that time.clock() is inaccurate. The problem is that the "time.clock()" statement takes several hundred microseconds to execute. >I had also considered forking a thread that would spin a loop checking >time.clock() and firing the TTL pulse after the appropriate interval, >but the real, ultimate resolution of time.clock() appears to be >~.00035s. If I increase process priority to real-time, it is ~.00028s >The alternative appears to be more C code... Are you seriously considering writing a real-time application in Python on Windows? The ONLY way to get small-integer microsecond responses in Windows is to write a kernel driver, and even then there are no guarantees. Windows is NOT a real-time system. If you have an environment where an unexpected delay of a millisecond or more is going to cause damage, then you need to redesign your application. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From rowen at cesmail.net Tue Jan 25 13:29:16 2005 From: rowen at cesmail.net (Russell E. Owen) Date: Tue, 25 Jan 2005 10:29:16 -0800 Subject: tkinter socket client ? References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> <1106311130.446259.30710@f14g2000cwb.googlegroups.com> <1106318469.311179.126140@c13g2000cwb.googlegroups.com> <1106319270.932204.180590@c13g2000cwb.googlegroups.com> <1106659122.977876.234250@z14g2000cwz.googlegroups.com> Message-ID: In article <1106659122.977876.234250 at z14g2000cwz.googlegroups.com>, "Tonino" wrote: >thanks for this info - I had to abandon the createfilehandler() method >as it is not supported in windows and the GUI "might" be used there at >some time ... > >So - I went the threading route - works well - for now - so I will >stick to it ... > >BUT - the next question: >In the Text() widget - why - when the text scrolls off the screen - >does the window not follow it ? > >I have added a scrollbar to it : > >self.center_frame = Frame(self.top_frame, background="tan", >relief=RIDGE) > >self.text=Text(self.center_frame,background='white') >scroll=Scrollbar(self.center_frame) >self.text.configure(yscrollcommand=scroll.set) > >self.text.pack(side=LEFT, fill=BOTH, expand=YES) >scroll.pack(side=RIGHT,fill=Y) >self.center_frame.pack(side=RIGHT, expand=YES, fill=BOTH) > > >but the window does not scroll to follow the text ? >Any ideas ? That's just how it works. But when you append text you can easily tell the text widget to display it, e.g. using "see". Here is the code I use (from RO.Wdg.LogWdg.py), which has these useful features: - auto-scrolls only if the user is already scrolled to the of text (so if a user is staring at some older data, it won't be jerked out from under them) - deletes excess text. def addOutput(self, astr, category=None): """Add a line of data to the log. Inputs: - astr: the string to append. If you want a newline, specify the \n yourself. - category: name of category or None if no category """ # set auto-scroll flag true if scrollbar is at end # there are two cases that indicate auto-scrolling is wanted: # scrollPos[1] = 1.0: scrolled to end # scrollPos[1] = scrollPos[0]: window has not yet been painted scrollPos = self.yscroll.get() doAutoScroll = scrollPos[1] == 1.0 or scrollPos[0] == scrollPos[1] if category: self.text.insert("end", astr, (category,)) else: self.text.insert("end", astr) extraLines = int(float(self.text.index("end")) - self.maxLineIndex) if extraLines > 0: self.text.delete("1.0", str(extraLines) + ".0") if doAutoScroll: self.text.see("end") -- Russell From jceasar at example.org Sat Jan 29 15:53:23 2005 From: jceasar at example.org (Jceasar) Date: Sat, 29 Jan 2005 14:53:23 -0600 Subject: Registration is accepted Message-ID: An HTML attachment was scrubbed... URL: -------------- next part -------------- The file Jol03.cpl attached to this message posed a potential virus risk to the network and has been removed. If you need to receive a .zip file from an external source, you may request an exception by emailing opssec at qwest.com. Thank you, Risk Mgmt-Info Sec From ptmcg at austin.rr._bogus_.com Fri Jan 21 17:22:03 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 21 Jan 2005 22:22:03 GMT Subject: why am I getting a segmentation fault? References: <1106330476.419418.46920@f14g2000cwb.googlegroups.com> Message-ID: "Jay donnell" wrote in message news:1106330476.419418.46920 at f14g2000cwb.googlegroups.com... > I have a short multi-threaded script that checks web images to make > sure they are still there. I get a segmentation fault everytime I run > it and I can't figure out why. Writing threaded scripts is new to me so > I may be doing something wrong that should be obvious :( > Here is a code excerpt from your link (the main routine, omits the class definition for ImageChecker, which extends threading.Thread): db = MySQLdb.connect(host="localhost", user="xxx", passwd="xxx", db="xxx") cursor = db.cursor() query = "select * from item order by rand() limit 0, 100" #query = "select * from item" cursor.execute(query) result = cursor.fetchall() maxThreads = 5 for r in result: while(threading.activeCount() > maxThreads): pass flag='good' #pass #print str(r[0]) + ', ' + str(r[7]) tmp = r[7].split('/') filename = tmp[-1] #print 'filename ' + filename filename = '/tmp/'+filename threadList = [] #r[7] is the url of the image #r[0] is the id for the row imageChecker = ImageChecker(r[7], filename, r[0]) imageChecker.start() threadList.append(imageChecker) ---------------------------------------------- 1. What happens after you fall out of the loop "for r in result"? Shouldn't you wait for the remaining threads to finish? Perhaps you need another busy-loop to wait for the threads to finish, something like while threading.activeCount() > 0: pass 2. Is this the best way to busy-wait? What about some kind of thread.join()? At least throw a sleep call in there or something, or this loop will churn and churn, diverting CPU from your threads that are actually trying to do some real work. 3. I find it easier to work with named variables than numeric subscripts. At the top of your for loop, try something like: id,height,width,numBytes,whatever,slkdjf1,slkdjf2,url = r This way you have much more meaningful names than r[0] and r[7], which you later have to comment to explain whats going on! 4. filename=r[7].split('/')[-1] is not terribly portable. See if there is a standard module for parsing filespecs (I'll bet there is). -- Paul From cdieterich at geosci.uchicago.edu Thu Jan 27 18:50:47 2005 From: cdieterich at geosci.uchicago.edu (Christian Dieterich) Date: Thu, 27 Jan 2005 17:50:47 -0600 Subject: inherit without calling parent class constructor? In-Reply-To: <10vii1r91ovdv91@corp.supernews.com> Message-ID: <44845B34-70BE-11D9-B56C-000A9582377C@geosci.uchicago.edu> On D?ardaoin, Ean 27, 2005, at 14:05 America/Chicago, Jeff Shannon wrote: > True, in the sense that B is instantiated as soon as a message is sent > to D that requires B's assistance to answer. If the "decision" is a > case of "only calculate this if we actually want to use it", then this > lazy-container approach works well. If the decision requires Yes, I see this advantage of a lazy container. Seems perfect to do something on request. See also below. > the descriptor approach does. In either case, the calculation happens > as soon as someone requests D.size ... Agreed. The calculation happens as soon as someone requests D.size. So far so good. Well, maybe I'm just not into it deep enough. As far as I can tell, In your class D the calculation happens for every instantiation of D, right? For my specific case, I'd like a construct that calculates D.size exactly once and uses the result for all subsequent instantiations. > If it will work for numerous D instances to share a single B instance > (as one of your workarounds suggests), then you can give D's > __init__() a B parameter that defaults to None. This sounds as if B needs to instantiated only once. In your example self._B is None for every new instantiation of D and then __getattr__() makes a new instances of self.B. > (However, from your other descriptions of your problem, it does sound > like a property / descriptor is a better conceptual fit than a > contained class is. I mostly wanted to point out that there are other > ways to use OO than inheritance...) I appreciate your input anyway. Thinking of how I could use containers it became clear, that I'm going to use them for something else, where I want something to be calculated upon request only. Christian From skip at pobox.com Wed Jan 12 06:37:17 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 12 Jan 2005 05:37:17 -0600 Subject: "Architecture of Python" was removed ? In-Reply-To: References: <004801c4f7cb$f62d1d30$1d02a8c0@cr> Message-ID: <16869.3053.896410.298943@montanaro.dyndns.org> Someone> Does anyone here have a copy of that document? Or who can tell Someone> me what is the email address of Jim Jackson or Kar-Han Tan. Nick> http://web.archive.org/web/20031222201953/http://wiki.cs.uiuc.edu/cs427/PYTHON Gerrit> This is again a nice document, and an example of a document that Gerrit> presumably has been removed because of maintenance Gerrit> reasons. Shouldn't we have a collection (archive) of these Gerrit> documents at python.org? Yes, perhaps. Note that it doesn't appear that the Wayback Machine contains the meat of the essay, just the front page. It came from a wiki. Perhaps the sysadmin folks at UIUC can dredge the content up from backup, though I suspect they'd be unlikely to do that. Ah, wait... Google to the rescue yet again. Try Googling for python cs427 site:uiuc.edu then pull the pages of interest out of Google's cache. Jim Jackson's UIUC email address is/was jwjackso at students.uiuc.edu. Jim, if you're out there, is it okay to reconstruct your old C427 assignment somewhere else? -- Skip Montanaro skip at mojam.com http://www.mojam.com/ From mcfletch at rogers.com Sun Jan 23 17:40:43 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 23 Jan 2005 17:40:43 -0500 Subject: Weakref.ref callbacks and eliminating __del__ methods Message-ID: <41F427EB.3000200@rogers.com> I'm looking at rewriting parts of Twisted and TwistedSNMP to eliminate __del__ methods (and the memory leaks they create). Looking at the docs for 2.3's weakref.ref, there's no mention of whether the callbacks are held with a strong reference. My experiments suggest they are not... i.e. I'm trying to use this pattern: class Closer( object ): """Close the OIDStore (without a __del__)""" def __init__( self, btree ): """Initialise the closer object""" self.btree = btree def __call__( self, oldObject=None ): """Regular call via self.close or weakref deref""" if self.btree: self.btree.close() self.btree = None class BSDOIDStore(oidstore.OIDStore): def __init__( self, filename, OIDs = None ): """Initialise the storage with appropriate OIDs""" self.btree = self.open( filename ) self.update( OIDs ) self.close = Closer( self.btree ) weakref.ref( self, self.close ) but the self.close reference in the instance is going away *before* the object is called. So, this approach doesn't *seem* to work (the Closer doesn't get called), so I can gather that the callbacks don't get incref'd (or they get decref'd during object deletion). I can work around it in this particular case by defining a __del__ on the Closer, but that just fixes this particular instance (and leaves just as many __del__'s hanging around). I'm wondering if there's a ready recipe that can *always* replace a __del__'s operation? I know I heard a rumour somewhere about Uncle Timmy wanting to eliminate __del__ in 2.5 or thereabouts, so I gather there must be *some* way of handling the problem generally. The thing is, weakref callbacks trigger *after* the object is deconstructed, while __del__ triggers before... must be something clever I'm missing. Throw an old doggie a bone? Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From bokr at oz.net Fri Jan 14 06:06:41 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 14 Jan 2005 11:06:41 GMT Subject: finding/replacing a long binary pattern in a .bin file References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> <41e6293f.725257715@news.oz.net> <10udjc3fmnhro9d@corp.supernews.com> Message-ID: <41e7a190.821594009@news.oz.net> On Thu, 13 Jan 2005 11:40:52 -0800, Jeff Shannon wrote: >Bengt Richter wrote: > >> BTW, I'm sure you could write a generator that would take a file name >> and oldbinstring and newbinstring as arguments, and read and yield nice >> os-file-system-friendly disk-sector-multiple chunks, so you could write >> >> fout = open('mynewbinfile', 'wb') >> for buf in updated_file_stream('myoldbinfile','rb', oldbinstring, newbinstring): >> fout.write(buf) >> fout.close() > >What happens when the bytes to be replaced are broken across a block >boundary? ISTM that neither half would be recognized.... > >I believe that this requires either reading the entire file into >memory, to scan all at once, or else conditionally matching an >arbitrary fragment of the end of a block against the beginning of the >oldbinstring... Given that the file in question is only a few tens of >kbytes, I'd think that doing it in one gulp is simpler. (For a large >file, chunking it might be necessary, though...) > Might as well post this, in case you're interested... warning, not very tested. You want to write a proper test? ;-) ----< sreplace.py >------------------------------------------------- def sreplace(sseq, old, new, retsize=4096): """ iterate through sseq input string chunk sequence treating it as a continuous stream, replacing each substring old with new, and generating a sequence of retsize returned strings, except that the last may be shorter depedning on available input. """ inbuf = '' endsseq = False out = [] start = 0 lenold = len(old) lennew = len(new) while not endsseq: start, endprev = old and inbuf.find(old, start) or -1, start if start<0: start = endprev # restore find start pos for chunk in sseq: inbuf+= chunk; break else: out.append(inbuf[start:]) endsseq = True else: out.append(inbuf[endprev:start]) start += lenold out.append(new) if endsseq or sum(map(len, out))>=retsize: s = ''.join(out) while len(s)>= retsize: yield s[:retsize] s = s[retsize:] if endsseq: if s: yield s else: out = [s] if __name__ == '__main__': import sys args = sys.argv[:] usage = """ Test usage: [python] sreplace.py old new retsize [rest of args is string chunks for test] where old is old string to find in chunked stream and new is replacement and retsize is returned buffer size, except that last may be shorter""" if not args[1:]: raise SystemExit, usage try: args[3] = int(args[3]) args[0] = iter(sys.argv[4:]) print '%r\n-----------\n%s\n------------' %(sys.argv[1:], '\n'.join(sreplace(*args[:4]))) except Exception, e: print '%s: %s' %(e.__class__.__name__, e) raise SystemExit, usage -------------------------------------------------------------------- As mentioned, not tested very much beyond what you see: [ 2:43] C:\pywk\ut>py24 sreplace.py x _XX_ 20 This is x and abcxdef 012x345 zzxx zzz x ['x', '_XX_', '20', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] ----------- Thisis_XX_andabc_XX_ def012_XX_345zz_XX__ XX_zzz_XX_ ------------ [ 2:43] C:\pywk\ut>py24 sreplace.py x _XX_ 80 This is x and abcxdef 012x345 zzxx zzz x ['x', '_XX_', '80', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] ----------- Thisis_XX_andabc_XX_def012_XX_345zz_XX__XX_zzz_XX_ ------------ [ 2:43] C:\pywk\ut>py24 sreplace.py x _XX_ 4 This is x and abcxdef 012x345 zzxx zzz x ['x', '_XX_', '4', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] ----------- This is_X X_an dabc _XX_ def0 12_X X_34 5zz_ XX__ XX_z zz_X X_ ------------ [ 2:44] C:\pywk\ut>py24 sreplace.py def DEF 80 This is x and abcxdef 012x345 zzxx zzz x ['def', 'DEF', '80', 'This', 'is', 'x', 'and', 'abcxdef', '012x345', 'zzxx', 'zzz', 'x'] ----------- ThisisxandabcxDEF012x345zzxxzzzx ------------ If you wanted to change a binary file, you'd use it something like (although probably let the default buffer size be at 4096, not 20, which is pretty silly other than demoing. At least the input chunks are 512 ;-) >>> from sreplace import sreplace >>> fw = open('sreplace.py.txt','wb') >>> for buf in sreplace(iter(lambda f=open('sreplace.py','rb'):f.read(512), ''),'out','OUT',20): ... fw.write(buf) ... >>> fw.close() >>> ^Z [ 3:00] C:\pywk\ut>diff -u sreplace.py sreplace.py.txt --- sreplace.py Fri Jan 14 02:39:52 2005 +++ sreplace.py.txt Fri Jan 14 03:00:01 2005 @@ -7,7 +7,7 @@ """ inbuf = '' endsseq = False - out = [] + OUT = [] start = 0 lenold = len(old) lennew = len(new) @@ -17,21 +17,21 @@ start = endprev # restore find start pos for chunk in sseq: inbuf+= chunk; break else: - out.append(inbuf[start:]) + OUT.append(inbuf[start:]) endsseq = True else: - out.append(inbuf[endprev:start]) + OUT.append(inbuf[endprev:start]) start += lenold - out.append(new) - if endsseq or sum(map(len, out))>=retsize: - s = ''.join(out) + OUT.append(new) + if endsseq or sum(map(len, OUT))>=retsize: + s = ''.join(OUT) while len(s)>= retsize: yield s[:retsize] s = s[retsize:] if endsseq: if s: yield s else: - out = [s] + OUT = [s] if __name__ == '__main__': import sys Regards, Bengt Richter From mike at hobbshouse.org Thu Jan 13 12:21:30 2005 From: mike at hobbshouse.org (Michael Hobbs) Date: Thu, 13 Jan 2005 17:21:30 -0000 Subject: why are people still using classic classes? References: Message-ID: <10udbgqh32a2901@corp.supernews.com> Simon Wittber wrote: > I've noticed that a few ASPN cookbook recipes, which are recent > additions, use classic classes. > > I've also noticed classic classes are used in many places in the > standard library. > > I've been using new-style classes since Python 2.2, and am suprised > people are still using the classic classes. > > Is there a legitimate use for classic classes that I am not aware of? > Is there a project to specifically migrate standard library classes to > new-style classes? I'm guessing that the biggest contributor to the continued prevalence of classic classes is the official Python Tutorial: http://docs.python.org/tut/node11.html#SECTION0011300000000000000000 I came into Python around the 2.2 timeframe and used the tutorial as my starting point. I had often read people referring to "classic classes" but assumed that it was some old pre-2.2 thing that I need not worry about. For the longest time, I had assumed that I was using new style classes because I created them exactly as prescribed in the 2.2 tutorial (which still hasn't changed for 2.3 or 2.4). Now, classic classes are my habit and I see no compelling reason to put in the effort to change my habits. Regards, - Mike From chris.lasher at gmail.com Thu Jan 13 11:14:01 2005 From: chris.lasher at gmail.com (Chris Lasher) Date: 13 Jan 2005 08:14:01 -0800 Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <41e5ebee.709560864@news.oz.net> Message-ID: <1105632841.461042.68310@c13g2000cwb.googlegroups.com> >Others have probably solved your basic problem, or pointed >the way. I'm just curious. >Given that the information content is 2 bits per character >that is taking up 8 bits of storage, there must be a good reason >for storing and/or transmitting them this way? I.e., it it easy >to think up a count-prefixed compressed format packing 4:1 in >subsequent data bytes (except for the last byte which have >less than 4 2-bit codes). My guess for the inefficiency in storage size is because it is human-readable, and because most in-silico molecular biology is just a bunch of fancy string algorithms. This is my limited view of these things at least. >I'm wondering how the data is actually used once records are >retrieved. This one I can answer. For my purposes, I'm just organizing the sequences at hand, but there are all sorts of things one could actually do with sequences: alignments, BLAST searches, gene annotations, etc. From tchur at optushome.com.au Wed Jan 12 01:29:49 2005 From: tchur at optushome.com.au (Tim Churches) Date: Wed, 12 Jan 2005 17:29:49 +1100 Subject: Python.org, Website of Satan Message-ID: <200501120629.j0C6TnHI022666@mail28.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From floydophone at gmail.com Mon Jan 3 20:08:00 2005 From: floydophone at gmail.com (floydophone at gmail.com) Date: 3 Jan 2005 17:08:00 -0800 Subject: Continuations Based Web Framework - Seaside. In-Reply-To: <1gprtcx.7y2fb7b25id2N%dial#####$#$#NOSPAM####$$##$tone@gmail.com> References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <1gprtcx.7y2fb7b25id2N%dial#####$#$#NOSPAM####$$##$tone@gmail.com> Message-ID: <1104800880.259621.60100@f14g2000cwb.googlegroups.com> Hi... I'm Peter Hunt. I've implemented stuff like this for a variety of different frameworks. I authored nevow.wolf and the more recent CherryFlow (http://trac.cherrypy.org/cgi-bin/trac.cgi/wiki/CherryFlow). I came up with this idea after looking at Cocoon FlowScript examples. Python generators suit continuation-based web development very nicely. If you take a look at CherryFlow version 1, the core of it is just about 15 lines. I'm constantly updating CherryFlow. I'll keep you posted. Also, if anyone wants to assist me with Subway, my Ruby-on-Rails clone, let me know :) From sjmachin at lexicon.net Sun Jan 9 19:03:34 2005 From: sjmachin at lexicon.net (John Machin) Date: 9 Jan 2005 16:03:34 -0800 Subject: Speed revisited In-Reply-To: <36c3u0tpbg6f98ta6cm4fkj2kn0dkv624m@4ax.com> References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> <1105237556.402188.126980@c13g2000cwb.googlegroups.com> <1105303172.147395.63580@c13g2000cwb.googlegroups.com> <36c3u0tpbg6f98ta6cm4fkj2kn0dkv624m@4ax.com> Message-ID: <1105315414.432202.249470@c13g2000cwb.googlegroups.com> Andrea Griffini wrote: > On 9 Jan 2005 12:39:32 -0800, "John Machin" > wrote: > > >Tip 1: Once you have data in memory, don't move it, move a pointer or > >index over the parts you are inspecting. > > > >Tip 2: Develop an abhorrence of deleting data. > > I've to admit that I also found strange that deleting the > first element from a list is not O(1) in python. My wild > guess was that the extra addition and normalization required > to have insertion in amortized O(1) and deletion in O(1) at > both ends of a random access sequence was going to have > basically a negligible cost for normal access (given the > overhead that is already present in python). > > But I'm sure this idea is too obvious for not having been > proposed, and so there must reasons for refusing it > (may be the cost to pay for random access once measured was > found being far from negligible, or that the extra memory > overhead per list - one int for remembering where the live > data starts - was also going to be a problem). > My wild guess: Not a common use case. Double-ended queue is a special purpose structure. Note that the OP could have implemented the 3-tape update simulation efficiently by reading backwards i.e. del alist[-1] Suggested projects for you, in increasing order of difficulty: 1. Grab the source code (listobject.c) and report back on how you would implement your proposal. 2. Convince folk that your implementation is faster and more robust and has beter internal documentation than anything the timbot could ever write. 3. Write a PEP that didn't cause a flamewar. From fuzzyman at gmail.com Tue Jan 25 03:11:30 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Jan 2005 00:11:30 -0800 Subject: Help on project, anyone? In-Reply-To: References: <35ienhF4lu88lU1@individual.net> <1106561458.167373.303270@c13g2000cwb.googlegroups.com> Message-ID: <1106640690.817073.248670@c13g2000cwb.googlegroups.com> Miki Tebeka wrote: > Hello Fuzzyman, > > > 3) Simple Version Control program for single programmer. A very simple > > way of doing version control/releases for small projects with only a > > single programmer. [3] > Subversion (and CVS) are dead simple to install and use. I've heard *lots* of people say exactly the opposite. > IMO in the long run you'll find yourself implementing most of their > features anyway. > > > [3] I think lots of people would find this useful. A version control > > system for projects where CVS/Subversion is overkill. This would be > > based on DirWatcher/FSDM ( > > http://www.voidspace.org.uk/python/programs.shtml#dirwatcher ) - All > > the code for finding which files have changed is already there, and > > there is an existing Tkinter GUI for Dirwatcher. > Adding changes to version control should be done as an explicit action by > the developer. Anything else is on the road to disaster, you'll find > yourself spending too much time backing out of changes you didn't want in. Yeah, my idea is pretty flexible. You could snapshot a 'release state', and roll back changes on individual files in between releases. You basically maintain it on your file system in the normal way and keep an archive of releases/changes. I think this probably works well with the may most small projects are actually managed. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml > > Bye. > -- > ------------------------------------------------------------------------ > Miki Tebeka > http://tebeka.bizhat.com > The only difference between children and adults is the price of the toys From apardon at forel.vub.ac.be Mon Jan 24 08:35:31 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Jan 2005 13:35:31 GMT Subject: finding name of instances created References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> <1106397218.724722.172660@c13g2000cwb.googlegroups.com> Message-ID: Op 2005-01-24, Nick Coghlan schreef : > Steven Bethard wrote: >> That is, you can just keep track of all the names of a Robot in the >> Robot object. In the simple case, where there's only one name, you can >> display it as such. In the more complicated case, where there's some >> aliasing, you can display the multiple aliases. This means you don't >> have to teach about aliasing right off the bat, but if a student >> accidentally discovers it on their own, the machinery's there to explain >> it... > > Incidentally, this discussion made me realise the real reason why using a lambda > to create a named function is evil: It is not a named function, it is just a lamda that is assigned to a name. > > Py> def f(): pass > ... > Py> f.func_name > 'f' > Py> f = lambda: None > Py> f.func_name > '' > > I think I've heard that explanation before, but it never really clicked. I just don't see what is so evil about it. Why is it so trouble some that a function wouldn't have a name, while most objects don't have a name. Why is it a problem doing something like: f = lambda: None But isn't it a problem doing something like v = None. Why don't we demand something like Py> assign v: None Py> v.obj_name 'v' -- Antoon Pardon From ionel.mc at gmail.com Sat Jan 15 10:58:41 2005 From: ionel.mc at gmail.com (ionel) Date: Sat, 15 Jan 2005 17:58:41 +0200 Subject: where can i fins some good pywin32 tutorials? Message-ID: need somethin to get started with mfc on python -- ionel. From oglycans at yahoo.com Thu Jan 13 16:07:18 2005 From: oglycans at yahoo.com (oglycans at yahoo.com) Date: 13 Jan 2005 13:07:18 -0800 Subject: how to control the mouse pointer with python? Message-ID: <1105650438.311153.167410@f14g2000cwb.googlegroups.com> Hi. Anybody know a way to control the mouse pointer (move it around and click on things) using python? Thanks. From martin at v.loewis.de Mon Jan 31 18:14:30 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 01 Feb 2005 00:14:30 +0100 Subject: msvcp71.dll and Python 2.4 C++ extensions In-Reply-To: References: Message-ID: <41FEBBD6.4010402@v.loewis.de> Matthias Baas wrote: > are there any guidelines about what to do if a Windows extension for > Python 2.4 requires the C++ runtime (msvcp71.dll)? No; it should "just work fine". The standard guidelines apply, of course: never try to mix different versions of similar DLLs. > If I want to > distribute a binary installer of an extension that contains C++ code, > should I really include the msvcp71.dll in the package? If you cannot expect your users to have that file, you should distribute it. Make sure you have read and understood the Microsoft license concerning the file. > It doesn't > sound like a good idea to me if every package places another copy of > this dll somewhere in the Python directory. Why not? If your installer follows Windows logo compliance rules, it should check whether the DLL is already present; if it is, it should check whether the version installed is newer than the one it would install, and if so, should skip installation. > Python 2.4 does install the C runtime (msvcr71.dll) in the Windows > system32 directory, doesn't it? It depends. If this is an allusers installation, it does so. For a per-user installation, the user might not have sufficient privileges to install into system32, so the installer won't install it there. > (btw, shouldn't this be installed in > the Python directory instead?) No. If you install the DLL into the Python directory, Python will not work anymore because python24.dll (installed into system32) will not find this DLL. If you then also move python24.dll into the Python directory, COM components that require python24.dll will fail to run. > So would it be possible that future > Python releases would also install the C++ runtime? Why should it? Nothing in the Python distribution requires C++. > I think it's > better if the dll would only be installed once by Python instead of > several times by every extension that uses C++. Why is that better? The DLL versioning rules, and the shared DLL refcounting mechanisms will make sure that the installation works just fine. > Currently, I do not package the C++ runtime and leave it up to the > user to install the dll if it isn't already somewhere on his system. > But this really is not a satisfying solution... Then you should probably include the DLL, or rewrite your extension to not use C++. Regards, Martin From ncoghlan at iinet.net.au Tue Jan 11 09:18:24 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 12 Jan 2005 00:18:24 +1000 Subject: [Python-Dev] PEP 246, redux In-Reply-To: <6EA3D69F-63B7-11D9-ADA4-000A95EFAE9E@aleax.it> References: <5.1.1.6.0.20050110113559.02bc2350@mail.telecommunity.com> <5.1.1.6.0.20050110113559.02bc2350@mail.telecommunity.com> <5.1.1.6.0.20050110132407.0344a9d0@mail.telecommunity.com> <6EA3D69F-63B7-11D9-ADA4-000A95EFAE9E@aleax.it> Message-ID: <41E3E030.3000209@iinet.net.au> Alex Martelli wrote: > "I really wish the language had > private inheritance because I'm using Abstract as a base just for code > reuse" Funny you should say that. . . what about a __nonconformant__ entry that accepts a list of base classes that is used to indicate inheritance without a proper is-a relationship? So if the isinstance check succeeds and there is no '__nonconformant__' entry, then adapt() just returns the object. If, on the other hand, __nonconformant__ is supplied, then adapt() can check the list of base classes that remains after removing the entries in __nonconformant__ to see if the object would *still* be an instance a subtype, even after removing the noncomformant bases, and if it is, return it. Otherwise, continue on to the rest of the adaptation process. This should give a better idea what I mean: # The 'fast path' if isinstance(obj, protocol): if not hasattr(obj, "__nonconformant__"): return obj conformant_bases = set(obj.__bases__) - set(obj.__nonconformant__) for base in conformant_bases: if issubtype(base, protocol): return obj # Continue on with the other adaptation possibilities (including __conform__) Then you can get 'discreet' inheritance (you have the methods, but you don't brag about the fact) by writing: class Dubious(Abstract): __noncomformant__ = [Abstract] # etc rather than: class Dubious(Abstract): def __comform__(self, protocol): if issubtype(protocol, Abstract): raise LiskovViolation # etc Regards, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From stephen.thorne at gmail.com Thu Jan 13 01:47:05 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 16:47:05 +1000 Subject: newbie q In-Reply-To: <34mgq0F4dq4buU1@individual.net> References: <34mgq0F4dq4buU1@individual.net> Message-ID: <3e8ca5c8050112224720b5585c@mail.gmail.com> On Thu, 13 Jan 2005 15:55:10 +1000, Egor Bolonev wrote: > how to get rid of 'for' operator in the code? > > import os, os.path > > def _test(): > src = 'C:\\Documents and Settings\\????\\My Documents\\My Music\\' > > for i in [x for x in os.listdir(src) if os.path.isfile(os.path.join(src, > x)) and len(x.split('.')) > 1 and x.split('.')[-1].lower() == 'm3u']: > os.remove(os.path.join(src, i)) > > if __name__ == '__main__': > _test() import glob for x in glob.glob("*.m3u"): os.remove(x) Regards, Stephen Thorne From lkirsh at cs.ubc.ca Thu Jan 20 04:48:41 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Thu, 20 Jan 2005 01:48:41 -0800 Subject: why are these not the same? In-Reply-To: References: Message-ID: D'oh I should've caught that myself. Thanks. Fredrik Lundh wrote: > Lowell Kirsh wrote: > >>On a webpage (see link below) I read that the following 2 forms are not the same and that the >>second should be avoided. They look the same to me. What's the difference? > > >>def functionF(argString="abc", argList = None): >> if argList is None: argList = [] >> ... >> >>def functionF(argString="abc", argList=None): >> argList = argList or [] >> ... > > > "is None" tests for None, "argList or" tests for a false value. None is > false, but many non-None objects are also false. > > "should be avoided" sounds like overly zealous advice to me; use the > latter form if you understand it. > > > > > From mahs at telcopartners.com Sat Jan 22 14:38:49 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sat, 22 Jan 2005 11:38:49 -0800 Subject: default value in a list In-Reply-To: <1gqs9gb.1mmtpcit05ruwN%aleaxit@yahoo.com> References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> <1gqs9gb.1mmtpcit05ruwN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: [explanation and the following code:] > >>> a, b, c = it.islice( > ... it.chain( > ... line.split(':'), > ... it.repeat(some_default), > ... ), > ... 3) > ... > ... > >>> def pad_with_default(N, iterable, default=None): > ... it = iter(iterable) > ... for x in it: > ... if N<=0: break > ... yield x > ... N -= 1 > ... while N>0: > ... yield default > ... N -= 1 Why not put these together and put it in itertools, since the requirement seems to crop up every other week? >>> line = "A:B:C".split(":") ... >>> def ipad(N,iterable, default = None): ... return it.islice(it.chain(iterable, it.repeat(default)), N) ... >>> a,b,c,d = ipad(4,line) >>> a,b,c,d ('A', 'B', 'C', None) Michael From nick at craig-wood.com Wed Jan 19 05:30:02 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 19 Jan 2005 10:30:02 GMT Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> Message-ID: Robin Becker wrote: > Paul Rubin wrote: > > "Reed L. O'Brien" writes: > > > >>I see rotor was removed for 2.4 and the docs say use an AES module > >>provided separately... Is there a standard module that works alike or > >>an AES module that works alike but with better encryption? > > > > > > If you mean a module in the distribution, the answer is no, for > > political reasons. > > > .....I'm also missing the rotor module and regret that something useful > was warned about and now removed with no plugin replacement. > > I had understood that this was because rotor was insecure, but you > mention politics. Are other useful modules to suffer from politics? > > What exactly are/were the political reasons for rotor removal? Presumably he is talking about crypo-export rules. In the past strong cryptography has been treated as munitions, and as such exporting it (especially from the USA) could have got you into very serious trouble. However I believe those restrictions have been lifted (the cat having been let out of the bag somewhat ;-), and its easy to do this for open source encryption software. A wade through http://www.bxa.doc.gov/Encryption/enc.htm Might be interesting. A case in point: the linux 2.6 kernel is chock full of crypo and comes with implementations of AES, ARC4, Blowfish, Cast5+6, DES, Serpent, Twofish, TEA, etc. The linux kernel+source surely goes everywhere python does so I don't think adding strong crypto modules to python is a problem now-a-days. AES in the core python library would be very useful and it would discourage people from writing their own crypto routines (looks easy but isn't!) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From lescault91967 at aol.com Thu Jan 6 22:41:06 2005 From: lescault91967 at aol.com (MIke) Date: Thu, 6 Jan 2005 22:41:06 -0500 Subject: This Program Realy Works Message-ID: MAKE LOTS OF MONEY QUICKLY, GUARANTEED 100%, NO SCAM! Turn 6.00 into 42,000! This is true!!.... Read this carefully to find out how!!.... READING THIS WILL CHANGE YOUR LIFE! I found this on a bulletin board and decided to try it. A little while back, I was browsing through newsgroups, and came across an article similar to this that said you could make thousands of cash within weeks with only an initial investment of .00! So I thought, "Yeah right, this must be a scam", but like most of us, I was curious, so I kept reading. Before you get skeptical, just take a few minutes to finish reading. HERE'S HOW IT WORKS WITH THIS PLAN, YOU REALLY CAN MAKE TONS OF TOTALLY LEGAL, FAST AND EASY CASH MONEY!! IT WORKS!!! BUT YOU HAVE TO FOLLOW IT CAREFULLY FOR IT TO WORK CORRECTLY AND IN YOUR FAVOR!!!! WITH ALL THE MONEY YOU ARE GONNA MAKE, YOU WILL SOON GET EVERYTHING YOU'VE ALWAYS DREAMED OF!!!! ALL YOU DO IS... All you do is send $1.00 to each of the 6 names and address stated in the article. You then place your own name and address in the bottom of the list at #6, and post the article in at least 200 newsgroups. (There are thousands.) No catch, that was it . So after thinking it over, and talking to a few people first, I thought about trying it. I figured, what have I got to lose except 6 stamps and 6.00, right? Like most of us I was a little skeptical and a little worried about the legal aspects of it all. So I checked it out with the U.S. Post Office (1-800-725-2161) and they confirmed that it is indeed legal! AND THEN GUESS WHAT... Then I invested the measly 6.00. Well, GUESS WHAT!!... Within 7 days, I started getting money just kept coming in. In my first week, I made about 25. By the end of the second week I had made a total of over 1,000! In the third week I had over 10,000 and it's still growing. This is now my fourth week and I have made a total of just over 42000, and it's still coming in rapidly. It's certainly worth 6. and 6 stamps. By the way, I have spent more than that on the lottery in the last month!! Let me tell you how this works and most importantly, why it works.... also, make sure you print a copy of this article NOW, So you can get the information off of it, as you need it. SO LET'S GET STARTED AND SEE WHAT HAPPENS STEP 1: Get 6 separate pieces of paper and write the following on eash piece of paper, "PLEASE PUT MY NAME ON YOUR MAILING LIST." Also, be sure to include your name and address. Now, get 6 U.S. $1.00 bills and place ONE inside EACH of the 6 pieces of paper so the bill will not be seen through the envelope, to prevent thievery. Next, place one paper in each of the 6 envelopes and seal them. You should now have 6 sealed envelopes, each with a piece of paper stating the above phrase, your name and address email , and a $1.00 bill. What you are doing is creating a service by this. THIS IS ABSOLUTELY LEGAL! STEP 2 : Mail the 6 envelopes to the following addresses: #1 John Christensen 5446 Santa Barbara Sparks, NV 89436 #2 Randall Hines 22 Stature Dr. Newark DE 19713 #3 Mike Sharrer 921 West State St. Coopersburg PA 18036 #4 Travis Montgomery 2211 Elmers Lane Norfolk NE 68701 #5 James Adair the third 22 Over Rd. Feasterville PA 19053 #6 Michael Lescault 123 Rhode Island Ave. Pawtucket, RI. 02860 STEP 3: Now take the #1 name off the list that you see above, move the other names up (6 becomes 5, 5 becomes 4, etc.) and add YOUR Name as number 6 on the list. STEP 4: Change anything you need to, but try to keep this article as close to original as possible. If you do not live in the U.S. or there is a foreign address, you must put an international stamp on your envelopes. Now, post your amended article to at least 200 newsgroups. ( I think there are close to 24,000 groups in all.) All you need is 200, but remember, the more you post, the more money you make!! DIRECTIONS FOR POSTING TO NEWSGROUP BULLETINS STEP 1: You do not need to re-type this entire letter to do your own posting. Simply put you cursor at the beginning of this letter and drag your cursor to the bottom of this letter. Then select 'copy' from the edit menu. This will copy the entire letter into the computer's temporary memory. STEP 2: Open a blank 'notepad' or word processor file and place your cursor at the top of the blank page. From the 'edit' menu select 'paste'. This will paste a copy of the letter into notepad so that you can add your name to the list. STEP 3: Save your new notepad file as a *.txt file. If you want to do your postings in different sittings, you'll always have this file to fo back to. STEP 4: Use your Internet provider and search engines to find various newsgroups (on-line forums, message boards, chat sites, discussions). STEP 5: Visit these message boards and post this article as a new message by higlighting the text of this letter and selecting paste from the edit menu. Fill in the Subject, and this will be the header that everyone sees as they scroll through the list of postings in a particular group. Then click the post message button. You're done with your first one! Congratulations... THAT'S IT! All you have to do is jump to different newsgroups and post away. After you get the hang of it, it will only take about 30 seconds for each posting!! ** REMEMBER, THE MORE NEWSGROUPS YOU POST IN, THE MORE MONEY YOU WILL MAKE!! ----BUT YOU HAVE TO POST A MINIMUM OF 200**----- That's it! You will begin receiving money from around the world within days! You may eventually want to rent a P.O. Box due to the large amount of mail you will receive. If you wish to stay anonymous, you can invent a name to use , as long as the postal service will deliver it. *JUST MAKE SURE ALL THE ADDRESSES ARE CORRECT* WITH 200 POSTINGS Out of 200 postings, say I receive only 5 replies ( a very low example). So then I made 5.00 with my name at #6 on the letter. Now, each of the 5 persons who just sent me $1.00 make the MINIMUM 200 postings, each with my name at #5, and only 5 persons repond to each of the original 5, that is another 25. Then those 25 each make 200 MINIMUM posts with my name at #4, and only 5 relies to each, and I will bring in an additional125! Now, those 125 persons turn around and post the MINIMUM 200 with my name at #3 and only receive 5 replies each, and I will make an additional 625! OK, now here is the fun part... Each of those 625 persons post a MINIMUM 200 letters with my name at #2, and they each only receive 5 replies, that just made me 3125!!! Those 3,125 persons will all deliver this message to 200 newsgroups with my name at #1, and if still 5 persons per 200 newsgroups react, I will receive an amazing 15625! With an original investment of only 6! AMAZING! DO IT OVER AND OVER When your name is no longer on the list, you just take the latest posting in the newsgroups, and send out another 6 to names on the list, putting your name at #6 again. Then start posting again. That's it! Do you realize that thousands of honest people just like you all over the world are joining the Internet and reading these articles everday? So can you afford 6 and see if it really works?? I think so.. People have said, "what if the plan is played out and no one sends you the money?" So what! What are the chances of that happening when there are tons of new honest users who are joining the Internet and newsgroups everyday? So, are you willing to give it a try? Estimates are about 20,000 to 50,000 new bulletin board users everyday, with thousands of those joining the Internet itself. ---Remember please play FAIRLY! This ensures a huge circle of wealth that grows with the Internet audience!!! Everyone benefits!!! Remember To Send The Six Envelopes To The Above Addresses, In Order To Create The Legal Service. At first I was scared to try this, but once I research it, I found that it is totally legal. When you send the six envelopes out, you create a service, a legal service. The Internet audience is expanding all the time. The audience is like an equity stock on the stock market, continuously going up. If you still think this is a fraud, take a few minutes to check it out, then.... you can start raking in the cash!! THIS CAN WORK IF WE ARE ALL IN IT TOGETHER!!!! From tundra at tundraware.com Wed Jan 12 04:28:28 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 12 Jan 2005 04:28:28 EST Subject: [ANN]: twander 3.160 Released And Available Message-ID: <41E4ED3E.2030900@tundraware.com> 'twander' Version 3.160 is now released and available for download at: http://www.tundraware.com/Software/twander The last public release was 3.146. Existing users are encouraged to upgrade to this release as it has a number of bug fixes and several nice new features including: - Mouse popups for all the menus (except Help). - Ability to force Unix-style paths under Windows when doing substitutions in command macros. (Very helpful for cygwin users.) - A smarter "adaptive" directory refresh mechanism. - A new "Shortcut" menu for fast navigation around the filesystem. Complete details of all fixes, changes, and new features can be found in the WHATSNEW.txt file included in the distribution. Users are strongly encouraged to join the twander-users mailing list as described in the documentation. What Is 'twander'? ------------------ 'twander' is a macro-programmable Filesystem Browser that runs on both Unix-like systems as well as Win32 systems. It embraces the best ideas of both similar GUI-driven programs (Konqueror, Windows Explorer) as well as text-based interfaces (Midnight Commander, List, Sweep). Or, If You Prefer The "Elevator Pitch" -------------------------------------- 'twander' is: - A better file browser for Unix and Win32. (Tested on FreeBSD, Linux, Win32.) - A way to make browsing the same on all the OSs you use. - A macro-programmable tool that lets *you* define the features. - A GUI navigation front-end for your shell. - A way to "can" workflows for your technically-challenged colleagues. - A way to free yourself from the shackles of the mouse. - A way to significantly speed up your day-to-day workflow. - A Python/Tkinter application - about 3100/1300 lines of code/comments - A RCT (Really Cool Tool) that will have you addicted in a day or two See the web page for more information, a screen shot, and the complete documentation. ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com From a at b.c Sun Jan 23 02:27:38 2005 From: a at b.c (Doug Holton) Date: Sun, 23 Jan 2005 01:27:38 -0600 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> Message-ID: Steve Holden wrote: > Yet again I will interject that XML was only ever intended to be wriiten > by programs. Hence its moronic stupidity and excellent uniformity. Neither was HTML, neither were URLs, neither were many things used the way they were intended. YAML, however, is specifically designed to be easier for people to write and to read, as is Python. From neil.benn at arcor.de Wed Jan 12 14:43:04 2005 From: neil.benn at arcor.de (Neil Benn) Date: Wed, 12 Jan 2005 20:43:04 +0100 Subject: Excel module for Python In-Reply-To: References: Message-ID: <41E57DC8.5030400@arcor.de> sam wrote: > Simon Brunning wrote: > >> On Wed, 12 Jan 2005 15:18:09 +0800, sam wrote: >> >>> I m wondering which Excel module is good to be used by Python? >> >> >> >> If you are on Windows, and you have Excel, then the Python for Windows >> extensions[1] are all you need to drive Excel via COM. O'Reilly's >> "Python Programming on Win32" covers COM scripting extensively - and >> by good fortune, driving Excel is the example they use, and the COM >> scripting chapter is on-line[2]. >> >> You'll also need to know the objects and methods that Excel exposes. >> These are documented on Microsoft's web site[3], or in the Excel VBA >> help, which is an optional part of they Office installation. >> > > No, I don't use MS windows. I need to generate Excel file by printing > data to it, just like Perl module Spreadsheet::WriteExcel. > > thanks > Sam Hello, If you can use jython then there is something that does this in java - it's called POI (search for POI HSSF Excel) in google. If you can't use jython and are desperate then you could set up a WebService/cgi/ and send the information back and forth. I spose you can do this with perl as well (don't know any perl so this bit is only a guess!). However the last time I looked (about a year ago) POI does have limitations with excel graphs. Cheers, Neil From pdemb at illx.org Mon Jan 3 09:38:50 2005 From: pdemb at illx.org (Peter Dembinski) Date: Mon, 03 Jan 2005 15:38:50 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> <7xsm5kfyse.fsf@ruckus.brouhaha.com> <41d7941f$1_3@127.0.0.1> <7x8y7cjo57.fsf@ruckus.brouhaha.com> <87zmzsax12.fsf@hector.domek> <87pt0na5zf.fsf@hector.domek> <87llbba55t.fsf@hector.domek> Message-ID: <87y8fah91h.fsf@hector.domek> Peter Hansen writes: > Roy Smith wrote: >> "Terry Reedy" wrote: >> >>> None has been reserved because there is no known good use for >>> overriding it. >> Should I infer from the above that there's a known bad use? > > Yes: making None equal to the integer 3. That's one of > six known bad uses.... it's possible there are more. ;-) Binding user variables to these names should raise exception (eg. AreYouInsaneException or WhatAreYouDoingException) :> From Marc.Poinot at onera.fr Fri Jan 21 11:09:16 2005 From: Marc.Poinot at onera.fr (Marc Poinot) Date: Fri, 21 Jan 2005 17:09:16 +0100 Subject: MPI and python+threads on IRIX Message-ID: <41F1292C.703EF3FE@onera.fr> Hi, I'm trying to add a dynamic module using MPI on a 2.3.4 Python with threads (posix). The interpreter blocks into the dlopen (dynload_shlib.c) if any reference to the IRIX libmpi.so (actually SGI/IRIX 6.5) appears. The docs say that the use of MPI+dlopen requires a call to MPI_Init_thread before the dlopen. I wonder how I can build a shared module using mpi if it blocks inside the dlopen ! It looks like the dlopen itself blocks at the time it reads the libmpi.so (is it possible). The MPI modules I've found are not ported on SGI (yes I know...) Any hints ? Help ? Piece of advice ? Idea ? Patch ? Coconut ? -MP- ----------------------------------------------------------------------- Marc POINOT Alias: marcvs Email: poinot at onera.fr ONERA -MFE/DSNA/ELSA Tel: 01.46.73.42.84 Info: elsa-info at onera.fr 29, Div. Leclerc Fax: 01.46.73.41.66 Site: 92322 Chatillon FRANCE Project: elsA Web: http://www.onera.fr From b at b.b Sat Jan 8 15:23:01 2005 From: b at b.b (Roose) Date: Sat, 08 Jan 2005 20:23:01 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> Message-ID: > Is an OS written in Lisp also ludicrous? Because it's been done. Can you point me to this? I'd like to see how "truly" Lisp it is. My first guess would be -- not very. And I'd like to install it on my PC. From ptmcg at austin.rr._bogus_.com Tue Jan 11 18:08:17 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 11 Jan 2005 23:08:17 GMT Subject: Time script help sought! References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> <1105477084.525279.312970@f14g2000cwb.googlegroups.com> <1105479292.689762.155510@f14g2000cwb.googlegroups.com> <1105480151.431987.327080@c13g2000cwb.googlegroups.com> Message-ID: "kpp9c" wrote in message news:1105480151.431987.327080 at c13g2000cwb.googlegroups.com... > still working on it and also fixing the input data. I think for > simplicity and consistency's sake i will have *all* time values input > and output as hh:mm:ss maybe that would be easier.... but i have a few > thousand find and replaceeseseses to do now (yes i am doing them by > hand) > > grr... this is hard! > Oh, I wasn't going to chime in on this thread, your data looked so well-formed that I wouldn't recommend pyparsing, but there is enough variability going on here, I thought I'd give it a try. Here's a pyparsing treatment of your problem. It will accommodate trailing comments or none, leading hours or none on timestamps, and missing end times, and normalizes all times back to the item start time. Most of your processing logic will end up going into the processVals() routine. I've put various examples of how to access the parsed tokens by field name, and some helper methods for converting to and from seconds and hh:mm:ss or mm:ss times. -- Paul from pyparsing import * data = """ Item_1 TAPE_1 1 00:23 8:23 Item_2 TAPE_1 2 8:23 9:41 Item_3 TAPE_1 3 9:41 10:41 Item_3 TAPE_1 4 10:47 11:19 Item_3 TAPE_1 5 11:21 11:55 Item_3 TAPE_1 6 11:58 12:10 Item_3 TAPE_1 7 12:15 12:45 Defect in analog tape sound. Item_3 TAPE_1 8 12:58 24:20 Defect in analog tape sound. Item_4 TAPE_1 9 24:33 Item_4 TAPE_1 10 25:48 Item_4 TAPE_1 11 29:48 Item_4 TAPE_1 12 31:46 Item_4 TAPE_1 13 34:17 Electronic sounds. Item_4 TAPE_1 14 35:21 Item_4 TAPE_1 15 36:06 Item_4 TAPE_1 16 37:01 01:37:38 """ def toSecs(tstr): fields = tstr.split(":") secs = int(fields[-1]) secs += int(fields[-2])*60 if len(fields)>2: secs += int(fields[-3])*60*60 return secs def secsToTime(secs): s = secs % 60 m = ((secs - s) / 60 ) % 60 h = (secs >= 3600 and (secs - s - m*60 ) / 3600 or 0) return "%02d:%02d:%02d" % (h,m,s) # globals for normalizing timestamps lastItem = "" itemStart = 0 # put logic here for processing various parse fields def processVals(s,l,t): global lastItem,itemStart print t.item,t.tape,t.recnum if not t.item == lastItem : lastItem = t.item itemStart = toSecs(t.start) startSecs = toSecs(t.start) print secsToTime(startSecs),"(%s)" % secsToTime(startSecs-itemStart) if t.end: endSecs = toSecs(t.end) print secsToTime(endSecs),"(%s)" % secsToTime(endSecs-itemStart) print endSecs-startSecs,"elapsed seconds" print secsToTime(endSecs-startSecs),"elapsed time" else: print "" print t.comment print # define structure of a line of data - sorry about the clunkiness of the optional trailing fields integer = Word(nums) timestr = Combine(integer + ":" + integer + Optional(":" + integer)) dataline = ( Combine("Item_"+integer).setResultsName("item") + Combine("TAPE_"+integer).setResultsName("tape") + integer.setResultsName("recnum") + timestr.setResultsName("start") + Optional(~LineEnd() + timestr, default="").setResultsName("end") + Optional(~LineEnd() + empty + restOfLine,default="-").setResultsName("comment") ) # set up parse handler that will process the actual fields dataline.setParseAction(processVals) # now parse the little buggers OneOrMore(dataline).parseString(data) will print out: Item_1 TAPE_1 1 00:00:23 (00:00:00) 00:08:23 (00:08:00) 480 elapsed seconds 00:08:00 elapsed time - Item_2 TAPE_1 2 00:08:23 (00:00:00) 00:09:41 (00:01:18) 78 elapsed seconds 00:01:18 elapsed time - Item_3 TAPE_1 3 00:09:41 (00:00:00) 00:10:41 (00:01:00) 60 elapsed seconds 00:01:00 elapsed time - Item_3 TAPE_1 4 00:10:47 (00:01:06) 00:11:19 (00:01:38) 32 elapsed seconds 00:00:32 elapsed time - Item_3 TAPE_1 5 00:11:21 (00:01:40) 00:11:55 (00:02:14) 34 elapsed seconds 00:00:34 elapsed time - ... From andre.roberge at gmail.com Fri Jan 21 19:13:19 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 21 Jan 2005 16:13:19 -0800 Subject: finding name of instances created Message-ID: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> Short version of what I am looking for: Given a class "public_class" which is instantiated a few times e.g. a = public_class() b = public_class() c = public_class() I would like to find out the name of the instances so that I could create a list of them e.g. ['a', 'b', 'c'] I've read the Python Cookbook, Python in a Nutshell, Programming Python, Learning Python, ... googled (probably missed something obvious), all to no avail. ===== Longer version: If I can do the above, I believe I could do the following thing which is what I am really after eventually. Given the statement >> a = public_class() I would like to generate >> my_dict['a'] = private_class() so that one could write >> a.apparently_simple_method() and that, behind the scene, I could translate that as >> my_dict['a'].not_so_simple_method() as well as do things like >> for name in my_dict: >> do_stuff(name) Any help, pointers, sketches or outline of solution would be greatly appreciated. Andr? From sridharinfinity at gmail.com Sun Jan 2 03:19:01 2005 From: sridharinfinity at gmail.com (Sridhar) Date: 2 Jan 2005 00:19:01 -0800 Subject: Frameworks for "Non-Content Oriented Web Apps" References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <1104653941.732418.15900@c13g2000cwb.googlegroups.com> You need Twisted - http://twistedmatrix.com --- : http://en.wikipedia.org/wiki/User:Sridharinfinity From claird at lairds.us Tue Jan 4 11:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 04 Jan 2005 16:08:03 GMT Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1104511661.928284.10200@z14g2000cwz.googlegroups.com> Message-ID: <31rqa2-c2b.ln1@lairds.us> In article , Alan Gauld wrote: >On Sat, 01 Jan 2005 16:08:07 GMT, claird at lairds.us (Cameron >Laird) wrote: > >> I argue that it's a false opposition to categorize projects in >> terms of use of single languages. Many projects are MUCH better >> off with a mix > >In practice I have *never* worked on an industrial scale project >that only used one language. The nearest I came was a small >protocol convertor that only used C, SQL and some shell and >awk - but that's still 4 languages! And the whole project was >only 40,000 lines of code in about 20 files. > >And most projects use many more, I'd guess around 5-8 on an >"average project" of around 300-500kloc. The biggest project I >worked on had about 3.5Mloc and used: > >Assembler (680x0 and Sparc), >C >C++ >Lisp(Flavors) >awk >Bourne shell >C shell - this was a mistake discovered too late to "fix" >PL/SQL >???? - A UI description language for a tool called TeleUse... >Pascal - No, I don't know why... >ASN.1 - with a commercial compiler > >We also had some IDL but since it was tool generated I'll ignore >it... > >We also had an experimental version running on a NeXt box so it >used Objective C for the UI instead of ???? and C++... > >A total of 13 languages... with 5 geographically dispersed teams >comprising a total of 200 developers (plus about 40 testers). >Interesting times...in the Chinese sense! . . . D. The TeleUSE language is "D". And I suspect your count is a lower bound. If you worked with TeleUSE, somebody probably was doing Motif configuration, which arguably is a(n impoverished configuration) language itself. From drinkmyjesus at aol.com Sat Jan 15 02:51:56 2005 From: drinkmyjesus at aol.com (drinkmyjesus at aol.com) Date: 14 Jan 2005 23:51:56 -0800 Subject: New computer Message-ID: <1105775516.246393.171850@f14g2000cwb.googlegroups.com> Hey- Check out this great site that is giving away totally FREE Desktop PCs! I've joined and I think you should as well. It's a completely legitimate offer, and this company has already given away $4 million in FREE stuff! All you have to do is join, complete an online offer, and refer friends to do the same. That's it! Here is my referral link. To help me get my Desktop PC, click this exact link to join, or copy and paste it into a browser: http://www.FreeDesktopPC.com/?r=13995904 this is my second free computer. Its awesome. Get it and sell it or use it. Its free. Who cares. From mikybNO at SPAMinterfree.it Fri Jan 28 18:09:09 2005 From: mikybNO at SPAMinterfree.it (Michele) Date: Fri, 28 Jan 2005 23:09:09 GMT Subject: boa constructor & mysql Message-ID: <2005012900090816807%mikybNO@SPAMinterfreeit> I've search a lot to found how visualize a mysql table in a gui (wxpython). I think to use wxgrid to visualize this table...but I don't know how... Anyone help me? Thanks a lot for the patience. Michele From pycon at python.org Sun Jan 23 16:07:00 2005 From: pycon at python.org (Steve Holden) Date: Sun, 23 Jan 2005 22:07:00 +0100 (CET) Subject: Microsoft to Provide PyCon Opening Keynote Message-ID: <20050123210700.EF4E41E4015@bag.python.org> Dear Python Colleague: The PyCon Program Committee is happy to announce that the opening keynote speech, at 9:30 am on Wednesday March 23 will be: Python on the .NET Platform, by Jim Hugunin, Microsoft Corporation Jim Hugunin is well-known in the Python world for his pioneering work on JPython (now Jython), and more recently for the IronPython .NET implementation of Python. Jim joined Microsoft's Common Language Runtime team in August last year to continue his work on Iron Python and further improve the CLR's support for dynamic languages like Python. I look forward to hearing what Jim has to say, and hope that you will join me and the rest of the Python community at PyCon DC 2005, at George Washington University from March 23-25, with a four-day sprint starting on Saturday March 19. Early bird registration rates are still available for a few more days. Go to http://www.python.org/moin/PyConDC2005/Schedule for the current schedule, and register at http://www.python.org/pycon/2005/ regards Steve Holden Chairman, PyCON DC 2005 -- PyCon DC 2005: The third Python Community Conference http://www.pycon.org/ http://www.python.org/pycon/ The scoop on Python implementations and applications From http Thu Jan 27 23:25:57 2005 From: http (Paul Rubin) Date: 27 Jan 2005 20:25:57 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> Message-ID: <7xu0p2dvsa.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > > I don't see why you can't make up your mind enough to issue simple > > statements like "the Python lib should have a module that does > > so-and-so > > I can say that assuming I know what so-and-so is. For the specific > case of AES, I would say "I don't think the Python lib necessarily > needs to have an AES module, but I would not object if it had one" Well, ok, you're changing your tune a little bit now, and getting more reasonable. Before, you were making blanket statements of any modules written for the Python stdlib. Now you're limiting it to AES and basing it on some AES-specific things. > (the latter part in consideration of consequences that inclusion > of crypto code might have). I would say the first thing I'd request would be your sense of how plausible it is that the current no-crypto policy might be relaxed. And I think this is about totally up to Guido, since (reading between the lines of those python-dev messages) he's concerned about the Dutch crypto restrictions, which makes some sense because he's Dutch and still has to deal with the Dutch government from time to time, while you or I might not care what the Dutch government thinks. I was about to mention that Rop Gongrijp has been operating a crypto company in Holland (www.nah6.com) but I now see that it's moved to Germany, and I wonder if those Dutch restrictions might be the reason. I don't know any details though. > > and it should meet such-and-such requirements > > I can only say such things if I know such-and-such in detail > to specify requirements. For the specific case of AES, I don't > know enough about it to specify requirements. I will have to > trust others (and by that, I mean *multiple* others) OK. If it helps, I can tell you that the Python crypto crowd hangs out on a mailing list called python-crypto and has discussed this module at some length. > > so if someone submits one that meets the requirements and passes > > code review and testing and doesn't have unexpected issues or > > otherwise fail to meet reasonable expectations, we'll use it". > > Because I cannot specify requirements, I cannot make such a promise. Again OK. I had thought from earlier discussions that you were a crypto developer and familiar with this stuff; no problem if you're not. However, in that case, you probably wouldn't be using the module if it got included. I think the best policy if you don't feel comfortable supporting including some module (whether it's crypto or something else) that you're not personally going to use, is don't support inclusion, but also don't obstruct it. If there's some other stdlib maintainers who are knowledgeable about that kind of module and have an opinion about it, then go along with them unless there's a clear reason not to. Like, if I were a stdlib maintainer and somebody submitted a fancy multigrid PDE solver, that's outside my expertise and I'd go along with whatever Tim recommended. > In addition, for any new module, there is one primary requirement > for acceptance that cannot be fulfilled in code quality: the > contributor should promise to support the module in a foreseeable > future (i.e. a couple of years). That's not too unreasonable, though I don't think I've heard it mentioned as a requirement before. > You are talking about such a thing. I don't know enough about the > functionality to specify what an obvious interface is, or to > recognize one if I see it. The thing to do then is just defer the whole issue to someone on the core team who uses that type of function. Only if no one on the team has an opinion do you start having to look for stuff like wide use of the module in the outside community. > > I don't know what OMG is, but there is no IETF requirement that any > > implementations be available in any particular language. > > See RFC 2026, section 4.1.2. Two independent implementations > are required for the document to advance to draft (!) standard. That says nothing about the implementation languages. Both might be in Python, or one might be in VHDL and the other in Ada, or whatever. This particular module we're discussing is a straightforward implementation of AES, DES, and FIPS 81, for which there are thousands of implementations in both hardware and software. For the specific Python API, there's a Python implementation and the proposed new module is a C implementation that does the exact same thing only faster. So that's two implementations, though not independent in the IETF sense, because they'd both be written by the same person. I've never heard of any requirement before that there be two separate implementations of every Python stdlib module, by the way. That would be silly. > > However, the result of my not writing an AES module is that Python > > doesn't have an AES module. > > That's not true. PyCrypto does have AES support. That's not in any Python distro that I know of. I'm talking about modules in the stdlib, not external modules. "Batteries included", you know. > That's what I'm saying: If you distribute the module to users for > a year, and users express interest and support for your choice of > API, I'll support inclusion of the module. "do it" involves more than > just writing the code. Well, that's nice of you to offer to support inclusion of a module that you're not likely to use yourself and whose functionality you don't really understand (I'm not being sarcastic). If you're going to offer such support it makes sense to impose an unusually high standard for offering it. I myself would probably never support including any such module no matter how long it was distributed, but rather would just defer the whole question to people experienced with such modules and trust their sense of what the acceptance criteria should be for a specific module. That is, I'd abstain from any decision. > It's very easy. If you are primarily do it for other people's > benefit, and if you don't find any satisfaction in the process > of doing it - THEN DON'T. I really mean that; this is how > free software works. People *volunteer* to do things. If they > don't volunteer - that's perfectly fine. That doesn't map well onto the real world. Say I'm a professional cook and I have a good recipe for spam, eggs, sausage, and spam. I write the PyCon organizers and ask if they'd like me to cook up a big batch to serve for breakfast for PyCon attendees (this is as a volunteer, all ingredients provided at my own expense, etc). Reasonable answers might be: 1) No, we don't want to serve breakfast at PyCon, we thought about it but decided against it. => OK, fine, I don't cook it. 2) Hey, that sounds good--cook enough for 500 people and bring it to the site before the conference starts, and we'll put it on the menu unless it's below expectations. => OK, fine, I start cooking. Nobody has made an ironclad promise, but the organizers have told me their basic intentions, which is good enough for me. 3) Hmm, that recipe sounds interesting, why don't you send one or two portions to the organizers, we'll try them and let you know. => OK, this is basically a prototype implementation, like the pure-Python version of the AES module, that's fine for testing but not fast enough to serve (e.g.) 500 web connections. I send the small batch and wait for an answer before deciding to start the much bigger job of making a 500-person batch. Your answer is more like "make enough for 500 people and bring it to the conference site and only then will we even THINK about whether to serve it for breakfast. Serving it at PyCon shouldn't matter to you, what are you, some kind of egotist? You like cooking, so if you make the 500 portions and then the organizers decline them, you can always hand them out in the street. If you don't find any satisfaction in that, THEN DON'T DO IT." If the cook's goal is not just to feed Python users in the street, but to actually improve PyCon itself by providing for PyCon to serve breakfast to attendees, I hope you can see why he might not think much of your answer. > As I said above - for the specific feature in question, I don't > care enough for the feature itself. Python will be just as useful > to me with the feature as it is without. I'm sure that's true of lots of modules. If you're the sole maintainer of the Python distro, then you have to evaluate every module that anyone submits. But since you're part of a reasonable sized group, I think it's best to examine the modules you care about, but don't feel that you have to have your hands in everything. From korimort at aon.at Wed Jan 12 08:13:00 2005 From: korimort at aon.at (Thomas Korimort) Date: Wed, 12 Jan 2005 14:13:00 +0100 Subject: how to visualize symbol table? Message-ID: <41e5220c$0$15240$91cee783@newsreader01.highway.telekom.at> Hi, how can i visualize the content of the symbol table in Python? Sometimes i want to know which symbols are imported from apackage and such kind of things Greetings, THomas Korimort From michele.simionato at gmail.com Tue Jan 11 04:15:00 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 11 Jan 2005 01:15:00 -0800 Subject: Python & unicode In-Reply-To: <1105434532.132061.24030@f14g2000cwb.googlegroups.com> References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> <1105434532.132061.24030@f14g2000cwb.googlegroups.com> Message-ID: <1105434900.511862.54740@f14g2000cwb.googlegroups.com> I forgot to add the following: >>> setattr(C, "?", u"The letter ?") >>> getattr(C, "?") u'The letter \xe8' >>> print getattr(C, "?") The letter ? Python identifiers can be generic strings, including Latin-1 characters; they cannot be unicode strings, however: >>> setattr(C, u"?", "The letter ?") Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 0: ordinal not in range(128) So you are right after all, but I though most people didn't know that you can have valid identifiers with accented letters, spaces, and non printable chars. > setattr(C, " ", "this works") > getattr(C, " ") Michele Simionato From google-groups at slippytoad.com Thu Jan 13 16:57:56 2005 From: google-groups at slippytoad.com (Nick Atkins) Date: 13 Jan 2005 13:57:56 -0800 Subject: Pygtk: How to remove title bar from a window Message-ID: <1105653476.254139.58810@f14g2000cwb.googlegroups.com> Hi all, I am writing an application using pyGTK that has several pop-up dialogs that show and hide in succession. I would like to prevent the user from closing the dialog and if possible I'd like to use a "title bar-less" window with a normal border so the X is not even available to click. Is this possible? I have tried using window.set_decorated(FALSE) but this also removes the border making the window look quite strange. Thanks, Nick. From ken at switchboard.ericsson.se Fri Jan 28 09:09:27 2005 From: ken at switchboard.ericsson.se (Kenneth Johansson) Date: Fri, 28 Jan 2005 15:09:27 +0100 Subject: Profiling python 2.3 References: Message-ID: On Fri, 28 Jan 2005 10:02:33 +0000, Stephen Kellett wrote: > In message , Kenneth > Johansson writes >>I wonder what would be a good way to profile a python program where the >>main thread starts two worker threads that do all the work. >> >>I get no infomation at all from the threads. > > Python Performance Validator (beta) > > http://www.softwareverify.com/pythonPerformanceValidator/index.html > > Stephen I develop on linux. Nice to see I do not have to recompile and relink to use the tool that's a real problem with other python stuff ;) From bokr at oz.net Sun Jan 9 16:12:08 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 09 Jan 2005 21:12:08 GMT Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> Message-ID: <41e19e14.427486833@news.oz.net> On 09 Jan 2005 03:10:15 -0800, Paul Rubin wrote: >Nick Coghlan writes: >> Trying to push it a level further (down to expressions) would, IMO, be >> a lot of effort for something which would hurt readability a lot. > >I think we should just try to do things in a simple and general way >and not try to enforce readability. For example, the >slightly-overcomplex code that I proposed might have been generated by >a macro, or even by a compiler from some other language. No human >would ever have to look at it, so it doesn't matter whether it's >easily readable. There's no reason to add needless constraints on the >language just to make writing ugly code difficult. The main goal >should be to make writing clear code easy, not to worry about whether >someone might also write ugly code. +1 ;-) Regards, Bengt Richter From pythongnome at hotmail.com Tue Jan 11 17:29:29 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Tue, 11 Jan 2005 22:29:29 GMT Subject: Game programming in Python In-Reply-To: References: Message-ID: Baza wrote: > I'm looking for any books or on-line resources on game programming using > Python. Does anyone have any advice? > -- > Computer says, 'no' > > www.panda3d.com, www.pygame.org, www.blender3d.com ... From skip at pobox.com Thu Jan 20 09:26:12 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 20 Jan 2005 08:26:12 -0600 Subject: Zen of Python In-Reply-To: <972ec5bd0501191641166972b0@mail.gmail.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> Message-ID: <16879.49028.243445.847968@montanaro.dyndns.org> >> The gist of "Flat is better than nested" is "be as nested as you have >> to be, no more," because being too nested is just a mess. Tim> Which I agree with, and which makes sense. However your "gist" is a Tim> different meaning. Not if you conflate "Flat is better than nested" with "Namespaces are one honking great idea -- let's do more of those!". seek-balance-in-all-things-my-son-ly, y'rs, Skip From mesteve_bpleaseremovethis at hotmail.com Sun Jan 2 17:16:50 2005 From: mesteve_bpleaseremovethis at hotmail.com (StvB) Date: Sun, 02 Jan 2005 22:16:50 GMT Subject: Python! Is! Truly! Amazing! References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: The way that Paul Graham sees Lisp: ($$$$$$$$$$$$)))yes!))))) ) "Roy Smith" wrote in message news:roy-D9F00D.12570402012005 at reader1.panix.com... > In article , > Ron Garret wrote: > >> In article <1104657461.868175.252380 at c13g2000cwb.googlegroups.com>, >> "Erik Bethke" wrote: >> >> > >> > I have NEVER experienced this kind of programming joy. >> >> Just wait until you discover Lisp! >> >> ;-) >> >> rg > > Shouldn't that be ;-)))))))))))))) ? From python at hope.cz Mon Jan 17 14:12:09 2005 From: python at hope.cz (python at hope.cz) Date: 17 Jan 2005 11:12:09 -0800 Subject: How to prevent the script from stopping before it should In-Reply-To: References: <1105981979.853318.269300@c13g2000cwb.googlegroups.com> <1105982387.852448.298900@c13g2000cwb.googlegroups.com> Message-ID: <1105989129.404687.140070@c13g2000cwb.googlegroups.com> Steve Holden wrote: > wittempj at hotmail.com wrote: > > > #import urllib, sys > > #pages = ['http://www.python.org', 'http://xxx'] > > #for i in pages: > > # try: > > # u = urllib.urlopen(i) > > # print u.geturl() > > # except Exception, e: > > # print >> sys.stderr, '%s: %s' % (e.__class__.__name__, e) > > will print an error if a page fails opening, rest opens fine > > > More generally you may wish to use the timeout features of TCP sockets. > These were introduced in Python 2.3, though Tim O'Malley's module > "timeoutsocket" (which was the inspiration for the 2.3 upgrade) was > available for earlier versions. > > You will need to import the socket module and then call > socket.setdefaulttimeout() to ensure that communication with > non-responsive servers results in a socket exception that you can trap. > > regards > Steve > -- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/ > Holden Web LLC +1 703 861 4237 +1 800 494 3119 Thank you wittempj at hotmail.com and Steve for some ideas.Finding the fact that the script hanged is not a big problem . I,however, would need a solution that I will not need to start again the script but the script re-start by itself. I am thinking about two threads, the main(master) that will supervise a slave thread.This slave thread will download the pages and whenever there is a timeout the master thread restart a slave thread. Is it a good solution? Or is there a better one? Thanks for help Lad From sjmachin at lexicon.net Mon Jan 24 15:56:04 2005 From: sjmachin at lexicon.net (John Machin) Date: 24 Jan 2005 12:56:04 -0800 Subject: "bad argument type for built-in operation" References: Message-ID: <1106600164.016115.24660@c13g2000cwb.googlegroups.com> Gilles Arnaud wrote: > Hello, > > I've got a nasty bug and no idea to deal with : > > here is the method : Big snip. The Python code is unlikely to be your problem. > and the trace > > in None [(-2.0, 2.0), (-2.0, 2.0)] [0.1385039192456847, > 0.87787941093093491] 2 2 > [0.1385039192456847, 0.87787941093093491] That's a very mangled trace! > the first call of the methode succeed > all following call failed. So the first call is leaving a bomb behind. > > I've got different scenario which call this low level methode, > many succeed, some failed this way. > > what's happened ? > If someone got an idea ? > what can raise this exception ? At this stage, without the benefit of look-ahead, one could only blame gamma rays or pointy-eared aliens :-) > > My program is written partially in python and partially in C. > the top level is in python which call a C optimisation routine > which use a callback (PyObject_CallMethod) to evaluate the cost in > python again. Aha! *Now* you tell us. *You* have "denormalised" the stack. Read your C code carefully. Use a debugger, or put some "printf()" in it. With PyObject_CallMethod, do the format descriptors and the arguments match? Are you testing the returned value for NULL and acting accordingly? Is the called-from-C Python method ever executed? Try putting a print statement (that shows the args) at the top. More generally, are you testing the returned value from each and every C API call? Are you testing for the correct error value (some return NULL, some -1, ...)? Are you doing the right thing on error? A catalogue of the different ways of messing things up using C would take forever to write. If you can't find your problem, post the code, either on the newsgroup or as a web page. Hope this helps, John From sjmachin at lexicon.net Tue Jan 11 20:47:36 2005 From: sjmachin at lexicon.net (John Machin) Date: 11 Jan 2005 17:47:36 -0800 Subject: SciTe In-Reply-To: <58%Ed.4827$C52.2609@newsread2.news.atl.earthlink.net> References: <58%Ed.4827$C52.2609@newsread2.news.atl.earthlink.net> Message-ID: <1105494456.015733.275590@f14g2000cwb.googlegroups.com> Lucas Raab wrote: > I didn't want to go through the rigamole of adding myself to the SciTe > mailing list, so I'm asking my question here. How do I choose a > different C/C++ compiler to compile in?? I don't use the g++ compiler; I > use the VC 7 compiler. > > TIA, > Lucas How the @#$% should we know? Don't be lazy; join the SciTe mailing list!!! From bulba at bulba.com Sat Jan 8 20:48:49 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 09 Jan 2005 02:48:49 +0100 Subject: windows mem leak References: <41XDd.70234$Jk5.40626@lakeread01> Message-ID: On Sat, 08 Jan 2005 15:00:05 -0500, Steve Holden wrote: >> Does the Win32 port of Python have a memory leak? I have some code that >> runs flawlessly on Linux, but bombs after a few hours on Windows. It's >> threaded and uses a lot of memory. >Yes, that's a well-known problem. Code that runs with a few errors will >port without any trouble at all to Windows, but once it runs flawlessly >on Linux it starts to leak memory on Windows. The PSU suspects a plot in >Redmond, the basic details of which ar You have my nomination for SOTW*. :-) * skit of the week / short story of the week -- It's a man's life in a Python Programming Association. From http Mon Jan 10 19:35:46 2005 From: http (Paul Rubin) Date: 10 Jan 2005 16:35:46 -0800 Subject: Writing huge Sets() to disk References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <7xmzvgren6.fsf@ruckus.brouhaha.com> Message-ID: <7xis64ree5.fsf@ruckus.brouhaha.com> Paul Rubin writes: > handle with builtin Python operations without putting some thought > into algorithms and data structures. From "ribosome" I'm guessing > you're doing computational biology. If you're going to be writing > code for these kinds of problems on a regular basis, you probably > ought to read a book or two on the topic. "CLRS" is a good choice: > > http://theory.lcs.mit.edu/~clr/ > http://mitpress.mit.edu/algorithms/ Correction to unclarity: I meant a book on the topic of algorithms and data structures (e.g. CLRS). Since you're presumably already a biologist, I wouldn't presume to suggest that you read a book on biology ;-). From godoy at ieee.org Wed Jan 19 10:45:23 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Wed, 19 Jan 2005 13:45:23 -0200 Subject: Accessing MDB files on Windows Message-ID: <1635068.ZTfiooUzB4@strongwill.g2ctech> Hi, What is the best way to deal with MDB files? I was thinking on using ODBC... I'll need to read and write some information to it. The load won't be so high, but there might be a lot of data. Any advices? Will my approach work? I'm not a Windows guy... :-) -- Godoy. From abpillai at gmail.com Thu Jan 6 05:24:35 2005 From: abpillai at gmail.com (Anand) Date: 6 Jan 2005 02:24:35 -0800 Subject: Contributor's List In-Reply-To: <1105006211.527899.318740@c13g2000cwb.googlegroups.com> References: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> <1105006211.527899.318740@c13g2000cwb.googlegroups.com> Message-ID: <1105007075.090543.47370@c13g2000cwb.googlegroups.com> I have no idea. I am just another contributor like you. Just doing a service to the Python community by providing the list at my site. However, I am not responsible for its content. Please direct your queries to the editors, if any. Thanks -Anand From sjmachin at lexicon.net Thu Jan 20 19:34:51 2005 From: sjmachin at lexicon.net (John Machin) Date: 20 Jan 2005 16:34:51 -0800 Subject: why no time() + timedelta() ? In-Reply-To: References: Message-ID: <1106267691.485671.45380@c13g2000cwb.googlegroups.com> Tim Peters wrote: > [josh] > > Why can't timedelta arithmetic be done on time objects? > > Obviously, because it's not implemented . > > > (e.g. datetime.time(5)-datetime.timedelta(microseconds=3) > > > > Nonzero "days" of the timedelta could either be ignored, or > > trigger an exception. > > And if the result is less than 0, or >= 24 hours, it could raise > OverflowError, or wrap around mod 24*60*60*1000000 microseconds, and > so on. There are so many arbitrary endcases that no agreement could > be reached on what they "should" do. So it's not supported at all. > In contrast, it was much easier to reach consensus on what datetime > arithmetic should do, so that was supported. Reminds me of the debate at the time whether "add months" functionality should be provided. Disagreement, including someone who shall remain nameless opining that Jan 31 + one month should return Mar 3 (or Mar 2 in a leap year). Not supported at all. Those of us who dabble in arcane esoterica like payrolls, pensions, mortgages, insurance, and government bloody regulations had a quick ROTFL and started typing: class RealWorldDateFunctionality(datetime.date): ... From steve at holdenweb.com Mon Jan 10 05:28:44 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Jan 2005 05:28:44 -0500 Subject: Python serial data aquisition In-Reply-To: References: <41e1b833$1_3@omega.dimensional.com> Message-ID: Flavio codeco coelho wrote: > mfuhr at fuhr.org (Michael Fuhr) wrote in message news:<41e1b833$1_3 at omega.dimensional.com>... > >>If the actual byte and/or bit order is different then you'll have >>to modify the expression, but this should at least give you ideas. > > > Thanks Michael and Steve, > > I'll put your Ideas to the test ASAP, meanwhile, could you point me to > references to these bit operations in Python? I am new to this stuff, > and might need to do more of this to support other hardware... > > I havent been able to find anything about this on the python > documentation.. > > Thanks a lot!! > > Flavio ord() is documented in section 2.1 of the library reference manual (Built-in Functions) - see http://docs.python.org/lib/built-in-funcs.html#l2h-53 for further information. Bitstring operations are at http://docs.python.org/lib/bitstring-ops.html#l2h-150 Hope this helps. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From sjmachin at lexicon.net Sun Jan 2 21:28:52 2005 From: sjmachin at lexicon.net (John Machin) Date: 2 Jan 2005 18:28:52 -0800 Subject: Calling Function Without Parentheses! References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> Message-ID: <1104719332.876804.193020@c13g2000cwb.googlegroups.com> Kamilche wrote: > What a debug nightmare! I just spent HOURS running my script through > the debugger, sprinkling in log statements, and the like, tracking down > my problem. > > I called a function without the ending parentheses. I sure do WISH > Python would trap it when I try to do the following: > MyFunc > > instead of: > > MyFunc() > > aaaaaaaaaaaah. Aaaaaaaaaaaah indeed. You must be using an extremely old version of pychecker. The version I have in my Python22 directory gave the same results as the current one; see below. C:\junk>type noparens.py [bangs inserted to defeat Google's lstrip() !def bar(): ! foo !def foo(): ! alist = [] ! alist.sort C:\junk>pychecker noparens.py C:\junk>c:\python24\python.exe c:\python22\Lib\site-packages\pychecker\checker.py noparens.py Processing noparens... Warnings... noparens.py:2: Statement appears to have no effect noparens.py:5: Statement appears to have no effect From tom at dtsam.com Tue Jan 18 18:33:14 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Tue, 18 Jan 2005 17:33:14 -0600 Subject: simultaneous multiple requests to very simple database References: Message-ID: "Eric S. Johansson" wrote in message news:mailman.871.1106087623.22381.python-list at python.org... > 99.9 percent of what I do (and I suspect this could be true for others) > could be satisfied by a slightly enhanced super dictionary with a record > level locking. BUT - Did you not mention! : > Estimated number of records will be in the ballpark of 50,000 to 100,000 in his > early phase and 10 times that in the future. Each record will run about > 100 to 150 bytes. . And > The very large dictionary must be accessed from > multiple processes simultaneously And > I need to be able to lock records > within the very large dictionary when records are written to And > although I must complete processing in less than 90 seconds. And - the hole in the bottom of the hull - all of the above using "a slightly enhanced super dictionary". *Super* dictionary??? *Slightly* enhanced??? Have you attempted any feasability tests? Are you running a Cray? There are many database systems available, and Python (probably) has free bindings to every one of them. Whichever one might choose, it would add simplicity, not complexity to what you are attempting. The problems you mention are precisely those that databases are meant to solve. The only tough (impossible?) requirement you have is that you don't want to use one. When you write that "super dictionary", be sure to post code! I could use one of those myself. Thomas Bartkus From deetsNOSPAM at web.de Thu Jan 13 07:36:36 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 13 Jan 2005 13:36:36 +0100 Subject: Unclear On Class Variables References: Message-ID: <34n8a5F4dec78U2@individual.net> Tim Daneliuk wrote: > I am a bit confused. I was under the impression that: > > class foo(object): > x = 0 > y = 1 > > means that x and y are variables shared by all instances of a class. > But when I run this against two instances of foo, and set the values > of x and y, they are indeed unique to the *instance* rather than the > class. > > It is late and I am probably missing the obvious. Enlightenment > appreciated ... Without actual code how you set the vars, no one can answer that question. -- Regards, Diez B. Roggisch From aleaxit at yahoo.com Sun Jan 2 17:25:47 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 2 Jan 2005 23:25:47 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> Message-ID: <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> Roy Smith wrote: > Stefan Axelsson wrote: > > Yes, ignoring most of the debate about static vs. dynamic typing, I've > > also longed for 'use strict'. > > You can use __slots__ to get the effect you're after. Well, sort of; it > only works for instance variables, not locals. And the gurus will argue > that __slots__ wasn't intended for that, so you shouldn't do it. There's a simple, excellent recipe by Michele Simionato, on both the online and forthcoming 2nd edition printed Cookbook, showing how to do that the right way -- with __setattr__ -- rather than with __slots__ . Alex From tmj at SPAMLESSjarmania.com Sun Jan 2 17:14:08 2005 From: tmj at SPAMLESSjarmania.com (Tim Jarman) Date: Sun, 02 Jan 2005 22:14:08 +0000 Subject: How to make executable file ? References: <33r5gcF449bt0U1@individual.net> <41d868ff@news.unimelb.edu.au> Message-ID: <33ra0eF42g7qiU1@individual.net> Maurice LING wrote: > Hi all, > > This may be OT but is there a way to do the same for *nix type of > system? Like cast a python interpreter with scripts together? > > I'm running Mac OSX here. > For OSX, google for py2app - for *nix in general, I believe freeze is your mman, although so many *nixen ship with Python these days it's not such an issue. -- Website: www DOT jarmania FULLSTOP com From kp8 at mac.com Tue Jan 11 15:15:24 2005 From: kp8 at mac.com (kpp9c) Date: 11 Jan 2005 12:15:24 -0800 Subject: Time script help sought! In-Reply-To: <1105471266.880133.318470@c13g2000cwb.googlegroups.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> Message-ID: <1105474524.083536.129220@f14g2000cwb.googlegroups.com> Thanks for this Everyone! Trying to work with all the stuff folks are giving me on this i a have come across a problem... down the line i notice that some of the times will also have an hour as well as in H:M:S (e.g. 1:22:40) so in some cases i would need to convert H:M:S to sec and some just M:S or should there just be a fun that passes all the times and converts them to H:M:S first and just appends a 00: ((e.g. 00:02:07) if there is no hour value? cheers, -kp From __peter__ at web.de Tue Jan 11 08:40:14 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Jan 2005 14:40:14 +0100 Subject: Exception not captured References: Message-ID: Miki Tebeka wrote: > Hello All, > > Can someone please explain how is the following code fragment possible? > (If you're interested I can place the whole project somewhere). > > def checkout(dest, log): > '''Get latest version from SCM > > client - SCM client to use > dest - Destination directory > ''' > try: > SCM.checkout(dest, log) > except SCMError, e: > raise NightlyError("Checkout") > except Exception, e: > import inspect > file = inspect.getsourcefile(e.__class__) > line = inspect.getsourcelines(e.__class__)[1] > print "%s:%d" % (file, line) > file = inspect.getsourcefile(SCMError) > line = inspect.getsourcelines(SCMError)[1] > print "%s:%d" % (file, line) > print SCMError is e.__class__ > raise SystemExit > > I get to the second "except" clause, and the printout is: > /home/mikit/work/nightly/scm/common.py:3 > /home/mikit/work/nightly/scm/common.py:3 > False > > How is this possible? Some kind of duplicate import, maybe? E.g.: >>> import sys >>> import inspect >>> getsource = inspect.getsource >>> del sys.modules["inspect"] >>> import inspect >>> getsource is inspect.getsource False Peter From apardon at forel.vub.ac.be Thu Jan 13 07:53:55 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jan 2005 12:53:55 GMT Subject: lambda References: Message-ID: Op 2005-01-13, Tim Leslie schreef : > Because if it takes more than a single line it deserves a name. So if I have a call with an expression that takes more than one line, I should assign the expression to a variable and use the variable in the call? But wait if I do that, people will tell me how bad that it is, because it will keep a reference to the value which will prevent the garbage collector from harvesting this memory. Besides python allows more than one statement on the same line. -- Antoon Pardon From philippecmartin at sbcglobal.net Tue Jan 11 01:32:26 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Tue, 11 Jan 2005 07:32:26 +0100 Subject: fetching method names from a class, and the parameter list from a methodRe: fetching method names from a class, and the parameter list from a method Message-ID: <1105425146.6920.3.camel@localhost> >>> import inspect >>> help(inspect) Thanks, I have not seen the func params yet, but the default values are so .... Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From aahz at pythoncraft.com Mon Jan 31 16:20:59 2005 From: aahz at pythoncraft.com (Aahz) Date: 31 Jan 2005 16:20:59 -0500 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> Message-ID: In article <1gr98se.102e9b1qnsknwN%aleaxit at yahoo.com>, Alex Martelli wrote: > >Some people claim a language should change the way you think -- a >frequent poster, excellent Python contributor, and friend, even has that >claim in his signature. Generally speaking, I change my .sig either when I get bored or when someone references it. So here's the new one. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger." --Roy Smith, c.l.py, 2004.05.23 From frans.englich at telia.com Mon Jan 31 23:17:10 2005 From: frans.englich at telia.com (Frans Englich) Date: Tue, 1 Feb 2005 04:17:10 +0000 Subject: Python's idiom for function overloads Message-ID: <200502010417.10481.frans.englich@telia.com> Hello, Since Python doesn't have static typing, how is the same result as traditional function overloads results in acheived? With function overloads the "selection of code path depending on data type" is transparent and automatic since the typing system figure out what goes to what. But in Python, when one wants to be able to pass different data types into a single "entry point" for functionality, how is that best done? To in a function do an if statement with the type() function? Cheers, Frans From peter at somewhere.com Thu Jan 13 09:58:03 2005 From: peter at somewhere.com (Peter Maas) Date: Thu, 13 Jan 2005 15:58:03 +0100 Subject: [perl-python] 20050112 while statement In-Reply-To: References: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> Message-ID: brianr at liffe.com schrieb: > "Xah Lee" writes: [...] > (As a matter of interest, is this sequence of posts intended to > demonstrate ignorance of both languages, or just one?) :) This sequence of posts is intended to stir up a debate just for the sake of a debate. It's a time sink. It's up to you wether you want to post to this thread or do something useful. :) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From andreasp at qbcon.com Fri Jan 28 02:16:38 2005 From: andreasp at qbcon.com (Andreas Pauley) Date: Fri, 28 Jan 2005 09:16:38 +0200 (SAST) Subject: Point of Sale In-Reply-To: <41F9193B.7090801@tokenexchange.com> References: <41F9193B.7090801@tokenexchange.com> Message-ID: On Thu, 27 Jan 2005, Evan Simpson wrote: > You may want to check out the Spread Toolkit, at www.spread.org, whose Python > wrapper lives at http://www.python.org/other/spread/doc.html. It's used by > the Zope Replication Service, for example. > > Cheers, > > Evan @ 4-am Thanks a lot, I need components like these desperately. I've also seen ICE from ZeroC (www.zeroc.com) and OSE (http://ose.sourceforge.net/browse.php?group=python-manual&entry=modules.htm) I haven't tried any of them yet, will have to do that a bit later. Andreas From itsme at yahoo.com Fri Jan 14 16:32:09 2005 From: itsme at yahoo.com (It's me) Date: Fri, 14 Jan 2005 21:32:09 GMT Subject: Why would I get a TypeEror? References: <34ql1vF4dqd9pU1@individual.net> Message-ID: Say again??? "Reinhold Birkenfeld" wrote in message news:34ql1vF4dqd9pU1 at individual.net... > It's me wrote: > > Sorry if my question was a little "lazy" and yes, I was asking about the > > "lazy evaluation". :=) > > > > I am surprised about this (and this can be dangerous, I guess). > > > > If this is true, I would run into trouble real quick if I do a: > > > > (1/x,1.0e99)[x==0] > > > > and that's not good. > > > > Something to keep in mind. :-( > > Lazy evaluation: use the (x==0 and 1e99 or 1/x) form! > > Reinhold From itsme at yahoo.com Mon Jan 3 13:56:20 2005 From: itsme at yahoo.com (It's me) Date: Mon, 03 Jan 2005 18:56:20 GMT Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: "Richards Noah (IFR LIT MET)" wrote in message news:crbur8$edu$1 at athen03.muc.infineon.com... > > Begging your pardon, but a better resource would be the brochure available > (http://www.pti-us.com/PTI/company/brochures/PSSE.pdf). It appears that the > program was probably (originally) written in C/C++ (using MFC for the GUI), > and now employs Python for adding modules and scripting support. Very > interesting stuff :) > > It was actually developed in Fortran some 35 years ago. Then migrated to F77. Then added a C/C++ layer to sit ontop. Then converted to API based. Then added a Python layer on top. The only thing unfortunate is that they went with MFC on the newest version. Yuck! From ville at spammers.com Mon Jan 17 07:35:02 2005 From: ville at spammers.com (Ville Vainio) Date: 17 Jan 2005 14:35:02 +0200 Subject: OCAMl a more natural extension language for python? References: Message-ID: >>>>> "Jelle" == Jelle Feringa // EZCT / Paris writes: Jelle> After reading about extending python with C/Fortran in the Jelle> excellent Python Scripting for Computational Science book Jelle> by Hans Langtangen, I'm wondering whether there's not a Jelle> more pythonic way of extending python. And frankly I think Jelle> there is: OCAML For many tasks the point of "extending" python is to gain access to libraries that have a C/C++ API. Extensions that merely provide a faster way to do something are much rarer. -- Ville Vainio http://tinyurl.com/2prnb From philippecmartin at sbcglobal.net Mon Jan 17 15:28:17 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 17 Jan 2005 21:28:17 +0100 Subject: how to find site-packages path (Michael Hoffman) - use distutils Message-ID: <1105993697.6720.3.camel@localhost> >>The flawless way would be to use distutils. In fact you shouldn't even >>need your own install script--it should do most of the work for you. The reason I have not so far is I have not found a way to get what I want done: 1) create directories in site-packages (I gather this shoudl be easy enough) 2) copy already compiled (.pyc) and source (.py) files to those directories 3) create directories and copy files in a directory kept in an environment variable Can distutils do this for me ? Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From lonetwin at gmail.com Sat Jan 29 08:35:55 2005 From: lonetwin at gmail.com (Steve) Date: Sat, 29 Jan 2005 19:05:55 +0530 Subject: The next Xah-lee post contest Message-ID: <5a309bd305012905357e14df62@mail.gmail.com> Hi All, For sometime now, I have just been a passive lurker on this list. Of late I saw an increase in the number of posts by Xah Lee, and I have to admit, what he lacks in understanding of the various programming languages he talks about, he makes up for in creativity. So, I was wondering, how would it be to be Mr Lee. That got me thinking of his next post. Well, I know through my days of lurking around, a lot of people here love creative challenges ...so here's one for you. Write up the next Xah Lee post ! The requirement are: a) The post should talk about a single language, although the example code needn't adhere to that restriction. b) It should explain the style, structure and design of some code snippet/program, though not necessarily of the same code snippet/program mentioned in the post. c) Should be written in English ... respect to English grammar is not mandatory. d) It *must* be flammable. Here's my contribution (tho' I'm not really in my most creative frame of mind): -------------------------------------------------- perl is fucked ! Its a language named with a word that can't even pass through spell-checker. What kind of programming language has a scalar variable but the array is not called vector ...it is array. Also the list comprehension feature of the language is entirely anal. Example $list = { i for i in range(100) } now is $list a function ?? No it's is an array ..... -------------------------------------------------- ..phew, this is hard !! I'll have another go later. You are welcomed to participate. Regards Steve From http Thu Jan 13 18:06:35 2005 From: http (Paul Rubin) Date: 13 Jan 2005 15:06:35 -0800 Subject: newbie ?s References: <1105656971.768148@sj-nntpcache-5> Message-ID: <7xekgpgc90.fsf@ruckus.brouhaha.com> "Venkat B" writes: > I'm looking build a CGI-capable SSL-enabled web-server around Python 2.4 on > Linux. > It is to handle ~25 hits possibly arriving "at once". Content is non-static > and built by the execution of py cgi-scripts talking to a few backend > processes. > > 1) I was wondering if anyone has opinions on the ability of CGIHTTPServer (a > forking variant) to be able to handle this. Why not use apache? > 2) If so, would something like pyOpenSSL be useful to make such a webserver > SSL-enabled. I haven't used pyOpenSSL but I don't see any other way to do it. Well maybe mxCrypto which I haven't used either. The SSL socket library doesn't understand certificates. From franco.fiorese at tin.it Fri Jan 28 15:53:42 2005 From: franco.fiorese at tin.it (Franco Fiorese) Date: Fri, 28 Jan 2005 20:53:42 GMT Subject: Pystone benchmark: Win vs. Linux (again) Message-ID: Hi all, I am relatively new about Python benchmarks. After some experiments I found that Python on my PC Windows XP has a relevant higher performance than on Linux. The simple test using pystone.py shows this: * Windows XP Pro: 16566.7 pystones/second * Linux (kernel 2.6.9 NPTL): 12346.2 pystones/second I have repeated the test, on Linux, also with other distributions and kernel but a relevant difference still exists with Windows offering a better performance. Is there any way, that you know, to get better performance under Linux? regards Franco From ark at acm.org Sat Jan 22 11:55:45 2005 From: ark at acm.org (Andrew Koenig) Date: Sat, 22 Jan 2005 16:55:45 GMT Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> <7xu0p9lk4h.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xu0p9lk4h.fsf at ruckus.brouhaha.com... > It's really irrelevant whether anyone is using a feature or not. If > the feature is documented as being available, it means that removing > it is an incompatible change that can break existing code which > currently conforms to the spec. If the "feature" is described as the > bug that it is, anything that relies on it is nonconformant. In this case, I think the right solution to the problem is two-fold: 1) from __future__ import lexical_comprehensions 2) If you don't import the feature, and you write a program that depends on a list-comprehension variable remaining in scope, the compiler should issue a diagnostic along the lines of Warning: This program should be taken out and shot. From cbfalconer at yahoo.com Sun Jan 23 05:47:10 2005 From: cbfalconer at yahoo.com (CBFalconer) Date: Sun, 23 Jan 2005 10:47:10 GMT Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: <41F37E6D.296D9EB1@yahoo.com> Xah Lee wrote: > ... snip ... > > the first paragraph of 9.1 "A Word About Terminology" is epitome > of masturbation. The entire 9.1 is not necessary. > > Large part of 9.2 "Python Scopes and Name Spaces" is again > masturbatory. PLONK for excessive OT crossposting and trolling. -- "If you want to post a followup via groups.google.com, don't use the broken "Reply" link at the bottom of the article. Click on "show options" at the top of the article, then click on the "Reply" at the bottom of the article headers." - Keith Thompson From eurleif at ecritters.biz Mon Jan 10 18:40:11 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 10 Jan 2005 18:40:11 -0500 Subject: Python & unicode In-Reply-To: <10u6347j23enuc3@news.supernews.com> References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> Message-ID: <34gi0fF4c1lntU1@individual.net> John Roth wrote: > It doesn't work because Python scripts must be in ASCII except for > the contents of string literals. Having a function name in anything > but ASCII isn't supported. To nit-pick a bit, identifiers can be in Unicode; they're simply confined to digits and plain Latin letters. From bulba at bulba.com Sun Jan 2 12:23:13 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 02 Jan 2005 18:23:13 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <63bgt0dsj237t5j08jo895emj15p2tkl2s@4ax.com> On Fri, 31 Dec 2004 21:08:02 GMT, claird at lairds.us (Cameron Laird) wrote: >Let me add a cautionary note, though: Big Companies, >including Oracle, Software AG, IBM, Cisco, and so on, have >adopted Tcl over and over. All of them still rely on Tcl >for crucial products. All of them also have employees who >sincerely wonder, "Tcl? Isn't that dead?" >I offer this as a counter-example to the belief that Adop- >tion by a heavyweight necessarily results in widespread >acceptance. It's a quiet adoption. It's not a firework show a la Java combined with blowing all those truckloads of money on it (I've read this good comment in one of the IT periodicals that in future Java will be cited as an example of work of genius - not a genius of computing, though, but of marketing). There is a rational element in this craziness: people around watch and see that $$$ has been sunk in this, so they know that this who sank all those $$$ has very, very much of motivation not to let this thing wither away. No guarantee, of course, but a much better chance they just won't drop it. The problem of Python is not that it's not used, but because some company like IBM didn't decide to blow $1 bln on it or smth. Using it alone and even announcing it is not enough. "put your money where your mouth is", or so the thinking goes. -- It's a man's life in a Python Programming Association. From letsgoloslos at yahoo.com Fri Jan 14 21:24:15 2005 From: letsgoloslos at yahoo.com (chrisg) Date: 14 Jan 2005 18:24:15 -0800 Subject: Threading Or Other Suggestions?!? References: Message-ID: <1105755855.294024.98420@c13g2000cwb.googlegroups.com> You could also use os.spawnl to launch it in a separate process. From fumanchu at amor.org Fri Jan 7 18:02:07 2005 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 7 Jan 2005 15:02:07 -0800 Subject: Exception report library Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339813B@exchange.hqamor.amorhq.net> Ian Bicking wrote: > I've been using one of several systems to catch unexpected > exceptions and log them (e.g., write to a file, display on > web page, email me, etc). But many are built into a > particular system, or have an interesting but incomplete > set of features... > I feel like there must be something out there, since every Python > programmer has to deal with this sort of thing to some degree...? And I replied: > I feel that way, too, but haven't found it...If we could put our > many heads together, I think this would be doable for the stdlib. Ian: > I'm not optimistic about a good exception handler in the standard > library; development slows down a lot at that point, and it's not a > reasonable candidate until it is designed and used Sure; I understand it's a long process, and should start independently. Me again: > Here are the pieces of the framework, by the way, which might also > benefit from some standardization: > > 1. Thread-safe application state > 2. Logging (+ exception handling) > 3. Configuration data (reading from various sources) > 4. Registry of Workers for getting things done on a schedule, > possibly recurring > 5. Registry of startup/shutdown functions > 6. Registry of active user interfaces > > I think the first three are all good candidates for a standard. > If we had a standard, thread-safe Application object, the rest > could be registerable plugins for that. You'd basically register > callbacks for app.startup and .shutdown methods to iterate over. Ian: > Hmm... I'm confused by these bits. Are you talking about > libraries for other parts of a web framework, besides exception > handling? If so, you might want to look into WSGI... Those are the bits I pulled out as specifically non-web-specific, which could be used for any kind of app (and tend to get rewritten for every framework). If your app is single-process, multi-threaded, it needs a state manager so two threads don't load or destroy global resources simultaneously. Most apps need logging and uncaught exception handling (as you noticed). Etcetera. One way to meet these needs once-and-for-all would be to have a (eventually standard) library for them, where you could mix and match the pieces you needed. So, you could write WSGI consumers of them, but they wouldn't be WSGI-specific in my mind. If they were, they'd just add to the "several systems" you were lamenting... ;) Robert Brewer MIS Amor Ministries fumanchu at amor.org From fredrik at pythonware.com Sun Jan 30 02:30:17 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 30 Jan 2005 08:30:17 +0100 Subject: is this sort method the same as the one in python 2.4 References: Message-ID: Raymond Hettinger wrote: >> I'm trying to emulate the sorted() method introduced in python 2.4. The >> only difference is that it takes a sequence as one of its arguments >> rather than being a method of the sequence class. Does my method do the >> same as the sorted()? > > Almost. This is closer to the mark: > > def sorted(iterable, cmp=None, key=None, reverse=False): > "return a sorted copy of its input" > if sys.version_info >= (2,4): > return sorted(iterable, cmp, key, reverse) with your code print sorted([1, 2, 3]) gives me a traceback that ends with File "test.py", line 6, in sorted return sorted(iterable, cmp, key, reverse) File "test.py", line 6, in sorted return sorted(iterable, cmp, key, reverse) File "test.py", line 6, in sorted return sorted(iterable, cmp, key, reverse) File "test.py", line 5, in sorted if sys.version_info >= (2,4): RuntimeError: maximum recursion depth exceeded in cmp the recursion isn't really that hard to explain, but the runtime error doesn't really seem right... ::: to fix the recursion, move the if-statement so you only define the function if needed: if sys.version_info < (2,4): def sorted(...): .... From gabriel.barros at gmail.com Sat Jan 29 19:38:55 2005 From: gabriel.barros at gmail.com (Gabriel B.) Date: Sat, 29 Jan 2005 22:38:55 -0200 Subject: naive doc question Message-ID: <5175a81c050129163826fcd734@mail.gmail.com> Is it just me that can't find a full reference in the docs? I wanted a list of all the methods of dict for example... where can i find it? Thanks, and sorry if this question is just dumb, i really can't find it From PeterMayne at ap.spherion.com Wed Jan 12 19:21:29 2005 From: PeterMayne at ap.spherion.com (PJDM) Date: 12 Jan 2005 16:21:29 -0800 Subject: Octal notation: severe deprecation References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> Message-ID: <1105575689.335040.174490@c13g2000cwb.googlegroups.com> John Machin wrote: > > 1. Octal notation is of use to systems programmers on computers where > the number of bits in a word is a multiple of 3. Are there any still in > production use? AFAIK word sizes were 12, 24, 36, 48, and 60 bits -- > all multiples of 4, so hexadecimal could be used. The PDP-11 was 16 bit, but used octal. With eight registers and eight addressing modes in instructions, octal was a convenient base. (On the 11/70, the front switches were marked in alternate pink and purple groups of three. ) > I don't see any mention of octal in GvR's "Python Regrets" or AMK's > "PEP 3000". Why not? Is it not regretted? I suspect that, as in other places, Python just defers to the underlying implementation. Since the C libraries treat "0n" as octal, so does Python. (So does JavaScript.) More "it sucks, but it's too late to change" than regrets. Maybe P3K will have an integer literal like "n_b" for "the integer n in base b". PJDM From b_b at net.hr Mon Jan 24 11:06:52 2005 From: b_b at net.hr (Brane) Date: Mon, 24 Jan 2005 17:06:52 +0100 Subject: how to ncurses on win32 platform Message-ID: <3nkds3kzc9mp.18yfed1y3vo9d$.dlg@40tude.net> please advice regards brane From http Wed Jan 12 15:49:32 2005 From: http (Paul Rubin) Date: 12 Jan 2005 12:49:32 -0800 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> <1g4nx7m906q79$.dlg@usenet.alexanderweb.de> <7xekgr7lpy.fsf@ruckus.brouhaha.com> <7x4qhn9q3g.fsf@ruckus.brouhaha.com> <7xr7kq1rk6.fsf@ruckus.brouhaha.com> <7xvfa2toed.fsf@ruckus.brouhaha.com> Message-ID: <7xpt0a4bkz.fsf@ruckus.brouhaha.com> Ian Bicking writes: > That sounds like you'd be implementing your own filesystem ;) Yes, this shouldn't be any surprise. Implementing a special purpose file system what every database essentially does. > If you are just trying to avoid too many files in a directory, another > option is to put files in subdirectories like: > > base = struct.pack('i', hash(page_name)) > base = base.encode('base64').strip().strip('=') > filename = os.path.join(base, page_name) Using subdirectories certainly keeps directory size down, and it's a good idea for MoinMoin given the way MoinMoin uses the file system. But for really big wikis, I think using the file system like that isn't workable even with subdirectories. Plus, there's the issue of how to find backlinks and how to do full text search. From sjmachin at lexicon.net Sat Jan 15 19:42:55 2005 From: sjmachin at lexicon.net (John Machin) Date: 15 Jan 2005 16:42:55 -0800 Subject: How to del item of a list in loop? In-Reply-To: References: <34rvjqF4f6l70U1@individual.net> <34s7omF4emdsaU1@individual.net> Message-ID: <1105836175.289357.158650@z14g2000cwz.googlegroups.com> Nick Coghlan wrote: > > I think this is about the best you can do for an in-place version: > for i, x in enumerate(reversed(lst)): > if x == 2: > del lst[-i] Don't think, implement and measure. You may be surprised. Compare these two for example: !def method_del_bkwds(lst, x): ! for inx in xrange(len(lst) - 1, -1, -1): ! if lst[inx] == x: ! del lst[inx] ! return lst !def method_coghlan(lst, x): ! for i, obj in enumerate(reversed(lst)): ! if obj == x: ! del lst[-i] ! return lst > > The effbot's version is still going to be faster though: > lst = [x for x in lst if x != 2] Have you measured this? From belred at gmail.com Sun Jan 30 14:58:58 2005 From: belred at gmail.com (Bryan) Date: Sun, 30 Jan 2005 11:58:58 -0800 Subject: The next Xah-lee post contest In-Reply-To: <20050130114008.797088857.whereU@now.com> References: <20050130114008.797088857.whereU@now.com> Message-ID: Eric Pederson wrote: >>From: Arthur > > >>Not sure how Xah got himself into all this. > > > > One can easily see that Java programmers are geeks who secretly wanted to make the football team and are now trying to conform, ignoring their language's critical lack of Prolog syntax. Python coders, similarly, do not recognize that they may be violating several open source patents each time they write: "class(Object):", and both languages may become unusable when the Government changes the inheritance tax. > > Rather than throw stones or make fun, all but the closet Republicans should examine how poor Xah came to such a state of misunderstanding IPv8, and try to help him. > >>From Aahz tag line we have a clue: > > "19. A language that doesn't affect the way you think about programming,is not worth knowing." --Alan Perlis > > Further understanding will require research. Was it Perl that did this to Mr. Lee's brain, or perhaps it was trying to ascertain the web services "standard"? Was it a massive PHP program that simply grew beyond comprehendability and blew all normal circuits? Or perhaps an attempt to jump straight from Fortran 77 into Ruby? > > Perhaps we will never know the cause, but surely when the ill come to us we must prescribe something. > > Ah, perhaps if he will join us in a song we will all be OK: > > Python Choir: > Lee's a lumberjack, and he's OK, > He codes all night and he posts all day. > > XL: > I cut down trees, I eat my lunch, > I go to the lavatory. > On Wednesdays I go shopping, > And have buttered scones for tea. > > Python Choir: > Lee cuts down trees, He eats his lunch, > He goes to the lavatory. > On Wednesdays he goes shopping, > And have buttered scones for tea. > > Lees a lumberjack, and he's OK, > He codes all night and he posts all day. > > XL: > I cut down trees, I skip and jump, > I like to press wild flowers. > I put on women's clothing, > And hang around in bars. > > Python Choir: > Lee cuts down trees, he skips and jumps, > He likes to press wild flowers. > He puts on women's clothing > And hangs around.... In bars??????? > > > Well. At least I feel better. For now. > > > > /Eric - sentenced to re-learn and write an application in Perl 5.0 > What will that do to my mind? > > > http://www.songzilla.blogspot.com > ::::::::::::::::::::::::::::::::::: > domainNot="@something.com" > domainIs=domainNot.replace("s","z") > ePrefix="".join([chr(ord(x)+1) for x in "do"]) > mailMeAt=ePrefix+domainIs > ::::::::::::::::::::::::::::::::::: > oh great... now you just legend-ized him on this group forever :( From samantha7395 at hotmail.com Tue Jan 18 13:57:18 2005 From: samantha7395 at hotmail.com (Samantha) Date: Tue, 18 Jan 2005 10:57:18 -0800 Subject: Print to Windows default Printer References: Message-ID: <1e-dnYx8z5eTwXDcRVn-3g@adelphia.com> Thanks for he quick response. This is small sample code from a PSP script to get Exit Info of a digital image. I want to print to the printer rather than the screen. ------- Info = App.Do( Environment, 'ReturnImageInfo' ) print print 'Input Device Information' for key in InputDeviceKeys: if OnlyExistingData == 0 or Info[key] != '': print key, ': ', Info[key] print print 'Artist Information' for key in ArtistKeys: if OnlyExistingData == 0 or Info[key] != '': print key, ': ', Info[key] print ------ Is there an easy way to do it. Right now I copy and paste to a txt file then print the file? S "Peter Hansen" wrote in message news:v46dnZlNecChxXDcRVn-3A at powergate.ca... > Samantha wrote: >> I am new to Python and I am having considerable trouble trying to print >> (using a simple script) to the default printer rather than the screen. >> Thanks for any help. > > Please show some example code, and explain in more detail > what you are trying to do. There are perhaps *dozens* > of different ways to do printing under Windows, and we > can't guess which approach you are trying, nor which > might be suitable for your needs. > > -Peter From itoakya at yahoo.co.jp Sat Jan 8 17:12:30 2005 From: itoakya at yahoo.co.jp (AkioIto) Date: 8 Jan 2005 14:12:30 -0800 Subject: Ranting about the state of Python IDEs for Windows References: Message-ID: <1105222350.906941.83130@c13g2000cwb.googlegroups.com> Carlos Ribeiro wrote: > Oh well. A mailing list is not the most appropriate place for rants (a > blog is better), but it's still better than keeping it for myself. > > I'm frustrated. My search for a good IDE to support my activities -- > doing development for Python in the Windows environment -- are not > being succesful as I had originally dreamt. I have big constraints on > what can I do now; money is not an option, and my current machine is > still useful but it's below par for more advanced stuff. It's my > fault? Probably. But it's all that I have -- a 500MHz PC with 64MB and > Win98 SE. It has to be Windows, for reasons beyond my control (read > wife and kids :-). > Look at http://www.pspad.com/en/index.html. Very good and smart editor for Python and other languages. You even can set menu for brazillian portuguese! And it's free... "A dica vem com um certo atrazo, mas espero que seja util". From FBatista at uniFON.com.ar Mon Jan 17 12:20:13 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 17 Jan 2005 14:20:13 -0300 Subject: How to prevent the script from stopping before it should Message-ID: [python at hope.cz] #- I have a script that downloads some webpages.The problem is that, #- sometimes, after I download few pages the script hangs( stops). What do you mean with "hangs"? It raises an error and quit? It just stops doing nothing? If the latter, what prints if you hit ctrl-c? . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bulba at bulba.com Thu Jan 6 19:27:30 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 01:27:30 +0100 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <7xhdluxh4i.fsf@ruckus.brouhaha.com> Message-ID: On 06 Jan 2005 15:38:53 -0800, Paul Rubin wrote: >> Making derived work proprietary in no way implies that the base >> work is publicly unavailable anymore. >Since you want to be able to incorporate GPL code in your proprietary >products, Nope. That is not what I'm arguing. Really, I think you have jumped to conclusion about that: I merely pointed out that I don't like what I perceive as end effect of what GPL license writers are attempting to achieve: vendor lock-in. I think I stated that clearly. > and say there's no problem since the base work is still >available from the same places it was available from before, fairness >would say you shouldn't mind that people incorporate code from your >products into THEIR products, since your version is still available >from you. I merely pointed out that previous poster's argument about "hijacking" the OSS product: that it's just not possible as long as this person is not in legal position to make _base_ work proprietary. I think I stated clearly: base work is still available regardless of whatever derived work creators do or don't do - esp. that they tend to release only binaries, thus making it impossible to create further derived works! >From the viewpoint of looking at availability of source code A, it's completely irrelevant if those guys are fishmongers or make derived work A' and redistribute only binary of A'. Not a single line of publicly available source code appeared or disappeared as the result of whatever they do. Amounts of binaries - yes, that is affected. But not the source code. >Really, you're just a freeloader looking for handouts. Rest assured this is not my motivation, esp. that I attempt not to use the GPL-ed software whenever I reasonably can (e.g. it's rather hard to abstain from using gcc sometimes, as you oft have a hard time compiling this damn thing with anything else -- see, the beginnings of vendor lock-in appear). And I thought I stated clearly that basically I have no problem with LGPL - which requires distributing modifications of the _base_ work, but not _your_ code. Oh, and "freeloading" argument really doesn't make much sense: since that software is available to EVERYONE, its availability / unavailability in the economic sense it is merely reducing / increasing costs equally for everyone (ceteris paribus, assuming both vendor A and B find that OSS product equally useful). I like to think of OSS as a "tide that rises all boats". -- It's a man's life in a Python Programming Association. From aisaac0 at verizon.net Sat Jan 22 22:07:22 2005 From: aisaac0 at verizon.net (David Isaac) Date: Sun, 23 Jan 2005 03:07:22 GMT Subject: problems with duplicating and slicing an array References: <7cffadfa05012017337858d171@mail.gmail.com> <1106325711.782439.305360@c13g2000cwb.googlegroups.com> Message-ID: Yun Mao wrote: >a[ [1,0], [0,1] ] , which should give me >[[4, 5], [1,2]] Numeric: take(take(a,[1,0]),[0,1],1) fwiw, Alan Isaac From timr at probo.com Sat Jan 15 02:55:57 2005 From: timr at probo.com (Tim Roberts) Date: Fri, 14 Jan 2005 23:55:57 -0800 Subject: from __future__ import decorators References: Message-ID: Jacek Generowicz wrote: > >I have some code, which makes copious use of the @decorator syntax I'm very curious to know what kind of application you are writing in which "copious use of the @decorator syntax" actually solved a problem productively. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steven.bethard at gmail.com Sat Jan 1 20:04:06 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 02 Jan 2005 01:04:06 GMT Subject: PEP 288 ponderings Message-ID: PEP 288 was mentioned in one of the lambda threads and so I ended up reading it for the first time recently. I definitely don't like the idea of a magical __self__ variable that isn't declared anywhere. It also seemed to me like generator attributes don't really solve the problem very cleanly. An example from the PEP[1]: def mygen(): while True: print __self__.data yield None g = mygen() g.data = 1 g.next() # prints 1 g.data = 2 g.next() # prints 2 I looked in the archives but couldn't find a good discussion of why setting an attribute on the generator is preferable to passing the argument to next. Isn't this example basically equivalent to: class mygen(object): def next(self, data): print data return None g = mygen() g.next(1) # prints 1 g.next(2) # prints 2 Note that I didn't even define an __iter__ method since it's never used in the example. Another example from the PEP: def filelike(packagename, appendOrOverwrite): data = [] if appendOrOverwrite == 'w+': data.extend(packages[packagename]) try: while True: data.append(__self__.dat) yield None except FlushStream: packages[packagename] = data ostream = filelike('mydest','w') ostream.dat = firstdat; ostream.next() ostream.dat = firstdat; ostream.next() ostream.throw(FlushStream) This could be rewritten as: class filelike(object): def __init__(self, packagename, appendOrOverwrite): self.data = [] if appendOrOverwrite == 'w+': self.data.extend(packages[packagename]) def next(self, dat): self.data.append(dat) return None def close(self): packages[packagename] = self.data ostream = filelike('mydest','w') ostream.next(firstdat) ostream.next(firstdat) ostream.close() So, I guess I have two questions: (1) What's the benefit of the generator versions of these functions over the class-based versions? (2) Since in all the examples there's a one-to-one correlation between setting a generator attribute and calling the generator's next function, aren't these generator attribute assignments basically just trying to define the 'next' parameter list? If this is true, I would have expected that a more useful idiom would look something like: def mygen(): while True: data, = nextargs() print data yield None g = mygen() g.next(1) # prints 1 g.next(2) # prints 2 where the nextargs function retrieves the arguments of the most recent call to the generator's next function. With a little sys._getframe hack, you can basically get this behavior now: py> class gen(object): ... def __init__(self, gen): ... self.gen = gen ... def __iter__(self): ... return self ... def next(self, *args): ... return self.gen.next() ... @staticmethod ... def nextargs(): ... return sys._getframe(2).f_locals['args'] ... py> def mygen(): ... while True: ... data, = gen.nextargs() ... print data ... yield None ... py> g = gen(mygen()) py> g.next(1) 1 py> g.next(2) 2 Of course, it's still a little magical, but I think I like it a little better because you can see, looking only at 'mygen', when 'data' is likely to change value... Steve [1] http://www.python.org/peps/pep-0288.html From http Thu Jan 6 10:32:25 2005 From: http (Paul Rubin) Date: 06 Jan 2005 07:32:25 -0800 Subject: Embedding a restricted python interpreter References: Message-ID: <7xbrc2a7zq.fsf@ruckus.brouhaha.com> Jp Calderone writes: > A Python sandbox would be useful, but the hosting provider's excuse > for not allowing you to use mod_python is completely bogus. All the > necessary security tools for that situation are provided by the > platform in the form of process and user separation. But mod_python is an apache module and runs in the same apache process with other users' scripts. From JoshuaACohen at gmail.com Thu Jan 6 15:57:29 2005 From: JoshuaACohen at gmail.com (Josh) Date: 6 Jan 2005 12:57:29 -0800 Subject: File Handling Problems Python I/O In-Reply-To: <1105044049.815913.17830@z14g2000cwz.googlegroups.com> References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> <1105034789.700445.291380@z14g2000cwz.googlegroups.com> <1105043692.497106.315270@z14g2000cwz.googlegroups.com> <1105044049.815913.17830@z14g2000cwz.googlegroups.com> Message-ID: <1105045049.653794.96490@z14g2000cwz.googlegroups.com> Micheal, Thanks for the advice as the programming I am doing will be run on both Windows and Linux based PC's, that being the main reason for my venture into Python. I'm glad to see that people are willing to help out even the newbie's. Josh From jdhunter at ace.bsd.uchicago.edu Fri Jan 28 18:00:23 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 28 Jan 2005 17:00:23 -0600 Subject: LinearAlgebra incredibly slow for eigenvalue problems In-Reply-To: <1106952951.834888.65430@f14g2000cwb.googlegroups.com> ("drife"'s message of "28 Jan 2005 14:55:51 -0800") References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> <1106952951.834888.65430@f14g2000cwb.googlegroups.com> Message-ID: >>>>> "drife" == drife writes: drife> Hi David, I performed the above check, and sure enough, drife> Numeric is --not-- linked to the ATLAS libraries. drife> I followed each of your steps outlined above, and Numeric drife> still is not linking to the ATLAS libraries. drife> My setup.py file is attached below. Are you sure that you 1) 'rm -rf build' before rebuilding 2) are using the python / Numeric that you think you are, eg, might you have one python in /usr/bin and another in /usr/local. root paths can differ from user paths which may effect which python is used at install time versus run time From daranrife at yahoo.com Tue Jan 11 17:15:44 2005 From: daranrife at yahoo.com (drife) Date: 11 Jan 2005 14:15:44 -0800 Subject: Rotation of eigenvector matrix using the varimax method Message-ID: <1105481744.502108.19930@f14g2000cwb.googlegroups.com> Hello, Has anyone a Python script for rotating an eigenvector matrix using the varimax (or quartimax or other) methods? Thanks in advance for your help. Daran From "j.p.t.j.berends\" at (none)student.tudelft.nl Wed Jan 5 10:59:11 2005 From: "j.p.t.j.berends\" at (none)student.tudelft.nl (none) Date: Wed, 05 Jan 2005 16:59:11 +0100 Subject: get the IP address of a host Message-ID: I want to determine the outside (non local, a.k.a. 127.0.0.x) ip addresses of my host. It seems that the socket module provides me with some nifty tools for that but I cannot get it to work correctly it seems. Can someone enlightened show a light on this: import socket def getipaddr(hostname='default'): """Given a hostname, perform a standard (forward) lookup and return a list of IP addresses for that host.""" if hostname == 'default': hostname = socket.gethostname() ips = socket.gethostbyname_ex(hostname)[2] return [i for i in ips if i.split('.')[0] != '127'][0] It does not seem to work on all hosts. Sometimes socket.gethostbyname_ex only retrieves the 127.0.0.x ip adresses of the local loopback. Does someone has a more robust solution? Targetted OS'es are Windows AND linux/unix. From hancock at anansispaceworks.com Mon Jan 24 18:01:33 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 24 Jan 2005 17:01:33 -0600 Subject: Looking for Form Feeds In-Reply-To: <41F5696D.9030100@novasyshealth.com> References: <41F5696D.9030100@novasyshealth.com> Message-ID: <200501241701.33232.hancock@anansispaceworks.com> On Monday 24 January 2005 03:32 pm, Greg Lindstrom wrote: > I also tried to create a ^M^L (typed in as Q M L) but that > gives me a syntax error when I try to run the program (re does not like > the control characters, I guess). Is it possible for me to pull out the > formfeeds in a straightforward manner? I suspect you should convert that to hexadecimal codes: '\x0c\x0b' (at least I *think* those are the characters you mean, I'm not really familiar with the ^X notation). That would be the simplest solution, probably. Anytime I get into unprintable characters, I like to switch to hex. So you could just do something like: pages = open('myfile.dat', 'rb').read().split('\x0c\x0b') to load each page into a list, for example. HTH, Terry -- -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From kent3737 at yahoo.com Thu Jan 20 09:01:01 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Thu, 20 Jan 2005 09:01:01 -0500 Subject: xml parsing escape characters In-Reply-To: <359o5cF4il48kU1@individual.net> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> Message-ID: <41efb72d$1_2@newspeer2.tds.net> Luis P. Mendes wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > this is the xml document: > > > <DataSet> > ~ <Order> > ~ <Customer>439</Customer> > (... others ...) > ~ </Order> > </DataSet> This is an XML document containing a single tag, , whose content is text containing entity-escaped XML. This is *not* an XML document containing tags , , , etc. All the behaviour you are seeing is a consequence of this. You need to unescape the contents of the tag to be able to treat it as structured XML. Kent From abpillai at gmail.com Thu Jan 6 05:22:41 2005 From: abpillai at gmail.com (Anand) Date: 6 Jan 2005 02:22:41 -0800 Subject: Contributor's List In-Reply-To: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> References: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> Message-ID: <1105006961.413793.40760@c13g2000cwb.googlegroups.com> Please direct any query to the Cookbook editors. Thanks -Anand From kent3737 at yahoo.com Tue Jan 25 15:40:13 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Tue, 25 Jan 2005 15:40:13 -0500 Subject: Help with saving and restoring program state In-Reply-To: <85b54e91.0501241556.d281f90@posting.google.com> References: <85b54e91.0501241556.d281f90@posting.google.com> Message-ID: <41f6ac25$1_3@newspeer2.tds.net> Jacob H wrote: > Hello list... > > I'm developing an adventure game in Python (which of course is lots of > fun). One of the features is the ability to save games and restore the > saves later. I'm using the pickle module to implement this. Capturing > current program state and neatly replacing it later is proving to be > trickier than I first imagined, so I'm here to ask for a little > direction from wiser minds than mine! > > When my program initializes, each game object is stored in two places > -- the defining module, and in a list in another module. The following > example is not from my actual code, but what happens is the same. > > (code contained in "globalstate" module) > all_fruit = [] > > (code contained in "world" module) > class Apple(object): # the class hierarchy goes back to object, anyway > def __init__(self): > self.foo = 23 > self.bar = "something" > globalstate.all_fruit.append(self) > apple = Apple() > > I enjoy the convenience of being able to refer to the same apple > instance through world.apple or globalstate.all_fruit, the latter > coming into play when I write for loops and so on. When I update the > instance attributes in one place, the changes are reflected in the > other place. But now comes the save and restore game functions, which > again are simplified from my real code: My understanding of pickle is that it will correctly handle shared references in the saved data. So if you pack all your global dicts into one list and pickle that list, you will get what you want. See code changes below: > > (code contained in "saveload" module) > import pickle > import world import globalstate > def savegame(path_to_name): > world_data = {} > for attr, value in world.__dict__.items(): > # actual code is selective about which attributes > # from world it takes -- I'm just keeping this > # example simple > world_data[attr] = value the_whole_shebang = [ world_data, globalstate.all_fruit, globalstate.all_items ] > fp = open(path_to_name, "w") pickle.dump(the_whole_shebang, fp) > fp.close() > > def loadgame(path_to_name): > fp = open(path_to_name, "r") the_whole_shebang = pickle.load(fp) world_data, globalstate.all_fruit, globalstate.all_items = the_whole_shebang > for attr, value in world_data.items(): > setattr(world, attr, value) > fp.close() Kent From rkern at ucsd.edu Mon Jan 31 02:12:06 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 30 Jan 2005 23:12:06 -0800 Subject: Image stats - going from Matlab to Python In-Reply-To: <1107153660.431217.145160@f14g2000cwb.googlegroups.com> References: <1107153660.431217.145160@f14g2000cwb.googlegroups.com> Message-ID: tjv at hotmail.com wrote: > Hi all, > I am working with images in python using PIL. I come from a MATLAB > background so I am finding it to be sometimes frustrating to do things > correctly and quickly. Yup. That's the curse of changing toolsets. > All I need to do is load an image and store a > list of pixel coordinates at which the alpha channel is set to 1. > In Matlab this would be easy...Lets say we have a 2x2x4 array that > represents the image. I would just type something like: > > indices = find(im(:,:,3)==1); > > then work with indices to get xy coords. Is there a similar way to > accomplish the same thing in python and PIL without having a nested for > loop and checking every pixel? > I would appreciate advice. Thanks very much for your attention! One way would be to use Numeric or numarray, which you will probably want anyway if you are doing Matlab-type stuff. If you are dealing with large images or are dealing with raw data on disk (as opposed to PNGs or GIFs), numarray might be best for you. A mildly tested example: import Numeric as N import Image filename = 'heavy_1.gif' img = Image.open(filename).convert('RGBA') data = img.tostring() arr = N.fromstring(data, N.UInt8) arr.shape = (img.size[1], img.size[0], 4) mask = (arr[:,:,3] == 255).flat idx = N.indices(arr.shape[:2]) idx.shape = (2, len(mask)) pixels = N.compress(idx, mask) # for all i, arr[pixels[0,i], pixels[1,i], 3] == 255 I'm sure there's some code floating around that makes these kinds of operations simpler. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From kartic.krishnamurthy at gmail.com Wed Jan 5 11:48:02 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 5 Jan 2005 08:48:02 -0800 Subject: Image capture In-Reply-To: References: <1104939479.011181.147650@f14g2000cwb.googlegroups.com> Message-ID: <1104943682.530470.113770@f14g2000cwb.googlegroups.com> Hi Catalin, Here are the modifications to your code. I am emailing you the complete file back to your email address. Please note that you need PIL (Python Imaging Library) to grab the window. I included a step to save the image, but you can do whatever you want with it. Thanks, --Kartic -------------- Unified Diff --------------- --- Catalin.txt Wed Jan 05 11:43:38 2005 +++ frmDesign.py Wed Jan 05 11:43:17 2005 @@ -1,7 +1,7 @@ from wxPython.wx import * from wxPython.grid import * from win32api import SendMessage -import win32ui +import win32ui, win32gui, ImageGrab WM_PAINT = 0xf WM_PRINT = 0x317 @@ -47,6 +47,10 @@ dc = wxMemoryDC() dc.SelectObject(bmp) dc.Clear() + win_sz = win32gui.GetWindowRect(self.grd.GetHandle()) + print win_sz + im = ImageGrab.grab((win_sz[0],win_sz[1],win_sz[2],win_sz[3])) + im.save('C:/TEMP/grid.jpg') SendMessage(self.grd.GetHandle(), WM_PAINT, dc.GetHDC(), 0) SendMessage(self.grd.GetHandle(), WM_PRINT, dc.GetHDC(), PRF_CHILDREN|PRF_CLIENT|PRF_OWNED) From stephen.thorne at gmail.com Sat Jan 29 10:11:32 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Sun, 30 Jan 2005 01:11:32 +1000 Subject: limited python virtual machine In-Reply-To: <16891.41849.882856.527798@montanaro.dyndns.org> References: <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> <16891.41849.882856.527798@montanaro.dyndns.org> Message-ID: <3e8ca5c805012907114062470c@mail.gmail.com> On Sat, 29 Jan 2005 08:53:45 -0600, Skip Montanaro wrote: > > >> One thing my company has done is written a ``safe_eval()`` that uses > >> a regex to disable double-underscore access. > > Alex> will the regex catch getattr(object, > Alex> 'subclasses'.join(['_'*2]*2)...?-) > > Now he has two problems. ;-) I nearly asked that question, then I realised that 'getattr' is quite easy to remove from the global namespace for the code in question, and assumed that they had already thought of that. Stephen. From fredrik at pythonware.com Wed Jan 19 16:10:05 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 19 Jan 2005 22:10:05 +0100 Subject: a question References: <797fe3d405011912511a609c1c@mail.gmail.com> Message-ID: Bill Mill wrote: > You've got a couple problems. First, you need to end the string before > putting a continuation in. >>> "no\ ... pe" 'nope' >>> "however\ File "", line 1 "however\ ^ SyntaxError: EOL while scanning single-quoted string (in the second case, the ^ is trying to point out that I added some whitespace after the backslash) From a at a.invalid Thu Jan 6 05:11:49 2005 From: a at a.invalid (Timo Virkkala) Date: Thu, 06 Jan 2005 10:11:49 GMT Subject: Why tuples use parentheses ()'s instead of something else like <>'s? In-Reply-To: <1104356661.326757.84590@f14g2000cwb.googlegroups.com> References: <1104299822.394489.161500@z14g2000cwz.googlegroups.com> <1gpjrru.wgin5135kfkvN%aleaxit@yahoo.com> <1104356661.326757.84590@f14g2000cwb.googlegroups.com> Message-ID: seberino at spawar.navy.mil wrote: > I can't thank you enough for your reply and for everyones' great info > on this thread. The end of your email gave a rock solid reason why it > is impossible to improve upon ()'s for tuples.... Actually, you missed the point. The parentheses don't have anything to do with the tuple. They are just used for disambiguation. It's the commas that define the tuple. -- Timo Virkkala From elbertlev at hotmail.com Mon Jan 24 23:40:03 2005 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: 24 Jan 2005 20:40:03 -0800 Subject: smtplib bug with Windows XP In-Reply-To: References: <1106614880.586616.19780@f14g2000cwb.googlegroups.com> Message-ID: <1106628003.054231.139170@z14g2000cwz.googlegroups.com> > Try manually, but think about these options: a firewall that > has suddenly been enabled, an SMTP server that now requires > authentication, some kind of proxy like what virus scanners > use (though why they would intercept outgoing mail I don't > know)... > > -Peter I bet it was the firewall on XP. From noreply at python.org Wed Jan 19 03:18:37 2005 From: noreply at python.org (Mail Administrator) Date: Wed, 19 Jan 2005 09:18:37 +0100 Subject: MDaemon Warning - virus found: Delivery reports about your e-mail Message-ID: <20050119081921.627281E4004@bag.python.org> ******************************* WARNING ****************************** Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado un fichero anexo(s) infectado(s). Por favor revise el reporte de abajo. Attachment Virus name Action taken ---------------------------------------------------------------------- message.pif I-Worm.Mydoom.m Removed ********************************************************************** This message was undeliverable due to the following reason: Your message could not be delivered because the destination computer was unreachable within the allowed queue period. The amount of time a message is queued before it is returned depends on local configura- tion parameters. Most likely there is a network problem that prevented delivery, but it is also possible that the computer is turned off, or does not have a mail system running right now. Your message could not be delivered within 3 days: Server 127.15.40.10 is not responding. The following recipients did not receive this message: Please reply to postmaster at python.org if you feel this message to be in error. From cam.ac.uk at mh391.invalid Fri Jan 14 06:16:59 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 14 Jan 2005 11:16:59 +0000 Subject: Python.org, Website of Satan In-Reply-To: References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: Peter Renzland wrote: > What is the simplest/fastest Python program to determine how many > IP addresses sum up to 666? > > The simplest/fastest enumerator? > > The simplest/fastest that determines which ones of them are home pages? This seems to work although it could be made more efficient or elegant. Also, the failed gethostbyaddr() calls take forever. from socket import gethostbyaddr, herror for a in xrange(256): if a < 666-255*3: continue for b in xrange(256): if a+b < 666-255*2: continue for c in xrange(256): if a+b+c < 666-255: continue for d in xrange(256): if a + b + c + d == 666: ip_address = "%d.%d.%d.%d" % (a, b, c, d) try: hostname, aliaslist, ipaddrlist = gethostbyaddr(ip_address) except herror: hostname = "NONE" print hostname, ip_address break -- Michael Hoffman From bulba at bulba.com Sun Jan 2 12:15:36 2005 From: bulba at bulba.com (Bulba!) Date: Sun, 02 Jan 2005 18:15:36 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: On Sat, 01 Jan 2005 13:28:16 -0600, "Rob Emmons" wrote: >> For managers of companies it's worse: the company makes >> VERY substantial investments into any technology it "marries", >> and that means big losses if it goes. Long-term stability >> of this technology in terms of "we're not going to be left out >> in cold alone with this technology to feed it" means a lot >> to them. Even a poor technology with external backing >> of big, stable vendor is better than the excellent technology >> without ...... >There is the stability issue you mention... but also probably the fear >issue. If you choose a solution from a major company -- then it fails for >some reason or they drop the product -- it's their fault -- you've got an >automatic fall guy. True. I have a bit of interest in economics, so I've seen e.g. this example - why is it that foreign branches of companies tend to cluster themselves in one city or country (e.g. China right now)? According to standard economics it should not happen - what's the point of getting into this overpriced city if elsewhere in this country you can find just as good conditions for business. The point is obviously "cover your ass" attitude of managers: if this investment fails, this manager can defend himself "but everybody invested in that particular place, too, so you see, at the time it was not a bad decision, we could not predict... yadda yadda". -- It's a man's life in a Python Programming Association. From steven.bethard at gmail.com Thu Jan 13 13:28:27 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 13 Jan 2005 11:28:27 -0700 Subject: sorted (WAS: lambda) In-Reply-To: <7x7jmh1eek.fsf@ruckus.brouhaha.com> References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <7x7jmh1eek.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > > That completely depends on the objects in question. Compare > > temp = all_posters[:] > temp.sort() > top_five_posters = temp[-5:] > > to: > > top_five_posters = all_posters.sorted()[-5:] > > which became possible only when .sorted() was added to Python 2.4. I believe you mean "when sorted() was added to Python 2.4": py> ['d', 'b', 'c', 'a'].sorted() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'list' object has no attribute 'sorted' py> sorted(['d', 'b', 'c', 'a']) ['a', 'b', 'c', 'd'] Note that sorted is a builtin function, not a method of a list object. It takes any iterable and creates a sorted list from it. Basically the equivalent of: def sorted(iterable): result = list(iterable) result.sort() return result Steve From steven.bethard at gmail.com Fri Jan 7 13:17:39 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Jan 2005 11:17:39 -0700 Subject: python3: 'where' keyword In-Reply-To: <3480qqF46jprlU1@individual.net> References: <3480qqF46jprlU1@individual.net> Message-ID: Andrey Tatarinov wrote: > Hi. > > It would be great to be able to reverse usage/definition parts in > haskell-way with "where" keyword. Since Python 3 would miss lambda, that > would be extremly useful for creating readable sources. > > Usage could be something like: > > >>> res = [ f(i) for i in objects ] where: > >>> def f(x): > >>> #do something > > or > > >>> print words[3], words[5] where: > >>> words = input.split() > > - defining variables in "where" block would restrict their visibility to > one expression How often is this really necessary? Could you describe some benefits of this? I think the only time I've ever run into scoping problems is with lambda, e.g. [lambda x: f(x) for x, f in lst] instead of [lambda x, f=f: for x, f in lst] Are there other situations where you run into these kinds of problems? > - it's more easy to read sources when you know which part you can skip, > compare to > > >>> def f(x): > >>> #do something > >>> res = [ f(i) for i in objects ] > > in this case you read definition of "f" before you know something about > it usage. Hmm... This seems very heavily a matter of personal preference. I find that your where clause makes me skip the 'res' assignment to read what the 'res' block contains. I had to read it twice before I actually looked at the list comprehension. Of course, I'm sure I could be retrained to read it the right way, but until I see some real benefit from it, I'd rather not have to. TOOWTDI-ily-yrs, Steve From fccoelho at gmail.com Tue Jan 11 03:09:46 2005 From: fccoelho at gmail.com (Flavio codeco coelho) Date: 11 Jan 2005 00:09:46 -0800 Subject: Python serial data aquisition References: <41e1b833$1_3@omega.dimensional.com> Message-ID: mfuhr at fuhr.org (Michael Fuhr) wrote in message news:<41e1b833$1_3 at omega.dimensional.com>... > If the actual byte and/or bit order is different then you'll have > to modify the expression, but this should at least give you ideas. Hi Michael, It all looks pretty god but there is a couple of things I still don't understand, 1) in Steve's solution (which seems equivalent to your own), he does the masking, shifts by seven, and then sums the two numbers while you, instead of summing, use a logical or. How can these operations be equivalent? or are they? Is the logical or equivalent to a concatenation? 2) why 7? why do we have shift 7 bits? is that so the 8th bit on byte one is aligned with the first bit on the second byte? thanks: From michele.simionato at gmail.com Tue Jan 4 10:32:07 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 4 Jan 2005 07:32:07 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) In-Reply-To: References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> Message-ID: <1104852727.673212.40060@z14g2000cwz.googlegroups.com> Yep, I did the same and got confused :-/ Michele From remi at cherrypy.org Wed Jan 19 13:15:02 2005 From: remi at cherrypy.org (Remi Delon) Date: 19 Jan 2005 10:15:02 -0800 Subject: ANN: Free Trac/Subversion hosting at Python-Hosting.com Message-ID: <585c0de9.0501191015.290eb537@posting.google.com> Hello everyone, To celebrate its second anniversary, Python-Hosting.com is happy to announce that it is now offering free Trac/Subversion hosting. This offer is limited to open-source, python projects. Trac and Subversion make a great combination for project management. More information about Trac can be found here: http://www.edgewall.com/trac The free offer includes: - Your own Trac site with HTTP and HTTPS access - Your own Subversion repository with HTTP and HTTPS access - Access to trac-admin through a web interface - Access to Trac and Subversion user configuration through a web interface - Web usage statistics of your Trac site - Nightly backups of your data to external servers If you want to know more about this offer and find out how to sign up, check out the following page: http://www.python-hosting.com/freetrac Remi. From __peter__ at web.de Tue Jan 11 10:23:34 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Jan 2005 16:23:34 +0100 Subject: Importing Problem on Windows References: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> Message-ID: brolewis wrote: > I have a directory that has two files in it: > > parse.py > parser.py > > parse.py imports a function from parser.py and uses it to parse out the > needed information. On Linux, the following code works without a > problem: > > parse.py, line 1: > from parser import regexsearch > > However, when I run the same command in Windows, I get the following > error: > > ImportError: cannot import name regexsearch > Any suggestions on why this would work on Linux but not on Windows? This has nothing to do with Linux vs. Windows. Depending on sys.path and your current working directory either your own parser.py or the parser.py module in the library is imported. If you want to play it safe, rename your parser.py to myparser.py or another name that is not already used by the standard library and avoid the confusion between the two modules. If you do that, don't forget to delete the compiled module parser.pyc or parser.pyo, too. Peter From steven.bethard at gmail.com Mon Jan 24 12:56:40 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 24 Jan 2005 10:56:40 -0700 Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) Message-ID: Philippe C. Martin wrote: > class Debug_Stderr: > __m_text = '' > __m_log_text = None > __m_dbg = None > __m_refresh_count = 0 I don't see the benefit in 99.9% of cases for making class variables like this "private". If you don't want people to use them, simply use the standard convention[1] for non-public variables: class Debug_Stderr: _text = '' _log_text = None _dbg = None _refresh_count = 0 A lot of the time, it actually makes sense to make (at least some of) the attributes public, e.g.: class Debug_Stderr: text = '' log_text = None dbg = None refresh_count = 0 I don't know what all the variables in this specific example are intended to be, but it certainly seems like something like 'refresh_count' might be useful to clients of the class. Name mangling is there to keep you from accidentally hiding such an attribute in a subclass, but how often is this really a danger? Can someone give me an example of where __-mangling really solved a problem for them, where a simple leading underscore wouldn't have solved the same problem? Steve [1] http://www.python.org/peps/pep-0008.html From irmen at -nospam-remove-this-xs4all.nl Thu Jan 20 13:14:19 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Thu, 20 Jan 2005 19:14:19 +0100 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> Message-ID: <41eff4fa$0$6209$e4fe514c@news.xs4all.nl> Istvan Albert wrote: > XML with elementtree is what makes me never have think about XML again. +1 QOTW -Irmen From bokr at oz.net Tue Jan 25 03:27:44 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 25 Jan 2005 08:27:44 GMT Subject: Retrieving modification time of file class was declared in References: <1106627951.152900.135310@z14g2000cwz.googlegroups.com> Message-ID: <41f601d4.1763682581@news.oz.net> On 24 Jan 2005 20:39:11 -0800, nathan_kent_bullock at yahoo.ca wrote: >Assume I am using a class Foo. I want to find out the modification time >of the file that that class was defined in. How would I go about this? > >If I could find out the name of the file that Foo was defined in then >it is easy, I could use os.path.getmtime(), but I can't even figure >that out. > >I realize that this wouldn't be a completely accurate way to tell the >last time this class was modified because it could inherit info from >other classes, or use functions from other modules that have been >modified, etc. > >Nathan Bullock > try this for about any object you can pass to finfo: ----< finfo.py >---------------- import sys, os def finfo(obj): if not hasattr(obj, '__name__'): obj = type(obj) name = '<%s instance>'%obj.__name__ else: name = obj.__name__ if type(obj) == type(sys): # module type modname = name else: # not module type, but be class now modname = obj.__module__ mod = sys.modules[modname] if modname == '__builtin__' or repr(mod) == ""%modname: path = sys.executable else: path = vars(sys.modules[modname]).get('__file__','??') if path != '??': tmod = os.path.getmtime(path) else: tmod = '???' return name, modname, path, tmod -------------------------------- Not very tested, but seems to retrieve info. The file in question for builtins is the interpreter executable, I supposed. Ignore the "ut." here, that's just my utilities grabbag [ 0:25] C:\pywk\sovm>py24 Python 2.4b1 (#56, Nov 3 2004, 01:47:27) [GCC 3.2.3 (mingw special 20030504-1)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from ut.finfo import finfo >>> finfo(finfo) ('finfo', 'ut.finfo', 'c:\\pywk\\ut\\finfo.pyc', 1106641080) >>> import time >>> time.ctime(finfo(finfo)[-1]) 'Tue Jan 25 00:18:00 2005' HIH Regards, Bengt Richter From drjonfox at gmail.com Mon Jan 17 10:36:55 2005 From: drjonfox at gmail.com (drjonfox at gmail.com) Date: 17 Jan 2005 07:36:55 -0800 Subject: Central New Jersey PIG Meeting -- Python Interest Group In Princeton PIG/IP Message-ID: <1105976215.038859.72730@z14g2000cwz.googlegroups.com> Central New Jersey PIG Meeting -- Python Interest Group In Princeton PIG/IP PIG/IP will hold its first meeting on Jan 19, 2005 at the Lawrenceville Library (Room #3). Jon Fox will speak about Python's 2.4 release and then open discussion about Python will be encouraged. When: Wednesday, January 19, 2005 at 7:00 PM Where: Mercer County Library Lawrenceville Branch 2751 Brunswick Pike Lawrenceville, NJ 08648 882-9246 Map and directions at http://www.lugip.org/meeting/location/ For more information about this group http://python.meetup.com/156/ or email Jon Fox at drjonfox at gmail.com From strombrg at dcs.nac.uci.edu Fri Jan 21 21:10:06 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Fri, 21 Jan 2005 18:10:06 -0800 Subject: pure python code to do modular-arithmetic unit conversions? Message-ID: Is there already a pure python module that can do modular-arithmetic unit conversions, like converting a huge number of seconds into months, weeks... or a bandwidth measure into megabits/s or gigabits/s or megabytes/s or gigabytes/s, whatever's the most useful (ala df -h)? Thanks! From a at a.invalid Thu Jan 27 03:38:48 2005 From: a at a.invalid (Timo Virkkala) Date: Thu, 27 Jan 2005 08:38:48 GMT Subject: python without OO In-Reply-To: <1106798140.896125.187850@f14g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> <1106798140.896125.187850@f14g2000cwb.googlegroups.com> Message-ID: beliavsky at aol.com wrote: > I think the OO way is slightly more obscure. It's obvious what x = > reverse(x) does, but it is not clear unless you have the source code > whether x.reverse() reverses x or if it returns a reversed list. If > x.reverse() does the former, a disadvantage relative to the procedural > approach is that a function can be used in an expression. It is clearer > and more concise to write Sure, it's clear if in written code you see x = reverse(x) To me it would also be clear to see x.reverse() But what if you just see in some list that there is a reverse(sequence) function, or that a sequence has a reverse() method? To me, neither of these is clear. Do they return a new, reversed sequence or reverse in place? When creating a new API, I would probably use a convention where reverse does it in place and reversed returns a new. So, in my API, reverse(x) y = reversed(x) x.reverse() y = x.reversed() -- Timo Virkkala From a at b.c Wed Jan 5 12:22:24 2005 From: a at b.c (Doug Holton) Date: Wed, 05 Jan 2005 11:22:24 -0600 Subject: How do I make Windows Application with Python ? In-Reply-To: <1r9ydq5jsele7.1c45eb2jskpli.dlg@40tude.net> References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> <1r9ydq5jsele7.1c45eb2jskpli.dlg@40tude.net> Message-ID: BOOGIEMAN wrote: > Thanks all for very detailed answers. BTW I tried this one but it seems > that it doesn't use VS'es visual designer. Also it doesn't have "build" > option so it is basicly only usefull to higlight Python syntax. > Active Sate Komodo looks like much better choice I don't know of any python IDE with a visual designer and a build to exe option. But since you are familiar with Visual Studio and you are developing on Windows, you might check out the free SharpDevelop IDE: http://www.icsharpcode.net/OpenSource/SD/ Then unzip this boo add-in into the SharpDevelop folder under Program Files: http://coedit.net/boo/BooBinding.zip Then you can start up SharpDevelop, create a new boo project, press the green play button, and your exe will be built and executed (the one below is only 4kb in size). We are working on adding support for SharpDevelop's visual form designer soon. To show a Windows message box instead of printing to the console like you were asking earlier, you can use code like this: import System.Windows.Forms MessageBox.Show("your message") Or for a more complete windows app: import System.Drawing import System.Windows.Forms class MainForm(Form): def constructor(): self.Text = "My Window" b = Button(Text: "Click Me") b.Location = Point(100,75) b.Click += def(): MessageBox.Show("Button clicked") #or: #b.Click += OnButtonClick self.Controls.Add(b) def OnButtonClick(): MessageBox.Show("Button clicked") f = MainForm() Application.Run(f) From markscottwright at gmail.com Tue Jan 18 12:11:06 2005 From: markscottwright at gmail.com (markscottwright at gmail.com) Date: 18 Jan 2005 09:11:06 -0800 Subject: makepy crashing Message-ID: <1106068266.402828.301030@f14g2000cwb.googlegroups.com> Has anyone sucessfully run makepy and Microsoft Word Object Library (9.0)? Mine crashes under XP Pro and Python 2.4. It only seems to be word that has the problem, though. I get a dialog that says that pythonwin.exe has crashed: AppName: pythonwin.exe AppVer: 0.0.0.0 ModName: ntdll.dll ModVer: 5.1.2600.1217 Offset: 000096f9 From fredrik at pythonware.com Mon Jan 31 11:41:50 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 31 Jan 2005 17:41:50 +0100 Subject: import doesn't work as i want References: <41fe5438$0$18865$8fcfb975@news.wanadoo.fr> <41fe5cfd$0$6597$8fcfb975@news.wanadoo.fr> Message-ID: Olivier Noblanc wrote: > how to move in function ? how to put code in a function? the same way you put code in a method. change if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() frame_1 = MyFrame(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() #startb = time.time() - starta #print startb app.MainLoop() to def main(): app = wx.PySimpleApp(0) wx.InitAllImageHandlers() frame_1 = MyFrame(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() #startb = time.time() - starta #print startb app.MainLoop() and call it from your main program: import inc.wxgrid inc.wxgrid.main() if you have trouble sorting out the imports, this might help: http://docs.python.org/ref/import.html http://www.python.org/doc/essays/packages.html http://effbot.org/zone/import-confusion.htm From snacktime at gmail.com Wed Jan 26 14:55:43 2005 From: snacktime at gmail.com (snacktime) Date: Wed, 26 Jan 2005 11:55:43 -0800 Subject: Set parity of a string In-Reply-To: <1f060c4c05012611503090c261@mail.gmail.com> References: <1f060c4c05012611503090c261@mail.gmail.com> Message-ID: <1f060c4c05012611554f727d29@mail.gmail.com> Correction on this, ETX is ok, it seems to be just STX with the data I am using. Chris On Wed, 26 Jan 2005 11:50:46 -0800, snacktime wrote: > I'm trying to figure out why the following code transforms ascii STX > (control-b) into "\x82". The perl module I use returns a value of > "^B", and that is also what the application I am communicating with > expects to see. Some ascii characters such as FS and GS come through > fine, but STX and ETX get transformed incorrectly (at least for what I > need they do). From http Sun Jan 9 06:42:36 2005 From: http (Paul Rubin) Date: 09 Jan 2005 03:42:36 -0800 Subject: Old Paranoia Game in Python References: <2005010903390916807%spk00@coxnet> Message-ID: <7x3bxau8ur.fsf@ruckus.brouhaha.com> Oh cool, I sort of remember that game from back in the day. I didn't play it very much so never got very far in it. I'll have to try your version. From rschroev_nospam_ml at fastmail.fm Thu Jan 6 10:44:03 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 06 Jan 2005 15:44:03 GMT Subject: The Industry choice In-Reply-To: <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> Message-ID: <71dDd.21829$En7.1635461@phobos.telenet-ops.be> Alex Martelli wrote: > Roel Schroeven wrote: > > >>Can you point to closed-source licenses that allow using the code *at >>all*? > > > As I recall, for example, Microsoft Visual C++ came with sources for > various libraries; all that the (closed-source) license for those > libraries forbade you from doing was to further distribute the _sources_ > themselves. You could do modifications big or small to those libraries > for whatever purposes, and redistribute the _compiled_ form of the code > as a DLL, or statically linked into your own programs, etc, etc. > > Is this what you mean by "allow using the code *at all*"? I think it's > a pretty common arrangement when the code being sold under closed-source > terms is a set of libraries, or a development system part of whose value > is a set of accompanying libraries. OK, I've been bitten by my exageration. There are indeed special cases such as some libraries. I was thinking more of end-user packages: if you somehow could lay your hands on the source code of Visual Studio itself, you're still not allowed to do anything with it. -- "Codito ergo sum" Roel Schroeven From skip at pobox.com Fri Jan 7 14:24:27 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 7 Jan 2005 13:24:27 -0600 Subject: Notification of PEP Updates In-Reply-To: <41DEC6C2.8030904@iinet.net.au> References: <41DEC6C2.8030904@iinet.net.au> Message-ID: <16862.57835.38948.120076@montanaro.dyndns.org> Nick> Let us know if it does anything odd (e.g. sending updates about Nick> other checkins) Note that the lone criterion for inclusion is the word "PEP" in the subject or the first few lines of the message. You might thus see the occasional checkin message that mentions "PEP" but isn't directly about a PEP. Nick> I believe the mail you receive should contain the checkin Nick> messages, along with a summary of the differences between the old Nick> version and the new version (handy if you can read a context diff, Nick> not so handy otherwise). I believe all the checkin messages come out as unified diffs these days, so they are a bit easier to read. Skip From eugene at boardkulture.com Sat Jan 29 07:17:37 2005 From: eugene at boardkulture.com (EuGeNe) Date: Sat, 29 Jan 2005 13:17:37 +0100 Subject: An mysql-python tutorial? In-Reply-To: References: Message-ID: Dfenestr8 wrote: > Hi. > > Been told by the admin of my (free!) server that he'd rather I should > learn to use mysql if I want to continue writing cgi scripts there. > > Not even sure exactly what mysql is. > > Is there a simple tutorial anywhere on the web about using python + mysql? http://www.devshed.com/c/a/Python/MySQL-Connectivity-With-Python/ that one put me on the right track (I think ;) -- EuGeNe [---- www.boardkulture.com www.actiphot.com www.xsbar.com ----] From ncoghlan at iinet.net.au Sun Jan 16 06:20:28 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 16 Jan 2005 21:20:28 +1000 Subject: generator expressions: performance anomaly? In-Reply-To: <1105854381.117059.59940@c13g2000cwb.googlegroups.com> References: <1105854381.117059.59940@c13g2000cwb.googlegroups.com> Message-ID: <41EA4DFC.1010301@iinet.net.au> John Machin wrote: > Background: There was/is a very recent thread about ways of removing > all instances of x from a list. /F proposed a list comprehension to > build the result list. Given a requirement to mutate the original list, > this necessitates the assignment to lst[:]. I tried a generator > expression as well. However while the listcomp stayed competitive up to > a million-element list, the genexp went into outer space, taking about > 20 times as long. The above timeit runs show a simpler scenario where > the genexp also seems to be going quadratic. > Comments, clues, ... please. Py> lc = [x for x in range(100)] Py> len(lc) 100 Py> ge = (x for x in range(100)) Py> len(ge) Traceback (most recent call last): File "", line 1, in ? TypeError: len() of unsized object It would be nice if unconditional ge's with known length inputs propagated __len__, but that is not currently the case. There's a similar performance glitch associated with constructing a tuple from a generator expression (with vanilla 2.4, detouring via list is actually faster) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From craig at postnewspapers.com.au Sat Jan 22 05:17:10 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 22 Jan 2005 18:17:10 +0800 Subject: need help on need help on generator... In-Reply-To: <1106387175.4103.16.camel@albert.localnet> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> <1106387175.4103.16.camel@albert.localnet> Message-ID: <1106389030.4103.21.camel@albert.localnet> On Sat, 2005-01-22 at 17:46 +0800, I wrote: > I'd be interested to know if there's a better solution to this than: > > .>>> inpath = '/tmp/msg.eml' > .>>> infile = open(inpath) > .>>> initer = iter(infile) > .>>> headers = [] > .>>> for line in initer: > .... if not line.strip(): > .... break > .... headers.append(tuple(line.split(':',1))) > .>>> data = ''.join(x for x in initer) > > because that seems like a pretty ugly hack (and please ignore the > variable names). Perhaps a way to get the file to seek back to the point > last read from the iterator when the iterator is destroyed? And now, answering my own question (sorry): Answer: http://tinyurl.com/6avdt so we can slightly simplify the above to: .>>> inpath = '/tmp/msg.eml' .>>> infile = open(inpath) .>>> headers = [] .>>> for line in infile: .... if not line.strip(): .... break .... headers.append(tuple(line.split(':',1))) .>>> data = ''.join(x for x in infile) at the cost of making it less clear what's going on and having someone later go "duh, why isn't he using read() here instead" but can't seem to do much more than that. Might it be worth providing a way to have file objects seek back to the current position of the iterator when read() etc are called? If not, I favour the suggestion in the referenced post - file should probably fail noisily, or at least emit a warning. What are others thoughts on this? -- Craig Ringer From nightmarch at gmail.com Tue Jan 25 22:06:51 2005 From: nightmarch at gmail.com (nightmarch) Date: Wed, 26 Jan 2005 11:06:51 +0800 Subject: I want update one record using ADO,but I can't ,why? In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E3398297@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E3398297@exchange.hqamor.amorhq.net> Message-ID: <31d9b15c05012519066a3dceca@mail.gmail.com> Sorry, I mean this code line " rs.Supports( wc.constants.adUpdate ) " got False result, So I can't update one record,i.e. I can't execute this code "rs.Fields.Item(0).Value = 11". And , if code is written like this: ##code------------------------- I got error msg like following: ##errorMsg---------------------------- On Tue, 25 Jan 2005 10:25:00 -0800, Robert Brewer wrote: > nightmarch wrote: > > I want update one record ,but I can't ,why? > > > > code like following: > > > > ##------------------------------------------------- > > import win32com.client as wc > > > > def main(): > > conn = wc.Dispatch(r'ADODB.Connection') > > rs = wc.Dispatch(r'ADODB.Recordset') > > connStr = "Provider=MSDAORA.1;Password=jmpower;User > > ID=jmpower;Data Source=jmgis_agps3;Persist Security Info=True" > > tblName = r'wjtmp' > > > > conn.Open(connStr ) > > > > rs.Open( tblName, conn, wc.constants.adOpenKeyset, > > wc.constants.adLockOptimistic ) > > > > if rs.Supports( wc.constants.adUpdate ): > > rs.Fields.Item(0).Value = 11 > > rs.Update() > > else: > > print "recordset can't update" > > > > rs.Close() > > conn.Close() > > > > if __name__ == '__main__': > > main() > > ##------------------------------------------------- > > You almost give us enough information to help out ,but you don't quite > ,why? > > What happens when you run the above? Is there any output? Error message? > > Does your update affect the membership of the record in the keyset? > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/ > htm/mdconkeysetcursors.asp > > Why are you using keysets at all? > > > Robert Brewer > MIS > Amor Ministries > fumanchu at amor.org > From duncan.booth at invalid.invalid Fri Jan 28 10:22:05 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Jan 2005 15:22:05 GMT Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> <7x3bwlsqnj.fsf@ruckus.brouhaha.com> <7x8y6diu6k.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > The Cookie issue is discussed some in that bug thread. But more > relevant is bug 471893. Sorry. Thanks. There's an interesting comment in that thread: A.M. Kuchling (akuchling) wrote: > Date: 2003-02-06 09:29 > > The Cookie classes that use pickle have DeprecationWarnings in > 2.3, and should disappear in 2.4. Its a real pity that nobody seems to have remembered to actually remove them. >> I think its a bit borderline whether this really was a security bug in >> Python rather than just a problem with the way some people used Python. > > If using a module the way it's documented results in a security hole, > that's definitely a security bug. > > If using the module in an obvious and natural way that looks correct > results in a security hole, I'd say it's at least an issue needing > attention, even if some sufficiently hairsplitting reading of the > documentation says that usage is incorrect. Principle of least > astonishment. Agreed. Principle of least astonishment is definitely good. From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Tue Jan 11 17:50:23 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Tue, 11 Jan 2005 23:50:23 +0100 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <41e41633$1@nntp0.pdx.net> Message-ID: <41e458a9$0$7090$8fcfb975@news.wanadoo.fr> Hi ! >>> It is a least-common-denominator argument, not a "this is better" argument. I understand, but I have a feeling of attempt at hegemony. Is english language really least-common-denominator for a russian who writes into cyrillic, or not anglophone chinese? And, did you think of klingons? ;-) Michel Claveau From http Sun Jan 9 06:10:15 2005 From: http (Paul Rubin) Date: 09 Jan 2005 03:10:15 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> Message-ID: <7xr7ku26zs.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > Trying to push it a level further (down to expressions) would, IMO, be > a lot of effort for something which would hurt readability a lot. I think we should just try to do things in a simple and general way and not try to enforce readability. For example, the slightly-overcomplex code that I proposed might have been generated by a macro, or even by a compiler from some other language. No human would ever have to look at it, so it doesn't matter whether it's easily readable. There's no reason to add needless constraints on the language just to make writing ugly code difficult. The main goal should be to make writing clear code easy, not to worry about whether someone might also write ugly code. From http Tue Jan 4 22:25:12 2005 From: http (Paul Rubin) Date: 04 Jan 2005 19:25:12 -0800 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> Message-ID: <7xvfach813.fsf@ruckus.brouhaha.com> "Rob Emmons" writes: > Me personally, I believe in free software, but always talk about open > source. My answer regarding forcing people to share -- I like the GPL > -- and I am perfectly happy to have anyone who does not like the GPL > not to use any GPLed software. I don't feel compelled to share. I'd go further. It's not possible to force anyone to share, but the GPL aims to remove software from a system that instead aims to force people NOT to share. As the MPAA knows, people do want to share, and forcing them not to do so is impossible without turning the world into a police state. Maybe if Python were GPL, then Bulba wouldn't use it, but since it's not GPL, some people find themselves much less willing to contribute to it than if it were GPL. (I myself contribute bug reports and maybe small patches, but resist larger projects since there are GPL'd things that I can do instead). So catering to the wishes of Bulba and Microsoft may actually be impeding Python development. Yes, there are some people selfless enough to do long and difficult unpaid software tasks so that Bulba and Bill G can get richer by stopping people from sharing it, but others of us only want to do unpaid programming if we can make sure that the results stay available for sharing. From gandalf at geochemsource.com Wed Jan 26 02:39:42 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Wed, 26 Jan 2005 08:39:42 +0100 Subject: How to assign In-Reply-To: References: Message-ID: <41F7493E.9010100@geochemsource.com> Jan Rienyer Gadil wrote: >Sort of a newbie question: >How am i going to assign to a variable anything the user inputs on a wxTxtCtrl? > > I'm affraid you have to do it manually. I think the best solution is to use a property like this: import wx class FrameMain(wx.Frame): def __init__(self, *args,**kwargs): DEFAULT_VALUE = "Some string here" wx.Frame.__init__(self, *args,**kwargs) self.txt = wx.TextCtrl(self,value=DEFAULT_VALUE) self._value = DEFAULT_VALUE self._txt_updating = False self.txt.Bind( wx.EVT_TEXT, self.TextChanged ) self.value = "Test value" # This will set the property and the text control too def TextChanged(self,event): self._value = self.txt.GetValue() print "Property changed to %s" % self._value def _GetTextValue(self): return self._value def _SetTextValue(self,value): if not self._txt_updating: self._txt_updating = True try: self.txt.SetValue(value) finally: self._txt_updating = False value = property(_GetTextValue,_SetTextValue,'Your variable') app = wx.PySimpleApp() frame = FrameMain(None, -1, "TextValue") frame.Show(True) app.MainLoop() In this example, the frame has a property called "value" and that has the same cached value as the text in the textcontrol. From kentsin at yahoo.com Sun Jan 16 11:37:25 2005 From: kentsin at yahoo.com (kent sin) Date: Sun, 16 Jan 2005 08:37:25 -0800 (PST) Subject: iTools Message-ID: <20050116163725.83800.qmail@web40511.mail.yahoo.com> Where can I download python-itools? I found it in the python packages index but the site is not contactable. Thank you. From bulba at bulba.com Thu Jan 6 16:50:10 2005 From: bulba at bulba.com (Bulba!) Date: Thu, 06 Jan 2005 22:50:10 +0100 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> Message-ID: On Thu, 06 Jan 2005 15:44:03 GMT, Roel Schroeven wrote: >I was thinking more of end-user packages: if you somehow could lay your >hands on the source code of Visual Studio itself, you're still not >allowed to do anything with it. And why would anybody want to waste their time reading the source code of Visual Studio? ;-) No, honestly, after all most of the time what programmers learn is just API. The very point of having libraries after all is not having to learn the low-level mechs of this thing, but just using them in a push-button manner! My boss read the C-tree code. I was programming reports and other "peripheral" stuff, so I never had to do it. I was just using a subset of the C-tree functionality, and even that was a very small subset actually. Now I'm sure that B-trees used in there are a wonder of engineering - however, I simply have other goals and not enough time to learn them to appreciate that. Personally, I think that for most people the _direct_ benefits of access to source code are greatly exagerrated. I would place much, much more emphasis on indirect, derived benefits of availability of source code. Yes, you CAN read the source code. But the point is, you DON'T WANT TO. Because economically speaking, division of labor applies, and idealistically speaking, it's better to stand on the shoulders of giants. -- It's a man's life in a Python Programming Association. From ncoghlan at iinet.net.au Tue Jan 4 05:17:53 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 04 Jan 2005 20:17:53 +1000 Subject: Hlelp clean up clumpsy code In-Reply-To: References: Message-ID: <41DA6D51.40107@iinet.net.au> It's me wrote: > Another newbie question. > > There must be a cleaner way to do this in Python: > > #### section of C looking Python code #### > a = [[1,5,2], 8, 4] > a_list = {} > i = 0 > for x in a: > if isinstance(x, (int, long)): > x = [x,] > for w in [y for y in x]: > i = i + 1 > a_list[w] = i > print a_list > ##### > > The code prints what I want but it looks so "C-like". How can I make it > more Python like? Firstly, calling your dictionary "a_list" is evil. . . Secondly, explaining what you want the code to do in English is handy when asking for help cleaning up code (since we then know which features are deliberate, and which are accidental implementation artificacts). If I'm reading the code correctly, you want to flatten a data structure which may contain either substructures or actual elements. A custom generator will do nicely: Py> def flatten(seq): ... for x in seq: ... if hasattr(x, "__iter__"): ... for y in flatten(x): ... yield y ... else: ... yield x ... Py> data = [[1,5,2],8,4] Py> val_to_pos = {} Py> for i, x in enumerate(flatten(data)): ... val_to_pos[x] = i + 1 ... Py> print val_to_pos {8: 4, 1: 1, 2: 3, 4: 5, 5: 2} Not any shorter, but this version works correctly for any leaf elements which don't supply __iter__ (e.g. strings), and internal elements which do (e.g. tuples) and the depth is limited only by the maximum level of recursion. Don't try to flatten a circular structure, though :) You may not even need to write the generator, since if you have Tkinter, that already supplies a near-equivalent function: Py> from Tkinter import _flatten as flatten Py> data = [[1,5,2],8,4] Py> val_to_pos = {} Py> for i, x in enumerate(flatten(data)): ... val_to_pos[x] = i + 1 ... Py> print val_to_pos {8: 4, 1: 1, 2: 3, 4: 5, 5: 2} It even works with strings as leaf elements: Py> data = [["abc","def",2],8,"xyz"] Py> flatten(data) ('abc', 'def', 2, 8, 'xyz') Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From Noah.Richards at infineon.com Mon Jan 3 12:19:33 2005 From: Noah.Richards at infineon.com (Richards Noah (IFR LIT MET)) Date: Mon, 3 Jan 2005 12:19:33 -0500 Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: > wrote in message > news:1104750017.235937.181370 at c13g2000cwb.googlegroups.com... > > Hello All, > > I am trying to convince my client to use Python in his new product. He > > is worried about the license issues. Can somebody there to point me any > > good commercial applications developed using python ?. The licence > > clearly says Python can be used for commercial applications. Is there > > any other implications like that of GPL to make the source open ? > > Thanks for any help. > > eeykay > > "It's me" wrote in message news:mBeCd.5832$5R.1770 at newssvr21.news.prodigy.com... > Shaw-PTI (www.pti-us.com) uses Python in their software. See: > http://www.pti-us.com/pti/news/index.cfm and search "2004 PSS/E User Group > Meeting" > Begging your pardon, but a better resource would be the brochure available (http://www.pti-us.com/PTI/company/brochures/PSSE.pdf). It appears that the program was probably (originally) written in C/C++ (using MFC for the GUI), and now employs Python for adding modules and scripting support. Very interesting stuff :) From mhartl at post.harvard.edu Wed Jan 12 14:50:39 2005 From: mhartl at post.harvard.edu (Michael Hartl) Date: 12 Jan 2005 11:50:39 -0800 Subject: counting items References: Message-ID: <1105559439.538736.87370@z14g2000cwz.googlegroups.com> There's a great function called "walk" at that iterates over arbitrary data (and is recursion-proof) at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/118845 It also supplies a recursion-proof way to flatten a list. (Once you can iterate over an arbitrary sequence, the flattened version is just [element for element in walk(sequence)].) I use both functions all the time. Adding a flatten function (along with walk) to Python sounds like a good idea to me. Having used Mathematica for many years, which uses Flatten[] all over the place, I was actually quite surprised to find that Python didn't have it. Michael From BOOGIEMANPN at YAHOO.COM Mon Jan 24 11:13:44 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Mon, 24 Jan 2005 17:13:44 +0100 Subject: Python 2.1 - 2.4 differences Message-ID: I found some e-book about Python 2.1, I want to print it but just to check first if sintax of Python 2.1 is same as 2.4 ? Also does anybody know where can I download any newer Python related e-book, because there isn't any published yet in my country. From tom at dtsam.com Mon Jan 31 14:34:11 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Mon, 31 Jan 2005 13:34:11 -0600 Subject: variable declaration References: Message-ID: "Alexander Zatvornitskiy" wrote in message news:MSGID_2=3A5025=2F3.131_41fde342 at fidonet.org... > Hello All! > > I'am novice in python, and I find one very bad thing (from my point of view) in > language. There is no keyword or syntax to declare variable, like 'var' in > Pascal, or special syntax in C. It can cause very ugly errors,like this: > > epsilon=0 > S=0 > while epsilon<10: > S=S+epsilon > epselon=epsilon+1 > print S > > It will print zero, and it is not easy to find such a bug! > > Even Visual Basic have 'Option Explicit' keyword! May be, python also have such > a feature, I just don't know about it? Exactly so! Python *does* require that your variables be declared and initialized before you use them. You did that with epsilon=0 and S=0 at the top. It is unfortunate, however, that the statement epselon=epsilon+1 also declares a new variable in the wrong place at the wrong time. Such mispellings are a *common* error caught instantly in languages that require a more formal declaration procedure. Another irksome sitiuation is that while Python does enforce strict type checking, you can re-declare variables and morph them in the middle of nowhere. S = 0 # It's an Integer! S = S + 'Hello' # No can do! Strong type checking forbids this. S = 'GoodBye' # Whoops - Now it's a string! Unfortunately legal! This seemingly demolishes all the good reasons one has for wanting strict type checking. That second example is just bad programming practice and easy to avoid. The problem you point out in your code, however, hurts! Was that an I, an l or a 1 in the variable name? Hey! - I like Python a lot. But nothings perfect Thomas Bartkus From bulba at bulba.com Tue Jan 4 13:26:14 2005 From: bulba at bulba.com (Bulba!) Date: Tue, 04 Jan 2005 19:26:14 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> On Mon, 03 Jan 2005 20:16:35 -0600, "Rob Emmons" wrote: >> This "free software" (not so much OSS) notion "but you can >> hire programmers to fix it" doesn't really happen in practice, >> at least not frequently: because this company/guy remains >> ALONE with this technology, the costs are unacceptable. >This certainly is the thinking, but I is the wrong thinking in many cases. >If companies could some how take a larger view and realize that by working >together here and there -- they enable and open development model which in >the end saves them money. AHHH but that's such a hard argument because it >takes vision, time, and trust. But the vision of what? Do we have clear, detailed, unambigous vision _of the process_ or just big ideological axes to grind? I'm afraid we're close to the latter situation - even though Python is remarkably different in this area than the "free software": clean, pragmatic, effective, free to include in closed-source. If Python were GPLed, I wouldn't use it: attempting to force people to share doesn't work. >It takes a whole vision change to work in this environment -- believing in >an economy of plenty rather than an economy of scarcity. Well, I'd say that lack of interchangeability in software is a big obstacle on this road: not that there's little source code, but that it's relatively hard (read: expensive) to combine the pieces. See: http://blogs.sun.com/roller/page/bmc/20040828#the_economics_of_software IMHO this: 'The problem is that for all of the rhetoric about software becoming a "commodity", most software is still very much not a commodity: one software product is rarely completely interchangeable with another.' ...hits the nail on the head. >> It depends on definition of "rational", on definition of your or >> company's goals and on the definitions of the situations that >> are the context. >I work for a very large company -- there is an internal culture that >defines what "rational" is: (a) Rational means outsourcing and doing less >inside the company, This could be made into a very strong argument for OSS: see the OSS developers as your "outsourced team" that works for almost nothing, i.e. "if we want to win them or get them to help, maybe we should contribute our bugfixes and enhancements to them". >(b) pretty much single sourcing commerical software, >(c) releasing nothing outside the company unless there is a direct >demonstratable significant business benifit related to our core products. That doesn't seem like a good idea to me. >I could argue these are not rational in the long run, but this is >the direction of the company as far as I know. This will change -- and >someone will get a big promotion for doing it -- but it will take a lot of >time. And of course someone already got a big promotion for outsourcing >and developing the single source stratagy -- bone headed as it is. As much as people tend to hate outsourcing, it frequently _does_ increase the efficiency of the industries, see this paper: http://econpapers.hhs.se/article/fipfednep/y_3A2003_3Ai_3Asep_3Ap_3A23-33_3An_3Av.9no.3.htm -- Real world is perfectly indifferent to lies that are the foundation of leftist "thinking". From jgrahn-nntq at algonet.se Wed Jan 12 16:38:01 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 12 Jan 2005 21:38:01 GMT Subject: Locale confusion References: <1105451372.655977.165250@f14g2000cwb.googlegroups.com> Message-ID: On 11 Jan 2005 05:49:32 -0800, Serge.Orlov at gmail.com wrote: > Jorgen Grahn wrote: > [snip] > >> >> frailea> cat foo >> import locale >> print locale.getlocale() >> locale.setlocale(locale.LC_CTYPE) >> print locale.getlocale() ... >> When I run it as a script it isn't though, and the setlocale() call > does not >> appear to fall back to looking at $LANG as it's supposed to(?), so my >> LC_CTYPE remains in the POSIX locale: ... >> So, is this my fault or Python's? I realize I could just adapt and > set >> $LC_CTYPE explicitly in my environment, but I don't want to > capitulate for a >> Python bug, if that's what this is. > > Try locale.setlocale(locale.LC_CTYPE,"") as in your C program. Oops, you are right. locale.setlocale(locale.LC_CTYPE,"") sets the locale from my environment (and gets it right!) while locale.setlocale(locale.LC_CTYPE) /returns/ the current locale. I don't know how I could have missed that, since it's clearly documented and also maps directly to C usage. > It would > be great if locale.setlocale with one parameter would be deprecated, > because it suddenly acts like getlocale. It's unpythonic. I dislike the term "unpythonic", but I tend to agree with you in practice here. Even better, but maybe not feasible, would be an approach to locales which doesn't involve changing a global state in this fashion. > By the way, since you took time to setup various LC_* variables there > is no need to play with LC_CTYPE category. Just use the standard idiom. > import locale > locale.setlocale(LC_ALL,"") Thanks for pointing that out. I picked out LC_CTYPE for my small program because I was in a hurry and didn't want to risk non-standard sorting elsewhere in the program. I hate what the LC_COLLATE=C does to swedish national characters, but I hate what LC_COLLATE=sv_SE does to non-alphabetic characters even more. To paraphrase Barbie: "i18n is hard". ;-) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From spam-trap-095 at at-andros.demon.co.uk Sun Jan 23 15:00:29 2005 From: spam-trap-095 at at-andros.demon.co.uk (Andrew McLean) Date: Sun, 23 Jan 2005 20:00:29 +0000 Subject: Fuzzy matching of postal addresses [1/1] References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: In case anyone is interested, here is the latest. I implemented an edit distance technique based on tokens. This incorporated a number of the ideas discussed in the thread. It works pretty well on my data. I'm getting about 95% matching now, compared with 90% for the simple technique I originally tried. So I have matched half the outstanding cases. I have spotted very few false positives, and very few cases where I could make a match manually. Although I suspect the code could still be improved. It took a bit of head scratching to work out how to incorporate concatenation of tokens into the dynamic programming method, but I think I got there! At least my test cases seem to work! -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: MinEditDistance5.py URL: -------------- next part -------------- -- Andrew McLean From bokr at oz.net Wed Jan 19 00:23:44 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 19 Jan 2005 05:23:44 GMT Subject: Has apparent 2.4b1 bug been fixed? flatten in Lib\compiler\ast.py overloads 'list' name References: <41ede67e.1232456679@news.oz.net> Message-ID: <41ededb0.1234298206@news.oz.net> On Wed, 19 Jan 2005 04:55:53 GMT, bokr at oz.net (Bengt Richter) wrote: >What am I missing? (this is from 2.4b1, so probably it has been fixed?) > I googled and found a bug report, but initial report kind of passes on it saying nested sequences will probably be tuples, so no panic (my paraphrased description). So I guess it's in the mill. So never mind. I should have googled first ;-/ > >def flatten(list): > l = [] > for elt in list: > ^^^^--must be expecting list instance or other sequence > t = type(elt) > if t is tuple or t is list: > ^^^^--looks like it expects to refer to the type, not the arg > for elt2 in flatten(elt): > l.append(elt2) > else: > l.append(elt) > return l > Regards, Bengt Richter From simonwittber at gmail.com Wed Jan 12 22:21:56 2005 From: simonwittber at gmail.com (Simon Wittber) Date: Thu, 13 Jan 2005 11:21:56 +0800 Subject: why are people still using classic classes? Message-ID: <4e4a11f805011219211feca15e@mail.gmail.com> I've noticed that a few ASPN cookbook recipes, which are recent additions, use classic classes. I've also noticed classic classes are used in many places in the standard library. I've been using new-style classes since Python 2.2, and am suprised people are still using the classic classes. Is there a legitimate use for classic classes that I am not aware of? Is there a project to specifically migrate standard library classes to new-style classes? Sw. From aleaxit at yahoo.com Sat Jan 1 11:28:55 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 1 Jan 2005 17:28:55 +0100 Subject: pickling a subclass of tuple References: <41d69113$0$14985$3a628fcd@reader2.nntp.hccnet.nl> Message-ID: <1gppyot.1rx6uz2fzk178N%aleaxit@yahoo.com> fedor wrote: > Hi all, happy new year, > > I was trying to pickle a instance of a subclass of a tuple when I ran > into a problem. Pickling doesn't work with HIGHEST_PROTOCOL. How should > I rewrite my class so I can pickle it? You're falling afoul of an optimization in pickle's protocol 2, which is documented in pickle.py as follows: # A __reduce__ implementation can direct protocol 2 to # use the more efficient NEWOBJ opcode, while still # allowing protocol 0 and 1 to work normally. For this to # work, the function returned by __reduce__ should be # called __newobj__, and its first argument should be a # new-style class. The implementation for __newobj__ # should be as follows, although pickle has no way to # verify this: # # def __newobj__(cls, *args): # return cls.__new__(cls, *args) # # Protocols 0 and 1 will pickle a reference to __newobj__, # while protocol 2 (and above) will pickle a reference to # cls, the remaining args tuple, and the NEWOBJ code, # which calls cls.__new__(cls, *args) at unpickling time # (see load_newobj below). If __reduce__ returns a # three-tuple, the state from the third tuple item will be # pickled regardless of the protocol, calling __setstate__ # at unpickling time (see load_build below). Essentially, and simplifying just a little...: you're inheriting __reduce_ex__ (because you're not overriding it), but you ARE overriding __new__ *and changing its signature* -- so, the inherited __reduce__ex__ is used, and, with this protocol 2 optimization, it essentially assumes that __new__ is similarly used -- or, at least, that a __new__ is used which does not arbitrarily change the signature! So, if you want to change __new__'s signature, and yet be picklable by protocol 2, you have to override __reduce_ex__ to return the right "args"... those your class's __new__ expects! For example, you could consider something like...: def __newobj__(cls, *args): return cls.__new__(cls, *args) class A(tuple): def __new__(klass, arg1, arg2): return super(A, klass).__new__(klass, (arg1, arg2)) def __reduce_ex__(self, proto=0): if proto >= 2: return __newobj__, (A, self[0], self[1]) else: return super(A, self).__reduce_ex__(proto) Note the key difference in A's __reduce_ex__ (for proto=2) wrt tuple's (which is the same as object's) -- that's after an "import a" where a.py has this code as well as an 'a = A(1, 2)'...: >>> a.a.__reduce_ex__(2) (, (, 1, 2)) >>> tuple.__reduce_ex__(a.a, 2) (, (, (1, 2)), {}, None, None) >>> Apart from the additional tuple items (not relevant here), tuple's reduce returns args as (, (1, 2)) -- two items: the class and the tuplevalue; so with protocol 2 this ends up calling A.__new__(A, (1,2))... BOOM, because, differently from tuple.__new__, YOUR override doesn't accept this signature! So, I suggest tweaking A's reduce so it returns args as (, 1, 2)... apparently the only signature you're willing to accept in your A.__new__ method. Of course, if A.__new__ can have some flexibility, you COULD have it accept the same signature as tuple.__new__ and then you wouldn't have to override __reduce_ex__. Or, you could override __reduce_ex__ in other ways, say: def __reduce_ex__(self, proto=0): if proto >= 2: proto = 1 return super(A, self).__reduce_ex__(proto) this would avoid the specific optimization that's tripping you up due to your signature-change in __new__. The best solution may be to forget __reduce_ex__ and take advantage of the underdocumented special method __getnewargs__ ...: class A(tuple): def __new__(klass, arg1, arg2): return super(A, klass).__new__(klass, (arg1, arg2)) def __getnewargs__(self): return self[0], self[1] This way, you're essentially choosing to explicitly tell the "normal" __reduce_ex__ about the particular arguments you want to be used for the __new__ call needed to reconstruct your object on unpickling! This highlights even better the crucial difference, due strictly to the change in __new__'s signature...: >>> a.a.__getnewargs__() (1, 2) >>> tuple.__getnewargs__(a.a) ((1, 2),) It IS, I guess, somewhat unfortunate that you have to understand pickling in some depth to let you change __new__'s signature and yet fully support pickling... on the other hand, when you're overriding __new__ you ARE messing with some rather deep infrastructure, particularly if you alter its signature so that it doesn't accept "normal" calls any more, so it's not _absurd_ that compensatory depth of understanding is required;-). Alex From hwlgw at hotmail.com Wed Jan 19 15:07:18 2005 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 19 Jan 2005 12:07:18 -0800 Subject: a question References: <3YvHd.80953$Jk5.28602@lakeread01> <6kwHd.48934$w62.45338@bgtnsc05-news.ops.worldnet.att.net> Message-ID: <1106165238.353672.272980@f14g2000cwb.googlegroups.com> Andrew Koenig wrote: > how about writing this instead? > > ('this is a ' > 'long string') Yes, nice. And to make that possible we have to write ('one-string-item',) instead of ('one-string-item') if we want a tuple with one string inside. Sometimes that feels like a wart to me, but now I know it, sometimes not. From fuzzyman at gmail.com Wed Jan 26 05:06:44 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 26 Jan 2005 02:06:44 -0800 Subject: python without OO In-Reply-To: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <1106734004.937008.46060@z14g2000cwz.googlegroups.com> It's perfectly possible to write good python code without using classes. (and using functions/normal control flow). You will have a problem with terrminology though - in python everything is an object (more or less). Common operations use attributes and methods of standard objects. For example : > somestring = 'fish' > if somestring.startswith('f'): > print 'It does' The above example uses the 'startswith' method of all string objects. Creating your own 'classes' of objects, with methods and attributes, is just as useful. You can certainly use/learn python without having to understand object oreinted programming straight away. On the other hand, Python's object model is so simple/useful that you *will* want to use it. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From rkern at ucsd.edu Fri Jan 7 05:50:47 2005 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 07 Jan 2005 02:50:47 -0800 Subject: The Industry choice In-Reply-To: <1gq0k74.1epsxog1dgcgbsN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <10trej2fl8dip65@corp.supernews.com> <1gq0k74.1epsxog1dgcgbsN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Until some judge passes some judgment, the intent and effect of GPL must > remain a matter of opinion. But RMS's opinion is probably more > meaningful than mine or yours -- certainly regarding intent, given his > role in designing that license. But it may not have practical effect in an actual dispute. I believe that in some jurisdictions[1], the important piece of information in interpreting a license is the common understanding of what the license means between the disputing parties. The author of the license, if he is not one of the disputing parties, has no say in what the license means for that dispute. [1] IANAL; TINLA. This is from my memory of what I read in Lawrence Rosen's book[2] that I don't have in front of me right now. See his book, chapter 12, I think, for more details. [2] http://www.rosenlaw.com/oslbook.htm > If he's badly erred, and one day a > judge endorses your opinion and says that a program which copies no GPL > source cannot be infected by GPL, ah well -- then I guess GPL is badly > designed as to putting its intents into practice. But until there is > some strong basis to think otherwise, I believe it's prudent to assume > RMS is probably right, and your statement therefore badly wrong. I've always found, especially in light of what I wrote above, the best thing to do is to ask the author himself what he wants. If he subscribes to an unreasonable interpretation of the license, it's better that you found out quickly and avoid getting sued even though you might end up winning. You also avoid inadvertantly stepping on anyone's toes and garnering ill-will even if you never go to court. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From b at b.b Sat Jan 8 15:28:03 2005 From: b at b.b (Roose) Date: Sat, 08 Jan 2005 20:28:03 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10u02s3deapvkd8@corp.supernews.com> Message-ID: Well can you describe what kind of things you want to do exactly? My guess is you are not out to develop a new algorithm for virtual memory or task scheduling. There are many parts to an OS shell. An example is the command line, i.e. bash and the like in Unix, and cmd.exe in Windows. In Windows, Windows Explorer could be considered part of the shell, as well as the start menu and all that user-specific stuff. Basically you need to pick your OS, and then find out what the API to program the shell to would be. e.g. in Windows you would do it with the Win32 API. This will let you do things like delete and create files, interact with user structures, the registry, etc. OR, as a first stab -- I would just write a prototype. i.e., don't tie it to a real OS. Just pretend you have your own "users", your own "file system", your own display space, etc. This will help you get a much better idea of what you want to do. "David Brown" wrote in message news:10u02s3deapvkd8 at corp.supernews.com... > So how would I make an OS Shell? > > From frans.englich at telia.com Mon Jan 17 15:55:33 2005 From: frans.englich at telia.com (Frans Englich) Date: Mon, 17 Jan 2005 20:55:33 +0000 Subject: Assigning to self In-Reply-To: References: Message-ID: <200501172055.33962.frans.englich@telia.com> On Monday 17 January 2005 19:02, Peter Otten wrote: > Frans Englich wrote: > > What the code attempts to do is implementing a, to the API user, > > transparent memory-saver by ensuring that no more than one instance of > > the class foo exists for a particular id. E.g, the user can simply > > "create" an instance and if one not already exists, it is created. > > By the time __init__() is called, a new Foo instance has already been > > created. Therefore you need to implement Foo.__new__(). E. g.: > >>> class Foo(object): > > ... cache = {} > ... def __new__(cls, id): > ... try: > ... return cls.cache[id] > ... except KeyError: > ... pass > ... cls.cache[id] = result = object.__new__(cls, id) > ... return result > ... def __init__(self, id): > ... self.id = id > ... def __repr__(self): > ... return "Foo(id=%r)" % self.id > ... I'm not sure, but I think this code misses one thing: that __init__ is called each time __new__ returns it, as per the docs Peter posted. Cheers, Frans From http Tue Jan 4 21:28:26 2005 From: http (Paul Rubin) Date: 04 Jan 2005 18:28:26 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> Message-ID: <7xoeg4txrp.fsf@ruckus.brouhaha.com> Jeremy Bowers writes: > So, nobody should have to write the docs because they should already be > there, but "somebody" should have to write the docs? > > You need to think more clearly about the pronouns you are slinging around. > Who is this "they" that should write the docs? The Python advocates who claim that Python is well-documented and take exception to when someone say it isn't. Their idea of "it's well-documented" seems to be "if there's parts that you think are poorly documented, feel free to document it". What kind of nonsense is that? "Python code runs just as fast as C code. If you think it's slower, feel free to speed it up". "Python's standard library includes a database module. If it isn't there, feel free to add one". "Programming in Python cures cancer. If your cancer doesn't clear up when you code in Python, feel free to submit a patch". Software advocacy, which Python has an awful lot of, involves extolling the virtues of a program as it exists in the present. Not as it could potentially exist if someone hypothetically added a bunch of work that hasn't yet been done. Python is good software, but its advocates are making claims that Python itself doesnt live up to. And no, I don't feel a responsibility to do the missing work, since I'm not the one making those advocacy claims. From snacktime at gmail.com Wed Jan 26 14:50:46 2005 From: snacktime at gmail.com (snacktime) Date: Wed, 26 Jan 2005 11:50:46 -0800 Subject: Set parity of a string In-Reply-To: References: Message-ID: <1f060c4c05012611503090c261@mail.gmail.com> I'm trying to figure out why the following code transforms ascii STX (control-b) into "\x82". The perl module I use returns a value of "^B", and that is also what the application I am communicating with expects to see. Some ascii characters such as FS and GS come through fine, but STX and ETX get transformed incorrectly (at least for what I need they do). What am I missing here? Chris > But here's one for you anyway. It raises an exception if any > input character is non-ASCII, otherwise when you call set_parity() > with a string and a parity parameter of 'even', 'mark', 'none', > 'odd', or 'space', it returns a string of the same length with > the high (parity) bits set appropriately. > > '''parity module for python''' > # Copyright 2005 Engenuity Corporation > # Released under the "MIT license" > # at http://www.opensource.org/licenses/mit-license.php > > import string > import operator > > def _makeTable(parity): > bitMap = {'even': [0,128], 'odd': [128,0], 'mark': [128,128]} > table = [] > for c in range(128): > even_odd = (sum(bool(c & 1< cp = chr(c | bitMap.get(parity, [0,0])[even_odd]) > table.append(cp) > table.extend(chr(c) for c in range(128, 256)) > table = ''.join(table) > return table, table[128:] > > _map = {} > for parity in 'even odd mark space none'.split(): > _map[parity] = _makeTable(parity) > > def set_parity(data, parity='none'): > '''return string with parity bits, accepting only ASCII characters > (0..127) as input''' > out = string.translate(data, *_map[parity.lower()]) > if len(out) != len(data): > raise ValueError('non-ASCII characters in input') > else: > return out > > if __name__ == '__main__': > print 'Running self-tests for parity.py' > > # check for invalid input handling > for input in [ '\xff', '\x80', 'test\xA0ing' ]: > try: > set_parity(input) > except ValueError: > pass > else: > assert False, 'no exception for non-ASCII input' > > # check for various valid inputs > for i, (parity, input, expected) in enumerate([ > ('space', 'test', 'test'), > ('SPACE', '\x00\x7f', '\x00\x7f'), > ('mark', 'test', '\xf4\xe5\xf3\xf4'), > ('Odd', '\x00test\x7f', '\x80\xf4\xe5s\xf4\x7f'), > ('even', '\x00\x01\x02\x03test\x7d\x7e\x7f', > '\x00\x81\x82\x03te\xf3t\x7d\x7e\xff'), > ]): > actual = set_parity(input, parity) > assert expected == actual, 'case %d: %r != %r' % (i, expected, actual) > > print 'All tests passed.' > -- > http://mail.python.org/mailman/listinfo/python-list > From philippecmartin at sbcglobal.net Wed Jan 12 10:27:43 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Wed, 12 Jan 2005 16:27:43 +0100 Subject: encryption/decryption help Message-ID: <1105543663.6716.8.camel@localhost> >>MD5 and SHA are by their very nature one way encryption. You cannot decrypt them. Indeed, the point of these algorithms is to sign data (like a fingerprint). In order to encrypt you may go for Symmetrical algos (AES, 3DES ....with those, the key must be known on both sides of the pipe) or Asymmetrical (RSA ... - where you get a private key on one side and a public key on the other - good but slow). Often you find hybrid methods: you start your session with a public/private style method just to exchange a symmetrical key that you'll use for the rest of the session. Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From apardon at forel.vub.ac.be Thu Jan 13 09:46:56 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jan 2005 14:46:56 GMT Subject: Unclear On Class Variables References: Message-ID: > > Well I find this a confusing behaviour on python's part. The fact > that instance.field can mean something different, depending on > where in a statement you find it, makes the behaviour inconsistent. > > I know people in general here are against declarations, but declarations > could IMO provide more consistency here and thus more obvious behaviour. Well just to show how confusing python can be, the following piece of code. | class Spam: | eggs = [2, 3] | | | sp1 = Spam() | sp2 = Spam() | | print sp1.eggs, id(sp1.eggs) | print sp2.eggs, id(sp2.eggs) | print '--------------------' | | sp1.eggs += [4,] | | print sp1.eggs, id(sp1.eggs) | print sp2.eggs, id(sp2.eggs) | print '--------------------' | | Spam.eggs = [3,5] | | print sp1.eggs, id(sp1.eggs) | print sp2.eggs, id(sp2.eggs) | print '--------------------' Which produces: [2, 3] 1075958860 [2, 3] 1075958860 -------------------- [2, 3, 4] 1075958860 [2, 3, 4] 1075958860 -------------------- [2, 3, 4] 1075958860 [3, 5] 1075959084 -------------------- From invalidemail at aerojockey.com Mon Jan 10 06:50:39 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 10 Jan 2005 03:50:39 -0800 Subject: python3: 'where' keyword In-Reply-To: <7xis65a5w6.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> <7xllb2f3z4.fsf@ruckus.brouhaha.com> <1105355380.040837.189270@c13g2000cwb.googlegroups.com> <7xis65a5w6.fsf@ruckus.brouhaha.com> Message-ID: <1105357839.696387.309900@c13g2000cwb.googlegroups.com> Paul Rubin wrote: > "Carl Banks" writes: > > > So do you approve of the movement to get rid of the print statement? > > > > Any little incremental change in Python you could make by having or not > > having a print statement would be minor compared to the H-Bomb of > > ugliness we'd get if suites of statements were to be allowed inside > > Python expressions. Having or not having a print statement might > > violate some small aspect of the Zen, but it won't rape the whole list. > > How about macros? Some pretty horrible things have been done in C > programs with the C preprocessor. But there's a movememnt afloat to > add hygienic macros to Python. Got any thoughts about that? How about this: Why don't you go to a Python prompt, type "import this", and read the Zen of Python. Consider each line, and whether adding macros to the language would be going against that line or for it. After you've done that, make an educated guess of what you think I'd think about macros, citing various Zens to support your guess. Then I'll tell you what my my thoughts about it are. > > So I don't know what point you're trying to make. > > Why should you care whether the output of a macro is ugly or not, > if no human is ever going to look at it? I don't. > > But to answer your question, I would prefer a Python without a print > > statement, since a print method could do anything the print statement > > could. > > A print -method-?!! [snip example] > > I've heard of people wanting to replace print with a function, but > hadn't heard of replacing it with a method. Are you trying to turn > Python into Ruby? I'll give you the benefit of the doubt that you just didn't think it over thoroughly. I was thinkging would be a method of file like objects. stdout.print("hello") -- CARL BANKS From ncoghlan at iinet.net.au Sun Jan 9 01:58:24 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 16:58:24 +1000 Subject: python3: 'where' keyword In-Reply-To: <7xsm5b2m93.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> Message-ID: <41E0D610.1080803@iinet.net.au> Paul Rubin wrote: > Nick Coghlan writes: > >>I think having to keep the names unique within the statement you are >>currently writing is a reasonable request :) > > > Um, you could say the same thing about the function, the module, etc. ;) > And, indeed, that is what Python currently says. When writing code, the relevant namespaces are the builtins, the module, any containing functions and the current function. Inadvertent conflicts with any of those can have surprising side effects. The idea of 'where' is to push that down one level, and allow a namespace to be associated with a single statement. Trying to push it a level further (down to expressions) would, IMO, be a lot of effort for something which would hurt readability a lot. Compare: x = sqrt(a) + sqrt(b) where: a = 2.0 b = 3.0 This brings the operation we care about (add the sqrt's of 2 and 3) right up front. A folding code editor could actually hide the details quite easily. We can look inside the statement if we want to know what x & y actually are. Versus: x = (sqrt(a) where: a = 2.) \ + sqrt (a) where: a = 3. We haven't gotten rid of anything here - all the stuff we're interested in clearing out of the way is still embedded in the middle of our statement. Also not insignificantly, we're trying to put a suite inside an expression, which will be rejected for all the reasons that have kept lambda restricted to a single expression despite numerous complaints over time. Now, nothing in the idea of a statement local namespace actually *rules out* the prospect of an expression local namespace, so it could be added at a later date. However, doing so would require some actual use cases, and an expression-friendly syntax. Perhaps something that involves providing the namespace directly, like: x = (sqrt(a) where (a=2.0)) + (sqrt(b) where (a=3.0)) It seems to make more sense to try for statement local namespaces *first*, and then see if expression local namespaces are worth it. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From frans.englich at telia.com Mon Jan 24 21:42:19 2005 From: frans.englich at telia.com (Frans Englich) Date: Tue, 25 Jan 2005 02:42:19 +0000 Subject: Distutils: blurring the file==module borders In-Reply-To: <797fe3d40501241817765fd2b1@mail.gmail.com> References: <200501250215.58729.frans.englich@telia.com> <797fe3d40501241817765fd2b1@mail.gmail.com> Message-ID: <200501250242.19841.frans.englich@telia.com> On Tuesday 25 January 2005 02:17, Bill Mill wrote: > read this thread, it should help you: > > http://mail.python.org/pipermail/tutor/2005-January/035124.html Thanks, it did. Not optimally, but in the way I suspected it would be solved. In short, the solution, when translated to my case, is to in __init__.py do `from ClassA import ClassA`, and hence get the /class/ ClassA in the module's namespace. Note, I did not do `from foo.ClassA import ClassA` because that failed. To me, it is kinda hackish; it doesn't show up in the pydocs, and no idea if it shadows the actual module(assuming they have identical names, which they have) but it appears it can't be solved in a better way. Another approach would to do copy&paste with the build system at install time, but I will not sink that low.. Cheers, Frans From stuartm at mathworks.com Mon Jan 24 10:57:47 2005 From: stuartm at mathworks.com (Stuart McGarrity) Date: Mon, 24 Jan 2005 10:57:47 -0500 Subject: Memory Usage References: Message-ID: Do you have a page file? The Mem column should be RAM usage and not total working set. Some of it could be swapped to the page file. A free tool like process explorer can give you better informaton than the task manager. "rbt" wrote in message news:ct2v9f$k3t$1 at solaris.cc.vt.edu... > Would a Python process consume more memory on a PC with lots of memory? > > For example, say I have the same Python script running on two WinXP > computers that both have Python 2.4.0. One computer has 256 MB of Ram > while the other has 2 GB of Ram. On the machine with less Ram, the process > takes about 1 MB of Ram. On the machine with more Ram, it uses 9 MB of > Ram. > > Is this normal and expected behavior? > > Thanks, > > rbt From aleaxit at yahoo.com Sat Jan 22 03:50:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 09:50:36 +0100 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> Message-ID: <1gqsayh.th49i518ixczeN%aleaxit@yahoo.com> Dave Benjamin wrote: > Can we get a show of hands for all of those who have written or are > currently maintaining code that uses the leaky listcomp "feature"? "Have written": guilty -- basically to show how NOT to do things. "Currently maintaining": you _gotta_ be kidding!-) > I guess I've been peripherally aware of it, but I almost always use > names like "x" for my loop variables, and never refer to them > afterwards. If Python were to change in this regard, I don't think it > would break any Python code that I've ever written or maintained... If it changed the semantics of for-loops in general, that would be quite inconvenient to me -- once in a while I do rely on Python's semantics (maintaining the loop control variable after a break; I don't recall if I ever used the fact that the variable is also maintained upon normal termination). (musing...): I think the reason there's no real use case for using a listcomp's control variable afterwards is connected to this distinction: listcomps have no `break'... Alex From philippecmartin at sbcglobal.net Fri Jan 21 08:08:11 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Fri, 21 Jan 2005 07:08:11 -0600 Subject: What's the best python web-developer's editor Message-ID: <1106312891.7175.4.camel@localhost> >>Emacs >>For both discrete and mixed python and html code, and why? >>There's no reason to use anything else. Although I tested and will keep testing other editors/ide, I also went back to emacs and am quite happy with it. However, I sometimes use snavigator (http://sourceforge.net/projects/sourcenav) when I need to browse through a project (although I could use emacs TAGS, I find snavigator to be the best free solution out there to parse large projects) Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From wittempj at hotmail.com Tue Jan 18 14:16:40 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 18 Jan 2005 11:16:40 -0800 Subject: hex notation funtion In-Reply-To: References: Message-ID: <1106075800.825535.254540@c13g2000cwb.googlegroups.com> This will do it: >>> int('10000000', 2) 128 >>> hex(int('10000000', 2)) '0x80' >>> From __peter__ at web.de Tue Jan 11 07:37:19 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Jan 2005 13:37:19 +0100 Subject: [csv module] duplication of end of line character in output file generated References: Message-ID: simon.alexandre wrote: > I use csv module included in python 2.3. I use the writer and encouter the > following problem: in my output file (.csv) there is a duplication of the > end of line character, so when I open the csv file in Ms-Excel a blank > line is inserted between each data line. > > OS: W2k > > Someone has an idea ? > > thanks in advance > > the source code is the following: > > --------------------------------------------------> > import csv > > class CsvDumper: > > def __init__(self): > self.object = > [['la','mb','mc','md'],['ma','mb','mc','md'],['ma','mb','mc','md']] > self.writer = csv.writer(file("Test.csv", "w")) Try opening the file in binary mode: file("Test.csv", "wb") > def DumpCsvFile(self): > for row in self.object: > self.writer.writerow(row) > > c = CsvDumper() > c.DumpCsvFile() From timr at probo.com Tue Jan 25 03:23:39 2005 From: timr at probo.com (Tim Roberts) Date: Tue, 25 Jan 2005 00:23:39 -0800 Subject: Why can't use cursor.nextset() in adodbapi package? References: Message-ID: <790cv0l0kbqmcf9ltfpfp35npd71latt71@4ax.com> nightmarch wrote: >Thank you Dennis! > >You mean I should execute many select statement like this " rec = >crsr.fetchall() " ? No, you misunderstand. nextset() is used when you issue several SELECT statements in a single request. The first fetchall() gets the results of the first SELECT statement. To get the next one, you use nextset(). Your example only had one SELECT: >> > >>> sql = "select * from wjtmp" >> > >>> crsr.execute(sql) >> > >>> rec = crsr.fetchone() >> > >>> crsr.nextset() If you are only issuing one SELECT, like most applications, then nextset() serves no purpose. If you did something like this: sql = "select * from wjtmp; select count(*) from wjtmp;" That's when you need nextset(). Personally, I've never used it. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From esj at harvee.org Tue Jan 18 12:57:21 2005 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 18 Jan 2005 12:57:21 -0500 Subject: simultaneous multiple requests to very simple database In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E33981ED@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E33981ED@exchange.hqamor.amorhq.net> Message-ID: <41ED4E01.1040400@harvee.org> Robert Brewer wrote: > Eric S. Johansson wrote: > >>I have an application where I need a very simple database, >>effectively a very large dictionary. The very large >>dictionary must be accessed from multiple processes >>simultaneously. I need to be able to lock records within >>the very large dictionary when records are written to. > > > Just to clarify, you want shared-read until a write, at which point you > want to lock just the item being written? Or would page or table locking > be acceptable at that point? just the item/record. I'm doing arrival rate calculations. each record contains a set of arrival times and I am rewriting the record every time a new entry arrives. complete page or table locking will work in the sense that it will prevent collisions but it will have an increasing impact as load and simultaneous table but not record accesses increase. ---eric From hans at zephyrfalcon.org Sat Jan 1 17:23:32 2005 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sat, 01 Jan 2005 17:23:32 -0500 Subject: UserDict deprecated In-Reply-To: References: Message-ID: Uwe Mayer wrote: >>>Why is the UserDict module is deprecated after Python 2.2. The >>>application of it I have in mind is, i.e. multiple inheritance from >>>"file" and "dic" - which is not possible. [...] > I was writing a class that read /writes some binary file format. I > implemented the functions from the file interface such that they are > refering to records. However, the file format has some header fields and > I'd wanted to grant access to those via the dict-interface. > > Another example: working with PyQt I have an instance of a QListView and > wanted to use the list-interface to get and set individual records. If it's just a matter of attribute access, implementing the relevant __getitem__ and __setitem__ methods will probably suffice. I don't think that deriving from dict or list will do you much good here... most of the methods will be irrelevant, or won't do what you want, so you have to override them anyway. -- Hans Nowak http://zephyrfalcon.org/ From pythongnome at hotmail.com Wed Jan 12 08:10:20 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Wed, 12 Jan 2005 13:10:20 GMT Subject: [OT] SciTe In-Reply-To: <41e4c577$0$6628$626a14ce@news.free.fr> References: <58%Ed.4827$C52.2609@newsread2.news.atl.earthlink.net> <41e4c577$0$6628$626a14ce@news.free.fr> Message-ID: <0l9Fd.4419$KJ2.747@newsread3.news.atl.earthlink.net> Fouff wrote: > I use Scintilla which is Scite with a lot of configurations files. > In directory exists a file "cpp.properties" and near the end of the file > is describe the command line use to compile, to link, ... > > I think you would be able to change here the compiler. > > regards > Fouff Thanks. From sp1d3rx at gmail.com Wed Jan 26 18:13:00 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 26 Jan 2005 15:13:00 -0800 Subject: Question Regarding SocketServer In-Reply-To: <1106692228.117977.104720@f14g2000cwb.googlegroups.com> References: <1106684900.771730.218060@f14g2000cwb.googlegroups.com> <1106688660.694617.290330@c13g2000cwb.googlegroups.com> <1106691478.621949.44020@z14g2000cwz.googlegroups.com> <1106692228.117977.104720@f14g2000cwb.googlegroups.com> Message-ID: <1106781180.062520.161800@c13g2000cwb.googlegroups.com> I am glad you were able to figure it out. It's strange that the pyc file didn't get updated... it should have automatically fixed itself. *shrug* that's one of those problems that aggrivate you to death... From peter at engcorp.com Fri Jan 21 09:01:00 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Jan 2005 09:01:00 -0500 Subject: Graph and Table implementation In-Reply-To: References: Message-ID: Jan Rienyer Gadil wrote: > could anyone please help me! > > what and how is the best implementation of creating a table based on What is a "table", to you? It could mean anything from something you intend to print, to a GUI-based representation similar to a spreadsheet, to a simple two-dimensional array of data in memory. > data coming from the serial port ? and also how would i be able to > create graphs (2D) based on these data? Platform? GUI framework, if you've chosen one? etc. etc. I might suggest using wxPython, with a wx.Grid and wxPyPlot, but given how little useful information you've provided, that could well be far from suitable. -Peter From gmuller at worldonline.nl Sat Jan 15 14:04:07 2005 From: gmuller at worldonline.nl (GerritM) Date: Sat, 15 Jan 2005 20:04:07 +0100 Subject: hash patent by AltNet; Python is prior art? Message-ID: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> ZDnet features an article about the had patent at AltNet http://news.zdnet.com/2100-9588_22-5534087.html . Apparantly this issue plays already for some time, now the p2p companies are threatened, becuase they use hashing to recognize files. As far as I know hasing is a very old technique used to quickly look up information. The use of hashing always requires an idnetity check, because the lookup is not unique (mapping a very big amount of possibilities on a limited amount of entries). This is a fast and robust way of finding information, if the right hashing function is used. How can this type of fundamental knowledge be patented? I am afraid this is again an example of a total failure of the current patent system. Unfortunately these ridiculous examples endanger smaller companies, open software activities amd innovation in general. kind regards, Gerrit -- Praktijk voor Psychosociale therapie Lia Charit? From jstroud at mbi.ucla.edu Fri Jan 7 22:28:09 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 7 Jan 2005 19:28:09 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: <7xvfa90w6g.fsf@ruckus.brouhaha.com> References: <7xvfa90w6g.fsf@ruckus.brouhaha.com> Message-ID: <200501071928.14651.jstroud@mbi.ucla.edu> On Friday 07 January 2005 01:24 pm, Paul Rubin wrote: > Nick Coghlan writes: > > Add in the fact that there are many, many Python programmers with > > non-CS backgrounds, and the term 'lambda' sticks out like a sore thumb > > from amongst Python's other English-based keywords. > > Richard Feynman told a story about being on a review committee for > some grade-school science textbooks. One of these book said something > about "counting numbers" and it took him a while to figure out that > this was a new term for what he'd been used to calling "integers". I think we should not try too hard to make everything "English" like. Its a crappy language anyway (though its the only one I speak good). Matt Neuberg, in _AppleScript: The Definitive Guide_, refers to "the English-likeness monster". His example is that instead of x = 4 you have to say copy 4 to x I think every reader of this list would prefer to look at the former. The point is that once we learn new symbolics of expression, they are as simple to decipher as plain old English if we format properly and gIvEnThAtwEiNcLuDEsOmEhElPfUlfORmaTtInGInOuRcOdEFroMtImEtOtiME. So I think that being fearful of new additions to the language (read "more ability for expression") is mainly fear of abuse by poor programmers--and that is akin to being afraid of the dark. James -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics 611 Charles E. Young Dr. S. MBI 205, UCLA 951570 Los Angeles CA 90095-1570 http://www.jamesstroud.com/ From itsme at yahoo.com Wed Jan 12 12:42:50 2005 From: itsme at yahoo.com (It's me) Date: Wed, 12 Jan 2005 17:42:50 GMT Subject: counting items Message-ID: Okay, I give up. What's the best way to count number of items in a list? For instance, a=[[1,2,4],4,5,[2,3]] I want to know how many items are there in a (answer should be 7 - I don't want it to be 4) I tried: b=len([x for y in a for x in y]) That doesn't work because you would get an iteration over non-sequence. I tried: g=lambda x: (1,len(x))[isinstance(x,(list,tuple,dict))] b=sum(lambda(x) for x in a) and that didn't work because I get a TypeError from the len function (don't know why) I can, of course: i=0 for x in a: if isinstance(x,(list,tuple,dict)): i += len(x) else: i += 1 but that's so C-like... Thanks, From hpk at trillke.net Tue Jan 4 17:08:38 2005 From: hpk at trillke.net (holger krekel) Date: Tue, 4 Jan 2005 23:08:38 +0100 Subject: Python evolution: Unease In-Reply-To: References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> Message-ID: <20050104220838.GA7646@solar.trillke.net> Hi Roman, On Wed, Jan 05, 2005 at 00:44 +0300, Roman Suzi wrote: > Python could have honest support of concepts. Everything else will be > available with them. > > That is the whole point that Python supports GP. It is only one step > to do concepts right (and GvR it seems want type-checking into Python 3.0 > anyway), so support for concepts/concept checking is very logical, > isn't it? As an innocent by-dropper into this thread: a) do you know Armin Rigo's "semantic model" page dealing with concepts? http://arigo.tunes.org/semantic_models.html b) do you have some concise definition of what you mean by "concept"? Myself, i appreciate the combination of testing and python's flexibility so much that i don't long for type declarations, at least not to the degree that would warrant syntax additions. Now for interfaces, for me this references more a documentation issue than a syntax one: I'd like to have a full-featured runtime browser that allows to quickly navigate cross-referenced life python objects. Back and forth in execution time, preferably. This probably requires the interpreter to help, track and record more information (which is one of the possibilities with PyPy). It doesn't neccessarily require any new syntax though. And I don't really see the point of adding interface hierarchies to already large frameworks. To me this adds to - what i call - "naming complexity", i.e. the number of names a programmer needs to remember to deal with a library or framework. For me, it's not really the syntax that is the problem with interfaces in Zope3 or twisted, but the sheer amount of names (each indicating certain concepts and behaviours) i am confronted with. Not sure why i am saying all this here but have fun, holger From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Jan 6 16:17:15 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Thu, 6 Jan 2005 22:17:15 +0100 Subject: Pb encodage & import Message-ID: <41ddaaef$0$2749$8fcfb975@news.wanadoo.fr> Bonsoir ! Hi ! My english is short, therefore, I do short. Two scripts, "i1.py" and "i2.py" : i1.py : import i2 print i2.GlobalA i2.py : GlobalA ="azerty" Like this, it's OK ; but : i1.py : import i2 print i2.GlobalA i2.py : GlobalA = "azerty" OK ============================== i1.py : import i2 print i2.GlobalA i2.py : # -*- coding: cp1252 -*- GlobalA = "azerty" SyntaxError ============================== i1.py : import i2 print i2.GlobalA i2.py : # -*- coding: utf-8 -*- GlobalA = "azerty" OK ============================== i1.py : # -*- coding: utf-8 -*- import i2 print i2.GlobalA i2.py : # -*- coding: utf-8 -*- GlobalA = "azerty" OK ============================== i1.py : # -*- coding: utf-8 -*- import i2 print i2.GlobalA i2.py : # -*- coding: cp1252 -*- GlobalA = "azerty" SyntaxError ============================== i1.py : # -*- coding: utf-8 -*- import i2 print i2.GlobalA i2.py : GlobalA = u"az?rty" #see unicode & accent OK ============================== i1.py : # -*- coding: utf-8 -*- import i2 print i2.GlobalA i2.py : # -*- coding: utf-8 -*- GlobalA = u"az?rty" #see unicode & accent UnicodeDecodeError ============================== All files are recorded in ANSI ; tests with Python 2.4 on Win-XP. Ideas, ou suggests ? @-salutations -- Michel Claveau From klachemin at comcast.net Fri Jan 7 15:56:33 2005 From: klachemin at comcast.net (Kamilche) Date: 7 Jan 2005 12:56:33 -0800 Subject: Calling Function Without Parentheses! In-Reply-To: <10tttc6vblse9@corp.supernews.com> References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> <41D8B5F4.1010903@mxm.dk> <1105113743.189469.115440@f14g2000cwb.googlegroups.com> <10tttc6vblse9@corp.supernews.com> Message-ID: <1105131393.355381.105800@c13g2000cwb.googlegroups.com> Uh, you're right! I wouldn't want to bog Python down with even more checking at run time. I guess I'm asking for syntax checks that are typically done only with compiled languages. It doesn't stop me from using Python, though! Since I don't have syntax checking, I find I have to test supporting routines thoroughly, to make sure it errs when it should err and runs when it should run. That's something that's always good to do, but it's especially useful in Python, which has no syntax checking before runtime. From bingham at cenix-bioscience.com Tue Jan 18 03:09:09 2005 From: bingham at cenix-bioscience.com (Aaron Bingham) Date: Tue, 18 Jan 2005 09:09:09 +0100 Subject: Fuzzy matching of postal addresses In-Reply-To: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <41ECC425.2000109@cenix-bioscience.com> Andrew McLean wrote: > I have a problem that is suspect isn't unusual and I'm looking to see if > there is any code available to help. I've Googled without success. > > Basically, I have two databases containing lists of postal addresses and > need to look for matching addresses in the two databases. More > precisely, for each address in database A I want to find a single > matching address in database B. I had a similar problem to solve a while ago. I can't give you my code, but I used this paper as the basis for my solution (BibTeX entry from http://citeseer.ist.psu.edu/monge00adaptive.html): @misc{ monge-adaptive, author = "Alvaro E. Monge", title = "An Adaptive and Efficient Algorithm for Detecting Approximately Duplicate Database Records", url = "citeseer.ist.psu.edu/monge00adaptive.html" } There is a lot of literature--try a google search for "approximate string match"--but very little publically available code in this area, from what I could gather. Removing punctuation, etc., as others have suggested in this thread, is _not_sufficient_. Presumably you want to be able to match typos or phonetic errors as well. This paper's algorithm deals with those problems quite nicely, -- -------------------------------------------------------------------- Aaron Bingham Application Developer Cenix BioScience GmbH -------------------------------------------------------------------- From michele.simionato at gmail.com Tue Jan 4 04:43:18 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 4 Jan 2005 01:43:18 -0800 Subject: Python evolution: Unease In-Reply-To: <7x652dk0gh.fsf@ruckus.brouhaha.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1104830276.579755.133870@f14g2000cwb.googlegroups.com> <7x652dk0gh.fsf@ruckus.brouhaha.com> Message-ID: <1104831798.408560.228940@c13g2000cwb.googlegroups.com> Maybe a PSF grant would help? I guess this has been considered ... Michele Simionato From aleaxit at yahoo.com Wed Jan 26 09:51:14 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 26 Jan 2005 15:51:14 +0100 Subject: fast list lookup References: <3e96ebd7.0501260641.159e007f@posting.google.com> Message-ID: <1gr06n6.170sqn1n6u0n4N%aleaxit@yahoo.com> Klaus Neuner wrote: > what is the fastest way to determine whether list l (with > len(l)>30000) contains a certain element? "if thecertainelement in l:" is the fastest way unless there are properties of l which you're not telling us about, or unless what you need is not just to determine whether l contains a certain element but rather something different (such as doing the same determination for several elements on an unchanging l). Alex From jeff at ccvcorp.com Thu Jan 27 13:59:22 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 27 Jan 2005 10:59:22 -0800 Subject: how to comment out a block of code In-Reply-To: <1106767695.572974.98920@z14g2000cwz.googlegroups.com> References: <1106767695.572974.98920@z14g2000cwz.googlegroups.com> Message-ID: <10vie53lfgid68a@corp.supernews.com> Xah Lee wrote: > is there a syntax to comment out a block of code? i.e. like html's > or perhaps put a marker so that all lines from there on are ignored? > thanks. Of course -- this feature is so important that all computer manufacturers worldwide have made a special button on the computer case just for this! Normally it's a large round button, with perhaps a green backlight. Press the button and hold it in for about 3 seconds, and the rest of your code/writing will be ignored just as it should be. Jeff Shannon Technician/Programmer Credit International From steven.bethard at gmail.com Fri Jan 21 20:57:58 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 18:57:58 -0700 Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) Message-ID: I wrote: > If you really want locals that don't contribute to arguments, I'd be > much happier with something like a decorator, e.g.[1]: > > @with_consts(i=1, deftime=time.ctime()) > def foo(x, y=123, *args, **kw): > return x*y, kw.get('which_time')=='now' and time.ctime() or deftime > > Then you don't have to mix parameter declarations with locals > definitions. > > Steve > > [1] I have no idea how implementable such a decorator would be. I'd > just like to see function constants declared separate from arguments > since they mean such different things. I played around with this, and I think it's basically implementable: py> import new py> class with_consts(object): ... def __init__(self, **consts): ... self.consts = consts ... def __call__(self, func): ... return new.function(func.func_code, ... dict(globals(), **self.consts)) ... py> @with_consts(y=123) ... def f(x): ... return x*y, str ... py> f(2) (246, ) I just update the function globals with the keywords passed to the decorator. The only problem is that updates to globals() aren't reflected in the function's globals: py> str = 5 py> f(2) (246, ) Steve From flamesrock at gmail.com Fri Jan 7 20:17:52 2005 From: flamesrock at gmail.com (flamesrock) Date: 7 Jan 2005 17:17:52 -0800 Subject: EOF for binary? Message-ID: <1105147072.909665.242360@z14g2000cwz.googlegroups.com> Hi, So if I understand correctly, there are NO eof characters in any binary file. If so, is there an easier way to check for the end of the file than: os.path.getsize(infile) <= infile.tell() Because that returns the error: # File "/usr/lib/python2.3/posixpath.py", line 142, in getsize # return os.stat(filename).st_size #TypeError: coercing to Unicode: need string or buffer, file found for me. -thanks in advance flamesrock From ed at leafe.com Thu Jan 13 07:55:44 2005 From: ed at leafe.com (Ed Leafe) Date: Thu, 13 Jan 2005 07:55:44 -0500 Subject: py2exe Excludes In-Reply-To: References: Message-ID: <6FE0D374-6562-11D9-A18A-003065B11E84@leafe.com> On Jan 13, 2005, at 12:04 AM, vincent wehren wrote: > Just a guess: What happens if you remove everything that's in the > "build" directory before running setup.py? There may still be files > around from an earlier build that *did* include the Dabo modules. Ah, that was it! I didn't realize that it would still pull those things in there. I wiped out the build directory and re-ran setup, and it's now what I expected. Thanks! ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From ialbert at mailblocks.com Mon Jan 10 15:21:56 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 10 Jan 2005 15:21:56 -0500 Subject: Writing huge Sets() to disk In-Reply-To: References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> Message-ID: Martin MOKREJ? wrote: > But nevertheless, imagine 1E6 words of size 15. That's maybe 1.5GB of raw > data. Will sets be appropriate you think? You started out with 20E20 then cut back to 1E15 keys now it is down to one million but you claim that these will take 1.5 GB. On my system storing 1 million words of length 15 as keys of a python dictionary is around 75MB. I. From fredrik at pythonware.com Sat Jan 22 08:26:00 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 14:26:00 +0100 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com><797fe3d405011911465ab59acd@mail.gmail.com><1106177050.630141.33090@c13g2000cwb.googlegroups.com><972ec5bd0501191641166972b0@mail.gmail.com><7xis5szpdj.fsf@ruckus.brouhaha.com><7xekggbrns.fsf@ruckus.brouhaha.com><7x651rwbib.fsf@ruckus.brouhaha.com><7xfz0uqe1d.fsf@ruckus.brouhaha.com><1gqsayh.th49i518ixczeN%aleaxit@yahoo.com><7xpszxljra.fsf@ruckus.brouhaha.com> <7x4qh9pqhw.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >> > Some languages let you say things like: >> > for (var x = 0; x < 10; x++) >> > do_something(x); >> > and that limits the scope of x to the for loop. >> >> depending on the compiler version, compiler switches, IDE settings, etc. > > Huh? I'm not sure what you're talking about. guess you haven't used some languages that do this long enough. in some early C++ compilers, the scope for "x" was limited to the scope containing the for loop, not the for loop itself. some commercial compilers still default to that behaviour. From bob_smith_17280 at hotmail.com Wed Jan 19 22:04:44 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Wed, 19 Jan 2005 22:04:44 -0500 Subject: list item's position Message-ID: Hi, I have a Python list. I can't figure out how to find an element's numeric value (0,1,2,3...) in the list. Here's an example of what I'm doing: for bar in bars: if 'str_1' in bar and 'str_2' in bar: print bar This finds the right bar, but not its list position. The reason I need to find its value is so I can remove every element in the list before it so that the bar I found somewhere in the list becomes element 0... does that make sense? Thanks, Bob From quentel.pierre at wanadoo.fr Sat Jan 8 09:36:09 2005 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Sat, 08 Jan 2005 15:36:09 +0100 Subject: The best way to do web apps with Python? In-Reply-To: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41dfefdc$0$8011$8fcfb975@news.wanadoo.fr> worzel a ?crit : > What is the best way to web developemnt with Python? Is there anything > close to PHP style in-page script placement that can create and use > other Python objects? I am not really interested in Zope (I believe that > is more a CMS than anything else?) I am also looking for something a > little more structured than a series of CGI Scripts. > There are quite a few web frameworks in Python, see http://www.python.org/moin/WebProgramming I'm biaised in favour of Karrigell (http://karrigell.sourceforge.net), the "Python Inside HTML" pages look and behave very much like PHP Regards, Pierre From jepler at unpythonic.net Thu Jan 13 18:43:01 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Thu, 13 Jan 2005 17:43:01 -0600 Subject: Octal notation: severe deprecation In-Reply-To: <41e6f606.777680996@news.oz.net> References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> <39ednWfqlrgB6HvcRVn-iA@powergate.ca> <41e6f606.777680996@news.oz.net> Message-ID: <20050113234300.GA1513@unpythonic.net> On Thu, Jan 13, 2005 at 11:04:21PM +0000, Bengt Richter wrote: > One way to do it consistently is to have a sign digit as the first > digit after the x, which is either 0 or base-1 -- e.g., +3 and -3 would be > > 2x011 2x101 > 8x03 8x75 > 16x03 16xfd > 10x03 10x97 ... so that 0x8 and 16x8 would be different? So that 2x1 and 2x01 would be different? Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From christian at mvonessen.de Wed Jan 26 15:20:25 2005 From: christian at mvonessen.de (Christian von Essen) Date: Wed, 26 Jan 2005 21:20:25 +0100 Subject: how to comment out a block of code References: <1106767695.572974.98920@z14g2000cwz.googlegroups.com> Message-ID: A bit of a hack of course, but you can enclose the code that should be commented out with ''' and ''' or """ and """ (not sure about the name of this tripple-quoting) OTOH, some (or even most if not all) Python editors support blockquoting by pushing a button or using shortcuts. SPE and IDLE for example. From ncoghlan at iinet.net.au Sun Jan 23 00:37:59 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 23 Jan 2005 15:37:59 +1000 Subject: dynamic call of a function In-Reply-To: <1106394057.320879.319110@f14g2000cwb.googlegroups.com> References: <3BCFE666.C8C6136C@c-s.fr> <1106394057.320879.319110@f14g2000cwb.googlegroups.com> Message-ID: <41F33837.6020306@iinet.net.au> kishore wrote: > Hi Luigi Ballabio, > > Thankyou very much for your reply, > it worked well. It does work in most cases, but "getattr(self, methodName)" is generally to be preferred over "vars(self.__class__)[methodName]", as the latter does not use Python's standard attribute lookup scheme. The semantics of the following two statements are basically identical: getattr(t, 'bar')() t.bar() Using vars() directly, however, results in a slightly different lookup process that will *usually* give the same answer as above, but not always. It's that 'not always' which can end up hurting. . . Regards, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steve at holdenweb.com Thu Jan 20 09:04:00 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 20 Jan 2005 09:04:00 -0500 Subject: Zen of Python In-Reply-To: <7xekggbrns.fsf@ruckus.brouhaha.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Tim Peters writes: > >>>Huh? [1,2,[3,4,5],[6,[[[[7]],8]]]] is a perfectly valid Python list. >> >>You're claiming not to know any relevant difference between Python >>lists and Lisp lists? Heh. > > > Python doesn't provide syntactic sugar for [1,[2,[3,[4,[]]]]] if > that's what you mean. In Lisp you'd say (1 2 3 4). It's still > a perfectly valid list in Python. Python by convention uses > multi-element arrays instead of lists of conses. > But how, in Lisp, would you transliterate the Python list [1, 2, 3, 4]? Clearly the Python list *is* different, and the tradeoff was to obtain speed of random access, presumably (I wasn't taking an interest in Python in its early days) anticipating that non-recursive algorithms would be the norm. > >>>And you can break out of a containing loop from a nested loop >>>with try/raise. >> >>Heh heh. Yes, you can. I've never seen a real Python program that >>did, but there's nothing to stop you. > > > I do that on a fairly routine basis. I won't say "often", but it's a > standard technique that finds a use now and then. > Well, I blush to say I have done that (once, if my memory serves me correctly), but it was an ugly program, and I did eventually refactor the code so that the loops were in separate scopes, which made it much cleaner. [...] > > There's a technique in numerical analysis called Richardson > extrapolation, where you compute an integral by [...] Wow. Anyone who feels the need to explain numerical analysis techniques to Tim Peters is wasting keystrokes big-time. Anyway, Richardson extrapolation is merely one of many successive approximation techniques, which is what you are talking about, no? > > I see the same thing happening in Python. It's going through > successively better approximations to get closer to a limit. Python > has it harder than some other languages, because it tries to serve the > needs of both throwaway scripts and large-scale development projects. > The result is that feature after feature starts out with an > implementation sufficient for small scripts, and then edges towards > the needs of large-scale projects. But it's often predictable at the > beginning what the final destination is going to be. So once we can > see where it's going, why not proceed to the finish line immediately > instead of bothering with the intermediate steps? Perhaps because we don't all have your psychic powers? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From ruses at users.ch Sat Jan 1 20:10:37 2005 From: ruses at users.ch (not [quite] more i squared) Date: Sun, 02 Jan 2005 02:10:37 +0100 Subject: Jython & IronPython Under Active Development? In-Reply-To: <1104039182.718016.78800@f14g2000cwb.googlegroups.com> References: <1104033303.754319.269650@c13g2000cwb.googlegroups.com> <1104039182.718016.78800@f14g2000cwb.googlegroups.com> Message-ID: <33ovhlF4174m3U1@individual.net> Simon John a ?crit : > jython just had a new and (thus) secret afaik > release From aleaxit at yahoo.com Sun Jan 9 06:41:47 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 9 Jan 2005 12:41:47 +0100 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1gq4ebf.17qqy8dk9ccr6N%aleaxit@yahoo.com> Message-ID: <1gq4frz.qt7y5notvifvN%aleaxit@yahoo.com> Nick Coghlan wrote: > Alex Martelli wrote: > > I wonder if 'with', which GvR is already on record as wanting to > > introduce in 3.0, might not be overloaded instead. > > Perhaps we could steal 'using' from the rejected decorator syntax. > > x = [f(x) for x in seq] using: > def f(x): > return x * x If 'with' is going to become a keyword anyway, I suspect that many, Guido included, would see giving 'with' two distinct syntax roles as a lower 'price' than introducing yet another keyword, as long of course as no ambiguity results. 'import', for example, is happily reused for both 'import foo' and 'from foo import bar'. In terms of readability I see nothing in it, either way, between 'with' and 'using' (and 'where', were it not for the wildly different semantics it has in SQL) -- e.g. your example seems to read just fine with any of these keywords. If the use Guido intends for 'with' is something like: with aname: .x = .y meaning aname.x = aname.y then there would be no ambiguity between this use of with as a leading keyword in the new statement, always followed by a name; and its use in the "with clause", where it always comes after an expression and is immediately followed by a colon. I mean, no ambiguity for either the parser or a human reader, I believe. Once the AST-branch is folded back into the CVS head, playing around with syntax should be much easier than today... Alex From belovedbob at XXgreennet.net Thu Jan 27 21:06:04 2005 From: belovedbob at XXgreennet.net (Robert Kaplan) Date: Thu, 27 Jan 2005 21:06:04 -0500 Subject: Greetings and win32 com events question Message-ID: <41f9d4f2$1@news.greennet.net> Hi, I'm new to the group, so greetings all! I'm working on an application try to respond to events in Microsoft Access using Python and win32com. However, I'm having trouble in setting up the event handlers. I can think of 2 approaches both of which yield win32com errors. First is the approach used the MSOfficeEvents.py test program. The problem is that the events to be picked up are not on the Application object but on a Form object created from it. class AcEvents def OnActivate(self): print "Hello from Access" return 1 self. ac = Dispatch ("Access.Application") self. db = self. ac. NewCurrentDatabase ("d:\\pyhack\\foo") self. fm = self. ac. CreateForm () self. ac. Visible = true self. fm = DispatchWithEvents (self. fm, AcEvents) blows out with self. fm = DispatchWithEvents (self. fm, AcEvents) File "D:\PYTHON22\Lib\site-packages\win32com\client\__init__.py", line 258, in DispatchWithEvents clsid = disp_class.CLSID AttributeError: 'NoneType' object has no attribute 'CLSID'. I also tried a variety of string arguments, but all of those also yielded an invalid class id error. The other approach is more Visual Basic like: self. ac = Dispatch ("Access.Application") self. db = self. ac. NewCurrentDatabase ("d:\\pyhack\\foo") self. fm = self. ac. CreateForm () self. ac. Visible = true self. ev = AcEvents () self. fm. OnActivate = self. ev. OnActivate this couldn't set the OnActivate attribute with the following error. File "D:\pyhack\1\Bob.py", line 132, in DoAccess self. fm. OnActivate = self. ev. OnActivate File "D:\PYTHON22\Lib\site-packages\win32com\client\__init__.py", line 503, in __setattr__ d.__setattr__(attr, value) File "D:\PYTHON22\Lib\site-packages\win32com\client\__init__.py", line 463, in __setattr__ self._oleobj_.Invoke(*(args + (value,) + defArgs)) TypeError: Objects of type 'instance method' can not be converted to a COM VARIANT Anyone know how to do this, either strategy is fine. Thanks Robert Kaplan (Remove XX for e-mail) From daniel.dittmar at sap.corp Tue Jan 18 13:05:37 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Tue, 18 Jan 2005 19:05:37 +0100 Subject: One-Shot Property? In-Reply-To: <20050118115456510-0500@braeburn.themorgue.org> References: <20050118115456510-0500@braeburn.themorgue.org> Message-ID: Kevin Smith wrote: > I have many cases in my code where I use a property for calculating a > value on-demand. Quite a few of these only need to be called once. > After that the value is always the same. In these properties, I set a > variable in the instance as a cached value and return that value on > subsequent calls. It would be nice if there was a descriptor that would > do this automatically. Actually, what would be really nice is if I > could replace the property altogether and put the calculated value in > its place after the first call, but the property itself prevents me from > doing that. Is this possible? If you use the old-fashioned __getattr__ method instead of properties. __getattr__ gets called only if the value can't be found in the instance dictionary. def __getattr__ (self, attrname): try: method = getattr (self, 'calculate_' + attrname) except AttributeError: raise AttributeError, attrname value = method () setattr (self, attrname, value) return value And probably also through metaclasses. And decorators. Daniel From cam.ac.uk at mh391.invalid Tue Jan 11 20:31:08 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 12 Jan 2005 01:31:08 +0000 Subject: shutil.move has a mind of its own In-Reply-To: References: Message-ID: Daniel Bickett wrote: > As it happens, the > desired locations are system folders (running windows xp, the folders > are as follows: C:\WINDOWS, C:\WINDOWS\SYSTEM, C:\WINDOWS\SYSTEM32). > To see if this factor was causing the problem, I tried it using the > interpreter, and found it to be flawless. I'm not entirely sure what that last sentence means. But does it mean that shutil.move() works fine if you do it interactively but not in your code? The simplest interpretation then would be that there is something wrong in your code. Why don't you post the debug output of that quoted section of code? What version of Python are you using? Is it the standard Windows distribution? -- Michael Hoffman From lists at swaroopch.info Tue Jan 4 09:56:38 2005 From: lists at swaroopch.info (Swaroop C H) Date: Tue, 04 Jan 2005 20:26:38 +0530 Subject: How to access database? In-Reply-To: References: Message-ID: Florian Lindner wrote: > Hello, > AFAIK python has a generic API for database access which adapters are > supposed to implement. How can I found API documentation on the API? I found these pages useful when learning the DB API: * http://www.kitebird.com/articles/pydbapi.html * http://www.amk.ca/python/writing/DB-API.html HTH, -- Swaroop C H Blog: http://www.swaroopch.info/ From Scott.Daniels at Acm.Org Mon Jan 10 19:11:29 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 10 Jan 2005 16:11:29 -0800 Subject: Writing huge Sets() to disk In-Reply-To: References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <41e2f24d$1@nntp0.pdx.net> Message-ID: <41e316cf@nntp0.pdx.net> Martin MOKREJ? wrote: >.... But I don't think I can use one-way hashes, as I need to reconstruct > the string later. I have to study hard to get an idea what the proposed > code really does. > > Scott David Daniels wrote: >> Tim Peters wrote: >>> .... Call the set of all English words E; G, C, and P similarly. >>> >>> This Python expression then gives the set of words common to all 4: >>> E & G & C & P >>> and for those unique to Polish. >>> P - E - G - C >> >> One attack is to define a hash to get sizes smaller. Suppose you find >> your word sets are 10**8 large, and you find you need to deal with sets >> of size 10**6. Then if you define a hash that produces an integer below >> 100, you'll find: >> E & G & C & P == Union(E_k & G_k & C_k & P_k) for k in range(100) >> P - E - G - C == Union(P_k - E_k - G_k - C_k) for k in range(100) >> where X_k = [v for v in X if somehash(v) == k] > > I don't understand here what would be the result from the hashing > function. :( ... Can you clarify this please in more detail? The trick is to build the X_k values into files. For example: for base in range(0, 100, 10): # work in blocks of 10 (or whatever) for language in ('English', 'German', 'Czech', 'Polish'): source = open(language) dests = [open('%s_%s.txt' % (language.lower(), base + n), 'w') for n in range(10)] for word in source: # Actually this is probably more involved code = somehash(word) - base if 0 <= code < base: dests[code].write(word + '\n') for dest in dests: dest.close() source.close() After running the above code, you get 400 files with names like, for example, 'english_33.txt'. 'english_33.txt' contains only words in English which hash to 33. Then you need to sort the different files (like 'english_33.txt') before using them in the next phase. If you can sort and dupe-elim in the same step, do that and get rid of the calls to dupelim below. Otherwise use dupelim below when reading the sorted files. If you must, you might want to do the sort and dupe-elim in Python: for language in ('english', 'german', 'czech', 'polish'): for hashcode in range(100): filename = '%s_%s.txt' % (language, hashcode) source = open(filename) lines = sorted(source) source.close() dest = open(filename, 'w') for line in dupelim(lines): dest.write(line) dest.close() >> def inboth(left, right): .... >> def leftonly(left, right): .... > Aaaah, so the functions just walk one line in left, one line in right, > if values don't match the value in left is unique, it walks again one > line in left and checks if it already matches the value in right file > in the last position, and so on until it find same value in the right file? Exactly, you must make sure you deal with cases where you pass values, match values, and run out of source -- that keeps these from being four- liners. >> For example: >> >> Ponly = open('polishonly.txt', 'w') >> every = open('every.txt', 'w') >> for hashcode in range(100): >> English = open('english_%s.txt' % hashcode) > ^^^^^^^^^^^^^^^^^^^^^^^^^^ this is some kind of eval? If hashcode == 33 then 'english_%s.txt' % hashcode == 'english_33.txt' So we are just finding the language-specific for-this-hash source. >>... for unmatched in leftonly(leftonly(leftonly(dupelim(Polish), >> dupelim(English)), dupelim(German)), dupelim(Czech)): >> Ponly.write(unmatched) >> for source in (Polish, English, German, Czech):#(paraphrased) >> source.seek(0) >> for match in inboth(inboth(dupelim(Polish), upelim(English)), >> inboth(dupelim(German), dupelim(Czech))): >> every.write(match) >> for source in (Polish, English, German, Czech):#(paraphrased) >> source.close() >> Ponly.close() >> every.close() --Scott David Daniels Scott.Daniels at Acm.Org From harold.fellermann at upf.edu Tue Jan 18 14:03:03 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 18 Jan 2005 20:03:03 +0100 Subject: pickling extension class Message-ID: <94A09CD0-6983-11D9-831B-003065FB7B26@upf.edu> Hi all, I have a problem pickling an extension class. As written in the Extending/Embedding Manual, I provided a function __reduce__ that returns the appropreate tuple. This seams to work fine, but I still cannot pickle because of the following error: >>> from model import hyper >>> g = hyper.PeriodicGrid(4,4,1) >>> g.__reduce__() (,(4.,4.,1.)) >>> import pickle >>> pickle.dump(g,file("test","w")) Traceback (most recent call last): File "pickle_test.py", line 5, in ? pickle.dump(g,file("test","w")) File "/sw/lib/python2.4/pickle.py", line 1382, in dump Pickler(file, protocol, bin).dump(obj) File "/sw/lib/python2.4/pickle.py", line 231, in dump self.save(obj) File "/sw/lib/python2.4/pickle.py", line 338, in save self.save_reduce(obj=obj, *rv) File "/sw/lib/python2.4/pickle.py", line 414, in save_reduce save(func) File "/sw/lib/python2.4/pickle.py", line 293, in save f(self, obj) # Call unbound method with explicit self File "/sw/lib/python2.4/pickle.py", line 760, in save_global raise PicklingError( pickle.PicklingError: Can't pickle : it's not found as hyper.PeriodicGrid >>> dir(hyper) ['Dir', 'Neighbors', 'PeriodicGrid', 'PeriodicPos', '__doc__', '__file__', '__name__', 'refcount'] >>> hyper.PeriodicGrid So pickle complains about the class PeriodicGrid not being found in the module hyper, but a dir() proves that python can find it. Has anyone an idea what's going wrong here? Any help appreceated, - harold - -- What is mind? -- Doesn't matter. What is matter? -- Never mind! -- From joh12005 at yahoo.fr Fri Jan 28 10:39:42 2005 From: joh12005 at yahoo.fr (Joh) Date: 28 Jan 2005 07:39:42 -0800 Subject: some kind of LFU dict... Message-ID: <63b5e209.0501280739.3887d82@posting.google.com> Hello, (first i'm sorry for my bad english...) for a program, i need to have some kind of dictionary which will contain a huge amount of keys and values. i have tried 'to do it simple' using a normal dict but when available memory was exhausted, my computer started to be really slow as it swap-ed. so i wondered if i can not use some kind of cache, i googled and found information on LRU, LFU, and LFU interested me : keep only most frequently used items inside dict (and memory) and writing others on disk for a possible future reuse. here is a silly attempt to do it, it still missed some features but before to continue i would like to have your opinions. i'm interested in any propositions or refactorisations :) and btw i may have missed others already/tuned/better solutions... best. --- import fileinput, pickle, random, shutil, sys class sLFU: TMP = """%s.bak""" """ a simple kind of Least Frequently Used container""" def __init__(self, size, ratio, filename = None): """ filename = a temporary file which will could be deleted""" self.d = {} # container self.size, self.ratio = size, ratio self.freqs, self.fmin = {}, 0 self.filename = filename if self.filename: open(self.filename, 'w') def __setitem__(self, obj, v): self.d[obj] = v self.freqs[obj] = self.freqs.get(obj, self.fmin) + 1 if len(self.d) > self.size: """ lfu = { (size / ratio) least frequently used objects... }""" freqs = [(f, obj) for (obj, f) in self.freqs.items()] # maybe should i use a generator () like # ((f, obj) for (obj, f) in self.freqs.items()) freqs.sort() lfu = {} # and here enumerate(sorted(freqs)) for i, (f, obj) in enumerate(freqs): if i > self.size / self.ratio: break lfu[obj] = self.d[obj] """ next minimal frequency will be max frequency of the lfu (maybe it would be better to substract this from others in self.freqs)""" self.fmin = f """ and now delete theses objects...""" for obj in lfu: del self.freqs[obj] del self.d[obj] if self.filename: """ now must save lfu to disk... as i do not managed to do otherwise, copy file to a tmp file and read it line by line, updating when necessary... there must be plenty rooms for improvement here :(""" shutil.copy(self.filename, self.TMP % self.filename) fhs = open(self.TMP % self.filename) fh = open(self.filename, 'w') """ flag to ignore 'value' line""" ignoreNext = False for i, line in enumerate(fhs): """ first copy old lfu which were already set, updating them if necessary...""" if ignoreNext: ignoreNext = False continue line = line.rstrip() if i % 2 == 0: obj = self.loads(line) if obj not in lfu and obj in self.d: """ obj available from memory, do not to keep it on disk...""" ignoreNext = True continue elif obj in lfu: """ obj was available from memory, but as a lfu, was removed and must be updated on disk""" fh.write("%s\n" % line) fh.write("%s\n" % self.dumps(lfu[obj])) del lfu[obj] ignoreNext = True continue """ default behaviour : copy line...""" fh.write("%s\n" % line) """ from now lfu should contain only unseen lfu objects, add them to file...""" fh = open(self.filename, 'a') for obj in lfu: fh.write("%s\n" % self.dumps(obj)) fh.write("%s\n" % self.dumps(lfu[obj])) def __getitem__(self, obj): if obj in self.d: """ from memory :)""" return self.d[obj] if self.filename: """ if a filename was provided, search inside file if such an obj is present, then return it ; else raise IndexErrror.""" fh = open(self.filename) found = False for i, line in enumerate(fh): line = line.rstrip() if found: v = self.loads(line) self.d[obj] = v self.freqs[obj] = self.fmin + 1 return v if obj == self.loads(line): found = True raise KeyError(obj) """ maybe class methods would have been better here, actually i would have liked static + class... totally arbitrary format, haved choosed to use pickle, odd line contain 'obj' (next) even line contain 'value' """ def dumps(self, s): return pickle.dumps(s).replace("\n", "\t") staticmethod(dumps) def loads(self, s): return pickle.loads(s.replace("\t", "\n")) staticmethod(loads) lfu = sLFU(2, 2, 'slfu.txt') lfu[1] 8 = {'1': 1fd2 'a'} lfu[2] = [] lfu[3] = '3' lfu[2] = [1,] lfu[2] = [1,2] lfu[4] = 4 lfu[5] = '5' print "#d", len(lfu.d) print lfu.d print "".join(open(lfu.filename).readlines()) From firstname.lastname at iki.fi-spam Sat Jan 1 16:26:59 2005 From: firstname.lastname at iki.fi-spam (Simo Melenius) Date: 01 Jan 2005 23:26:59 +0200 Subject: Securing a future for anonymous functions in Python References: <10t84q9icqjnie7@news.supernews.com> <41d607d8.1558267600@news.oz.net> Message-ID: bokr at oz.net (Bengt Richter) writes: > ISTM you don't need "end" -- just put the def expression in parens, > and let the closing paren end it, e.g.: I first rejected any parens as not being native to how classes/toplevel functions/control blocks are written in Python. However, this looks quite clear to me. I'd expect that in most cases it would be difficult to mistake a block of statements in parentheses with e.g. tuple notation. And parensing works with the old "lambda" already, of course. br, S From steven.bethard at gmail.com Fri Jan 21 14:44:30 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 12:44:30 -0700 Subject: problems with duplicating and slicing an array In-Reply-To: References: <7cffadfa05012017337858d171@mail.gmail.com> Message-ID: py> import numarray as na py> a = na.array([[1,2,3],[4,5,6]]) Yun Mao wrote: > Thanks for the help. numarray doesn't provide what I look for either. e.g. > a = array( [[1,2,3],[4,5,6]] ) > I sometimes what this: a[ [1,0], :], py> a[[1,0]] array([[4, 5, 6], [1, 2, 3]]) > or even a[ [1,0], [0,1] ] , which should give me > [[4, 5], [1,2]] py> a[:,:2][[1,0]][[0,1]] array([[4, 5], [1, 2]]) Not the same syntax, of course, but doable. Steve From invalidemail at aerojockey.com Tue Jan 25 12:39:16 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 25 Jan 2005 09:39:16 -0800 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: <1106624803.825442.73870@f14g2000cwb.googlegroups.com> Message-ID: <1106674756.039497.232880@c13g2000cwb.googlegroups.com> Roy Smith wrote: > "Carl Banks" wrote: > > > > Imbed > > EMBED. > > My apologies for being sloppy. And with an initial capital, so it just > jumps off the page at you :-) Ok. Prescriptive language isn't normally my cup of tea, but there's always something. And usually it's very silly. > > > Python, or Perl, or TCL, or Ruby, or PHP, > > > > Not PHP. PHP is one of the better (meaning less terrible) examples of > > what happens when you do this sort of thing, which is not saying a lot. > > But, that's exactly my point. To be honest, I've never used PHP. But > however bad it may be, at least it's got a few years of people fixing > bugs, writing books, writing add-on tools, etc, behind it. Better to > use somebody else's well-known and well-supported mess of a scripting > language than to invest several person-years inventing your own mess > that's no better. Well, if you look at it that way, I guess so. My mindset was closer to "hacked-up quasi-languages are evil" than "hacked-up quasi-languages are not worth the time to implement when there are plenty of hacked-up quasi-languages already out there, not to mention some real languages." -- CARL BANKS From flupke at nonexistingdomain.com Fri Jan 7 08:38:40 2005 From: flupke at nonexistingdomain.com (flupke) Date: Fri, 07 Jan 2005 13:38:40 GMT Subject: 2 versions of python on 1 machine In-Reply-To: <0fydnX5CmoCCwkDcRVn-2w@powergate.ca> References: <0fydnX5CmoCCwkDcRVn-2w@powergate.ca> Message-ID: Peter Hansen wrote: > > On my machine, I have a folder called c:\bin where I put useful > batch files. I have a python23.bat and a python24.bat file, > which basically just call c:\python23\python.exe or > c:\python24\python.exe as required. For various reasons which > may or may not apply to you as well, I also have each of them > set the PYTHONHOME variable to point to the right folder > as well. > > The content of each batch file is like this: > @echo off > c:\python23\python.exe %1 %2 %3 %4 %5 %6 %7 %8 %9 > > -Peter I used the 2 batch files technique and removed c:\python23 from my path var and all is fine now. Where did you find more info on PYTHONHOME and PYTHONPATH because the docs don't seem to contain a whole lot of info. Thanks Benedict From tzot at sil-tec.gr Fri Jan 21 04:02:52 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 21 Jan 2005 11:02:52 +0200 Subject: tkinter socket client ? References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> Message-ID: <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> On 20 Jan 2005 22:25:52 -0800, rumours say that "Tonino" might have written: [tkinter gui for a socket client, lots of data from the socket] >NOW - HOW do I get the server's sent data to continuiosly print in the >Text() widget ? You need to use: yourTextWidget.insert(Tkinter.END, data) # to insert the data yourRootWindow.update_idletasks() # to update the GUI -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From fortepianissimo at gmail.com Fri Jan 21 09:40:59 2005 From: fortepianissimo at gmail.com (fortepianissimo) Date: 21 Jan 2005 06:40:59 -0800 Subject: Example of resolving an alias using Carbon.File module? In-Reply-To: <1106286928.806519.67720@c13g2000cwb.googlegroups.com> References: <1106286928.806519.67720@c13g2000cwb.googlegroups.com> Message-ID: <1106318459.779438.181380@f14g2000cwb.googlegroups.com> Problem solved: from Carbon.File import * fs, _, _ = ResolveAliasFile('/some/path', 1) print fs.as_pathname() From ncoghlan at iinet.net.au Mon Jan 31 07:08:07 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 31 Jan 2005 22:08:07 +1000 Subject: test_socket.py failure In-Reply-To: References: Message-ID: <41FE1FA7.7000508@iinet.net.au> x2164 at mailcity.com wrote: > hi all, > > Linux 2.4.28 > Glibc 2.2.5 > gcc 2.95.3 > > > I'm new to Python. > > I've compiled Python 2.4 from tar file. > > When running 'make test' i'm getting a failure > in test_socket. > Two questions. First, what does the following code give when you run it at the interactive prompt?: Py> import socket Py> socket.getservbyname('daytime') 13 Second, is there an entry for 'daytime' in /etc/services? Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From http Sat Jan 22 13:46:01 2005 From: http (Paul Rubin) Date: 22 Jan 2005 10:46:01 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> Message-ID: <7xpszxcnfa.fsf@ruckus.brouhaha.com> "Fredrik Lundh" writes: > "lack of understanding of how Python is used" > > wonderful. I'm going to make a poster of your post, and put it on my > office wall. Excellent. I hope you will re-read it several times a day. Doing that might improve your attitude. From timj at tolisgroup.com Mon Jan 17 16:18:04 2005 From: timj at tolisgroup.com (brucoder) Date: 17 Jan 2005 13:18:04 -0800 Subject: Adjusting the 1024 byte stdin buffer limit References: <1105989047.516986.59990@z14g2000cwz.googlegroups.com> <1105989764.168794.113430@z14g2000cwz.googlegroups.com> Message-ID: <1105996684.110078.303400@f14g2000cwb.googlegroups.com> Hi All, - Thanks, but it seems I may have been a bit more confused that even I thought. It turns out to be an issue with Apple's OS X pty/tty interface. Even though the mediator tool is set up to read in up to 20K of data, the pty interface blocks at 1024 bytes. When testing this under Linux, I'm fine. And, Solaris 8 weaves an even more diabolical 255 character limit :( . - Looks like I'll need to be a bit more creative than simply spawning a shell. - Tim Fredrik Lundh wrote: > "brucoder" wrote: > > > Currently, when sending a data stream that exceeds 1024 bytes via > > stdin, the stream blocks at the 1024th byte. This precludes completion > > of the submission of the data stream. > > you can pass in a buffer size when you open a file: > > >>> help(open) > > class file(object) > | file(name[, mode[, buffering]]) -> file object > | > | Open a file. The mode can be 'r', 'w' or 'a' for reading (default), > | writing or appending. The file will be created if it doesn't exist > | when opened for writing or appending; it will be truncated when > | opened for writing. Add a 'b' to the mode for binary files. > | Add a '+' to the mode to allow simultaneous reading and writing. > | If the buffering argument is given, 0 means unbuffered, 1 means line > | buffered, and larger numbers specify the buffer size. > | Add a 'U' to mode to open the file for input with universal newline > | support. Any line ending in the input file will be seen as a '\n' > | in Python. Also, a file so opened gains the attribute 'newlines'; > | the value for this attribute is one of None (no newline read yet), > | '\r', '\n', '\r\n' or a tuple containing all the newline types seen. > | > | 'U' cannot be combined with 'w' or '+' mode. > | > | Note: open() is an alias for file(). > > or use os.fdopen() to reopen an existing file handle: > > >>> help(os.fdopen) > > fdopen(fd [, mode='r' [, bufsize]]) -> file_object > > Return an open file object connected to a file descriptor. > > assuming "sending via stdin" means using a pipe, this page explains why all > this probably won't matter: > > http://www.opengroup.org/onlinepubs/7990989799/xsh/write.html > > (see the "Write requests to a pipe or FIFO" section) > > From steve at holdenweb.com Sat Jan 8 14:22:33 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 08 Jan 2005 14:22:33 -0500 Subject: Working with recordsets In-Reply-To: References: <1105119853.927871.293390@z14g2000cwz.googlegroups.com> Message-ID: AdSR wrote: > chema.rey at gmail.com wrote: > >> Hi. >> >> I have one recorset that I would like to pass to 2 functions, one is >> for create an CSV file and the other one is to create a HTML file. The >> problem is that the recordset is totally read in the first function, >> and then when I pass it to the second funtion the recordset is in the >> last record. >> >> I've read docs, but I think that one cursor doesn't have something >> like movefirst() method. Anybody have an idea to solve this? >> >> Thank's. >> > > Try loading the whole recordset with the fetchall() method and use the > resulting sequence in your functions. It won't be memory-efficient but > it will be easy to do. > > AdSR Or, if this doesn't suit, try creating two separate cursors from the same connection and execute the same query on each. There's some chance that your database driver/backend combination will optimize the queries then. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From yaniv_vi at yahoo.com Tue Jan 4 14:52:17 2005 From: yaniv_vi at yahoo.com (yaniv_vi at yahoo.com) Date: 4 Jan 2005 11:52:17 -0800 Subject: python and activex Message-ID: <1104868337.380580.247840@z14g2000cwz.googlegroups.com> Hi , Has anybody used jython and visual j++ togheter to do python and activeX integration ? is there a simpler way (except win32all , which i feel is non trivial , at least not as dragging components ) Thanks ,yaniv From fredrik at pythonware.com Mon Jan 24 07:44:18 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 13:44:18 +0100 Subject: Py2.4 .exe installer References: Message-ID: Facundo Batista: > The bigger problem I'm facing is that the "official" operating system > installed in the PCs is Win NT 4.0, tweaked and restricted, and it's > impossible to install the Microsoft package that enables the .msi as a > installer. > > Result: they can not install Py24.msi. > > There's somewhere a Py24.exe installer? you could of course install it on a W2K or WXP box, and zip it up (don't forget the python24.dll under /windows/system32; you can copy it to the \python24 directory before zipping it all). copy, unzip, and you're done. if you need to register the interpreter on the target machine (so you can install extensions), use this little script: http://effbot.org/zone/python-register.htm From craig at postnewspapers.com.au Fri Jan 7 00:54:18 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 07 Jan 2005 13:54:18 +0800 Subject: File Handling Problems Python I/O In-Reply-To: <1105034789.700445.291380@z14g2000cwz.googlegroups.com> References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> <1105034789.700445.291380@z14g2000cwz.googlegroups.com> Message-ID: <1105077258.28776.67.camel@rasputin.localnet> On Fri, 2005-01-07 at 02:06, Josh wrote: > Peter, > > Thank you for the rookie correction. That was my exact problem. I > changed the address to use forward slashes and it works perfect. I did > not know that a backslash had special meaning within a string, but now > I do! Thanks again There's another common mistake you might want to head off now, too. Consider the following program: -------- directory = r"c:\mydata" datafilename = "something.txt" datafile = open(directory + datafilename,"r") --------- It's very common for this to happen, usually when the paths are originally written with trailing slashes then changed to not have them later. Rather than saying "all paths must have trailing slashes", manually formatting in slashes, or other platform-specific uglyness, consider using the os.path module to take care of it: -------- import os directory = r"c:\mydata" datafilename = "something.txt" datafile = open(os.path.join(directory,datafilename),"r") -------- This will work on any platform (so long as the literal paths are correct) and will work no matter whether or not there are trailing path separators on the input strings. os.path.join can take more than two arguments, too. os.path has lots of other handy tools, so I strongly recommend checking it out. -- Craig Ringer From guy at NOSPAM.r-e-d.co.nz Mon Jan 17 06:05:10 2005 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Tue, 18 Jan 2005 00:05:10 +1300 Subject: getting a class attribute using a keyword argument Message-ID: Hello, I have a list of class instances. I wish to get the appropriate class attribute in each class instance depending on a SINGLE keyword in the calling class. How do I get the calling method to correctly recognise the keyword as a keyword and not a class attribute? See example code below (which doesn't work). class tocall: def __init__(self): self.title = "test" self.name = "name" def callingmethod(self,**kw): for key in kw: if tocall.key == kw[key]: return tocall.key which should work as such(but doesn't): print callmethod(title = "test") print callmethod(name = "name") Regards, Guy From beliavsky at aol.com Sun Jan 9 18:40:15 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 9 Jan 2005 15:40:15 -0800 Subject: read numbers from file and covert to integer References: Message-ID: <1105314015.776099.151250@c13g2000cwb.googlegroups.com> If you have a file "ints.txt" with contents 10 20 30 40 50 60 You could read integers into a list with ivec = [] for text in open("ints.txt","r"): words = text.split() for x in words: ivec.append(int(x)) print ivec If you know you want to read two integers into variables a,b from a line you could write a,b = int(words[0]),int(words[1]) Excuse me, but if your question is really so elementary that this post answered it, you should probably read a book or tutorial. From http Mon Jan 10 20:11:41 2005 From: http (Paul Rubin) Date: 10 Jan 2005 17:11:41 -0800 Subject: Port blocking References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> <34f8ovF47d783U1@individual.net> Message-ID: <7xvfa43h2q.fsf@ruckus.brouhaha.com> Mark Carter writes: > >>Also, is there a good tool for writing database UIs? > > Yes, quite a few. > > Ah yes, but is there really? For example, I did a search of the TOC of > GTK+ Reference Manual: Try looking on freshmeat or sourceforge instead. From peter at engcorp.com Wed Jan 26 16:30:30 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 Jan 2005 16:30:30 -0500 Subject: Inherting from object. Or not. In-Reply-To: References: Message-ID: <3eSdndWMePFqlmXcRVn-jg@powergate.ca> Frans Englich wrote: > What is the difference between inherting form object, and not doing it? Although this doesn't provide a description of all the implications, it does give you the basic answer to the question and you can easily do further research to learn more: http://www.python.org/doc/2.2.1/whatsnew/sect-rellinks.html#SECTION000310000000000000000 (Summary: inheriting from object gives you a "new-style" class, not doing so gives you a classic class, and there are a variety of differences resulting from that.) -Peter From ncoghlan at iinet.net.au Sat Jan 8 01:08:43 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 16:08:43 +1000 Subject: python3: 'where' keyword In-Reply-To: <3480qqF46jprlU1@individual.net> References: <3480qqF46jprlU1@individual.net> Message-ID: <41DF78EB.6040502@iinet.net.au> Andrey Tatarinov wrote: > Hi. > > It would be great to be able to reverse usage/definition parts in > haskell-way with "where" keyword. Since Python 3 would miss lambda, that > would be extremly useful for creating readable sources. > > Usage could be something like: > > >>> res = [ f(i) for i in objects ] where: > >>> def f(x): > >>> #do something Hmm, this is actually a really interesting idea. Avoiding accidental namespace conflicts is certainly one of the advantages of using lambdas. This idea has the virtue of being able to do the same thing, but have full access to Python's function syntax and assignment statements in the 'expression local' suite. In fact, any subexpressions in a complicated expression can be extracted and named for clarity without fear of screwing up the containing namespace, which would be an enormous boon for software maintainers. It also allows the necessary but uninteresting setup for an expression to be moved "out of the way", bringing the expression that does the real work to prominence. From the interpreter's point of view, the meaning would probably be something like: namespace = locals() exec where_suite in globals(), namespace exec statement in globals(), namespace res = namespace["res"] del namespace Making the 'where' clause part of the grammar for the assignment statement should be enough to make the above example parseable, too. The clause might actually make sense for all of the simple statement forms in the grammar which contain an expression: expression statement assignment statement augmented assignment statement del statement print statement return statement yield statement raise statement exec statement The clause really isn't appropriate for break, continue, import or global statements, as they don't contain any expressions :) For compound statements, a where clause probably isn't appropriate, as it would be rather unclear what the where clause applied to. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tzot at sil-tec.gr Mon Jan 3 09:25:32 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 03 Jan 2005 16:25:32 +0200 Subject: Switch statement (was: Lambda going out of fashion) References: <3e8ca5c8041222201332fb0b92@mail.gmail.com> Message-ID: On Thu, 23 Dec 2004 19:57:27 GMT, rumours say that rzed might have written: [Why did PEP 275 stall?] >It seems to me that it was regarded as misguidod. QOTPE +1 (PE=Python Era) Oncoming Python book: "Hitchhiker's Guido to the Python Language" -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From fred at adventistcare.org Mon Jan 3 13:12:25 2005 From: fred at adventistcare.org (Sells, Fred) Date: Mon, 3 Jan 2005 13:12:25 -0500 Subject: Developing Commercial Applications in Python Message-ID: <777056A4A8F1D21180EF0008C7DF75EE03317240@sunbelt.org> At Sunrise Software International, we build commercial applications for Cabletron and the Florida DMV. This was ~10 years ago; so no useful docs available, but we had no problems with license. -----Original Message----- From: Richards Noah (IFR LIT MET) [mailto:Noah.Richards at infineon.com] Sent: Monday, January 03, 2005 12:20 PM To: python-list at python.org Subject: Re: Developing Commercial Applications in Python > wrote in message > news:1104750017.235937.181370 at c13g2000cwb.googlegroups.com... > > Hello All, > > I am trying to convince my client to use Python in his new product. He > > is worried about the license issues. Can somebody there to point me any > > good commercial applications developed using python ?. The licence > > clearly says Python can be used for commercial applications. Is there > > any other implications like that of GPL to make the source open ? > > Thanks for any help. > > eeykay > > "It's me" wrote in message news:mBeCd.5832$5R.1770 at newssvr21.news.prodigy.com... > Shaw-PTI (www.pti-us.com) uses Python in their software. See: > http://www.pti-us.com/pti/news/index.cfm and search "2004 PSS/E User Group > Meeting" > Begging your pardon, but a better resource would be the brochure available (http://www.pti-us.com/PTI/company/brochures/PSSE.pdf). It appears that the program was probably (originally) written in C/C++ (using MFC for the GUI), and now employs Python for adding modules and scripting support. Very interesting stuff :) -- http://mail.python.org/mailman/listinfo/python-list From fredrik at pythonware.com Thu Jan 13 18:30:50 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 14 Jan 2005 00:30:50 +0100 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com><7xmzvfn096.fsf@ruckus.brouhaha.com> <41e6f4b7.777345834@news.oz.net> Message-ID: Bengt Richter wrote: > Hm, that makes me wonder, is there an intermediate "returning of value" in > x = y = z = 123 > ? no. that statement evaluates the expression (123 in this case), and assigns the result (the integer object 123) to each target (x, y, z), in order. or to quote the language reference: An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right. From br44114 at yahoo.com Tue Jan 18 22:49:54 2005 From: br44114 at yahoo.com (bogdan romocea) Date: Tue, 18 Jan 2005 19:49:54 -0800 (PST) Subject: DDE client help Message-ID: <20050119034955.75129.qmail@web50306.mail.yahoo.com> Dear Python experts, I'm facing a simple problem which however I'm having a hard time solving. I have a DDE server with data that changes from time to time. I need to put together a DDE client that would 'notice' updated values on the server and append them as a new row in a text file. 1. How do I connect to the DDE server, and ask for data? In OpenOffice.org it looks very simple: =DDE("FPS";"TIME";"PRC") I also have some VB code which does the same thing: Private Sub Command1_Click() Text1.LinkTopic = "FPS|TIME" Text1.LinkItem = Text4.Text Text1.LinkMode = vbLinkAutomatic I checked the DDE client sample code from C:\Python24\Lib\site-packages\win32\Demos\dde, however I got stuck here: conversation.ConnectTo("FPS","PRC") Traceback (most recent call last): File "", line 1, in ? conversation.ConnectTo("FPS","PRC") error: ConnectTo failed 2. Once I manage to connect to the DDE server, how do I append the new data values in a text file? Suggestions and sample code will be highly appreciated. Thank you, b. __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail From merkosh at hadiko.de Fri Jan 7 05:49:25 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Fri, 07 Jan 2005 11:49:25 +0100 Subject: missing sys.setappdefaultencoding Message-ID: Hi, well, I wrote a nice python program which won't work if the default encoding has not been set from ascii to latin-1 or latin-15. However, the command sys.setappdefaultencoding is missing on a Python installation with Python 2.3.4 on Gentoo where it is present on Debian. Any ideas how to deal with this? Thanks in advance, Ciao Uwe From fumanchu at amor.org Sun Jan 23 01:34:30 2005 From: fumanchu at amor.org (Robert Brewer) Date: Sat, 22 Jan 2005 22:34:30 -0800 Subject: Python Scripting Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398260@exchange.hqamor.amorhq.net> Ali Polatel wrote: > I want to ask you a question about python scripting. > I want to know if I can design web-pages with python Yes. > or at least write html files with python. Yes. > and if I write html files with python and some CGI scripts > and upload them to the web-page .. does the people who view > those pages have to have python interpreters in their computers? No. > Another question is ... I am writing a bot for a chess server > in python and this bot should update a web-page when it gets > some commands from the server. How can i make a programme update > a web-page? If the file is local: open(filename, 'w').write(content) If the file is remote and you need to upload it via ftp, check out the ftplib module in the standard library, for starters. Robert Brewer MIS Amor Ministries fumanchu at amor.org From mwm at mired.org Sun Jan 2 18:18:43 2005 From: mwm at mired.org (Mike Meyer) Date: Sun, 02 Jan 2005 17:18:43 -0600 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <86ekh3qv1o.fsf@guru.mired.org> Bulba! writes: > This "free software" (not so much OSS) notion "but you can > hire programmers to fix it" doesn't really happen in practice, > at least not frequently: because this company/guy remains > ALONE with this technology, the costs are unacceptable. Yes, but fixing python software - even sloppily written python software - is pretty easy. I regularly see contracts to add a feature to or fix a bug in some bit of OSS Python. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From club4_2 at mail.ru Tue Jan 25 23:41:27 2005 From: club4_2 at mail.ru (Club-B42) Date: Wed, 26 Jan 2005 14:41:27 +1000 Subject: py2exe problem Message-ID: i've compiled my programm using command "python setup.py py2exe >1" python script works fine, but .exe version fails with ===================================================================== D:\[Egor]\Scripts\B-4-2\la2luncher\dist>la2launcher.exe Traceback (most recent call last): File "la2launcher.py", line 9, in ? File "config.pyc", line 11, in ? File "config.pyc", line 8, in u LookupError: no codec search functions registered: can't find encoding ===================================================================== python 2.3 ===================================================================== running py2exe creating D:\[Egor]\Scripts\B-4-2\la2launcher\build creating D:\[Egor]\Scripts\B-4-2\la2launcher\build\bdist.win32 creating D:\[Egor]\Scripts\B-4-2\la2launcher\build\bdist.win32\winexe creating D:\[Egor]\Scripts\B-4-2\la2launcher\build\bdist.win32\winexe\collect creating D:\[Egor]\Scripts\B-4-2\la2launcher\build\bdist.win32\winexe\temp creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist *** searching for required modules *** *** parsing results *** creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 copying C:\Python23\tcl\tcl8.4\auto.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\ascii.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\big5.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1250.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1251.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1252.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1253.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1254.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1255.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1256.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1257.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp1258.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp437.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp737.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp775.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp850.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp852.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp855.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp857.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp860.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp861.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp862.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp863.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp864.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp865.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp866.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp869.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp874.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp932.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp936.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp949.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\cp950.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\dingbats.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\ebcdic.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\euc-cn.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\euc-jp.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\euc-kr.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\gb12345.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\gb1988.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\gb2312-raw.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\gb2312.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso2022-jp.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso2022-kr.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso2022.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-1.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-10.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-13.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-14.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-15.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-16.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-2.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-3.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-4.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-5.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-6.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-7.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-8.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\iso8859-9.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\jis0201.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\jis0208.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\jis0212.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\koi8-r.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\koi8-u.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\ksc5601.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macCentEuro.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macCroatian.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macCyrillic.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macDingbats.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macGreek.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macIceland.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macJapan.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macRoman.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macRomania.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macThai.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macTurkish.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\macUkraine.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\shiftjis.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\symbol.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\encoding\tis-620.enc -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\encoding copying C:\Python23\tcl\tcl8.4\history.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\http1.0 copying C:\Python23\tcl\tcl8.4\http1.0\http.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\http1.0 copying C:\Python23\tcl\tcl8.4\http1.0\pkgIndex.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\http1.0 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\http2.4 copying C:\Python23\tcl\tcl8.4\http2.4\http.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\http2.4 copying C:\Python23\tcl\tcl8.4\http2.4\pkgIndex.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\http2.4 copying C:\Python23\tcl\tcl8.4\init.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 copying C:\Python23\tcl\tcl8.4\ldAout.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\msgcat1.3 copying C:\Python23\tcl\tcl8.4\msgcat1.3\msgcat.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\msgcat1.3 copying C:\Python23\tcl\tcl8.4\msgcat1.3\pkgIndex.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\msgcat1.3 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\opt0.4 copying C:\Python23\tcl\tcl8.4\opt0.4\optparse.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\opt0.4 copying C:\Python23\tcl\tcl8.4\opt0.4\pkgIndex.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\opt0.4 copying C:\Python23\tcl\tcl8.4\package.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 copying C:\Python23\tcl\tcl8.4\parray.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 copying C:\Python23\tcl\tcl8.4\safe.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 copying C:\Python23\tcl\tcl8.4\tclIndex -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\tcltest2.2 copying C:\Python23\tcl\tcl8.4\tcltest2.2\pkgIndex.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\tcltest2.2 copying C:\Python23\tcl\tcl8.4\tcltest2.2\tcltest.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4\tcltest2.2 copying C:\Python23\tcl\tcl8.4\word.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tcl8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\bgerror.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\button.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\choosedir.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\clrpick.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\comdlg.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\console.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\arrow.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\bind.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\bitmap.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\browse -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\button.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\check.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\clrpick.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\colors.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\cscroll.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\ctext.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\dialog1.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\dialog2.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\entry1.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\entry2.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\entry3.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\filebox.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\floor.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\form.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\hello -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\hscale.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\icon.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\image1.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\image2.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\earth.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\earthris.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\face.bmp -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\flagdown.bmp -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\flagup.bmp -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\gray25.bmp -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\letters.bmp -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\noletter.bmp -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\pattern.bmp -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\tcllogo.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\images\teapot.ppm -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos\images copying C:\Python23\tcl\tk8.4\demos\items.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\ixset -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\label.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\labelframe.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\license.terms -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\menu.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\menubu.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\msgbox.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\paned1.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\paned2.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\plot.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\puzzle.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\radio.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\README -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\rmt -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\rolodex -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\ruler.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\sayings.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\search.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\spin.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\square -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\states.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\style.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\tclIndex -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\tcolor -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\text.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\timer -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\twind.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\unicodeout.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\vscale.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\demos\widget -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\demos copying C:\Python23\tcl\tk8.4\dialog.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\entry.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\focus.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\logo.eps -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\logo100.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\logo64.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\logoLarge.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\logoMed.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\pwrdLogo.eps -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\pwrdLogo100.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\pwrdLogo150.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\pwrdLogo175.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\pwrdLogo200.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\pwrdLogo75.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\README -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\images\tai-ku.gif -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\images copying C:\Python23\tcl\tk8.4\license.terms -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\listbox.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\menu.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\mkpsenc.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\msgbox.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 creating D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\cs.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\de.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\el.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\en.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\en_gb.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\es.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\fr.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\it.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\nl.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\msgs\ru.msg -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4\msgs copying C:\Python23\tcl\tk8.4\obsolete.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\optMenu.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\palette.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\panedwindow.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\pkgIndex.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\safetk.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\scale.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\scrlbar.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\spinbox.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\tclIndex -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\tearoff.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\text.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\tk.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\tkfbox.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\unsupported.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 copying C:\Python23\tcl\tk8.4\xmfbox.tcl -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\tcl\tk8.4 creating python loader for extension '_sre' creating python loader for extension '_tkinter' *** finding dlls needed *** *** create binaries *** *** byte compile python files *** byte-compiling C:\Python23\lib\UserDict.py to UserDict.pyc byte-compiling C:\Python23\lib\atexit.py to atexit.pyc byte-compiling C:\Python23\lib\copy.py to copy.pyc byte-compiling C:\Python23\lib\copy_reg.py to copy_reg.pyc byte-compiling C:\Python23\lib\lib-tk\FixTk.py to FixTk.pyc byte-compiling C:\Python23\lib\lib-tk\Tkconstants.py to Tkconstants.pyc byte-compiling C:\Python23\lib\lib-tk\Tkinter.py to Tkinter.pyc byte-compiling C:\Python23\lib\linecache.py to linecache.pyc byte-compiling C:\Python23\lib\macpath.py to macpath.pyc byte-compiling C:\Python23\lib\ntpath.py to ntpath.pyc byte-compiling C:\Python23\lib\os.py to os.pyc byte-compiling C:\Python23\lib\os2emxpath.py to os2emxpath.pyc byte-compiling C:\Python23\lib\popen2.py to popen2.pyc byte-compiling C:\Python23\lib\posixpath.py to posixpath.pyc byte-compiling C:\Python23\lib\re.py to re.pyc byte-compiling C:\Python23\lib\repr.py to repr.pyc byte-compiling C:\Python23\lib\shutil.py to shutil.pyc byte-compiling C:\Python23\lib\sre.py to sre.pyc byte-compiling C:\Python23\lib\sre_compile.py to sre_compile.pyc byte-compiling C:\Python23\lib\sre_constants.py to sre_constants.pyc byte-compiling C:\Python23\lib\sre_parse.py to sre_parse.pyc byte-compiling C:\Python23\lib\stat.py to stat.pyc byte-compiling C:\Python23\lib\string.py to string.pyc byte-compiling C:\Python23\lib\traceback.py to traceback.pyc byte-compiling C:\Python23\lib\types.py to types.pyc byte-compiling C:\Python23\lib\warnings.py to warnings.pyc byte-compiling D:\[Egor]\Scripts\B-4-2\la2launcher\build\bdist.win32\winexe\temp\_sre.py to _sre.pyc byte-compiling D:\[Egor]\Scripts\B-4-2\la2launcher\build\bdist.win32\winexe\temp\_tkinter.py to _tkinter.pyc byte-compiling D:\[Egor]\Scripts\B-4-2\la2launcher\config.py to config.pyc byte-compiling D:\[Egor]\Scripts\B-4-2\la2launcher\my_os.py to my_os.pyc *** copy extensions *** copying C:\Python23\DLLs\_sre.pyd -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist copying C:\Python23\DLLs\_tkinter.pyd -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist *** copy dlls *** copying C:\WINDOWS\system32\python23.dll -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist copying C:\Python23\DLLs\tcl84.dll -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist copying C:\Python23\w9xpopen.exe -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist copying C:\Python23\DLLs\tk84.dll -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist setting sys.winver for 'D:\[Egor]\Scripts\B-4-2\la2launcher\dist\python23.dll' to 'py2exe' copying C:\Python23\lib\site-packages\py2exe\run.exe -> D:\[Egor]\Scripts\B-4-2\la2launcher\dist\la2launcher.exe ===================================================================== From sedolan at bellsouth.net Sat Jan 8 20:27:06 2005 From: sedolan at bellsouth.net (Sean Dolan) Date: Sat, 08 Jan 2005 20:27:06 -0500 Subject: tuples vs lists In-Reply-To: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: worzel wrote: > I get what the difference is between a tuple and a list, but why would I > ever care about the tuple's immuutability? > Also, do you say 'too-ple' or 'chu-ple' - if you get my drift. (tomato or > tomato kind of thing) > TIA > > I use the Festival Speech Synthesis System to learn pronunciations sometimes. The American english voice is quite accurate. -- Sean Dolan From ialbert at mailblocks.com Mon Jan 17 10:39:41 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 17 Jan 2005 10:39:41 -0500 Subject: Integration with java (Jpype vs. JPE) In-Reply-To: References: <34s5krF4c85d5U1@individual.net> Message-ID: Cameron Laird wrote: > Someone really ought to include a couple of sentences to that effect > on the front page of . Now I remember visiting this site, but never understood how it actually worked. Examples such as: from jpype import * startJVM("d:/tools/j2sdk/jre/bin/client/jvm.dll", "-ea") java.lang.System.out.println("hello world") shutdownJVM() in three different versions are the only code examples that to show "complete" working snippets. I'm still clueless as to how would one say share a list between python and java. Istvan. From kartic.krishnamurthy at gmail.com Wed Jan 26 10:43:16 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 26 Jan 2005 07:43:16 -0800 Subject: FTP Server In-Reply-To: <1106748382.746575.52550@c13g2000cwb.googlegroups.com> References: <1106743852.600769.72820@c13g2000cwb.googlegroups.com> <1106746068.798541.219240@c13g2000cwb.googlegroups.com> <1106748382.746575.52550@c13g2000cwb.googlegroups.com> Message-ID: <1106754196.016985.289680@f14g2000cwb.googlegroups.com> Michele - Listen to your inner voice :-) If simple is all you want, try twisted. You can use mktap to create a simple ftp server and be ready to serve in a few minutes. And if you are upto it, get buried in the documents and you can customize your ftp server. If you are looking for something simpler but not asynchronous, I found this at the Vault called pyFTPDrop, which is aimed at *NIX. http://www.mythi.cx/python/pyFTPdrop.py / Thank you, --Kartic PS: I am sure Medusa is fairly straightforward too, but I have no experience with it. From martin at v.loewis.de Sat Jan 29 05:24:54 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 29 Jan 2005 11:24:54 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xacqt56ga.fsf@ruckus.brouhaha.com> References: <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> Message-ID: <41fb646a$0$31784$9b622d9e@news.freenet.de> Paul Rubin wrote: > Oops, sorry, it's in the os module: > > http://docs.python.org/lib/os-miscfunc.html > > The difference is simply a matter of the packaging. No, it's not. It also is a matter of code size, and impact. Small additions can be reviewed and studied more easily, and need to be tested on less users. A new module is on a larger scale than a mere new function. > Unless you're saying that if I > wanted to add AES to the string module (so you could say > 'spam and sausage'.aes_encrypt('swordfish banana')) instead of writing a > separate module, then we wouldn't need this discussion. Indeed, if it was a single new function to an existing module, I would not require that this be delivered to users first. It is entire new libraries that I worry about. If you would propose a change to the string module to add an aes_encrypt function, I would immediately reject that patch, of course, because that function does not belong to the string module. > What matters is the code complexity, not whether > something is in a separate module or not. A module *is* typically more complex than a single function. If your new module has only a single new function, we should discuss whether it really needs to be a separate module. > Well, if he indicates that it's not a policy and that the question is > still open, then I could see getting interested again in writing an > AES module. At the moment I continue to see his python-dev post as > quite discouraging. And, again, I consider this perfectly fine. This would be a volunteer effort, and volunteers are free to work on whatever they please. Furthermore, people who want an AES module for Python could get one from http://sourceforge.net/projects/cryptkit/ Maybe Bryan Mongeau will contribute this code to Python some day. > Not true. For example, you once invited me to work on an ancillary > message feature for the socket module (SF bug 814689), and so it's > been on my want-to-do-one-of-these-days list since then. I think it's > reasonable for me to have taken your message there as an expression of > interest, sufficient to get me to want to work on it. So it's bogus > to say the Python developers should avoid expressing interest in > something that hasn't already been written. I did not say that. I said we don't normally invite people to work on anything - I said not that we *should* not invite them. Now that you mention it, I find that there is an important exception from my factual statement: I do regularly ask people reporting bugs or requesting features to work fixing the bugs or implementing the features. It is perfectly fine if they say "no" then. If they say yes, there is an implied promise that I'll review their code when they are done. As it appears to be clear that you are not going to implement an AES module in the foreseeable future, and as it also seems to be clear that you cannot talk me into changing my views on how Python should be developed, I think further discussing this entire thing is pointless. Regards, Martin From Scott.Daniels at Acm.Org Fri Jan 7 12:39:02 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 07 Jan 2005 09:39:02 -0800 Subject: sorting on keys in a list of dicts In-Reply-To: <10tr9ejf05pv660@corp.supernews.com> References: <10tr9ejf05pv660@corp.supernews.com> Message-ID: <41dec66b$1@nntp0.pdx.net> Jeff Shannon wrote: > Jp Calderone wrote: >> L2 = [(d[key], i, d) for (i, d) in enumerate(L)] >> L2.sort() >> L = [d for (v, i, d) in L2] > Out of curiosity, any reason that you're including the index? Others have already remarked that this preserves sort stability (which is, in fact a lovely property). There is another property which hasn't been mentioned: As written, only the key and the index are compared. Try sorting: tricky = [dict(a=5j, b=1), dict(a=4j, b=1)] or: similar = [(5j, 1), (4j, 1)] without the index. --Scott David Daniels Scott.Daniels at Acm.Org From ziongmail-py at yahoo.com Fri Jan 14 13:02:28 2005 From: ziongmail-py at yahoo.com (Ziong) Date: Sat, 15 Jan 2005 02:02:28 +0800 Subject: Newbie: module structure and import question References: <8fb821f9.0501120706.499dd04c@posting.google.com> Message-ID: <41e80972$1_1@rain.i-cable.com> Thx Rob. yes i know it's related to search path, but i don't know how to set it in a practical way (beside hard coding). my concern is, if i want to create a custom module/library, i don't know what py file will import it and where the working directory should be. sometime like my example, even i don't know where the root directory of my module will place, and i expect it can place in anywhere, how should i set the sys.path? i know that maybe a stupid question, please forgive me, i'm just a newbie. i have read all online documents in python.org. but i wouldn't find the answer. yes, i'm asking is it normally only put one class in one py file. thanks for your advice. But if i put a set of classes in a py file as a module, will it increase the dependency of each class? back to my example, of course, i can put BaseA and ClassA together in one py file. what should i do when i need to add one more class later, "ClassB", which also extend BaseA. Put it into the same file or in a new file? if put in in the same file, i think it should difficult to maintain versioning. i'm quite confuse in this, maybe because i learn Java before. Thx again, Rob. "Rob Emmons" ??? news:pan.2005.01.14.01.59.50.569440 at member.fsf.org ???... > > hi all, > > i have question on how to design a module structure. > > for example, i have 3 files. > > [somewhere]/main.py > > [somewhere]/myLib/Base/BaseA.py > > [somewhere]/myLib/ClassA.py > > .... > > ..... > > It's fine when i run main.py. > > however when i run ClassA.py individually, it would fail in import > > statment since the import path is incorrect. > > I would like to know is something wrong in my design, or something i > > missed. > > I think your issue is your module search path. Take a look at the doc for > sys.path in the library reference. These are the directories that python > searchies for modules. Usually the "." directory is included in this > which makes python search the current working directory. Your example > fails because your working directories are probably different when you ran > the two modules. In any case always consider how you've setup sys.path > and your libraries and modules. > > > Also, in practical usage, is that one class in one py file? > > I'm not exactly clear what your asking -- but I think yor asking if you'd > normally only put one class in one py file. My answer is no -- generally > you'd put many functions and classes in each py file. Modules are high > level and should be used to create libraries essentailly -- this means > many fucntions and classes per module. > > Rob > > From steven.bethard at gmail.com Thu Jan 27 15:29:35 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 13:29:35 -0700 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: Francis Girard wrote: > Le jeudi 27 Janvier 2005 20:16, Steven Bethard a ?crit : > >>flamesrock wrote: >> >>>The statement (1 > None) is false (or any other value above 0). Why is >>>this? >> >>What code are you executing? I don't get this behavior at all: >> >>py> 100 > None >>True >>py> 1 > None >>True >>py> 0 > None >>True >>py> -1 > None >>True >>py> -100 > None >>True >> > > > Wow ! What is it that are compared ? I think it's the references (i.e. the > adresses) that are compared. The "None" reference may map to the physical 0x0 > adress whereas 100 is internally interpreted as an object for which the > reference (i.e. address) exists and therefore greater than 0x0. > > Am I interpreting correctly ? Actually, I believe None is special-cased to work like this. From object.c: static int default_3way_compare(PyObject *v, PyObject *w) { ... if (v->ob_type == w->ob_type) { ... Py_uintptr_t vv = (Py_uintptr_t)v; Py_uintptr_t ww = (Py_uintptr_t)w; return (vv < ww) ? -1 : (vv > ww) ? 1 : 0; } ... /* None is smaller than anything */ if (v == Py_None) return -1; if (w == Py_None) return 1; ... } So None being smaller than anything (except itself) is hard-coded into Python's compare routine. My suspicion is that even if/when objects of different types are no longer comparable by default (as has been suggested for Python 3.0), None will still compare as smaller than anything... Steve From steven.bethard at gmail.com Tue Jan 4 09:35:57 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 04 Jan 2005 14:35:57 GMT Subject: why does UserDict.DictMixin use keys instead of __iter__? In-Reply-To: <1104836152.639270.196200@z14g2000cwz.googlegroups.com> References: <1104836152.639270.196200@z14g2000cwz.googlegroups.com> Message-ID: <1RxCd.847728$8_6.18665@attbi_s04> John Machin wrote: > Steven Bethard wrote: > >>So I was looking at the Language Reference's discussion about >>emulating container types[1], and nowhere in it does it mention that >> .keys() is part of the container protocol. > > I don't see any reference to a "container protocol". Sorry, I extrapolated "container protocol" from this statement: "Containers usually are sequences (such as lists or tuples) or mappings (like dictionaries), but can represent other containers as well. The first set of methods is used either to emulate a sequence or to emulate a mapping" and the fact that there is a "sequence protocol" and a "mapping protocol". But all I was really reading from this statement was that the "first set of methods" (__len__, __getitem__, __setitem__, __delitem__ and __iter__) were more integral than the second set of methods (keys(), values(), ...). > What I do see is > (1) """It is also recommended that mappings provide the methods keys(), > ...""" You skipped the remaining 13 methods in this list: "It is also recommended that mappings provide the methods keys(), values(), items(), has_key(), get(), clear(), setdefault(), iterkeys(), itervalues(), iteritems(), pop(), popitem(), copy(), and update() behaving similar to those for Python's standard dictionary objects." This is the "second set of methods" I mentioned above. I don't understand why the creators of UserDict.DictMixin decided that keys(), from the second list, is more important than __iter__, from the first list. >>Because of this, I would assume that to >>use UserDict.DictMixin correctly, a class would only need to define >>__getitem__, __setitem__, __delitem__ and __iter__. > > > So I can't see why would you assume that, given that the docs say in > effect "you supply get/set/del + keys as the building blocks, the > DictMixin class will provide the remainder". This message is reinforced > in the docs for UserDict itself. Sorry, my intent was not to say that I didn't know from the docs that UserDict.DictMixin required keys(). Clearly it's documented. My question was *why* does it use keys()? Why use keys() when keys() can be derived from __iter__, and __iter__ IMHO looks to be a more basic part of the mapping protocol. > In any case, isn't UserDict past history? Why are you mucking about > with it? UserDict is past history, but DictMixin isn't. As you note, DictMixin is even mentioned in the section of the Language Reference that we're discussing: "The UserDict module provides a DictMixin class to help create those methods from a base set of __getitem__(), __setitem__(), __delitem__(), and keys()." Steve From ishwor.gurung at gmail.com Fri Jan 28 07:40:46 2005 From: ishwor.gurung at gmail.com (Ishwor) Date: Fri, 28 Jan 2005 23:10:46 +1030 Subject: How to test that an exception is raised ? In-Reply-To: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> References: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> Message-ID: <34534aed05012804402d870dc1@mail.gmail.com> [snipped alot of codes that doesn't mean much ] if you want to check for exception then it goes like this try: catch IOError: sorry i won't bother to read your code because i can't read, i think i am tired and need to go to bed. ;-) -- cheers, Ishwor Gurung From Scott.Daniels at Acm.Org Fri Jan 7 11:22:39 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 07 Jan 2005 08:22:39 -0800 Subject: Python evolution: Unease In-Reply-To: References: <7xacrpdxy3.fsf@ruckus.brouhaha.com><7x652che6z.fsf@ruckus.brouhaha.com><7x4qhw859p.fsf@ruckus.brouhaha.com><7xk6qrnbum.fsf@ruckus.brouhaha.com><41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> Message-ID: <41deb485$1@nntp0.pdx.net> Terry Reedy wrote: > Even though I currently only have 80 ... I realize that my stinginess > with disk space for more serious stuff is obsolete. A gigabyte would > cover Python + Wxpython + numarray + scipy + pygame + a lot > of other stuff. > > Would it be possible, at least for Windows, to write a Python script > implementing a 'virtual distribution'? > IE, download Python, install it, download next package, install it, > etc. -- prefereably table driven? I would suggest looking to the Enthought distribution as a reasonable base (gets you an awful lot). Enthought has a _large_ collection, covering a lot of stuff that has general utility. Their production stuff is still at Python 2.3.3, but I believe they have a 2.4 version coming soon. The list of what they put in the 2.3.3 package is truly impressive: wxPython, PIL, VTK, MayaVi, Numeric, SciPy, ScientificPython, F2PY, Chaco, Traits, PyCrust, ZODB, Gadfly, PySQLite, and ctypes. All for one sub-90-Meg download. I add VPython to get dirt-simple 3-D stuff; you'd probably add pygame. The key to this is Enthought's attention to testing a stable "sumo" collection. I add a few packages that are much more anachronistic. My thought basically is that, since I want at least four of the packages, getting a "blessed" superset eases my installation woes. If you can wait, the plan for MacEnthon (Python 2.4 on Mac) looks great: http://www.scipy.org/wikis/featurerequests/MacEnthon I seem to remember discussion about synchronizing with the windows 2.4 version to have essentially the same list. --Scott David Daniels Scott.Daniels at Acm.Org From aleaxit at yahoo.com Sat Jan 1 05:01:26 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 1 Jan 2005 11:01:26 +0100 Subject: what is lambda used for in real code? References: <1104531721.3724.18.camel@localhost.localdomain> Message-ID: <1gpphwq.1n4ahpdanj12jN%aleaxit@yahoo.com> Terry Reedy wrote: > "Adam DePrince" wrote in message > news:1104531721.3724.18.camel at localhost.localdomain... > > In sort, we must preserve the ability to create an anonymous function > > simply because we can do so for every other object type, and functions > > are not special enough to permit this special case. > > Please show me how to create an anonymous type, module, or class, > especially with an expression. Number, sequences, and dicts have easily new.module('') creates a module and can be used within an expression. Of course 'anonymous' is doubtful, i.e.: >>> new.module('').__name__ '' but then >>> (lambda:23).__name__ '' So the parallel is there, roughly. You can create old-style classes similarly, with new.classobj, and new-style ones by calling type, which is more analogous to, say, creating sets by calling set, decimal numbers by calling decimal.Decimal, and so on. So the creating isn't a big problem -- by analogy with other types it should be done by calling some callable, either built-in or from the library. And, we do have new.function for that; problem is the code object that you need to pass as the first argument... there's new.code, too, but it wants a gazillion args, including a codestring that's not nice to put together;-). "Not for the faint of heart" as the docs say. Contents of modules and classes are less problematic. Well, new.module should perhaps take an optional dict argument, like new.classobj or calling type -- right now it's hard to create _and populate_ the module within the same expression. Not that I have any use case for this, though. And there's the rub...: > printable values. Functions, like classes and module do not*, so > definition names act as a standin and as a pointer to the source code that > produced the object. If functions are not special relative to classes and > modules, which is the grouping they belong with, then we should get rid of > lambda ;-) Yes but... we DO have a few real use cases for functions, which we don't really have for modules and classes, _and_ making the *contents* of a function object is harder too...:-( Alex From fuzzyman at gmail.com Wed Jan 26 03:23:06 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 26 Jan 2005 00:23:06 -0800 Subject: snakespell and myspell In-Reply-To: References: <1106657932.301181.150050@z14g2000cwz.googlegroups.com> Message-ID: <1106727786.284129.309420@z14g2000cwz.googlegroups.com> Jarek Zgoda wrote: > Fuzzyman wrote: > > > I'm looking to implement a plugin spell checker. > > > > I'm probably going to go with PyEnchant, as it looks to be the most > > promising currently maintained spell checker. > > > > I just wondered if anyone knew what happened to snakespell and myspell. > > Both seem to have dissapeared from the net. People have reported good > > results from both - and it seems a shame to lose them. > > Well, myspell-python is no longer maintained, original author resigned > some time ago and I didn't found anybody who would like to take > responsibility on this package. I provide myspell-1.0 download from my > project page at BerliOS (http://developer.berlios.de/projects/jpa/), but > I do not maintain this package. > > If you look for spell-checking library, I'd consider using python > binding for aspell, available at > http://www.republika.pl/wmula/proj/aspell-python/ (currently I'm > rewriting my program to use python-aspell). This library is actively > maintained and Wojtek Mula is active member of Polish Python community. > The problem with aspell is (as far as I can see anyway) that the library you mention is aimed at aspell 0.50.5 or the up to date 0.60 series. aspell for windows is currently only at 0.50.3. Hmmm.... I think I'll explore PyEnchant for the moment. I need to see how easy it is to add words to a user dictionary. Regards, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > -- > Jarek Zgoda > http://jpa.berlios.de/ | http://www.zgodowie.org/ From bob_smith_17280 at hotmail.com Mon Jan 24 22:31:32 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Mon, 24 Jan 2005 22:31:32 -0500 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: Message-ID: Rocco Moretti wrote: > Python's also dangerous. Every time you do an "import module", you put > your system at risk of crashing, having the hard-drive wiped Have you been drinking again? From marklists at mceahern.com Mon Jan 24 10:52:54 2005 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 24 Jan 2005 09:52:54 -0600 Subject: Finding a script's home directory? In-Reply-To: <41F516ED.3090503@mediapulse.com> References: <41F516ED.3090503@mediapulse.com> Message-ID: <41F519D6.8040009@mceahern.com> Gabriel Cooper wrote: > In one of my python programs has a data file I need to load. My > solution was to say: > > if os.path.exists(os.path.join(os.getcwd(), "config.xml")): > self.cfgfile = os.path.join(os.getcwd(), "config.xml") > > Which works fine... as long as you're *in* the script's home directory > when you run it (as in, run it as: ./startApp.py as opposed to > ./myApp/startApp.py). > > If I run it from an alternate directory the program looks for the > config.xml file in my current directory not the app's home directory. > So how do I get the script's home directory? import os.path dirname = os.path.dirname(__file__) // m From danb_83 at yahoo.com Wed Jan 19 00:50:58 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 18 Jan 2005 21:50:58 -0800 Subject: python/cgi/html bug In-Reply-To: References: Message-ID: <1106113858.360940.298900@c13g2000cwb.googlegroups.com> Dfenestr8 wrote: > Hi. > > I've written a cgi messageboard script in python, for an irc chan I happen > to frequent. > > Bear with me, it's hard for me to describe what the bug is. So I've > divided this post into two sections: HOW MY SCRIPTS WORKS, and WHAT THE > BUG IS. > ... > The problem is when someone posts a new topic, and that topic happens to > have "" double quotes, or any other strange character, some strange > glitches occur. Use cgi.escape(topic, True) to convert HTML special characters to the equivalent ampersand escape sequences. From aleaxit at yahoo.com Thu Jan 6 07:25:09 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 6 Jan 2005 13:25:09 +0100 Subject: Python evolution: Unease References: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> <41dcc35a$0$3872$afc38c87@news.optusnet.com.au> Message-ID: <1gpyxxv.wxsci81e0054aN%aleaxit@yahoo.com> Robert Kern wrote: ... > >> I love eric3, but if you're an eclipse fan, look at enthought's > >> "envisage" IDE -- it seems to me that it has superb promise. ... > > Is it available for download somewhere? > > Alex is, I think, jumping the gun a bit. Envisage isn't quite ready for > prime time as your day to day IDE. It might be useful to you right now I apologize if I gave a misleading impression: I did not mean it was ready to use, or _already_ here; I suggested "looking at" in the sense of "paying attention to", and specifically mentioned "promise". Since the subthread was about future IDE developments, I thought it was appropriate to mention envisage, in the context of comparisons with eclipse's plugin-centered architecture. > as a platform to build a dynamic GUI application (Envisage's intended > use) if you are willing to get your hands dirty and help us build > Envisage. Hence, it is not being advertised widely. I saw a Pycon proposed talk about it, so I didn't stop to consider the "not advertised widely" issue. Thinking about it, I realize Pycon is almost 3 months from now, so wanting to enthuse about envisage then doesn't imply already wanting to widely advertise it now; sorry. > But Alex is right; Envisage does hold a lot of promise. The very concept of an architecture based on a spare skeleton and copious plugins is intrinsically excellent, and I think that by now eclipse has proven it's also practically viable for real-world powerful IDEs/platforms/frameworks. Alex From http Thu Jan 6 18:38:53 2005 From: http (Paul Rubin) Date: 06 Jan 2005 15:38:53 -0800 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: <7xhdluxh4i.fsf@ruckus.brouhaha.com> Bulba! writes: > Making derived work proprietary in no way implies that the base > work is publicly unavailable anymore. Since you want to be able to incorporate GPL code in your proprietary products, and say there's no problem since the base work is still available from the same places it was available from before, fairness would say you shouldn't mind that people incorporate code from your products into THEIR products, since your version is still available from you. Really, you're just a freeloader looking for handouts. From just at xs4all.nl Mon Jan 17 07:52:47 2005 From: just at xs4all.nl (Just) Date: Mon, 17 Jan 2005 13:52:47 +0100 Subject: (objects as) mutable dictionary keys References: Message-ID: In article , Peter Maas wrote: > Antoon Pardon schrieb: > > Dictionary lookup with mutable types like lists is a source of > > unpleasant surprises for the programmer and therefore impossible in > > Python. > > > > > > It is not impossible in Python. Is too. > > It may be discouraged but it is not > > impossible since I have already done so. > > Wouldn't this raise a TypeError? Or did you wrap them with an object? He created a list subclass that redefines __hash__, so he cheated :). Just From reinhold-birkenfeld-nospam at wolke7.net Sat Jan 15 04:57:42 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 15 Jan 2005 10:57:42 +0100 Subject: How to del item of a list in loop? In-Reply-To: <34rvjqF4f6l70U1@individual.net> References: <34rvjqF4f6l70U1@individual.net> Message-ID: <34s7omF4emdsaU1@individual.net> Reinhold Birkenfeld wrote: > skull wrote: >> Hi everybody, it is my first post in this newsgroup. >> I am a newbie for python though I have several years development experience in c++. >> recently, I was stumped when I tried to del item of a list when iteration. >> >> here is the wrong way I did: >> >> lst = [1, 2, 3] >> for i in lst: >> print i >> if i == 2: >> lst.remove(i) >> >> the result is: >> >> 1 >> 2 >>>>> >> >> as you would see, '3' is missing. this problem is caused by 'lst.remove(i)'. >> apparently, 'marked-and-sweep' is a solution to deal with this issue. >> but I think there SHOULD BE more 'wise' trick. I want to get your help. > > Quick solution: > > for i in lst[:] > > iterates over a copy. Addition: In Py2.4, I can't find a problem with for i in reversed(lst) Any objections? Reinhold From rm at rm.net Sat Jan 22 15:00:04 2005 From: rm at rm.net (rm) Date: Sat, 22 Jan 2005 21:00:04 +0100 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> Message-ID: <35fpq0F4mh1ffU1@individual.net> Fredrik Lundh wrote: > "rm" wrote: > > >>100% right on, stuff (like this)? should be easy on the users, and if possible, on the developers, >>not the other way around. > > > I guess you both stopped reading before you got to the second paragraph > in my post. YAML (at least the version described in that spec) isn't easy on > users; it may look that way at a first glance, and as long as you stick to a > small subset, but it really isn't. that's not just bad design, that's plain evil. > > and trust me, when things are hard to get right for developers, users will > suffer too. > > > > > you stopped reading too early as well, I guess: "maybe their stated goal is not reached with this implementation of their idea" and the implementation being the spec, furthermore, "users will suffer too", I'm suffering if I have to use C++, with all its exceptions and special cases. BTW, I pickpocketed the idea that if there is a choice where to put the complexity, you never put it with the user. "pickpocket" is strong, I've learned it from an analyst who was 30 years in the business, and I really respect the guy, basically he was always right and right on. On the other hand, the management did not always like what he thought :-) bye, rm From aleaxit at yahoo.com Fri Jan 7 04:05:09 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 10:05:09 +0100 Subject: Excluded and other middles in licensing References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> <75r0b2-ohg.ln1@lairds.us> Message-ID: <1gq0jpn.1es49j7jrk3k5N%aleaxit@yahoo.com> Robert Kern wrote: ... > >>While most people may not think of such programs as "closed source", > >>they most definitely ARE: the definition of open source is very strict > >>about this aspect. ... > > With my mathematical background, I'm consistent about calling > > these "non-open" rather than "closed". I don't insist others > > adopt my nomenclature ... > > I'm with Cameron on this one. There is no "official" definition of closed-source as there is of open-source, but I'm with the Wikipedia: http://en.wikipedia.org/wiki/Closed_source "any program whose licensing terms do not qualify as open source". I'm not disputing it would be useful to draw many distinctions within the universe of programs with non-opensource licenses, just pointing out that such distinctions are not currently reflected in a popular definition. Since it's a wiki, it may be worthwhile editing it to add some materials to start influencing popular usage and perception, maybe. Alex From ncoghlan at iinet.net.au Thu Jan 20 04:49:16 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 20 Jan 2005 19:49:16 +1000 Subject: Dictionary keys (again) (was Re: lambda) In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: <41EF7E9C.7010006@iinet.net.au> Antoon Pardon wrote: > As you said yourself, people use shortcuts when they express themselves. > With 'mutable key' I mean a mutable object that is used as a key. > That doesn't contradict that the key itself can't change because > it is inaccessible. Yeah - this was the point of terminology that was getting confused, I think. And your interpretation was closer to the strict sense of the words. >>Well, the Zen of Python states "In the face of ambiguity, refuse the temptation >>to guess". > > But python does guess in the case of the value. If I want to establish a > relationship between "foo" and [3, 5, 8] then I can be in big trouble > if that list gets mutated in something else. However, the actual promise a Python dict makes is that it maps from keys by value to values by identity. That is, "k1 == k2" implies "d[k1] is d[k2]". An identity test on mutable objects is entirely unambiguous (hence they can be values), but comparison is not (hence they cannot be keys). Restricting keys to immutable objects eliminates the ambiguity. Copying keys would also prevent mutation and eliminate the ambiguity. The restriction approach is a *definite* performance enhancement over the copying approach, though (this is probably the origin of the mantra "the restriction to mutable keys is a performance enhancement"). The resulting semantics of the restriction to immutable objects are also significantly less surprising than those of the copying approach. An identity dict would make the promise that "k1 is k2" implies "d[k1] is d[k2]". In this case, the mutability of the key is irrelevant, so the behaviour is unambiguous without any additional restrictions. > But they don't have to be immutable within the dictionary itself, that > is just an implementation detail. The only thing that matters is that > the dictionary can reproduce the relationship. How that is done is > immaterial. Given the Python interpreter's current definition of "immutable" as "defines __hash__", it's a little hard to have an unhashable object as a key :) >>In short, sane hash tables require immutable keys, and how mutable keys acquire >>the requisite immutability is going to be application dependent. > > > No they don't, that is just the most easy implementation. If some > implementation would constantly change the internal objects but > consulting the dictionary wouldn't show any different effect then > that would be fine too. And even in this case a mutation > from the outside would probably cause havoc because it would ruin > the sanity of the internal structure. If you insist: s/immutable/effectively immutable/ And no data type can be expected to tolerate having their invariants violated by external code messing with internal data structures. >>Provision of a safe_dict or identity_dict would merely allow a programmer to >>state their intent at the time the container is created, rather than having to >>state it whenever keys are generated or referenced. > > Well that would be a good thing IMO. True - I'm not sure how that 'merely' snuck in there :) > Good enough in any case for me to > spend some time analyzing the requirements. Whether I'll actually > implement something depends on how much time I have and how often I > need it. My preference is for the identity dict - its performance would actually be *better* than that of a standard dict in the domains where it applies (annotation and classification of objects are the two main uses I can see for such a data structure). This aligns quite well with the stated goal of the collections module (providing data structures that are less general purpose than the standard builtins, but deliver better performance for their particular use cases) Regards, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From claird at lairds.us Thu Jan 27 09:08:08 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 27 Jan 2005 14:08:08 GMT Subject: Point of Sale References: Message-ID: In article , Andreas Pauley wrote: >Hi, > >My company has given me a rather cool project: >I have to provide them with an open-source python-based point-of-sale / >cash register system that can integrate with their existing ERP backend. > >The project will include development to ensure that the features they >require are included in the open-source POS system. > >Can you recommend anything that I can use? . . . Research. I think you're expecting an answer of the "I used open-source openPOS project, and it worked great for me", but I suspect all that is premature. What does POS mean to you? What are your platform constraints? Does your company have expectations about how POS will work? What access (CORBA? RMI? SOAP? ...) is there to the ERP? From steve at holdenweb.com Mon Jan 17 15:16:10 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 15:16:10 -0500 Subject: Adjusting the 1024 byte stdin buffer limit In-Reply-To: <1105989764.168794.113430@z14g2000cwz.googlegroups.com> References: <1105989047.516986.59990@z14g2000cwz.googlegroups.com> <1105989764.168794.113430@z14g2000cwz.googlegroups.com> Message-ID: brucoder wrote: > Currently, when sending a data stream that exceeds 1024 bytes via > stdin, the stream blocks at the 1024th byte. This precludes completion > of the submission of the data stream. > But surely the blocking will only last as long as the consuming process leaves buffered input unread? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From 2004b at usenet.alexanderweb.de Wed Jan 12 11:48:27 2005 From: 2004b at usenet.alexanderweb.de (Alexander Schremmer) Date: Wed, 12 Jan 2005 17:48:27 +0100 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> <1g4nx7m906q79$.dlg@usenet.alexanderweb.de> <7xekgr7lpy.fsf@ruckus.brouhaha.com> <7x4qhn9q3g.fsf@ruckus.brouhaha.com> Message-ID: On 11 Jan 2005 21:24:51 -0800, Paul Rubin wrote: [backlinks] >> Searching instead of indexing makes it very resilient :-) > > How does it do that? It has to scan every page in the entire wiki?! > That's totally impractical for a large wiki. So you want to say that c2 is not a large wiki? :-) Kind regards, Alexander From grante at visi.com Sat Jan 15 13:08:54 2005 From: grante at visi.com (Grant Edwards) Date: 15 Jan 2005 18:08:54 GMT Subject: interpret 4 byte as 32-bit float (IEEE-754) References: <34t1p2F4foiplU1@individual.net> <41e952b9$1@nntp0.pdx.net> Message-ID: <41e95c36$0$82380$a1866201@visi.com> On 2005-01-15, Scott David Daniels wrote: >> I've read some bytes from a file and just now I can't interpret 4 bytes >> in this dates like a real value. > OK, here's the skinny (I used blocks & views to get the answer): > > import struct > bytes = ''.join(chr(int(txt, 16)) for txt in '3F 8C CC CD'.split()) > struct.unpack('>f', bytes) Just be careful. That doesn't work for all 32-bit IEEE floating point values: >>> import struct >>> bytes = '\xff\xff\xff\xff' >>> print struct.unpack('>f',bytes) (-6.8056469327705772e+38,) 0xffffff is _not_ -6.8...e38. It's a NaN. IIRC, it doesn't work for infinities either. I haven't tried denormals. -- Grant Edwards grante Yow! It's hard being at an ARTIST!! visi.com From peter at engcorp.com Wed Jan 12 10:41:23 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 Jan 2005 10:41:23 -0500 Subject: Excel module for Python In-Reply-To: References: Message-ID: sam wrote: >> On Wed, 12 Jan 2005 15:18:09 +0800, sam wrote: >>> I m wondering which Excel module is good to be used by Python? [snip] > No, I don't use MS windows. I need to generate Excel file by printing > data to it, just like Perl module Spreadsheet::WriteExcel. Excel can read CSV files, so just use the standard Python module "csv" and write your files that way. -Peter From kp8 at mac.com Tue Jan 11 16:53:48 2005 From: kp8 at mac.com (kpp9c) Date: 11 Jan 2005 13:53:48 -0800 Subject: Time script help sought! In-Reply-To: <1105480151.431987.327080@c13g2000cwb.googlegroups.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> <1105477084.525279.312970@f14g2000cwb.googlegroups.com> <1105479292.689762.155510@f14g2000cwb.googlegroups.com> <1105480151.431987.327080@c13g2000cwb.googlegroups.com> Message-ID: <1105480428.116581.24040@c13g2000cwb.googlegroups.com> so all the imput will look more like this now... ( no comments either) tem_133, DAT_20, 7, 00:58:25, 01:15:50 Item_134, DAT_20, 8, 01:15:50, 01:32:15 Item_135, DAT_21, 1, 00:01:00, 00:36:15 Item_136, DAT_60, 3, 00:18:30 Item_136, DAT_60, 4, 00:19:30 Item_136, DAT_60, 5, 00:23:00, 00:28:00 Item_137, DAT_21, 4, 00:37:00, 00:47:00 Item_139, DAT_21, 2, 00:36:15 Item_139, DAT_21, 3, 00:42:15, 01:00:50 Item_140, DAT_21, 4, 01:00:50 Item_140, DAT_21, 5, 01:25:10, 01:26:35 ..... snip... From fredrik at pythonware.com Sun Jan 23 13:04:19 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 19:04:19 +0100 Subject: What is print? A function? References: <200501231801.50080.frans.englich@telia.com> Message-ID: Frans Englich wrote: > Nah, I don't think it's a function, but rather a builtin "statement". But it's > possible to invoke it as an function; print( "test" ) works fine. > > So I wonder, what _is_ exactly the print statement? The untraditional way of > invoking it(without paranteses) makes me wonder. it's a statement. (expr) is an expression (in parenthesis), so when you type print("test") python sees: print ("test") (see the language reference for details) > The reason I thinks about this is I need to implement a debug print for my > program; very simple, a function/print statement that conditionally prints > its message whether a bool is true. Not overly complex. > > I tried this by overshadowing the print keyword, but that obviously didn't > work.. Is defining a two-liner function the right way to go yup. something like this might be useful: def printif(cond, fmt, *args): if cond: print fmt % args From http Thu Jan 6 20:24:21 2005 From: http (Paul Rubin) Date: 06 Jan 2005 17:24:21 -0800 Subject: The Industry choice References: <7xhdluxh4i.fsf@ruckus.brouhaha.com> Message-ID: <7xzmzmni9m.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > >I don't like what I perceive as end effect of what GPL license > >writers are attempting to achieve: vendor lock-in. > And my counter-argument is that I believe your perception is wrong. If > I agreed with your focus on lock-in, I'd say that what the GPL is trying > to lock in is a specific legal philosophy by subverting the existing > system. Bulba's perception is wrong in a different way too. The GPL tries to encourage the enlargement of a public resource, namely a codebase shareable by a worldwide community of users and developers, a cyber equivalent of a public park whose facilities anyone can visit and use but nobody can take away and exclude others from using. The idea of referring to such a shared community resource as a "vendor" is just bizarre. From aleaxit at yahoo.com Tue Jan 11 13:35:08 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 11 Jan 2005 19:35:08 +0100 Subject: how to set doc-string of new-style classes References: Message-ID: <1gq8p18.109u52rvr55yoN%aleaxit@yahoo.com> harold fellermann wrote: ... > But, I cannot > even find out a way to set the doc string, when I CREATE a class using > type(name,bases,dict) ... At least this should be possible, IMHO. >>> x=type('x',(),dict(__doc__='hi there')) >>> x.__doc__ 'hi there' Alex From roy at panix.com Fri Jan 7 12:12:15 2005 From: roy at panix.com (Roy Smith) Date: 7 Jan 2005 12:12:15 -0500 Subject: Getting rid of "self." References: <740c3aec05010705393048a374@mail.gmail.com> <10ttf1slqmefi28@news.supernews.com> Message-ID: In article <10ttf1slqmefi28 at news.supernews.com>, John Roth wrote: > >"Roy Smith" wrote in message >news:crmdqk$jo6$1 at panix2.panix.com... >> Simon Brunning wrote: >>>On 7 Jan 2005 08:10:14 -0800, Luis M. Gonzalez wrote: >>>> The word "self" is not mandatory. You can type anything you want >>>> instead of self, as long as you supply a keyword in its place (it can >>>> be "self", "s" or whatever you want). >>> >>>You *can*, yes, but please don't, not if there's any chance that >>>anyone other than you are going to have to look at your code. >>>'self.whatever' is clearly an instance attribute. 's.whatever' isn't >>>clearly anything - the reader will have to go off and work out what >>>the 's' object is. >> >> +1. >> >> If there is one coding convention which is constant through the Python >> world, it's that the first argument to a class method is named >> "self". Using anything else, while legal, is just being different for >> the sake of being different. > >Didn't you mean instance method? Class methods are a different >beast, and the few examples I've seen seem to use the word "klas". Sorry, yes. My bad. I used to work with a C++ guy who always used "class" when he should have used "instance". It drove me crazy. :-) From FBatista at uniFON.com.ar Tue Jan 4 13:42:41 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 4 Jan 2005 15:42:41 -0300 Subject: Python evolution: Unease Message-ID: [Skip Montanaro] #- This being the Internet and all, it's not clear that #- referencing external #- documentation is somehow worse than incorporating it #- directly into the #- distribution. The problem is Internet access. For example, once I put together a "Python CD" as a present for my father. Inside it put Linux & Windows installers (Python itself and wxWindows (this name then)). And of course, the whole documentation package, in PDF. Of course, I didn't parse the whole docs to see what other documents I could include. And to my father is kinda complicated (and expensive!) access internet and read the docs there. I mean, it's perfectly possible, but would be better IMO to have the docs concentrated. . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Sat Jan 1 11:46:55 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Jan 2005 11:46:55 -0500 Subject: The Industry choice In-Reply-To: <7xfz1lal5d.fsf@ruckus.brouhaha.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xfz1lal5d.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: [...] > There's lots of times when I have a cool programming idea, and find > when I sit down at the computer that I can implement the main points > of the idea and get a neat demo running rather quickly. That creates > a very happy, liberating feeling, plus gives me something to show off > to friends or co-workers. But turning it into a finished product with > no rough edges is an order of magnitude more work. It seems to me > that IDLE and a lot of the rest of Python are examples of someone > having a cool idea and writing a demo, then releasing it with a lot of > missing components and rough edges, without realizing that it can't > reasonably be called complete without a lot more work. ^Python^open source^ regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From steve at holdenweb.com Sat Jan 1 15:08:01 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Jan 2005 15:08:01 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: Rob Emmons wrote: >>For managers of companies it's worse: the company makes >>VERY substantial investments into any technology it "marries", >>and that means big losses if it goes. Long-term stability >>of this technology in terms of "we're not going to be left out >>in cold alone with this technology to feed it" means a lot >>to them. Even a poor technology with external backing >>of big, stable vendor is better than the excellent technology >>without ...... > > > There is the stability issue you mention... but also probably the fear > issue. If you choose a solution from a major company -- then it fails for > some reason or they drop the product -- it's their fault -- you've got an > automatic fall guy. On the other hand, an open source solution or > otherwise less accepted solution ... it will probably be consider > your fault by the organization. It's a rational decision to avoid > personal risk when you don't get much reward for choosing something > different. > You are ignoring the fact that with the open source solution you do at least have the option of hiring bright programmers to support the framework which has now become moribund, whereas when a company goes bust there's no guarantee the software IP will ever be extricated from the resulting mess. So I'm not sure I'd agree with "rational" there, though "comprehensible" might be harder to argue with. Personally I'd feel in a better position standing before a Board of Directors and saying "While it's true that our chosen software platform isn't being supported by the original team any more, we do have options to continue to move it forward, including forming a consortium with other users". Avoidance of blame is way too large a motivator in large organizations, and it leads to many forms of sub-optimal decision making. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From nick at craig-wood.com Thu Jan 13 03:31:44 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 13 Jan 2005 08:31:44 GMT Subject: Refactoring; arbitrary expression in lists References: <41e5cb07.701137402@news.oz.net> Message-ID: Stephen Thorne wrote: > Why not use a regexp based approach. Good idea... You could also use sre.Scanner which is supposed to be fast like this... import re, sre scanner = sre.Scanner([ (r"\.php$", "application/x-php"), (r"\.(cc|cpp)$", "text/x-c++-src"), (r"\.xsl$", "xsl"), (r"Makefile", "text/x-makefile"), (r".", None), ]) def detectMimeType( filename ): t = scanner.scan(filename)[0] if len(t) < 1: return None # raise NoMimeError return t[0] for f in ("index.php", "index.php3", "prog.cc", "prog.cpp", "flodge.xsl", "Makefile", "myMakefile", "potato.123"): print f, detectMimeType(f) ... prints index.php application/x-php index.php3 None prog.cc text/x-c++-src prog.cpp text/x-c++-src flodge.xsl xsl Makefile text/x-makefile myMakefile text/x-makefile potato.123 None -- Nick Craig-Wood -- http://www.craig-wood.com/nick From philippecmartin at sbcglobal.net Tue Jan 25 09:55:16 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Tue, 25 Jan 2005 08:55:16 -0600 Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) In-Reply-To: <8c7f10c605012502281d9c9b29@mail.gmail.com> References: <1106590633.15475.3.camel@localhost> <8c7f10c605012502281d9c9b29@mail.gmail.com> Message-ID: <1106664916.7197.2.camel@localhost> Well I _was_ a bit slow on that one ! So I will happily stick to the double underscore. Regards, Philippe Le mardi 25 janvier 2005 ? 10:28 +0000, Simon Brunning a ?crit : > On Mon, 24 Jan 2005 12:17:13 -0600, Philippe C. Martin > wrote: > > > > I use "__"for private variables because I must have read on net it was > > the way to do so - yet this seems to have changed - thanks: > > > > http://www.network-theory.co.uk/docs/pytut/tut_77.html > > Nope, that's still the right way to make a member 'really' private. > Stephen was pointing out a very common Python idiom - "private by > convention", and suggesting that using it would be more appropriate. > > A member with a single preceding underscore is private by convention. > That is to say, there is no mechanism in place to prevent clients of > the class accessing these members, but they should consider themselves > to have been warned that they do so at their own risk. > > If you take the back off the radio, the warranty is void. ;-) > > I (and by inference Stephen) feel that this is a more "Pythonic" > approach. Give the programmer the information that they need, but > don't try to stop them from doing what they need to do. > -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From francis.girard at free.fr Mon Jan 24 08:09:25 2005 From: francis.girard at free.fr (Francis Girard) Date: Mon, 24 Jan 2005 14:09:25 +0100 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <20050123222743.GA32583@unpythonic.net> References: <63b5e209.0501210558.686f5c10@posting.google.com> <200501232255.08496.francis.girard@free.fr> <20050123222743.GA32583@unpythonic.net> Message-ID: <200501241409.25598.francis.girard@free.fr> Ok, I think that the bottom line is this : For all the algorithms that run after their tail in an FP way, like the Hamming problem, or the Fibonacci sequence, (but unlike Sieve of Eratosthene -- there's a subtle difference), i.e. all those algorithms that typically rely upon recursion to get the beginning of the generated elements in order to generate the next one ... ... so for this family of algorithms, we have, somehow, to abandon recursion, and to explicitely maintain one or many lists of what had been generated. One solution for this is suggested in "test_generators.py". But I think that this solution is evil as it looks like recursion is used but it is not and it depends heavily on how the m235 function (for example) is invoked. Furthermore, it is _NOT_ memory efficient as pretended : it leaks ! It internally maintains a lists of generated results that grows forever while it is useless to maintain results that had been "consumed". Just for a gross estimate, on my system, percentage of memory usage for this program grows rapidly, reaching 21.6 % after 5 minutes. CPU usage varies between 31%-36%. Ugly and inefficient. The solution of Jeff Epler is far more elegant. The "itertools.tee" function does just what we want. It internally maintain a list of what had been generated and deletes the "consumed" elements as the algo unrolls. To follow with my gross estimate, memory usage grows from 1.2% to 1.9% after 5 minutes (probably only affected by the growing size of Huge Integer). CPU usage varies between 27%-29%. Beautiful and effecient. You might think that we shouldn't be that fussy about memory usage on generating 100 digits numbers but we're talking about a whole family of useful FP algorithms ; and the best way to implement them should be established. For this family of algorithms, itertools.tee is the way to go. I think that the semi-tutorial in "test_generators.py" should be updated to use "tee". Or, at least, a severe warning comment should be written. Thank you, Francis Girard FRANCE Le dimanche 23 Janvier 2005 23:27, Jeff Epler a ?crit?: > Your formulation in Python is recursive (hamming calls hamming()) and I > think that's why your program gives up fairly early. > > Instead, use itertools.tee() [new in Python 2.4, or search the internet > for an implementation that works in 2.3] to give a copy of the output > sequence to each "multiply by N" function as well as one to be the > return value. > > Here's my implementation, which matched your list early on but > effortlessly reached larger values. One large value it printed was > 6412351813189632 (a Python long) which indeed has only the distinct > prime factors 2 and 3. (2**43 * 3**6) > > Jeff > > from itertools import tee > import sys > > def imerge(xs, ys): > x = xs.next() > y = ys.next() > while True: > if x == y: > yield x > x = xs.next() > y = ys.next() > elif x < y: > yield x > x = xs.next() > else: > yield y > y = ys.next() > > def hamming(): > def _hamming(j, k): > yield 1 > hamming = generators[j] > for i in hamming: > yield i * k > generators = [] > generator = imerge(imerge(_hamming(0, 2), _hamming(1, 3)), _hamming(2, > 5)) generators[:] = tee(generator, 4) > return generators[3] > > for i in hamming(): > print i, > sys.stdout.flush() From rublind at gmail.com Mon Jan 10 00:46:12 2005 From: rublind at gmail.com (rublind at gmail.com) Date: 9 Jan 2005 21:46:12 -0800 Subject: Datetime module Message-ID: <1105335972.454019.46450@c13g2000cwb.googlegroups.com> I am writing a script that acts as an AIM bot [using twisted.IM's base scripts] and I want to add a logging feature. I got it to log who sends what to whom, but what I want to add is the date and time that the message was sent (or recieved by the bot), I tried to look at datetime on my own, and I couldn't get anything to work. Anyone know a simple way to get the current date and/or time? Thanks! From gmane-schpam at joefrancia.com Sat Jan 8 18:31:18 2005 From: gmane-schpam at joefrancia.com (Joe Francia) Date: Sat, 08 Jan 2005 18:31:18 -0500 Subject: The best way to do web apps with Python? In-Reply-To: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: worzel wrote: > What is the best way to web developemnt with Python? Is there > anything close to PHP style in-page script placement that can create > and use other Python objects? I am not really interested in Zope (I > believe that is more a CMS than anything else?) I am also looking for > something a little more structured than a series of CGI Scripts. > > While on the topic - what is the expectataion of Python for this kind > of stuff? Would one use Python for certain other things but turn to > PHP for web apps - or would one use their Python skills in place of > PHP? > > TIA > You may want to look here for some thoughts on the matter: http://pyre.third-bit.com/pyweb/index.html I lean towards Quixote and/or CherryPy, with ZODB as the storage. Both are conceptually similar (I'm comparing v2 of both), but I favor Quixote just slightly more, mostly for Quixote's better form handling. Cheetah is a very nice templating package, but in Quixote I just use its own PTL, since it's built-in. If you wanted to stick with PHP for some reason, Drupal is a very nicely designed framework (or CivicSpace, which is developed in parallel with Drupal, with a number of added-on features). Quixote: http://www.mems-exchange.org/software/quixote/ CherryPy: http://www.cherrypy.org/ ZODB: http://zope.org/Wikis/ZODB/FrontPage Cheetah: http://www.cheetahtemplate.org/ Drupal: http://www.drupal.org/ CivicSpace: http://www.civicspacelabs.org/ jf From ianb at colorstudy.com Wed Jan 12 15:41:02 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Wed, 12 Jan 2005 14:41:02 -0600 Subject: OT: MoinMoin and Mediawiki? In-Reply-To: <7xvfa2toed.fsf@ruckus.brouhaha.com> References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> <1g4nx7m906q79$.dlg@usenet.alexanderweb.de> <7xekgr7lpy.fsf@ruckus.brouhaha.com> <7x4qhn9q3g.fsf@ruckus.brouhaha.com> <7xr7kq1rk6.fsf@ruckus.brouhaha.com> <7xvfa2toed.fsf@ruckus.brouhaha.com> Message-ID: <41E58B5E.30805@colorstudy.com> Paul Rubin wrote: > Paul Rubin writes: > >>>>How does it do that? It has to scan every page in the entire wiki?! >>>>That's totally impractical for a large wiki. >>> >>>So you want to say that c2 is not a large wiki? :-) >> >>I don't know how big c2 is. My idea of a large wiki is Wikipedia. >>My guess is that c2 is smaller than that. > > > I just looked at c2; it has about 30k pages (I'd call this medium > sized) and finds incoming links pretty fast. Is it using MoinMoin? > It doesn't look like other MoinMoin wikis that I know of. I'd like to > think it's not finding those incoming links by scanning 30k separate > files in the file system. c2 is the Original Wiki, i.e., the first one ever, and the system that coined the term. It's written in Perl. It's a definitely not an advanced Wiki, and it's generally relied on social rather than technical solutions to problems. Which might be a Wiki principle in itself. While I believe it used full text searches for things like backlinks in the past, I believe it uses some kind of index now. > Sometimes I think a wiki could get by with just a few large files. > Have one file containing all the wiki pages. When someone adds or > updates a page, append the page contents to the end of the big file. > That might also be a good time to pre-render it, and put the rendered > version in the big file as well. Also, take note of the byte position > in the big file (e.g. with ftell()) where the page starts. Remember > that location in an in-memory structure (Python dict) indexed on the > page name. Also, append the info to a second file. Find the location > of that entry and store it in the in-memory structure as well. Also, > if there was already a dict entry for that page, record a link to the > old offset in the 2nd file. That means the previous revisions of a > file can be found by following the links backwards through the 2nd > file. Finally, on restart, scan the 2nd file to rebuild the in-memory > structure. That sounds like you'd be implementing your own filesystem ;) If you are just trying to avoid too many files in a directory, another option is to put files in subdirectories like: base = struct.pack('i', hash(page_name)) base = base.encode('base64').strip().strip('=') filename = os.path.join(base, page_name) -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From http Wed Jan 19 20:09:19 2005 From: http (Paul Rubin) Date: 19 Jan 2005 17:09:19 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> Message-ID: <7xacr4ewjk.fsf@ruckus.brouhaha.com> Robin Becker writes: > > Presumably he is talking about crypo-export rules. In the past strong > > cryptography has been treated as munitions, and as such exporting it > > (especially from the USA) could have got you into very serious > > trouble. > > well since rotor is a german (1930's) invention it is a bit late for > Amricans (Hollywood notwithstanding) to be worried about its export 1. I think the concern was not about exporting from the US, but rather importing into some countries that restrict the use of crypto. But the cat is out of the bag on that one too. Just about every web browser includes an SSL stack and those browsers are in use everywhere. 2. It's irrelevant for the purpose of export rules how old an invention is or where it was invented. I don't know where machine guns were invented, but they're at least 100 years old and you can't export those without a license either. My gripe with the crypto rules are not about the age or nationality of crypto rotor machines (rotor is not a clone of the Enigma by the way; it just operates on related principles) but rather on the control of information in general. Exporting a machine gun is much different from publishing a description of one. Software is just a precise type of description. From kent3737 at yahoo.com Sat Jan 29 21:42:12 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Sat, 29 Jan 2005 21:42:12 -0500 Subject: bound vs unbound functions In-Reply-To: <1107040729.535936.42230@c13g2000cwb.googlegroups.com> References: <1107040729.535936.42230@c13g2000cwb.googlegroups.com> Message-ID: <41fc46e3_1@newspeer2.tds.net> Michael Tobis wrote: > I'm trying to do metaprogramming. I'm sure I've got this all wrong > wrong wrong, but somehow my approach hasn't yet hit a brick wall. > > Anyway, I'd like to dynamically add a method to an instance at > instantiation time. Something like > > ###### > In [71]: class quux(object): > ....: def __init__(self,stuff): > ....: template = "def foo(self,b): print b + %s" % stuff > ....: exec(template) > ....: self.bazz = foo > ....: > > > In [72]: q = quux(5) > > In [73]: q.bazz(4) > --------------------------------------------------------------------------- > TypeError Traceback (most recent call > last) > > /Users/tobis/PyNSol/ > > TypeError: foo() takes exactly 2 arguments (1 given) > > In [74]: q.bazz("not much",4) > 9 > ######## The thread Steve quoted suggests using new.instancemethod(): import new class quux(object): def __init__(self,stuff): template = "def foo(self,b): print b + %s" % stuff exec(template) self.bazz = new.instancemethod(foo, self, quux) There is no need for exec; you can define foo() directly as a nested function: class quux(object): def __init__(self,stuff): def foo(self,b): print b + stuff self.bazz = new.instancemethod(foo, self, quux) Of course for this simple example you can just remember stuff as an attribute: class quux(object): def __init__(self,stuff): self.stuff = stuff def bazz(self, b): print b + self.stuff Kent > > So the straightforward question is why, even though bazz is a method of > class quux, it doesn't have that extra call parameter 'self'. Is this a > problem? If I actually need a reference to self is it OK to do: > > In [76]: q.bazz(q,4) > > ? > > The more vague question is why do people despise 'exec', and how should > I do this sort of thing instead? From drummmachine at aol.commmmm Thu Jan 20 23:27:49 2005 From: drummmachine at aol.commmmm (Drummmachine) Date: 21 Jan 2005 04:27:49 GMT Subject: Does anyone want one? Message-ID: <20050120232749.14147.00000205@mb-m10.aol.com> http://www.freeiPods.com/?r=14249501 just go here to get started. It's very easy and very real. This is no scam. Complete an offer, get 5 others to do the same and you'll receive a free Ipod of your choice. thanks for your time. Free ipods are real. From gilles.arnaud at cea.fr Mon Jan 24 10:00:16 2005 From: gilles.arnaud at cea.fr (Gilles Arnaud) Date: Mon, 24 Jan 2005 16:00:16 +0100 Subject: "bad argument type for built-in operation" Message-ID: Hello, I've got a nasty bug and no idea to deal with : here is the method : def denormer(self, var) : " denorme un vecteur d'entree " try: #a = map(self.decerner, self.param, var) #a = [self.decerner(x, y) for x, y in map(None, self.param, var)] a = [] print 'in', None, self.param, var, len(self.param), len(var), str(self.decerner) #return map(undoc, self.param, var) print map(None, var) print map(None, self.param) #print zip(var, var) #print zip(self.param, self.param) #print map(lambda x, y: (x,y), self.param, var) #print zip(self.param, var) b = [] print '$', ii = range(len(var)) print ii, '$', for i in ii : print '%', b.append((self.param[i], var[i])) print b, '/', print '$', print b for x,y in b : print x, y z = undoc(x, y) print z a.append(z) except TypeError, c : print 'E', str(self.decerner), self.param, var print 'E2', str(c) raise return a in fact the method was initially reduce to return map(self.decerner, self.param, var) all the commented line produced the same exception raised this method unnormalize an input vector (var) and the trace in None [(-2.0, 2.0), (-2.0, 2.0)] [0.1385039192456847, 0.87787941093093491] 2 2 [0.1385039192456847, 0.87787941093093491] [(-2.0, 2.0), (-2.0, 2.0)] $ [0, 1] $ % [((-2.0, 2.0), 0.1385039192456847)] / % [((-2.0, 2.0), 0.1385039192456847), ((-2.0, 2.0), 0.87787941093093491)] / $ [((-2.0, 2.0), 0.1385039192456847), ((-2.0, 2.0), 0.87787941093093491)] (-2.0, 2.0) 0.138503919246 % 0.277007838491 (-2.0, 2.0) 0.877879410931 % 1.75575882186 in None [(-2.0, 2.0), (-2.0, 2.0)] [0.38111874838950943, 0.74880175070169164] 2 2 [0.38111874838950943, 0.74880175070169164] [(-2.0, 2.0), (-2.0, 2.0)] $ [0, 1] $ % [((-2.0, 2.0), 0.38111874838950943)] / % [((-2.0, 2.0), 0.38111874838950943), ((-2.0, 2.0), 0.74880175070169164)] / E [(-2.0, 2.0), (-2.0, 2.0)] [0.38111874838950943, 0.74880175070169164] E2 bad argument type for built-in operation [...] the first call of the methode succeed all following call failed. I've got different scenario which call this low level methode, many succeed, some failed this way. what's happened ? If someone got an idea ? what can raise this exception ? My program is written partially in python and partially in C. the top level is in python which call a C optimisation routine which use a callback (PyObject_CallMethod) to evaluate the cost in python again. From jello at comics.com Wed Jan 12 14:17:09 2005 From: jello at comics.com (rzed) Date: Wed, 12 Jan 2005 19:17:09 GMT Subject: ConfigParser - add a stop sentinel? References: Message-ID: Larry Bates wrote in news:nZqdnQYU7Z5O_XjcRVn-jA at comcast.com: [responding to the idea of placing a sentinel in an ini file, and modifying ConfigParser to stop receiving input when it is encountered]: > You should probably consider NOT doing what you suggest. You > would need to do some rather extensive work so you can support > the .write method of ConfigParser. With a little ingenuity > I've been able to user ConfigParser to support some very > different and complex syntaxes on different projects. If this > won't work, just have two different (separate) files. > > If you are dead set on combining these two, put your foreign > syntax lines into the file as comments. ConfigParser will > not process them, and you can have some other class extract > only the comments and parse them independently. I'm not sure I understand what you mean about the .write method of ConfigParser. I'm not trying to alter the *behavior* of ConfigParser at all, just giving it an alternative end of input (apart from EOF). And I'm not trying to replicate ConfigParser in my own configuration stuff. If I were, I'd just use ConfigParser. What I am doing is specifying a cluster of parameters on a single line in a compact, comma-separated form. I can easily split each parameter line and use the appropriate values, but it's not something ConfigParser is designed to accommodate, as far as I can tell. I don't want to put them into comments (though I could, I see), because I comment my own lines with hashmarks as well. I suppose I could lead off with double hashmarks and just strip off the first to get the desired effect, but it's an annoyance and it doesn't contribute to understanding what the config file is supposed to do. Still, as a workaround, it is something to consider. I just can't imagine that I'm the first person in history to have stumbled on such a use case, though. If ConfigParser would have a way to just take in raw data line-by-line within some group heading, that would work for this case just as well, and it seems to me that *that* might be useful in some other applications also ... though that's not what I'm talking about in this instance. -- rzed From dbasch at yahoo.com Tue Jan 11 18:16:53 2005 From: dbasch at yahoo.com (Derek Basch) Date: Tue, 11 Jan 2005 15:16:53 -0800 (PST) Subject: CGI, anydbm.open() and linux file permissions Message-ID: <20050111231653.84157.qmail@web20825.mail.yahoo.com> Hello, I have a CGI script which uses anydb.open() to create a DBM. However I get this traceback: /usr/lib/python2.3/bsddb/__init__.py in hashopen(file='/var/www/bp/predictor/tools.dbm', flag='c', mode=438, pgsize=None, ffactor=None, nelem=None, cachesize=None, lorder=None, hflags=0) 190 if ffactor is not None: d.set_h_ffactor(ffactor) 191 if nelem is not None: d.set_h_nelem(nelem) 192 d.open(file, db.DB_HASH, flags, mode) 193 return _DBWithCursor(d) 194 d = , d.open = , file = '/var/www/bp/predictor/tools.dbm', global db = , db.DB_HASH = 2, flags = 65, mode = 438 DBAccessError: (13, 'Permission denied') args = (13, 'Permission denied') The permissions on the CGI script (/usr/lib/cgi-bin/evaluator.py) are: -rwxr-xr-x 1 bpeters bpeters 2446 Jan 11 14:42 evaluator.py and the permissions on the target DBM creation directory (/var/www/bp/predictor/) are: drwxr-xr-x 2 bpeters bpeters 4096 Jan 11 14:45 predictor Can anyone tell me what I need to do to allow the CGI script to create the DBM in the target directory? That is short of changing everything to root. Thanks everyone, Derek Basch __________________________________ Do you Yahoo!? Meet the all-new My Yahoo! - Try it today! http://my.yahoo.com From john.abel at pa.press.net Wed Jan 26 08:55:24 2005 From: john.abel at pa.press.net (John Abel) Date: Wed, 26 Jan 2005 13:55:24 +0000 Subject: FTP Server In-Reply-To: <1106746068.798541.219240@c13g2000cwb.googlegroups.com> References: <1106743852.600769.72820@c13g2000cwb.googlegroups.com> <1106746068.798541.219240@c13g2000cwb.googlegroups.com> Message-ID: <41F7A14C.1080303@pa.press.net> michele.simionato at gmail.com wrote: >>If you're after a simple FTP server, have a look at medusa. >> >> >Uhm ... Medusa does not seem actively maintained nowadays. > > M.S. > > > AFAIK, it's maintained to the extent, that if you find bugs/enhance it and let the medusa-dev list know, it more than likely will get fixed/added. For what it's worth, I have a medusa-based FTP server running on Linux (daemon) and Win32 (service), without any problems at all. John From http Sun Jan 9 09:23:49 2005 From: http (Paul Rubin) Date: 09 Jan 2005 06:23:49 -0800 Subject: Python3: on removing map, reduce, filter References: <34csn1F4a46hqU1@individual.net> Message-ID: <7xekguof4a.fsf@ruckus.brouhaha.com> Andrey Tatarinov writes: > How does GvR suggestions on removing map(), reduce(), filter() > correlate with the following that he wrote himself (afaik): > > http://www.python.org/doc/essays/list2str.html I think that article was written before list comprehensions were added to Python. From tim.peters at gmail.com Mon Jan 10 18:36:09 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 10 Jan 2005 18:36:09 -0500 Subject: Writing huve ge Sets() to disk In-Reply-To: <41E2F38C.30200@ribosome.natur.cuni.cz> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> <41E2E69C.7080104@ribosome.natur.cuni.cz> <1f7befae0501101245679b26f2@mail.gmail.com> <41E2F38C.30200@ribosome.natur.cuni.cz> Message-ID: <1f7befae05011015362e17f610@mail.gmail.com> [Tim Peters] >> As I mentioned before, if you store keys in sorted text files, >> you can do intersection and difference very efficiently just by using >> the Unix `comm` utiltity. [Martin MOKREJ?] > Now I got your point. I understand the comm(1) is written in C, but it still > has to scan file1 once and file2 n-times, where n is a number of lines > in file1, right? Without any index ... I'll consider it, actually will test, > thanks! `comm` is much more efficient than that. Note that the input files have to be sorted. Then, in a single pass over both files (not 2 passes, not 3, not n, just 1), it can compute any subset of these three (do `man comm`): 1. The words common to both files. 2. The words unique to "the first" file. 3. The words unique to "the second" file. It's essentially just doing a merge on two sorted lists, and how it works should be obvious if you give it some thought. It takes time proportional to the sum of the lengths of the input files, and nothing *can* be faster than that. > I was really hoping I'll get an answer how to alter the indexes for dictionaries > in python. Sorry, I don't have a guess for what that might mean. > You convinced me not to even try to construct to theoretical dictionary, > as it will take ages just to create. Even if I'd manage, I couldn't > save it (the theoretical and possibly not even the dict(theoret) - dict(real) > result). Worse, it didn't sound like a good approach even if you could save it. > Still, before I give the whole project, once more: > > I'll parse some text files, isolates separate words and add them to > either Set(), list, dict, flatfile line by line. > > Depending on the above, I'll compare them and look for those unique > to some "language". I need to keep track of frequencies used > in every such language, Frequencies of what? "A language" here can contain some words multiple times each? > so the dict approach would be the best. The number stored as a value vould > be a float ^H^H^H^H^H^H Decimal() type - very small number. Integers are the natural type for counting, and require less memory than floats or decimals. > Once more, I expect to have between E4 or E5 to E8??? words > stored in 20 dictionaries (remember words of sizes in range 1-20? > Every of those 20 dictionaries should be, I believe, indexed just once. > The indexing method should know all entries in a given file are of same > size, i.e. 5 chars, 15 chars, 20 chars etc. I think you're making this more complicated than it needs to be. > I already did implement the logic to walk through those 20 different > dictionaries from language a and from language b and find uout those > unique to a or common to both of them. Why I went to ask on this list > was to make sure I took right approach. Sets seemed to be better solution > for the simple comparison (common, unique). To keep track of those > very small frequencies, I anyway have to have dictionaries. I say > that again, how can I improve speed of dictionary indexing? > It doesn't matter here if I have 10E4 keys in dictionary or > 10E8 keys in a dictionary. What reason do you have for believing that the speed of dictionary indexing is worth any bother at all to speed up? Dict lookup is generally considered to be extremely fast already. If you're just *guessing* that indexing is the bottleneck, you're probably guessing wrong -- run a profiler to find out where the real bottleneck is. From mahs at telcopartners.com Tue Jan 25 15:51:25 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 25 Jan 2005 12:51:25 -0800 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: References: Message-ID: Steven Bethard wrote: > Michael Spencer wrote: > >> Safe eval recipe posted to cookbook: >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 > > > This recipe only evaluates constant expressions: > > "Description: > Evaluate constant expressions, including list, dict and tuple using the > abstract syntax tree created by compiler.parse" > > It means you can't eval arbitrary Python code -- it's basically just a > data parser. Handy in some situations, but not the equivalent of a > limited Python virtual machine. Indeed. But it's easy to extend this to arbitrary constructs. You just need to decide what code to emit for the other 50 or so ast node types. Many of those are boiler-plate binops. > >> Likewise, function calls are easily intercepted > > I'm not sure I follow this... How do you intend to intercept all > function calls? Sorry, should have been more precise. In the AST, Function calls have their own node type, so it is easy to 'intercept' them and execute them conditionally > [snip] > > It sounds like you're suggesting overriding the global attribute access > mechanism. Is that right? So that every time Python encountered an > attribute access, you would verify that the attribute being accessed is > not on the 'dangerous' list? Just in the context of the AST-walker, yes I don't know how to do that without > basically rewriting some of Python's C code, though certainly I'm no > expert in the area... Not messing with the CPython interpreter > > Also, I'm not sure identity is sufficient: > > py> import sys > py> import new > py> new.module('newsys') > py> newsys = new.module('newsys') > py> newsys.__dict__.update(sys.__dict__) > py> newsys is sys > False > py> newsys == sys > False Right - the crux of the problem is how to identify dangerous objects. My point is that if such as test is possible, then safe exec is very easily implemented within current Python. If it is not, then it is essentially impossible. Let's assume that it is indeed not possible to know in general whether an object is safe, either by inspecting its attributes, or by matching its identity against a black list. It might still be possible to have a reliable test within a problem-specific domain i.e., white-listing. This, I think, is what you meant when you said: > I wish there was a way to, say, exec something with no builtins and with import disabled, so you would have to specify all the available bindings, e.g.: > > exec user_code in dict(ClassA=ClassA, ClassB=ClassB) I believe that if you can come up with a white-list, then the rest of the problem is easy. Michael From itsme at yahoo.com Tue Jan 4 10:12:36 2005 From: itsme at yahoo.com (It's me) Date: Tue, 04 Jan 2005 15:12:36 GMT Subject: Hlelp clean up clumpsy code References: Message-ID: Thanks, Steve and Nick. Yes, that's what I need to do. I didn't know it's call "flattening" a list structure but that's precisely what I needed to do. Steve, I am using 2.3 and so I will go with Nick's version. Thanks to both for helping. "Nick Coghlan" wrote in message news:mailman.121.1104833878.22381.python-list at python.org... > It's me wrote: > > Another newbie question. > > > > There must be a cleaner way to do this in Python: > > > > #### section of C looking Python code #### > > a = [[1,5,2], 8, 4] > > a_list = {} > > i = 0 > > for x in a: > > if isinstance(x, (int, long)): > > x = [x,] > > for w in [y for y in x]: > > i = i + 1 > > a_list[w] = i > > print a_list > > ##### > > > > The code prints what I want but it looks so "C-like". How can I make it > > more Python like? > > Firstly, calling your dictionary "a_list" is evil. . . > > Secondly, explaining what you want the code to do in English is handy when > asking for help cleaning up code (since we then know which features are > deliberate, and which are accidental implementation artificacts). > > If I'm reading the code correctly, you want to flatten a data structure which > may contain either substructures or actual elements. > > A custom generator will do nicely: > > Py> def flatten(seq): > ... for x in seq: > ... if hasattr(x, "__iter__"): > ... for y in flatten(x): > ... yield y > ... else: > ... yield x > ... > Py> data = [[1,5,2],8,4] > Py> val_to_pos = {} > Py> for i, x in enumerate(flatten(data)): > ... val_to_pos[x] = i + 1 > ... > Py> print val_to_pos > {8: 4, 1: 1, 2: 3, 4: 5, 5: 2} > > Not any shorter, but this version works correctly for any leaf elements which > don't supply __iter__ (e.g. strings), and internal elements which do (e.g. > tuples) and the depth is limited only by the maximum level of recursion. Don't > try to flatten a circular structure, though :) > > You may not even need to write the generator, since if you have Tkinter, that > already supplies a near-equivalent function: > > Py> from Tkinter import _flatten as flatten > Py> data = [[1,5,2],8,4] > Py> val_to_pos = {} > Py> for i, x in enumerate(flatten(data)): > ... val_to_pos[x] = i + 1 > ... > Py> print val_to_pos > {8: 4, 1: 1, 2: 3, 4: 5, 5: 2} > > It even works with strings as leaf elements: > > Py> data = [["abc","def",2],8,"xyz"] > Py> flatten(data) > ('abc', 'def', 2, 8, 'xyz') > > Cheers, > Nick. > > -- > Nick Coghlan | ncoghlan at email.com | Brisbane, Australia > --------------------------------------------------------------- > http://boredomandlaziness.skystorm.net From http Sat Jan 8 23:33:30 2005 From: http (Paul Rubin) Date: 08 Jan 2005 20:33:30 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> Message-ID: <7xr7kv8bmt.fsf@ruckus.brouhaha.com> "Roose" writes: > My point was that you can't do a lot of hardware interface programming in > pure Python -- there would be so much non-trivial code in C that it would be > hard to call it a Python OS. Why do you say that? Is the same thing not true of C, where you need some assembly code at the lowest levels? Because Linux has some assembly code, would you say that it's not written in C? > So this basically proves my point -- that you need different hardware > altogether in order to make an OS in a high level language like Lisp or > Python. It doesn't prove anything of the sort. The Lisp hardware was needed for performance reasons, back in the day. From yunmao at gmail.com Fri Jan 21 00:10:02 2005 From: yunmao at gmail.com (Yun Mao) Date: Fri, 21 Jan 2005 00:10:02 -0500 Subject: problems with duplicating and slicing an array In-Reply-To: References: <7cffadfa05012017337858d171@mail.gmail.com> Message-ID: <7cffadfa0501202110328c61b5@mail.gmail.com> Hi all, Thanks for the help. numarray doesn't provide what I look for either. e.g. a = array( [[1,2,3],[4,5,6]] ) I sometimes what this: a[ [1,0], :], or even a[ [1,0], [0,1] ] , which should give me [[4, 5], [1,2]] Because I don't really care about arrays with dimension >2, I did a little hacking with Numeric.Matrix.Matrix. It is more compatible with Matlab style slicing (except that the index starts from 0, not 1). This class automatically does copy, which is what I needed. Here is the code if somebody is interested (The wordy getAttr part is due to a "feature" in Numeric.Matrix based on the assumption that probably nobody is going to inherent it again :) ): #==========begin code========= from Numeric import * from Matrix import Matrix, UserArray import types def _isSeq(t): if isinstance(t, types.ListType): return True if (isinstance(t, ArrayType) or isinstance(t, UserArray)): return len(t.shape)==1 or \ (len(t.shape)==2 and t.shape[0]==1) return False class Mat(Matrix): def __getitem__(self, index): """Matlab style slicing: e.g. a[ [3,2], [2,1] ], a[1] """ if isinstance(index, types.TupleType) and len(index)==1 \ or _isSeq(index): if self.array.shape[0]!=1: return self._rc(self.array.flat).__getitem__(index) if not _isSeq(index): return Matrix.__getitem__(self, index) return self._rc(take(self, array(index).flat, 1)) elif isinstance(index, types.TupleType): assert len(index)==2 if not (_isSeq(index[0]) or _isSeq(index[1])): return Matrix.__getitem__(self, index) r = self.array tmp = slice(None, None, None) if _isSeq(index[0]): r = take(r, array(index[0]).flat,0) else: r = self._rc(r).__getitem__(self, (index[0], tmp)) if _isSeq(index[1]): r = take(r, array(index[1]).flat,1) else: r = self._rc(r).__getitem__( (tmp,index[1])) return self._rc(r) elif isinstance(index, types.IntType): return self.array.flat[index] return Matrix.__getitem__(self, index) def __getattr__(self, attr): if attr == 'A': return squeeze(self.array) elif attr == 'T': return self._rc(Numeric.transpose(self.array)) elif attr == 'H': if len(self.array.shape) == 1: self.array.shape = (1,self.array.shape[0]) return self._rc(Numeric.conjugate(Numeric.transpose(self.array))) elif attr == 'I': return self._rc(LinearAlgebra.inverse(self.array)) elif attr == 'real': return self._rc(self.array.real) elif attr == 'imag': return self._rc(self.array.imag) elif attr == 'flat': return self._rc(self.array.flat) elif attr == 'length': return max(self.array.shape) else: raise AttributeError, attr + " not found." #========end code======== > numarray supports matlab style indexing if you pass the ind as an > array or list of indices (but not a tuple, I found to my surprise). > As pointed out already, for Numeric you need to use the take function > > >>> from numarray import array > >>> x = array([1,2,3,4,5,6,7,8,9]) > >>> ind = [3,5,7] > >>> inda = array(ind) > >>> indt = tuple(ind) > >>> x[ind] > array([4, 6, 8]) > >>> x[inda] > array([4, 6, 8]) > >>> x[indt] > Traceback (most recent call last): > File "", line 1, in ? > IndexError: too many indices. > > I'm sure the tuple "surprise" is a documented feature. > > JDH > From sam.wun at authtec.com Sun Jan 23 08:06:51 2005 From: sam.wun at authtec.com (sam) Date: Sun, 23 Jan 2005 21:06:51 +0800 Subject: compile python to binary Message-ID: Hi, I have seen some software written in python and delivered as binary form. How does these binary code get generated by python compiler? Thanks Sam. From flamesrock at gmail.com Tue Jan 4 01:54:22 2005 From: flamesrock at gmail.com (flamesrock) Date: 3 Jan 2005 22:54:22 -0800 Subject: FS: PC Doctor In-Reply-To: <1104817852.587703.310920@c13g2000cwb.googlegroups.com> References: <1104817852.587703.310920@c13g2000cwb.googlegroups.com> Message-ID: <1104821662.790475.237460@c13g2000cwb.googlegroups.com> *blinks* stop spamming asshole From bill.mill at gmail.com Fri Jan 28 11:17:59 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 28 Jan 2005 11:17:59 -0500 Subject: Dynamic class methods misunderstanding In-Reply-To: <35v5jdF4rk3m7U1@individual.net> References: <35v5jdF4rk3m7U1@individual.net> Message-ID: <797fe3d405012808171954a2b4@mail.gmail.com> Diez, On Fri, 28 Jan 2005 16:57:37 +0100, Diez B. Roggisch wrote: > > > > Why doesn't m get the implicit self parameter in the self.method() > > call? How would I make it a proper member of the class, so that a > > self.method() call would work with the above "m" function? > > Use new.instancemethod: > > import new > > class Test: > def __init__(self, method): > self.m = new.instancemethod(method, self, Test) > Beautiful! thank you very much. Looking into the "new" module in python 2.4, that's equivalent to: self.m = type(self.__init__)(method, self, Test) I didn't know that you could call types to create another type. Peace Bill Mill bill.mill at gmail.com From andre.roberge at gmail.com Mon Jan 24 08:52:14 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 24 Jan 2005 05:52:14 -0800 Subject: finding name of instances created In-Reply-To: References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> Message-ID: <1106574734.302094.93730@f14g2000cwb.googlegroups.com> Ryan Paul wrote: > On Mon, 24 Jan 2005 13:19:45 +0000, Ryan Paul wrote: > > > > > A working solution: > > > > class A: > > pass > > > > a = A() > > b = A() > > c = A() > > > > [x for x,y in locals().items() if > > hasattr(y,"__class__") and y.__class__ == A] > > > > Just wanted to clarify, because I know that the intellectually deficient > amongst you will say that isinstance is better than using __class__... > > In this case isinstance isnt desirable because it will catch > instances of any objects that inherit A, not just instances of A. Observe: > > class A: pass > class B(A): pass > > a = A() > b = A() > c = A() > d = B() > > >>> [x for x,y in locals().items() if isinstance(y,A)] > ['a', 'c', 'b', 'd'] > > >>> [x for x,y in locals().items() if > ... hasattr(y,"__class__") and y.__class__ == A] > ['a', 'c', 'b'] Actually, it this case, isinstance *is* desirable (or rather *would have been*), exactly for the reason that you point out. After teaching about objects, one of the next subject would be that of inheritance. E.G. class BetterRobot(Robot): ... # create a robot that can turn right directly... However, I have been convinced that it would be much truer to Python to give the robot fake names (robot1, robot2, ...), and then have students name their own robots through declarations like: cleese = Robot(name="Cleese") or cleese = Robot() cleese.name = "Cleese" ===== Andr? > > -- SegPhault From fredrik at pythonware.com Mon Jan 24 06:33:46 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 12:33:46 +0100 Subject: delay and force in Python References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com><41EE6658.8000409@iinet.net.au> <41F4DA78.90703@iinet.net.au> Message-ID: Nick Coghlan wrote: >> How's this: >> >> Py> from itertools import islice >> Py> print islice((x for x in xrange(1, 996) if x % 2 == 0), 1, 2).next() >> 4 > > Wouldn't it be nice if this could be spelt: > > print (x for x in xrange(1, 996) if x % 2 == 0)[2] as I've always said, the sooner we can all use the itertools goodies without even noticing, the better. From secun at yahoo.com Thu Jan 27 16:18:56 2005 From: secun at yahoo.com (Chris) Date: Thu, 27 Jan 2005 21:18:56 GMT Subject: Help with web dashboard Message-ID: I've written some python scripts to handle different tasks on my Windows network. I would like for them to be accessible via a single web page (kind of like a dashboard) but have the scripts run on the web server (also a Windows box). Can anyone recommend a way (web server / language / method) of doing this? Security is important since this page will be accessible inside the company, but only people with the appropriate user name / password should be able to run the scripts. From spam at nospam.org Wed Jan 26 22:28:39 2005 From: spam at nospam.org (Erik Johnson) Date: Wed, 26 Jan 2005 20:28:39 -0700 Subject: building Python: up arrow broken on SuSE Linux 8.2 References: <41f6c3f7$1@nntp.zianet.com> Message-ID: <41f85dd8@nntp.zianet.com> > Do you have the GNU readline library installed and within Python's > reach (lib in LD_LIBRARY_PATH or in /etc/ld.so.conf with subsequent > call of ldconfig)? I think you are on the right path. I later found an Apple article online that answered essentially my question saying libreadline wasn't included on the Apple Python distribution the OP was asking about. I now notice this in the output of configure: checking for rl_pre_input_hook in -lreadline... no checking for rl_completion_matches in -lreadline... no My system has /lib/libreadline.so.4.3. I guess it does not define these newer functions and so that is why the readline module was not configured in Setup to start with? That is the presumption I am working on. So I downloaded & built libreadline version 5.0. I have libreadline.a and shlib/libreadline.so.5.0 files. Having done Python & other scripting languages for a while, I have sort of forgotten all the ugly details about C compilation. I'm trying to figure out how to get Python2.3.4. statically linked with the .a file and not muck with the system shared libraries and let other applications fend for themselves. Any advice on how to statically link in this library so the Python build is happy? Thanks, -ej ----- Original Message ----- From: "Peter Maas" Newsgroups: comp.lang.python Sent: Wednesday, January 26, 2005 3:22 AM Subject: Re: building Python: up arrow broken on SuSE Linux 8.2 > Erik Johnson schrieb: > > I am trying to upgrade my Python installation. After downloading > > sources and building Python 2.3.4, I am unable to use the command > > history editing feature in the interactive interpreter (where the > > up-arrow would previously give you the last command line to edit, > > it now just prints "^[[A".) > > > -- > ------------------------------------------------------------------- > Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 > E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') > ------------------------------------------------------------------- From deetsNOSPAM at web.de Fri Jan 28 09:07:23 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 28 Jan 2005 15:07:23 +0100 Subject: a sequence question References: Message-ID: <35uv4oF4rrsjcU1@individual.net> l = [1,2,3,4] for a, b in zip(l[::2], l[1::2]): print a,b -- Regards, Diez B. Roggisch From nnorwitz at gmail.com Fri Jan 21 09:41:09 2005 From: nnorwitz at gmail.com (Neal Norwitz) Date: 21 Jan 2005 06:41:09 -0800 Subject: tkinter socket client ? In-Reply-To: <1106311130.446259.30710@f14g2000cwb.googlegroups.com> References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> <1106311130.446259.30710@f14g2000cwb.googlegroups.com> Message-ID: <1106318469.311179.126140@c13g2000cwb.googlegroups.com> You are probably looking for Tkinter.createfilehandler(). Here are some snippets to get you started: tk_reactor = Tkinter._tkinter self.sd = socket(AF_INET, SOCK_STREAM) self.sd.connect((HOST, PORT)) tk_reactor.createfilehandler(self.sd, Tkinter.READABLE, self.handle_input) def handle_input(self, sd, mask): data = self.sd.recv(SIZE) (Sorry if the formatting is busted, blame google groups.) HTH, Neal From marc.huffnagle at gmail.com Thu Jan 27 17:42:27 2005 From: marc.huffnagle at gmail.com (enigma) Date: 27 Jan 2005 14:42:27 -0800 Subject: String Fomat Conversion References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> Message-ID: <1106865747.829698.119740@c13g2000cwb.googlegroups.com> Do you really need to use the iter function here? As far as I can tell, a file object is already an iterator. The file object documentation says that, "[a] file object is its own iterator, for example iter(f) returns f (unless f is closed)." It doesn't look like it makes a difference one way or the other, I'm just curious. From http Thu Jan 20 02:01:56 2005 From: http (Paul Rubin) Date: 19 Jan 2005 23:01:56 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> <7xacr4ewjk.fsf@ruckus.brouhaha.com> <41ef4a7a.1323588509@news.oz.net> Message-ID: <7xwtu8vb17.fsf@ruckus.brouhaha.com> bokr at oz.net (Bengt Richter) writes: > Isn't the SSL dependent on OS or at least shared lib support? Firefox has its own implementation. IE uses wininet which is built Windows. I'm not aware of any no-crypto version of Windows but even if there is one, the US version is running, like, everywhere. > Wasn't there a default 40-bit version that was ok (weak), but you had > to declare yourself US resident to download 128-bit support? That was years ago. The regulations changed since then, so they all have 128 bits now. > I dimly recall encountering this sort of thing installing Netscape > a long time ago, I think. Is 128 just standard now? And now that 128 > is wobbly(?), will the same thing be replayed with the ante upped? 128 isn't wobbly. It will be a long time before any machine can do 2**128 operations to break a message. From b at b.b Thu Jan 6 20:50:52 2005 From: b at b.b (Roose) Date: Fri, 07 Jan 2005 01:50:52 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: <0WlDd.8830$5R.1182@newssvr21.news.prodigy.com> What exactly do you mean by an operating system? If you don't want to program in C/C++ then you're going to have a hard time. I don't want to be too discouraging, but with that attitude I doubt you would get very far. It sounds like you want to make more of an OS shell -- no? You can implement a shell on top of any OS and probably do it in a language like Python. But if it is going to be a complete OS in pure Python, uh, it won't be! You'll have to do a lot of stuff in C, at the least interface with the hardware. "David Brown" wrote in message news:10trb0mgiflcj4f at corp.supernews.com... > Hello. I recently came across a free operating system called Unununium (or > something like that) and it was developed in Python and Assembly. > > Now, I have been looking for a way to make an operating system for a long > long time and the only possibilities I could find were C++ and assembly. I > don't mind assembly so much if I don't have to use it very often. But C++ is > so complicated and errors are pretty much impossible to find in the code for > me. > > So, I was wondering if it would be possible to find a bootloader that loads > a python file at startup or something... > > Is there an example somewhere of a Python OS? > > Thanks! > > From mail at tuxipuxi.org Fri Jan 14 06:50:59 2005 From: mail at tuxipuxi.org (Michael Goettsche) Date: Fri, 14 Jan 2005 12:50:59 +0100 Subject: Using Sqlite with Python under Windows Message-ID: <200501141250.59702.mail@tuxipuxi.org> Hello guys, I succeeded in convincing my CS teacher to use Python and Sqlite instead of Microsoft Access to get started with databases. We are working on a windows terminal server to which I have no admin access, so I'd like to ask you which module is best suited to use Sqlite with Python under windows. The best would be a module which is easy to install without further dependencies. Thanks in advance, Michael From the_schlops at yahoo.de Sat Jan 15 12:51:29 2005 From: the_schlops at yahoo.de (Wolfram Kraus) Date: Sat, 15 Jan 2005 18:51:29 +0100 Subject: Associate objects with Tix.Tree Message-ID: Heyho! I want to associate objects with the nodes of a Tix.Tree. Is this possible, because the following example won't work: --8<-- Cut here ------------------------- import Tix class C: pass root = Tix.Tk() top = Tix.Frame(root, relief=Tix.RAISED, bd=1) tixtree = Tix.Tree(top) tixtree.pack(expand=1, fill=Tix.BOTH, padx=10, pady=10, side=Tix.LEFT) c=C() print c tixtree.hlist.add(c, itemtype=Tix.IMAGETEXT, text='foo', image=tixtree.tk.call('tix', 'getimage', 'folder')) tixtree.setmode(c, 'open') root.mainloop() --8<-- Cut here ------------------------- Can this somehow be done? TIA, Wolfram From ebolonev at mail.ru Thu Jan 13 00:55:10 2005 From: ebolonev at mail.ru (Egor Bolonev) Date: Thu, 13 Jan 2005 15:55:10 +1000 Subject: newbie q Message-ID: <34mgq0F4dq4buU1@individual.net> how to get rid of 'for' operator in the code? import os, os.path def _test(): src = 'C:\\Documents and Settings\\????\\My Documents\\My Music\\' for i in [x for x in os.listdir(src) if os.path.isfile(os.path.join(src, x)) and len(x.split('.')) > 1 and x.split('.')[-1].lower() == 'm3u']: os.remove(os.path.join(src, i)) if __name__ == '__main__': _test() From craig at postnewspapers.com.au Sat Jan 22 06:53:27 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 22 Jan 2005 19:53:27 +0800 Subject: need help on need help on generator... In-Reply-To: <1gqshv6.linw9y1anlov0N%aleaxit@yahoo.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> <1106387175.4103.16.camel@albert.localnet> <1gqshv6.linw9y1anlov0N%aleaxit@yahoo.com> Message-ID: <1106394807.4103.54.camel@albert.localnet> On Sat, 2005-01-22 at 12:20 +0100, Alex Martelli wrote: > Craig Ringer wrote: > > > .>>> data = ''.join(x for x in infile) > > Maybe ''.join(infile) is a better way to express this functionality? > Avoids 2.4 dependency and should be faster as well as more concise. Thanks - for some reason I hadn't clicked to that. Obvious in hindsight, but I just completely missed it. > > Might it be worth providing a way to have file objects seek back to the > > current position of the iterator when read() etc are called? If not, I > > It's certainly worth doing a patch and see what the python-dev crowd > thinks of it, I think; it might make it into 2.5. I'll certainly look into doing so. I'm not dumb enough to say "Sure, I'll do that" before looking into the code involved and thinking more about what issues could pop up. Still, it's been added to my increasingly frightening TODO list. > > favour the suggestion in the referenced post - file should probably fail > > noisily, or at least emit a warning. > > Under what conditions, exactly, would you want such an exception? When read() or other methods suffering from the same issue are called after next() without an intervening seek(). It'd mean another state flag for the file to keep track of - but I doubt it'd make any detectable difference in performance given that there's disk I/O involved. I'd be happier to change the behaviour so that a warning isn't necessary, though, and I suspect it can be done without introducing backward compatibility issues. Well, so long as nobody is relying on the undefined file position after using an iterator - and I'm not dumb enough to say nobody would ever do that. I've really got myself into hot water now though - I'm going to have to read over the `file' source code before impulsively saying anything REALLY stupid. -- Craig Ringer From tjreedy at udel.edu Thu Jan 13 15:18:25 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Jan 2005 15:18:25 -0500 Subject: how to stop google from messing Python code References: <1105620098.878376.110250@z14g2000cwz.googlegroups.com> Message-ID: "Xah Lee" wrote in message news:1105620098.878376.110250 at z14g2000cwz.googlegroups.com... > i'm using groups-beta.google.com to post python code. > > Is there a way to stop google from messing with my format? it seems to > have eaten the spaces in my python code. > thanks. 1. don't post, or 2. don't use google to post -- there is no real excuse for doing so. Just about every computer comes with a newsreader. Get a free account with news.gmane.org and read/post gmane.comp.python. Terry J. Reedy From garabik at kassiopeia.juls.savba.sk Tue Jan 11 03:38:32 2005 From: garabik at kassiopeia.juls.savba.sk (Radovan Garabik) Date: 11 Jan 2005 08:38:32 GMT Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> Message-ID: <34hhk8F4bh2erU1@individual.net> "Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle." wrote: > Hi ! > >>>> and plain Latin letters > > But not all letters (no : ? ? ? ? ? ? ? etc.) > ... and some more letters that are not latin (j,w,u,z) ok, I'd better shut up :-) -- ----------------------------------------------------------- | Radovan Garab?k http://melkor.dnp.fmph.uniba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From macrocosm at fastmail.fm Sun Jan 9 09:57:47 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Sun, 09 Jan 2005 09:57:47 -0500 Subject: Python Operating System??? In-Reply-To: References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> Message-ID: <41E1466B.8090508@fastmail.fm> Roose wrote: > .... > >It's a difference of degree, but an important difference. I haven't looked >at Linux or Windows NT source, but my guess is the assembly used is just >small functions for accessing special CPU instructions for atomicity, >context switching, and the like. > >I KNOW they don't have huge amounts of assembly simply because they run on >different architectures. > > >But are you really going to write a virtual memory system in Python? Are >you going to write a file system, and a task scheduler in Python? Are you >going to have people write device drivers in Python? > Cleese!! > I'm not saying it >can't be done, but it would be a poor engineering decision, and the >rationale thus far seems to be "Python is cool, I like OSes, let's write a >whole OS in Python". If that's not the case then let me know what your >rationale is. > > > From mt at 3planes.com Mon Jan 31 22:41:27 2005 From: mt at 3planes.com (Michael Tobis) Date: 31 Jan 2005 19:41:27 -0800 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1107188359.375703.110590@f14g2000cwb.googlegroups.com> <1gr9lyc.1rrm543162uefN%aleaxit@yahoo.com> Message-ID: <1107229287.315380.222790@c13g2000cwb.googlegroups.com> Alex Martelli wrote: > Michael Tobis wrote: > he can perfectly > well correct his misexpression if he cares to -- not my job to try to > read his mind and perform exegesis on his words. Well, I hate to try to tell you your job, but it doesn't seem to be to be all that great of a marketing strategy to actively chase people away... Hey, he might have been a Nutshell customer. > I think it would have been true, but weak and insufficient. Not only > experienced Python users have that opinion: lack of declarations didn't > faze me even I was a total newbie It did me, and it did many others. Perhaps you are unrepresentative. It's one thing to say "no can do, sorry", it's another to say "you don't need this anyway and if you think you do you aren't worthy". In fact, it was your book I spent the most time thumbing through looking for the "use strict" equivalent that I was absolutely certain must exist. Hell, even Fortran eventually gave in to "IMPLICIT NONE". It's practically the only thing I've ever expected to find in Python that hasn't vastly exceeded my expectations, aand I'm sure Alexander is not the only person to be put off by it. In fact, I'd recommend a paragraph early in the Nutshell book saying "there are no declarations, no use strict, no implicit none, sorry, forget it", and an index listing under "declarations" pointing to a detailed exegesis of their nonexistence. It would have saved me some time. It's true that in some sense an assignment is all the declaration you need. I think Carl Banks's point (what we think of as assignment as a carryover from other languages is really rebinding, and in many cases can be avoided) is also helpful. But that doesn't make the "epselon" bug go away, and wanting to have a way to catch it quickly isn't, to my mind, obviously a criminal act. Also, based on what DogWalker demonstrates, it's really not that alien to Python and should be feasible. > > Also, the assertion that "Python has no declarations whatsoever" is no > > longer obviously true. In the 2.4 decorator syntax, a decorator line is > > not executable, but rather a modifier to a subsequent symbol binding. I > > call it a declaration. > > You may call it a strawberry, if you wish, but that doesn't mean it will > taste good with fresh cream. It's nothing more and nothing less than an > arguably weird syntax for a perfectly executable statement: This may well be true in implementation, but cognitively it is a declaration that modifies the reference and not the referent. I see that it is a big deal to ask for more of these, but I don't see why. > > Let me add that I remain unconvinced that a language cannot combine the > > best features of Python with very high performance, which is ultimately > > I'm also unconvinced. Fortunately, so is the EU, so they have approved > very substantial financing for the pypy project, which aims in good part > exactly at probing this issue. I hope this works out, but it's hard for me to see how pypy will avoid lots of hashing through dictionaries. I'm willing to help it by declaring an immutable reference. Here, don't look this up; it always points to that. I'm guessing that this will also be considered a bad idea, and maybe someday I'll understand why. I'm looking for insight, not controversy. > If any single individual can be called > the ideator of pypy, I think it's Armin Rigo, well-known for his > excellent psyco specializing-compiler for Python: I'm hoping I can make the meeting. Maybe proximity to the core group will help me approach the sort of enlightenment I seek. Just being in the vicinity of Ian Bicking's aura on occasion has been most inspiring. > Almost nobody really liked the splat-syntax for decorators, except of > course Guido, who's the only one who really counts (the BDFL). But that > was strictly a syntax-sugar issue Um, sugar isn't exactly what I'd call it. I think it matters a lot though. Python's being easy on the eyes is not a trivial advantage for some people, myself incuded. > If "declarative statement" means anything, I guess it means "having to > tell stuff to the compiler to be taken into account during compilation > but irrelevant at runtime". Python does have one such wart, the > 'global' statement, and it's just as ugly as one might imagine, but > fortunately quite marginal, so one can almost forget it. I am trying to talk about having expressive power in constraining references as well as the referents. Python studiously avoids this, but decorators change that. I am not deep enough into the mojo as yet to have more than a glimmer of an idea about the distinction you are making. It's not the one I'm trying to make. decorators may not be implemented as declarations, but they cognitively act as declarations, and that's what I care about here. > I have nothing against a declarative style _per se_ -- it just doesn't > fit Python's "everything happens at runtime" overall worldview, and that > simple and powerful worldview is a good part of what makes Python tick > SO well. I'm glad you have said something something I absolutely agree with. I'm alarmed at the suggestions here that class and def blocks are declarative. The fact that they're executable is really a core part of the beauty of Python. However, I don't see how an 'import strict' would necessarily violate this, nor an "import immutableref", which is something I would find useful in trying to wrestle with NumArray, and which a high-performance Python could (I think) use to advantage. Now I may be wrong; in fact I'd bet against me and in favor of you and Frederik if I had to bet. It's just that I don't see why I'm wrong. -- mt From steve at holdenweb.com Sun Jan 9 20:09:58 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 09 Jan 2005 20:09:58 -0500 Subject: path to python file given module In-Reply-To: <1105317971.205487.82770@c13g2000cwb.googlegroups.com> References: <1105315568.887724.260370@c13g2000cwb.googlegroups.com> <1105315923.520581.280580@c13g2000cwb.googlegroups.com> <1105317971.205487.82770@c13g2000cwb.googlegroups.com> Message-ID: Gene wrote: > that method doesn't seem to work as well on UNIX: > > wla apocalypse[94] ~/filegen > ls > filegen.py OLDwla_csv2objects.py wlaclasses.py > filegen.pyc templates/ wlaclasses.pyc > gen_all_from_csv.py test.py* > wla apocalypse[95] ~/filegen > python > .... Use the module's __file__ attribute: >>> import Image >>> Image.__file__ '/usr/lib/python2.4/site-packages/PIL/Image.pyc' >>> While this doesn't give you the source, it goves you enough to make a fair guess about where the source is likely to be, and a littel further manipulation should be able to confirm that. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From aleaxit at yahoo.com Thu Jan 27 10:19:57 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 27 Jan 2005 16:19:57 +0100 Subject: exclude binary files from os.walk References: <41f8167b$0$8648$a1866201@visi.com> Message-ID: <1gr228k.xxl2uu1om1vprN%aleaxit@yahoo.com> Craig Ringer wrote: > That's not really safe when dealing with utf-8 files though, and IIRC > with UCS2 or UCS4 as well. The Unicode BOM its self might (I'm not sure) > qualify as ASCII. Nope, both bytes in the BOM have the high-order bit set -- they're 0xFF and 0xFE -- so they definitely don't qualify as ASCII. Alex From jeff at ccvcorp.com Mon Jan 24 19:13:57 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 24 Jan 2005 16:13:57 -0800 Subject: Tuple slices In-Reply-To: <35lckuF4kbtbfU1@individual.net> References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> Message-ID: <10vb3enf8qvld4@corp.supernews.com> [My newsreader crapped out on sending this; apologies if it appears twice.] George Sakkis wrote: > "Terry Reedy" wrote in message > news:mailman.1226.1106605134.22381.python-list at python.org... > >>Aside from the problem of not being able to delete the underlying object, >>the view object for a tuple would have to be a new type of object with a >>new set of methods. > > It *could*, but it doesn't have to. One can represent a view as essentially an object with a pointer > to a memory buffer and a (start,stop,step) triple. Then a "real tuple" is just a "view" with the > triple being (0, len(sequence), 1). Except that that's not how Python tuples *are* constructed, and it'd be a pretty big deal to redo the architecture of all tuples to support this relatively special case. Even if this re-architecting were done, you're still constructing a new object -- the difference is that you're creating this (start,stop,step) triple instead of duplicating a set of PyObject* pointers, and then doing math based on those values instead of straightforward pointer access. I'm not at all convinced that this really saves you a significant amount for tuple slices (really, you're still constructing a new tuple anyhow, aren't you?), and it's going to cost a bit in both execution time and complexity in the common case (accessing tuples without slicing). If there's a big cost in object construction, it's probably going to be the memory allocation, and for a reasonable tuple the size of the memory required is not going to significantly affect the allocation time. Jeff Shannon Technician/Programmer Credit International From peter at somewhere.com Thu Jan 6 15:48:46 2005 From: peter at somewhere.com (Peter Maas) Date: Thu, 06 Jan 2005 21:48:46 +0100 Subject: Embedding a restricted python interpreter In-Reply-To: References: Message-ID: <345mkrF46jc4cU1@individual.net> Jp Calderone schrieb: >>But mod_python is an apache module and runs in the same apache process >>with other users' scripts. > > > I am uncertain as to how this differs from mod_php (the alternative > discussed in the OP's story). I've been away from PHP for a while, so > perhaps mod_php has gained some features of which I am unaware? I think PHP has a safe mode which solves the probem of isolating scripts of different users on application level. This is not optimal but better than nothing. Best solution would probably be to create a thread for each request that can operate only with the id of an authenticated user. But this seems to be a problem with Apache or with Linux? -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From francis.girard at free.fr Thu Jan 27 15:06:22 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 27 Jan 2005 21:06:22 +0100 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: <200501272106.22291.francis.girard@free.fr> Le jeudi 27 Janvier 2005 20:16, Steven Bethard a ?crit?: > flamesrock wrote: > > The statement (1 > None) is false (or any other value above 0). Why is > > this? > > What code are you executing? I don't get this behavior at all: > > py> 100 > None > True > py> 1 > None > True > py> 0 > None > True > py> -1 > None > True > py> -100 > None > True > Wow ! What is it that are compared ? I think it's the references (i.e. the adresses) that are compared. The "None" reference may map to the physical 0x0 adress whereas 100 is internally interpreted as an object for which the reference (i.e. address) exists and therefore greater than 0x0. Am I interpreting correctly ? > > (The reason I ask is sortof unrelated. I wanted to use None as a > > variable for which any integer, including negative ones have a greater > > value so that I wouldn't need to implement any tests or initializations > > for a loop that finds the maximum of a polynomial between certain x > > values. Anything is greater than nothing, no?) > > Yup, that's the behavior I get with None. > > Steve From marklists at mceahern.com Sun Jan 2 18:19:42 2005 From: marklists at mceahern.com (Mark McEahern) Date: Sun, 02 Jan 2005 17:19:42 -0600 Subject: ? about file() and open() In-Reply-To: <1104706607.022890.314500@c13g2000cwb.googlegroups.com> References: <1104706607.022890.314500@c13g2000cwb.googlegroups.com> Message-ID: <41D8818E.3040503@mceahern.com> Sean wrote: >Was wondering if there was any difference between these two functions. > > None, as shown here: D:\Python23>python Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> file == open True >>> >I have read some text that said file() wasn't introduced until 2.2 and >that it was synonymous with open(). Does this mean that I should be >using file() where I used open() before? > > Google is your friend: http://www.google.com/search?q=file+vs.+open+python http://mail.python.org/pipermail/python-dev/2004-July/045931.html // m From esj at harvee.org Thu Jan 13 23:27:49 2005 From: esj at harvee.org (Eric S. Johansson) Date: Thu, 13 Jan 2005 23:27:49 -0500 Subject: a ConfigParser wtf moment In-Reply-To: <1105675916.355620.324340@f14g2000cwb.googlegroups.com> References: <1105675916.355620.324340@f14g2000cwb.googlegroups.com> Message-ID: <41E74A45.5030605@harvee.org> grahamd at dscpl.com.au wrote: > To avoid this, you need to write something like: > > . list = [] > . for key in configuration.options("core"): > . list.append((key,configuration.get("core",substitution)) > . print list > > This cause me problems for a different reason, ie., that user vars keys > appear in what items() returns. I avoid using items() for this reason. it turns out, I originally discovered this problem through the get with substitutions. It's too late to muck with it now but if you are really interested I will generate a test case showing the failure or else prove I was hallucinating. My current workaround is to look for a %( in every value returned and if so do a string substitution. value = base.get(section,item, 1) if value.find("%(") != -1: value = value% self.interpolation_symbols yes, it is as ugly as a roadkill toad but it gets the job done. I've spent away too much time on this problem for this particular project. I think we all know the feeling. ---eric From aaronwmail-usenet at yahoo.com Fri Jan 7 14:59:25 2005 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 7 Jan 2005 11:59:25 -0800 Subject: OT: google groups bug, or worse? Message-ID: <1105127965.616198.302710@z14g2000cwz.googlegroups.com> I'm concerned that google groups is not correctly reflecting the python lists. A month ago I announced the xsdbXML framework to the python list and the python-announce list. As you can see from the links below the python announce submission was approved by the moderators (thanks!) and the python list submission also went out, but the messages cannot be found at google groups. http://mail.python.org/pipermail/python-list/2004-December/254479.html http://mail.python.org/pipermail/python-announce-list/2004-December/003583.html Is it a google bug? Or is it something darker, like an anti-Python conspiracy at google? Inquiring minds want to know. -- Aaron Watters === There are 3 kinds of people, those who can count and those who can't. -- folklore. From jacek.generowicz at cern.ch Fri Jan 7 03:56:02 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 07 Jan 2005 09:56:02 +0100 Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> Message-ID: Peter Hansen writes: > Jacek Generowicz wrote: > > Peter Hansen writes: > >>Why the heck would I ever have to do "rectangle operations" on a > >>regular basis? ;-) > > Well, given that all editors are cat equivalent[*], you don't _have_ > > to use any of their features :-) > > This "cat equivalent" thing is a red-herring. I can rarely type more > than a line of code without making a typographical error. Sometimes > I won't catch that error until a bit later. Using "cat" alone would > provide me little opportunity to fix the error, so I would never > be able to produce a working program longer than a few lines. And have you ever tried to write a serious program on a Turing Machine? This is exactly my point: Turing Equivalence is only theoretical. In practise some languages are more powerful than others. Same goes for editors. > But the whole argument is fairly moot... I've needed a rectangle > operation only once in the last ten years, Whereas I use rectangle operations, on average, a few times every day ... because they are part of my standard toolbox, they suggest themselves as the right solution to many a problem. There are plenty of programmers out there who "have only needed classes once in the last ten years". More powerful editors, just like more powerful languages, can make their users more productive. Complicated editors, just like complicated programming languages, can make their users less productive[*]. The optimal point in complexity-expressiveness space will be different for different individuals, be it for editors or programming languages. [*] I suspect that there are a few around here who would interpret this as an indictment against the direction in which Python is going :-) From bulba at bulba.com Thu Jan 6 20:22:04 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 02:22:04 +0100 Subject: [OT] Re: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <86ekh3qv1o.fsf@guru.mired.org> <03mlt0di3rcntvu7rlrk9k2m9bq8435bs5@4ax.com> <87r7kyck0m.fsf_-_@hector.domek> Message-ID: On Thu, 06 Jan 2005 22:42:01 +0100, Peter Dembinski wrote: >[...] > >> That's remarkable, first time I see smth like this - >> out of curiosity, could you say a word where was that? >Are you the same Bulba I know from alt.pl.comp.os.hacking? No, but I like to see I have an evil twin out there. :-) -- It's a man's life in a Python Programming Association. From just at xs4all.nl Mon Jan 17 10:29:17 2005 From: just at xs4all.nl (Just) Date: Mon, 17 Jan 2005 16:29:17 +0100 Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: In article , Antoon Pardon wrote: > >> I don't see a big difference between these principles > >> and the hash key principle, > > > > Than you haven't looked hard enough. > > All of these can get unexpected behaviour because of the > assignment-doesn't-copy semantics. The same semantics > that can cause problems if you work with mutable dictionary > keys. Again, the difference is: 1. assigning mutable objects *can* cause unexpected behavior (however, it's a useful feature, everyone using Python for longer than a day or two knows this, and then it's *expected* behavior. 2. mutating dict keys *does* *always* cause problems. (unless you use an identity hash/cmp) It's nonsense to forbid 1) since it's a useful feature. It's useful to forbid ("discourage") 2) since mutating dict keys is seldom useful (and when it is, Python lets you support it in your own objects). Just From ed at leafe.com Mon Jan 10 20:39:03 2005 From: ed at leafe.com (Ed Leafe) Date: Mon, 10 Jan 2005 20:39:03 -0500 Subject: Dabo 0.3 Released Message-ID: <930D4114-6371-11D9-B1AE-003065B11E84@leafe.com> We are pleased to announce Dabo 0.3, the third major release of our data application framework. The Dabo framework is a true 3-tier design, with data access and UI code separated from your business logic. And since it's Python, and uses wxPython for its UI, it is completely cross-platform, having been tested on Linux, Windows and OS X. Download from http://dabodev.com/download This marks the first major release of Dabo since we changed the licensing of Dabo. It is now released under the MIT License, which gives you much more freedom to do what you want with the code. See http://www.opensource.org/licenses/mit-license.html for the exact terms of the license. It is our hope that this will remove any reservations that people may have had about working with GPL software, and as a result grow the user base of the framework. Over the past few months we have gotten some wonderful feedback from people who are interested in our work and who are interested in a solid application framework for developing database apps. The framework is now very solid and reliable, and Dabo applications are being used daily. But there is still more we plan on adding, so like all pre-release software, use with caution. Anyone interested in contributing to Dabo, or who just want to find out what it is all about is encouraged to join our mailing lists: dabo-users: for those interested in learning how to work with Dabo to create applications, and for general help with Dabo. http://leafe.com/mailman/listinfo/dabo-users dabo-dev: for those interested in the ongoing development of Dabo. This list contains lots of lively discussion on design issues, as well as notices of all commits to the code repository. http://leafe.com/mailman/listinfo/dabo-dev Here is a brief summary of what's new in Dabo 0.3: Dabo Framework: Support for PostgreSQL added in addition to existing support for MySQL and Firebird databases. Improved unicode support in data cursors. Support for fulltext searches added. Child requeries and transaction support added to bizobj and cursor classes. Several new controls have been added, including a window splitter and a grid-like list control. The GridSizer has been added, making laying out of controls in a grid-like pattern a breeze. The API for all the sizers has been greatly simplified, too. Menus have had wxPython-specific code removed, and are now much simpler to create and manage. A 'Command Window' has been added to the base menu. This allows you to enter commands interactively in a running application, which makes debugging and testing so much simpler. Once you've developed an app with a Command Window at your disposal, you'll never want to develop without it! And, of course, more bug fixes than we'd like to say! Dabo IDE: The appWizard has been moved from the Demo project to here, as well as the FieldSpecEditor. There is a new connection editor for visually setting up database connection information and storing it in an XML file. The appWizard can now generate parent/child/grandchild/... relationships. The FieldSpecEditor (for visually controlling the appearance and behavior of wizard-generated apps) has been greatly improved, with interactive ordering and live previews of changes. The editor can now toggle word wrap, jump to any line in the file, and comment/uncomment blocks of code. Dabo Demo: There's now a MineSweeper game - written in Dabo, of course! All of the other demos have been updated to work with the changes in the rest of the framework. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From philippecmartin at sbcglobal.net Sat Jan 8 10:59:23 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Sat, 08 Jan 2005 16:59:23 +0100 Subject: printing line numbers for debugging purpose Message-ID: <1105199963.7467.4.camel@localhost> Hi, All of the methods from my program return None on error (i.e; I do not want to assert and have the program exit). Is it possible to print the current source file name/line number ? ex: in C/C++ I would use the macros __FILE__ and __LINE__. Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From joh12005 at yahoo.fr Mon Jan 24 17:06:49 2005 From: joh12005 at yahoo.fr (Joh) Date: 24 Jan 2005 14:06:49 -0800 Subject: need help on generator... (re) Message-ID: <63b5e209.0501241406.4fb5980b@posting.google.com> hello, thanks to all who replied to my post (2005-01-21) - (i can not post inside the original thread as i get "Unable to retrieve message csr7ep$3db$05$1 at news.t-online.com" from googlenews :( > Do you mean: > [1,2], [2,3], [3,4], [1,2,3], [2,3,4], [1,3,4] > (E.g. all elements in the power set except the empty set, the sets with > one element and the sets with all elements.) > Otherwise, please describe your desired sets in verbal - I cannot see > the point. yes it was my wishes, but having the others empty, one and all elements wasn't a big trouble, actually i wanted to understand more generators. > Here is an (untested) variant that accepts any iterable while trying to > remain memory-efficient. This makes it necessary to shuffle the order of > the output a bit. > from itertools import tee, islice > def gen(iterable, start, end): > it = iter(iterable) > while True: > it, a = tee(it) > a = tuple(islice(a, end-1)) > for sz in xrange(start, len(a)+1): > yield a[:sz] > it.next() > > if __name__ == "__main__": > print list(gen(range(1, 5), 2, 4)) please, this one looks interesting, could you explain a bit how it works and why it "remain memory-efficient" ? thanks, From sumitsu at cc.gatech.edu Thu Jan 20 17:31:12 2005 From: sumitsu at cc.gatech.edu (Branden Smith) Date: Thu, 20 Jan 2005 17:31:12 -0500 Subject: IDLE Problem in Windows XP Message-ID: <41F03130.4080709@cc.gatech.edu> Hi, I am a teaching assistant for an introductory course at Georgia Tech which uses Python, and I have a student who has been unable to start IDLE on her Windows XP Home Edition machine. Clicking on the shortcut (or the program executable) causes the hourglass to appear momentarily (and the process to momentarily appear in the process monitor), but nothing happens thereafter. Attempting to start IDLE from the script results in exactly the same output described in this discussion, suggesting that a socket error occurs, presumably for the Python loopback connection: https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1017978&group_id=5470 The potential solutions mentioned in the discussion have had no effect, however. Obviously, something is preventing Python from establishing a loopback socket connection, but after disabling firewall software, antiviral software, and Windows's built-in firewall, the problem remains. Does anyone have any ideas as to what might cause this problem? It shows up with both Python 2.4 and 2.3. Version 2.2 works as it should. Thanks, Branden Smith .::. CS 1321 TA sumitsu at cc.gatech.edu From andy at andygross.org Mon Jan 10 00:34:17 2005 From: andy at andygross.org (Andy Gross) Date: Mon, 10 Jan 2005 00:34:17 -0500 Subject: a new Perl/Python a day In-Reply-To: References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: <455C5963-62C9-11D9-9ABC-000A95CED3AC@andygross.org> On Jan 10, 2005, at 12:11 AM, Scott Bryce wrote: > > No. Perl may have some interesting idiosyncrasies, especially for a > programmer with little or no Unix experience, but I find it neither > frustrating, inane nor incompetent. The more I use it, the more I like > it. I don't see what UNIX experience has to do with it. I have plenty of it, and still have to look at the documentation to remember that I need to type '$|' to turn buffering off. Ditto for the rest of the perl line-noise syntax. /arg > http://mail.python.org/mailman/listinfo/python-list From donn at drizzle.com Sun Jan 2 14:02:37 2005 From: donn at drizzle.com (Donn Cave) Date: 2 Jan 2005 13:02:37 -0600 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> <7xsm5kfyse.fsf@ruckus.brouhaha.com> <41d7941f$1_3@127.0.0.1> <7x8y7cjo57.fsf@ruckus.brouhaha.com> Message-ID: <41d8454d$1_1@127.0.0.1> Quoth Paul Rubin : | "Donn Cave" writes: |> Yes, it would be really weird if Python went that way, and the |> sort of idle speculations we were reading recently from Guido |> sure sounded like he knows better. But it's not like there aren't |> some interesting issues farther on downstream there, in the compare |> function. cmp(), and str() and so forth, play a really big role in |> Python's dynamically typed polymorphism. It seems to me they are |> kind of at odds with static type analysis | | I don't understand that. If I see "str x = str(3)", then I know that | x is a string. Sure, but the dynamically typed polymorphism in that function is about its parameters, not its result. If you see str(x), you can't infer the type of x. Of course you don't need to, in Python style programming this is the whole point, and even in say Haskell there will be a similar effect where most everything derives the Show typeclass. But this kind of polymorphism is pervasive enough in Python's primitive functions that it's an issue for static type analysis, it seems to me, especially of the type inference kind. cmp() is more of a real issue than str(), outside of the type inference question. Is (None < 0) a valid expression, for example? Donn Cave, donn at drizzle.com From itsme at yahoo.com Mon Jan 3 11:41:54 2005 From: itsme at yahoo.com (It's me) Date: Mon, 03 Jan 2005 16:41:54 GMT Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: Shaw-PTI (www.pti-us.com) uses Python in their software. See: http://www.pti-us.com/pti/news/index.cfm and search "2004 PSS/E User Group Meeting" wrote in message news:1104750017.235937.181370 at c13g2000cwb.googlegroups.com... > Hello All, > I am trying to convince my client to use Python in his new product. He > is worried about the license issues. Can somebody there to point me any > good commercial applications developed using python ?. The licence > clearly says Python can be used for commercial applications. Is there > any other implications like that of GPL to make the source open ? > Thanks for any help. > eeykay > From X-Man at tj.mx Tue Jan 25 02:33:18 2005 From: X-Man at tj.mx (X-Man) Date: Tue, 25 Jan 2005 07:33:18 GMT Subject: ANNOUNCE: Altova ... blah blah blah References: <8u9Hd.344$Jg7.182@fe51.usenetserver.com> <41ed567c$0$6208$e4fe514c@news.xs4all.nl> Message-ID: In article <41ed567c$0$6208$e4fe514c at news.xs4all.nl>, irmen at -nospam- remove-this-xs4all.nl says... > Altova Announcements wrote: > > Altova Unveils ............. > [spam] > > Well now, I didn't like their products very much already, > but this spam has certainly made them drop another few > steps down on my scale. Hmpf. > > --Irmen > Yes. I find Altova's work to be high-quality but narrow-minded and arrogant. An example: Though all of the marketing material for StyleVision extols its usefulness for arbitrary, free-standing forms and reports, the only HTML or PDF one can actually generate is restricted to a frustrating subset which Altova has decided is useful -- and "useful" to them means "already supported by the Altova Authentic front end". From francis.girard at free.fr Fri Jan 28 08:57:07 2005 From: francis.girard at free.fr (Francis Girard) Date: Fri, 28 Jan 2005 14:57:07 +0100 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <7x3bwmggi3.fsf@ruckus.brouhaha.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> <7x3bwmggi3.fsf@ruckus.brouhaha.com> Message-ID: <200501281457.09366.francis.girard@free.fr> Le vendredi 28 Janvier 2005 08:27, Paul Rubin a ?crit?: > Francis Girard writes: > > Thank you Nick and Steven for the idea of a more generic imerge. > > If you want to get fancy, the merge should use a priority queue (like > in the heapsort algorithm) instead of a linear scan through the > incoming iters, to find the next item to output. That lowers the > running time to O(n log k) instead of O(n*k), where k is the number of > iterators and n is the length. The goal was only to show some FP construct on small problems. Here the number of iterators are intended to be fairly small. Otherwise, yes, you could exploit the fact that, at one loop execution, you already seen most of the elements at previous loop execution, storing them in some heap structure and therefore not having to recan the whole list of "already seen" iterator values at each loop execution. Thank you Francis Girard From fuzzyman at gmail.com Wed Jan 5 05:47:11 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 5 Jan 2005 02:47:11 -0800 Subject: Embedding a restricted python interpreter In-Reply-To: References: Message-ID: <1104922031.642263.44380@c13g2000cwb.googlegroups.com> Fredrick Lundh (at www.effbot.org ) was working on a 'cut down python' that only implements the bits of python he likes !! It would be great if the core of that interpreter could be used as a 'restricted interpreter'. If you could externally disable os, sys, os.path modules etc and limit the set of modules, then you could have a useful restricted environment. It would need a special interpreter though - so NO is the short answer. Regards, Fuzzy http://www,voidspace.org.uk/python/index.shtml From jacek.generowicz at cern.ch Thu Jan 6 03:41:01 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 06 Jan 2005 09:41:01 +0100 Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> Message-ID: Peter Hansen writes: > Why the heck would I ever have to do "rectangle operations" on a > regular basis? ;-) Well, given that all editors are cat equivalent[*], you don't _have_ to use any of their features :-) But just like Python (particularly in the hands of a skilled Python programmer) is more productive than a Turing Machine, any featureful editor (in the hands of an experienced user) is far more productive than "cat > file". [*] A bit like Turing equivalence: any program you can write in any other editor, you could also write with "cat > file" From matternc at comcast.net Mon Jan 17 14:26:13 2005 From: matternc at comcast.net (Chris Mattern) Date: Mon, 17 Jan 2005 14:26:13 -0500 Subject: [perl-python] 20050116 defining a function References: <1105886753.149519.194980@z14g2000cwz.googlegroups.com> <1105983516.736238.314050@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > errata: > > * the variables in the perl section should be declared inside the > subroutine. > * the @_[0] should've been $_[0] > > thanks for Dave Cross for pointing them out. > > * the Mathematica Apply should be Select... > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html Here's a thought: don't post code you haven't tested! -- Christopher Mattern "Which one you figure tracked us?" "The ugly one, sir." "...Could you be more specific?" From lidaobing at gmail.com Thu Jan 27 08:05:44 2005 From: lidaobing at gmail.com (Li Daobing) Date: 27 Jan 2005 05:05:44 -0800 Subject: a question about boost.python Message-ID: <1106831144.415765.18970@f14g2000cwb.googlegroups.com> I can't use .def(str(self)) I write a simple example, without `str', I can build it well, but with this one, I can't build //Rational.cpp #include #include using namespace std; using namespace boost::python; class Rational {}; ostream& operator<<(ostream& os, Rational r){ return os; } BOOST_PYTHON_MODULE(Rational) { class_("Rational") .def(str(self)) // __str__ ; } // end. I don't know how to write Jamfile, so I write a Makefile, it works if i don't use .def(str(self)) # Makefile CC = g++ CFLAGS = -Wall -W -fPIC -I/usr/include/boost \ -I/usr/include/python2.3 -DBOOST_PYTHON_DYNAMIC_LIB \ -O2 LDFLAGS = -L/usr/local/lib -lboost_python -L/usr/lib/python2.3 \ -Wl,-rpath-link,. -fPIC CXXFLAGS = $(CFLAGS) SLIB = hello.so Rational.so all: $(SLIB) %.so : %.o /usr/bin/objcopy --set-section-flags .debug_str=contents,debug $^ $(CC) $(LDFLAGS) $^ -shared -o $@ clean : rm -f $(WORLD) $(OBJS) # end. or a simple setup.py, it also works if I don't use `str' # setup.py from distutils.core import setup, Extension ext_modules = [Extension('Rational', ['Rational.cpp'], define_macros=[('BOOST_PYTHON_DYNAMIC_LIB', None)], libraries=['boost_python'])] setup(name="itcc", version="0.2.2", author='Li Daobing', author_email='lidaobing at gmail.com', ext_modules = ext_modules ) # end. This is the error message: $ make g++ -Wall -W -fPIC -I/usr/include/boost -I/usr/include/python2.3 -DBOOST_PYTHON_DYNAMIC_LIB -O2 -c -o Rational.o Rational.cpp Rational.cpp: In function `std::ostream& operator<<(std::ostream&, Rational)': Rational.cpp:10: warning: unused parameter `Rational r' /usr/include/boost/python/def_visitor.hpp: In static member function `static void boost::python::def_visitor_access::visit(const V&, classT&) [with V = boost::python::def_visitor, classT = boost::python::class_] ': /usr/include/boost/python/def_visitor.hpp:67: instantiated from `void boost::python::def_visitor::visit(classT&) const [with classT = boost::python::class_, DerivedVisitor = boost::python::api::object]' /usr/include/boost/python/class.hpp:225: instantiated from `boost::python::class_& boost::python::class_::def(const boost::python::def_visitor&) [with Derived = boost::python::api::object, W = Rational, X1 = boost::python::detail::not_specified, X2 = boost::python::detail::not_specified, X3 = boost::python::detail::not_specified]' Rational.cpp:15: instantiated from here /usr/include/boost/python/def_visitor.hpp:31: error: no matching function for call to `boost::python::api::object::visit(boost::python::class_&) const' make: *** [Rational.o] Error 1 From bokr at oz.net Thu Jan 13 15:39:44 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 20:39:44 GMT Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> <34o183F4b3in3U1@individual.net> Message-ID: <41e6d952.770332109@news.oz.net> On Thu, 13 Jan 2005 22:41:54 +0300, Andrey Tatarinov wrote: >Nick Coghlan wrote: >> Nick Coghlan wrote: >> >>> Semantics >>> --------- >>> The code:: >>> >>> with: >>> >>> >>> translates to:: >>> >>> def unique_name(): >>> >>> >>> unique_name() >> I've come to the conclusion that these semantics aren't what I would >> expect from the construct. Exactly what I would expect can't really be >> expressed in current Python due to the way local name bindings work. The >> main thing to consider is what one would expect the following to print: >> >> def f(): >> a = 1 >> b = 2 >> print 1, locals() >> print 3, locals() using: >> a = 2 >> c = 3 >> print 2, locals() >> print 4, locals() >> >> I think the least suprising result would be: >> >> 1 {'a': 1, 'b': 2} # Outer scope >> 2 {'a': 2, 'c': 3} # Inner scope >> 3 {'a': 2, 'b': 2, 'c': 3} # Bridging scope >> 4 {'a': 1, 'b': 2} # Outer scope > >as for me, I would expect following: > >1 {'a': 1, 'b': 2} >2 {'a': 2, 'b': 2, 'c': 3'} >3 {'a': 2, 'b': 2, 'c': 3'} >4 {'a': 1, 'b': 2} locals() doesn't automatically show everything that is visible from its local scope: >>> def foo(): ... a = 1 ... b = 2 ... print 1, locals() ... def inner(): ... a = 2 ... c = 3 ... print 2, locals() ... inner() ... print 4, locals() ... >>> foo() 1 {'a': 1, 'b': 2} 2 {'a': 2, 'c': 3} 4 {'a': 1, 'b': 2, 'inner': } -- unless you actually use it (this is a bit weird maybe?): >>> def foo(): ... a = 1 ... b = 2 ... print 1, locals() ... def inner(): ... a = 2 ... c = 3 ... print 2, locals(), 'and b:', b ... inner() ... print 4, locals() ... >>> foo() 1 {'a': 1, 'b': 2} 2 {'a': 2, 'c': 3, 'b': 2} and b: 2 4 {'a': 1, 'b': 2, 'inner': } of course a difference using the new syntax is that 'inner' is not bound to a persistent name. > >otherwise that would be impossible to do calculations based on scope >variables and "using:" would be useless =), consider example of usage: > >current_position = 1 >current_environment # = ... >current_a_lot_of_other_parameters # = ... >scores = [count_score(move) for move in aviable_moves] using: > def count_score(move): > #walking through current_environment > return score No worry, UIAM. Regards, Bengt Richter From pinard at iro.umontreal.ca Mon Jan 10 09:09:03 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Mon, 10 Jan 2005 09:09:03 -0500 Subject: a new Perl/Python a day In-Reply-To: <455C5963-62C9-11D9-9ABC-000A95CED3AC@andygross.org> References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> <455C5963-62C9-11D9-9ABC-000A95CED3AC@andygross.org> Message-ID: <20050110140903.GA23895@alcyon.progiciels-bpi.ca> [Andy Gross] > On Jan 10, 2005, at 12:11 AM, Scott Bryce wrote: > >No. Perl may have some interesting idiosyncrasies > I [...] still have to look at the documentation to remember that I > need to type '$|' to turn buffering off. Ditto for the rest of the > perl line-noise syntax. Behind each language, there is a culture. The Perl man pages give many mnemonic tricks to remember special variable names like the above, and if you are willing to play the game the way it was written, you might even have some fun at it, and easily be proficient at this "line-noise". I did a lot of Perl for many years, and still appreciate what Perl is (or at least was). Python does not change Perl in my eyes. However, Python is significantly more legible and maintainable, the comparison merely stresses the unreadability of Perl. No doubt that I prefer Python, but Python not being there, Perl would be quite useful to me. -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From phil at freehackers.org Mon Jan 31 23:32:40 2005 From: phil at freehackers.org (Philippe Fremy) Date: Tue, 01 Feb 2005 05:32:40 +0100 Subject: Python's idiom for function overloads In-Reply-To: References: Message-ID: <41ff066c$0$6473$636a15ce@news.free.fr> Hi Frans, > Since Python doesn't have static typing, how is the same result as traditional > function overloads results in acheived? With dynamic typing obviously. :-) You can not reproduce the C++ overload idiom but you can get something close with manual type testing. > To in a > function do an if statement with the type() function? I am not aware of any other method. def a( arg1 ): if type(arg1) == types.IntType: return aWithInt(arg1) if type(arg1) == types.ListType: return aWithList(arg1) ... As you see, it is a bit tedious sometimes. If you want to juggle with completely different signatures, you have to play with variable argument lists. But I have found in my experience that the best way to get close to the C++ idiom, while improving readbility, is by using kwparams: def a(**kwparams): if kwparams.has_key('argInt'): aWithInt(kwparams['argInt']) if kwparams.has_key('argString'): aWithString(kwparams['argString']) The parsing code is the same, but the intent of the user is better expressed and you can catch misuse in a better fashion: if kwparams.has_key('argInt') and kwparams.has_key('argString'): print "You stupid moron, a can be used only with string or int but not both at the same time!" sys.exit(1) The example speaks better in a real case. Imagine a processPixmap function: processPixmap( pixmap=QPixmap(...) ) processPixmap( filename='my_pixmap.png' ) processPixmap( buffer=my_pixmap_string_content ) It works actually even better with multiple arguments. regards, Philippe From gsakkis at rutgers.edu Sun Jan 9 13:10:08 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Sun, 9 Jan 2005 20:10:08 +0200 Subject: Pre/Postconditions with decorators References: <1105094828.619317.315340@z14g2000cwz.googlegroups.com><34814fF43bm4cU1@individual.net> Message-ID: <34dac0F47d7tlU1@individual.net> "Stephen Thorne" wrote: > Unresolved Problems: > 1) How do you handle duck types, i.e. a method that accepts StringIO, > cStringIO or any other object that has a .readlines(), .seek() and > .read() method? I think the 'proper' way of checking duck types (among other things) is by defining appropriate protocols; check pyProtocols (http://peak.telecommunity.com/PyProtocols.html) for details. > 2) How do you turn off the type checking for production code? Currently I don't, but that's easy to do if desired by checking __debug__ in the decorator and return the passed function if it is false: def params(**checkedArgs): if not __debug__: return lambda function: function # else return a typechecked proxy of function (...) > Otherwise I quite like it. Please publish it somewhere. Thanks. I'll post an entry on Vaults of Parnassus as soon as I publish it. George From steve at holdenweb.com Sun Jan 9 11:01:27 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 09 Jan 2005 11:01:27 -0500 Subject: use a file as a database, access rights In-Reply-To: References: Message-ID: Torsten Mohr wrote: > Hi, > > i'd like to write a script that makes use of a database. > > It would be great if the database would store all its data > in a file, that would be great for data exchange. > > It would also be great if i could use SQL, as i have some > experience in that. > > Also, i NEED access rights to certain parts of the database. > Several people should work on it and NEED to have different > access rights. > > > Can anybody give me some recommendations on what to use? > > Sounds to me like you need to add a rights layer to gadfly. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From tjreedy at udel.edu Tue Jan 25 02:38:05 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 Jan 2005 02:38:05 -0500 Subject: is extending an object considered acceptable usage? References: Message-ID: "mike" wrote in message news:qijJd.14679$Gc2.13828 at fe06.lga... > sometimes i want a list of categories, and from each i want to be able to > access a list of its items. in this case is it considered acceptable to > just create a list of those items and assign it as a property of their > category? eg: To me, Python is about being what it is, and not any other language. It is about writing correct readable algorithms. It is about enjoying programming. It is about programmers being responsible for their own code. I hope you find this more helpful than any yes or no could be. Terry J. Reedy From brion at pobox.com Tue Jan 11 17:14:32 2005 From: brion at pobox.com (Brion Vibber) Date: Tue, 11 Jan 2005 14:14:32 -0800 Subject: OT: MoinMoin and Mediawiki? In-Reply-To: <7xu0pn4x88.fsf@ruckus.brouhaha.com> References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <34h7m9F43vomsU1@individual.net> <7xsm58lcms.fsf@ruckus.brouhaha.com> <7xu0pn4x88.fsf@ruckus.brouhaha.com> Message-ID: <34j1dbF4cd4ocU1@individual.net> Paul Rubin wrote: > I think mod_php doesn't play nice with apache2 but am not aware of any > cgi interoperability problems. Generally it's recommended to configure apache2 in the child process mode (eg the way that 1.3 works) when using PHP as many library modules are alleged not to be threadsafe. Some Linux distributions ship standard this way. -- brion vibber (brion @ pobox.com) From cookedm+news at physics.mcmaster.ca Fri Jan 28 18:42:26 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Fri, 28 Jan 2005 18:42:26 -0500 Subject: LinearAlgebra incredibly slow for eigenvalue problems References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> <1106952951.834888.65430@f14g2000cwb.googlegroups.com> Message-ID: "drife" writes: > Hi David, > > I performed the above check, and sure enough, Numeric > is --not-- linked to the ATLAS libraries. > > I followed each of your steps outlined above, and Numeric > still is not linking to the ATLAS libraries. > > My setup.py file is attached below. > # delete all but the first one in this list if using your own LAPACK/BLAS > sourcelist = [os.path.join('Src', 'lapack_litemodule.c')] > # set these to use your own BLAS; > > library_dirs_list = ['/d2/lib/atlas'] > libraries_list = ['lapack', 'ptcblas', 'ptf77blas', 'atlas', 'g2c'] > > # set to true (1), if you also want BLAS optimized matrixmultiply/dot/innerproduct > use_dotblas = 1 > include_dirs = ['/d2/include'] This all look right (assuming you've got the right stuff in /d2). When it compiles, does it look like it's actually doing the linking? After doing python setup.py build, you can run ldd on the libraries in the build directory (something like build/lib.linux-i386-2.3/lapack_lite.so). If that's linked, then it's not being installed right. You don't have a previous Numeric installation that's being picked up instead of the one you're trying to install, do you? At the interpreter prompt, check that >>> import Numeric >>> Numeric.__file__ gives you something you're expecting, and not something else. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From wolfgang.keller.nospam at gmx.de Fri Jan 21 10:51:01 2005 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: Fri, 21 Jan 2005 16:51:01 +0100 Subject: Python-enterprise (integration) SIG/mailinglist/etc.? Message-ID: <15x0cn5gc5nhv.fnluxjlz7ljj.dlg@40tude.net> Hello, Python seems to be used quite a lot for (the integration of) enterprise applications. Just as an example, there are at least three (projects for the implementation of) ERP systems in Python: - GNUenterprise - ERP5 - TinyERP There are also a lot of different modules already available which supply useful functionalities for (the integration of) enterprise applications, such as PEAK, Twisted, OmniORBpy, Modeling, etc... However, what seems to be missing is some kind of coordination/communication resource and/or (link) repository for such modules, so that one can find out easily what exists already, whether it fits one's requirements and if not, where to find other people who would participate in the implementation of what's missing. So, here's the question: How about creating a Python-Enterprise(-Integration)-SIG/-mailinglist/whatever? Such a group could also start standardisation for such things as a "Python Messaging System", a "Python Component Model" and maybe (reference) implementations could be included in the Python distribution some day (no I don't think it should be called "PEE" :-). TIA, Wolfgang Keller From skip at pobox.com Fri Jan 21 11:04:33 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 21 Jan 2005 10:04:33 -0600 Subject: Zen of Python In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> Message-ID: <16881.10257.653477.308921@montanaro.dyndns.org> Steve> The fact that a bright bunch like the Python developers didn't Steve> realize that it would be sensible to have a local scope for the Steve> list comprehension variable is a perfect demonstration of that Steve> point. Actually, I seem to recall that the topic came up, but at the time the goal was that list comprehensions be semantically the same as for loops, so the fact that the loop variable survived to pollute the namespace was deemed okay. Skip From kent3737 at yahoo.com Tue Jan 4 07:48:17 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Tue, 04 Jan 2005 07:48:17 -0500 Subject: The Industry choice In-Reply-To: <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> Message-ID: <41da8e78$1_3@newspeer2.tds.net> Alex Martelli wrote: > Roy Smith wrote: > > >>Stefan Axelsson wrote: >> >>>Yes, ignoring most of the debate about static vs. dynamic typing, I've >>>also longed for 'use strict'. >> >>You can use __slots__ to get the effect you're after. Well, sort of; it >>only works for instance variables, not locals. And the gurus will argue >>that __slots__ wasn't intended for that, so you shouldn't do it. > > > There's a simple, excellent recipe by Michele Simionato, on both the > online and forthcoming 2nd edition printed Cookbook, showing how to do > that the right way -- with __setattr__ -- rather than with __slots__ . The recipe is here (it took me a few minutes to find it, I found the title misleading): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252158 Kent From j.p.t.j.berends at [N0SP4M].nl Thu Jan 6 10:05:57 2005 From: j.p.t.j.berends at [N0SP4M].nl (J Berends) Date: Thu, 06 Jan 2005 16:05:57 +0100 Subject: sorting on keys in a list of dicts In-Reply-To: References: Message-ID: Jp Calderone wrote: > On Thu, 06 Jan 2005 15:31:22 +0100, J Berends wrote: > >>Suppose I have a list of dictionaries and each dict has a common keyname >>with a (sortable) value in it. >> >>How can I shuffle their position in the list in such way that they >>become sorted. >> > > > In Python 2.4, > > import operator > L.sort(key=operator.itemgetter(key)) > > In Python 2.3, > > L2 = [(d[key], i, d) for (i, d) in enumerate(L)] > L2.sort() > L = [d for (v, i, d) in L2] > > Jp the 2.3 version seems to work quite nicely! thanks. Using the 2.3 for version compatibility. Thanks! From eurleif at ecritters.biz Thu Jan 20 02:13:05 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 20 Jan 2005 02:13:05 -0500 Subject: Solutions for data storage? In-Reply-To: References: Message-ID: <3593spF4i5j1dU1@individual.net> Robert Brewer wrote: > Try svn://casadeamor.com/dejavu/trunk if you want a truly Pythonic query > syntax. Wait a couple of days, and I'll have version 1.3 ready and > online at http://www.aminus.org/rbre/python -- lots of changes from > 1.2.6 which is there now, but at least you can read old docs online now > without svn. Thanks a lot for the reply. I've skimmed the documentation (very well-written, by the well), and I really like the looks of what I've seen so far. I'm a bit confused about where sandboxes get created, though; in a Web application, would I give each request a sandbox of its own, or create one for the entire application, or what? From alipolatel at yahoo.com Sun Jan 23 13:46:44 2005 From: alipolatel at yahoo.com (Ali Polatel) Date: Sun, 23 Jan 2005 10:46:44 -0800 (PST) Subject: on the way to find pi! In-Reply-To: <1d6cdae30501231034140ba539@mail.gmail.com> Message-ID: <20050123184644.20812.qmail@web61006.mail.yahoo.com> that's just little near to pi... pi is so far away ;) __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Wed Jan 5 21:20:00 2005 From: grante at visi.com (Grant Edwards) Date: 06 Jan 2005 02:20:00 GMT Subject: Example of using pty to control a process? References: <1104976111.041702.255710@c13g2000cwb.googlegroups.com> Message-ID: <41dca050$0$64503$a1866201@visi.com> On 2005-01-06, morphex wrote: > I'm trying to get the output from the command top on Linux, using > python. I'd like to start top, get a page of output, and then send top > the letter 'q' to end the process. Man, you like to do things the hard way. Me OTOH, I'm lazy. I'd use popen(), start top in "batch" mode and tell it to execute one iteration. import os lines = os.popen("top -b -n 1","r").read().split('\n') print lines > Looking around I've figured that the module pty can be used > for this, however, I can't find any good examples of how to > use it. Any ideas as to where I can look? I've you're dead set on using pty, I can tell you how to do it in C, and maybe you can extrapolate. -- Grant Edwards grante Yow! .. I think I'd at better go back to my DESK visi.com and toy with a few common MISAPPREHENSIONS... From steven.bethard at gmail.com Wed Jan 26 16:25:02 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 14:25:02 -0700 Subject: Help With Python In-Reply-To: <87ekg8c4d0.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> References: <87ekg8c4d0.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: Nick Vargish wrote: > Here's my Monty Pythonic answer: > > ## cut here > class Viking(): > > def __init__(): > pass > > def order(): > return 'Spam' > > # this is one viking making one order repeated 511 times. if you want > # 511 vikings making seperate orders, you'll have to write a loop. > v = Viking() > orders = [ v.order() ] * 511 > > print ', '.join(orders) No need to write a loop: py> class Viking(object): ... def order(self): ... return 'Spam' ... py> v = Viking() py> orders = [v.order()] * 7 py> ', '.join(orders) 'Spam, Spam, Spam, Spam, Spam, Spam, Spam' py> orders = [Viking().order()] * 7 py> ', '.join(orders) 'Spam, Spam, Spam, Spam, Spam, Spam, Spam' Steve From danb_83 at yahoo.com Sat Jan 1 00:20:28 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 31 Dec 2004 21:20:28 -0800 Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <1104549662.978986.77480@c13g2000cwb.googlegroups.com> Message-ID: <1104556828.320101.74750@z14g2000cwz.googlegroups.com> M.E.Farmer wrote: > Grant Edwards wrote: > >Not sure what Google Groups does to it... > The usual... it mangles it. > I don't get it, Google uses Python too, they know it is whitespace > signifigant. And for a long time, Google groups postings *were* whitespace significant. But the new interface broke it. > I made a complaint several weeks ago to Google support, > asking them too quit stripping leading whitespace, > and the sent me a reply saying they appreciated my feedback. > Maybe they just need more feedback :) I send them some earlier today. So far, I've only received their auto-reply. From stephen.thorne at gmail.com Thu Jan 6 18:02:40 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Fri, 7 Jan 2005 09:02:40 +1000 Subject: Pre/Postconditions with decorators In-Reply-To: References: Message-ID: <3e8ca5c80501061502203041ff@mail.gmail.com> On 6 Jan 2005 13:33:42 -0800, Rittersporn wrote: > @condition("number>0 and number<2","result>=0") > def sqrt(number): > import math > return math.sqrt(number) > > @condition("list(seq) is not None","sum(seq)==result") > def my_sum(seq): > tmp=0 > for element in seq: > tmp+=element > return tmp > > print sqrt(1.2) > print my_sum([1,2,3]) I think it would be nicer to have the pre and post conditions being compilable. @condition((list(seq) is not None for seq in args), (sum(seq)==result for ((seq,), result) in (args, result)) or something silly like that. Personally, I'd prefer this: @precondition(list(seq) is not None for seq in args) @postcondition(sum(seq)==result for ((seq,), result) in (args, result)) (this is, of course, using the framehack lambda replacement presented in a thread about a week ago). Stephen. Stephen. From jamesthiele.usenet at gmail.com Sun Jan 30 14:57:23 2005 From: jamesthiele.usenet at gmail.com (jamesthiele.usenet at gmail.com) Date: 30 Jan 2005 11:57:23 -0800 Subject: type() takes one or *three* arguments!? Message-ID: <1107115043.242733.259890@z14g2000cwz.googlegroups.com> I was looking at Simon Burton's Povray.py code (part of pypov) and saw this line: globals()[name] = type( name, (KWItem,), {} ) # nifty :) where 'KWItem' was a class. It did seem nifty, but it was unclear to me what was happening. I went to python.org's online documentation which said that type() takes one argument. So I fired up python: >>> type(42) >>> type("x", (type(42),), {}) OK, It appears that type() with 3 arguments constructs a class. Is this documented somewhere? If not can someone explain what is going on? james From phil_nospam_schmidt at yahoo.com Thu Jan 13 08:43:06 2005 From: phil_nospam_schmidt at yahoo.com (phil_nospam_schmidt at yahoo.com) Date: 13 Jan 2005 05:43:06 -0800 Subject: Octal notation: severe deprecation References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> <39ednWfqlrgB6HvcRVn-iA@powergate.ca> Message-ID: <1105623786.097982.94650@c13g2000cwb.googlegroups.com> Peter Hansen wrote: > and-google at doxdesk.com wrote: > > In Mythical Future Python I would like to be able to use any base in > > integer literals, which would be better. Example random syntax: > > > > flags= 2x00011010101001 > > umask= 8x664 > > answer= 10x42 > > addr= 16x0E800004 # 16x == 0x > > gunk= 36x8H6Z9A0X > > I think I kinda like this idea. Allowing arbitrary values, > however, would probably be pointless, as there are very > few bases in common enough use that a language should make > it easy to write literals in any of them. So I think "36x" > is silly, and would suggest limiting this to 2, 8, 10, and > 16. At the very least, a range of 2-16 should be used. > (It would be cute but pointless to allow 1x000000000. :-) > > -Peter > > > How about base 24 and 60, for hours and minutes/seconds? From steve at holdenweb.com Tue Jan 25 21:21:17 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 25 Jan 2005 21:21:17 -0500 Subject: Open Folder in Desktop In-Reply-To: <1106635751.661619.253930@c13g2000cwb.googlegroups.com> References: <1106635751.661619.253930@c13g2000cwb.googlegroups.com> Message-ID: Kamilche wrote: > Is there a command you can execute in Python that will open a window on > the desktop, such as 'My Documents'? Kind of like 'system', but for > folder names, not just programs. I'm running on Windows 2000. > os.system("start .") works for me. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From peter at engcorp.com Thu Jan 13 08:56:10 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 08:56:10 -0500 Subject: Unclear On Class Variables In-Reply-To: References: Message-ID: Simon Brunning wrote: > On 13 Jan 2005 07:18:26 EST, Tim Daneliuk wrote: > But you are being mislead by the fact that integers are immutable. > 'spam.eggs = 2' is *creating* an instance member - there wasn't one > before. Have a look at what happens with a mutable object: Simon, it's really not about mutability at all. You've changed the example, which was binding a name (specifically setting an attribute), to one in which you are simply calling a method on the object. If you change your example to bind the name the same way, even with a mutable, it will work the same way as Tim's original did with integers: >>> class Spam(object): ... eggs = [3] ... >>> spam = Spam() >>> spam2 = Spam() >>> spam.eggs = [7] >>> spam2.eggs [3] -Peter From mwm at mired.org Wed Jan 5 14:59:35 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 05 Jan 2005 13:59:35 -0600 Subject: smtp question References: Message-ID: <868y77pryw.fsf@guru.mired.org> "Philippe C. Martin" writes: > Hi, > > I am testing the smtp module and have the following question: > > in the code below (taken from net sample) prior to adding the "Subject:" > field, the email client found the "From" and the "To". Without the > "Subject:" field on I get this: > > Email client = Evolution: the "From" field is blank > Email client = KMail: the "To" field is blank > > Any clue ? > > Thanks and regards, > > Philippe > ********************** > > import smtplib > > def prompt(prompt): > return raw_input(prompt).strip() > > > fromaddr = prompt("From: ") > toaddrs = prompt("To: ").split() > print "Enter message, end with ^D (Unix) or ^Z (Windows):" > > # Add the From: and To: headers at the start! > msg = ("From: %s\r\nTo: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs))) > while 1: > try: > line = raw_input() > except EOFError: > break > if not line: > break > msg = msg + line > > print "Message length is " + repr(len(msg)) > > server = smtplib.SMTP('smtp.sbcglobal.yahoo.com') > server.set_debuglevel(1) > server.login ('xxxxx','yyyyyyy') > server.sendmail(fromaddr, toaddrs, 'Subject:from python\n\n'+msg) You've got \n\n after the Subject line, not \r\n. That is being treated as two newlines, thus ending the headers. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From warren.ali at gmail.com Thu Jan 20 18:08:06 2005 From: warren.ali at gmail.com (warren ali) Date: 20 Jan 2005 15:08:06 -0800 Subject: DbfilenameShelf instance has no attribute 'writeback' Message-ID: <1106262486.089616.99130@f14g2000cwb.googlegroups.com> Anyone have any idea why this is failing with the following error class _IndexFile: """An _IndexFile is an implementation class that presents a Sequence and Dictionary interface to a sorted index file.""" def __init__(self, pos, filenameroot): self.pos = pos self.file = open(_indexFilePathname(filenameroot), _FILE_OPEN_MODE) self.offsetLineCache = {} # Table of (pathname, offset) -> (line, nextOffset) self.rewind() self.shelfname = os.path.join(WNSEARCHDIR, pos + ".pyidx") try: import shelve self.indexCache = shelve.open(self.shelfname, 'r') except: pass Exception exceptions.AttributeError: "DbfilenameShelf instance has no attribute 'writeback'" in Exception exceptions.AttributeError: "DbfilenameShelf instance has no attribute 'writeback'" in Exception exceptions.AttributeError: "DbfilenameShelf instance has no attribute 'writeback'" in Exception exceptions.AttributeError: "DbfilenameShelf instance has no attribute 'writeback'" in The code still returns the correct restults but each result come back with this exception. From http Tue Jan 4 08:56:29 2005 From: http (Paul Rubin) Date: 04 Jan 2005 05:56:29 -0800 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <7xpt0liawq.fsf@ruckus.brouhaha.com> Message-ID: <7xk6qtb8mq.fsf@ruckus.brouhaha.com> Ville Vainio writes: > But the people working on wxPython, pygtk, pyqt, pydev, whatever, are > largely not the same guys that commit stuff to CPython CVS. Right, but for that reason, they don't count as being working on Python. > Type declarations are a feature that might benefit IronPython and > Jython more than they would CPython. CPython seems to be what drives quite a few language design decisions. From Scott.Daniels at Acm.Org Sat Jan 15 12:43:45 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 15 Jan 2005 09:43:45 -0800 Subject: interpret 4 byte as 32-bit float (IEEE-754) In-Reply-To: <34t1p2F4foiplU1@individual.net> References: <34t1p2F4foiplU1@individual.net> Message-ID: <41e952b9$1@nntp0.pdx.net> franzkowiak wrote: > I've read some bytes from a file and just now I can't interpret 4 bytes > in this dates like a real value. An extract from my program: > def l32(c): > return ord(c[0]) + (ord(c[1])<<8) + (ord(c[2])<<16) + (ord(c[3])<<24) > ... > value = l32(f.read(4)) <--- 3F 8C CC CD should be 1.11 > OK, here's the skinny (I used blocks & views to get the answer): import struct bytes = ''.join(chr(int(txt, 16)) for txt in '3F 8C CC CD'.split()) struct.unpack('>f', bytes) I was suspicious of that first byte, thought it might be an exponent, since it seemed to have too many on bits in a row to be part of 1.11. -Scott David Daniels Scott.Daniels at Acm.Org From fuzzyman at gmail.com Mon Jan 24 09:32:56 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Jan 2005 06:32:56 -0800 Subject: Py2.4 .exe installer In-Reply-To: References: Message-ID: <1106577176.109945.273940@z14g2000cwz.googlegroups.com> I built Movable Python for use on a windows box where I didn't have admin rights. See : http://sourceforge.net/projects/movpy Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From steven.bethard at gmail.com Mon Jan 10 11:13:17 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 10 Jan 2005 09:13:17 -0700 Subject: else condition in list comprehension In-Reply-To: <1105372193.185270.279290@c13g2000cwb.googlegroups.com> References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> <1105305000.052714.188980@c13g2000cwb.googlegroups.com> <1105372193.185270.279290@c13g2000cwb.googlegroups.com> Message-ID: Luis M. Gonzalez wrote: > It's me wrote: >>> z = [i + (2, -2)[i % 2] for i in range(10)] >> >> But then why would you want to use such feature? Wouldn't that make >> the code much harder to understand then simply: >> >> z=[] >> for i in range(10): >> if i%2: >> z.append(i-2) >> else: >> z.append(i+2) >> >> Or are we trying to write a book on "Puzzles in Python"? > > Once you get used to list comprehensions (and it doesn't take long), > they are a more concise and compact way to express these operations. After looking the two suggestions over a couple of times, I'm still undecided as to which one is more readable for me. The problem is not the list comprehensions (which I love and use extensively). The problem is the odd syntax that has to be used for an if/then/else expression in Python. I think I would have less trouble reading something like: z = [i + (if i % 2 then -2 else 2) for i in range(10)] but, of course, adding a if/then/else expression to Python is unlikely to ever happen -- see the rejected PEP 308[1]. Steve [1] http://www.python.org/peps/pep-0308.html From irmen at -nospam-remove-this-xs4all.nl Thu Jan 20 12:06:56 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Thu, 20 Jan 2005 18:06:56 +0100 Subject: xml parsing escape characters In-Reply-To: <41efb72d$1_2@newspeer2.tds.net> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efb72d$1_2@newspeer2.tds.net> Message-ID: <41efe52f$0$6220$e4fe514c@news.xs4all.nl> Kent Johnson wrote: [...] > This is an XML document containing a single tag, , whose content > is text containing entity-escaped XML. > > This is *not* an XML document containing tags , , > , etc. > > All the behaviour you are seeing is a consequence of this. You need to > unescape the contents of the tag to be able to treat it as > structured XML. The unescaping is usually done for you by the xml parser that you use. --Irmen From pierre.barbier at cirad.fr Mon Jan 24 03:06:19 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Mon, 24 Jan 2005 09:06:19 +0100 Subject: Help with Threading In-Reply-To: References: Message-ID: <41f4ac17$0$29097$626a14ce@news.free.fr> Philip Smith a ?crit : > Hi > > I am fairly new to Python threading and my needs are simple(!) > > I want to establish a number of threads each of which work on the same > computationally intensive problem in different ways. > > I am using the thread module rather than the threading module. > > My problem is I can't see how (when one thread completes) to ensure that the > other threads terminate immediately. > > Appreciate some simple advice > > Phil > > With Python's threads, you have to handle this kindd a feature yourself. For example, you can create a single object containing a boolean set to False by default. When one of your algorithm finishes, the boolean is set to True. All your algorithm should regularly test this boolean and exit if it is True ! Note that the boolean has to be inside another object because Boolean types is not mutable. Now, if you really want to be able to "kill" your threads, you will need another thread interface. For example, Qt threads allows that ... and WxPython offers you some functions to do exactly what I described. Pierre From apardon at forel.vub.ac.be Fri Jan 28 04:56:40 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Jan 2005 09:56:40 GMT Subject: A proposal idea for string.split with negative maxsplit References: Message-ID: Op 2005-01-28, Fredrik Lundh schreef : > Antoon Pardon wrote: > >> This behaviour would remain but additionally we would have the >> following. >> >>>>> "st1:st2:st3:st4:st5".split(':',-2) >> ["st1:st2:st3" , "st4" , "st5"] >> >> What do people think here? > >>>> "st1:st2:st3:st4:st5".rsplit(':', 2) > ['st1:st2:st3', 'st4', 'st5'] Damn, I was looking in the wrong version of the docs when I was looking for this. Sorry about that. -- Antoon Pardon From chris.peressotti at utoronto.ca Thu Jan 27 14:47:53 2005 From: chris.peressotti at utoronto.ca (Chris P.) Date: 27 Jan 2005 11:47:53 -0800 Subject: PythonWin (build 203) for Python 2.3 causes Windows 2000 to grind to a halt? Message-ID: <3f233389.0501271147.43572416@posting.google.com> I've been having a problem with PythonWin that seemed to start completely spontaneously and I don't even know where to START to find the answer. The only thing I can think of that marks the point between "PythonWin works fine" and "PythonWin hardly every works fine" was that I changed the size of my Virtual Paging file, noticing that it was too small (I currently have a P4 with 1G of RAM). I tried returning it to its original (smaller) size, but it didn't fix the problems. The first time I noticed it, I was using PythonWin and then right-clicked on My Computer to use "Explore". Instead of the usual full listing (approx 10 items), I got a mini-listing of 4 items. Then, after clicking "Explore", I either don't get a new window at all OR I get a strange file explorer that won't let me look at files, won't let me copy files, etc. The "mini-lising" thing also happens if I click the "Start" button while PythonWin is open. Another problem is trying to open another program while PythonWin is running - generally, the program will not start, but I also don't get any kind of error popping up on the screen. My request is just ignored (although I sometimes get a "system beep".) If I already have other programs open and then open PythonWin, my menu bar might refuse to function. Is it significant that, when the menu bar IS working, the drop-down menu fades in quite slowly, instead of popping up immediately? At the end of this message, I've pasted a screen dump of a message I get when I try to open a file and I've got other apps open (note that I can have very few, non-memory intensive apps open and I still get it). Thanks for any help you can give, - Chris [SCREEN DUMP AFTER I TRY TO OPEN A .PY FILE] File "C:\Python23\Lib\site-packages\pythonwin\pywin\mfc\docview.py", line 91, in CreateNewFrame wnd.LoadFrame(self.GetResourceID(), -1, None, context) # triggers OnCreateClient... win32ui: LoadFrame failed win32ui: CreateNewFrame() virtual handler (>) raised an exception TypeError: PyCTemplate::CreateNewFrame must return a PyCFrameWnd object. From stephen.thorne at gmail.com Mon Jan 10 16:17:54 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Tue, 11 Jan 2005 07:17:54 +1000 Subject: a new Perl/Python a day In-Reply-To: References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: <3e8ca5c805011013175ff50988@mail.gmail.com> On Mon, 10 Jan 2005 18:38:14 GMT, gabriele renzi wrote: > > You're joking, right? > > please consider that the message you all are asking are crossposted to > comp.lang.perl.misc and comp.lang.python, avoid the crossgroup flames :) Yuck. I'm on the python-list at python.org and I was extremely confused until you pointed out the crossposting. Maybe that mail2news gateway should be upgraded to point out crossposted usenet posts... Stephen. From skip at pobox.com Sun Jan 30 22:21:02 2005 From: skip at pobox.com (Skip Montanaro) Date: Sun, 30 Jan 2005 21:21:02 -0600 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <7xzmysqmxk.fsf@ruckus.brouhaha.com> Message-ID: <16893.42014.312134.252550@montanaro.dyndns.org> Nick> I think one of the special things about Python is its batteries Nick> included approach, and a crypto library would seem to be an Nick> obvious battery to install since it doesn't (or needn't) depend on Nick> any other library or application. Obvious for some I suppose (I've never used any). While it might be convenient to not have to distribute some third party library in addition to Python, there is a fundamental problem implementing a crypto algorithm from scratch for inclusion into Python. There is always the problem that the new code has to be more rigorously tested than typical code and new bugs means a new distribution of Python, not just a replacement library. A bug in code that is not security-related generally means something doesn't work and only rarely means a security hole has been opened on the computer. A bug in security-related code more often means the latter as well. I'd much rather trust a widely-disseminated piece of crypto code that is simply wrapped by Python than one that was written expressly written for Python (and that will likely not be exercised much outside the Python community). I realize the sha module is incorporated this way. It has this comment: * This code for the SHA algorithm was noted as public domain. The original * headers are pasted below. * * Several changes have been made to make it more compatible with the * Python environment and desired interface. While I imagine the changes were fairly small, the guys involved are all very smart, and the code is fairly straightforward (little, if any, memory allocation going on), there is still the possibility that a bug lurks in either the incorporated code or in the changes to it. How quickly could the Python community respond if a bug was found and fixed in the public domain SHA code? How much harder would it be for people to adapt if they had to reinstall Python instead of just an external library? Skip From jpmieville at bluewin.ch Tue Jan 18 15:55:48 2005 From: jpmieville at bluewin.ch (jean-paul) Date: 18 Jan 2005 12:55:48 -0800 Subject: Excel module for Python In-Reply-To: References: <87brbpdqct.fsf@andreasen.org> Message-ID: <1106081748.579677.222140@f14g2000cwb.googlegroups.com> I generate a lot pseudo excel file. Just write row by row on file and separate every cell of a row by a tab and put an .xls extension on the file name. When you double click. It opens directly EXCEL and you have directly the column and the row. It is easier than the CSV or SYLK files. If you want to format it automatically you can either define a VBA macro or use python com. Cheers, Jean-Paul From apardon at forel.vub.ac.be Tue Jan 11 03:22:30 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 11 Jan 2005 08:22:30 GMT Subject: tuples vs lists References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dfe2a6$0$22729$636a15ce@news.free.fr> <41e2e8cf$0$5744$626a14ce@news.free.fr> Message-ID: Op 2005-01-10, Bruno Desthuilliers schreef : > Antoon Pardon a ?crit : >> Op 2005-01-08, Bruno Desthuilliers schreef : >> >>>worzel a ?crit : >>> >>>>I get what the difference is between a tuple and a list, but why would I >>>>ever care about the tuple's immuutability? >>> >>>Because, from a purely pratical POV, only an immutable object can be >>>used as kay in a dict. > > s/kay/key/ > >> This is not true. > > Chapter and verse, please ? I don't need chapter and verse. I have already used mutable objects as keys and it works just fine. >>> class hlst(list): >>> >>> def __hash__(self): >>> sum = 0 >>> for el in self: >>> sum += hash(el) >>> return sum % 0x37777777 >>> >>> lst = hlst([3,5,7]) >>> lst [3, 5, 7] >>> lst[0] = 12 >>> lst [12, 5, 7] >>> d = {} >>> d[lst] = 4 >> >>>So you can use tuples for 'composed key'. >> >> lists can be so used too. Just provide a hash. > > Please show us an example, and let's see how useful and handy this is > from a "purely practical POV" ?-) It is handy from a pratical point of view when most operations you do on your data are the equivalent of appending, deleting and changing one element. Simulating these with tuples will cost you more than putting a copy of your list in the dictionary as a precaution against accidently mutating a key. -- Antoon Pardon From ovazquez at gmail.SPAM.com Tue Jan 25 00:22:05 2005 From: ovazquez at gmail.SPAM.com (Orlando Vazquez) Date: Tue, 25 Jan 2005 05:22:05 GMT Subject: Retrieving modification time of file class was declared in In-Reply-To: <1106627951.152900.135310@z14g2000cwz.googlegroups.com> References: <1106627951.152900.135310@z14g2000cwz.googlegroups.com> Message-ID: <1IkJd.53158$06.43207@clgrps12> nathan_kent_bullock at yahoo.ca wrote: > Assume I am using a class Foo. I want to find out the modification time > of the file that that class was defined in. How would I go about this? > > If I could find out the name of the file that Foo was defined in then > it is easy, I could use os.path.getmtime(), but I can't even figure > that out. > > I realize that this wouldn't be a completely accurate way to tell the > last time this class was modified because it could inherit info from > other classes, or use functions from other modules that have been > modified, etc. > > Nathan Bullock > Off the top of my head, without having done too much experimentation here's what you could try. Caveat: there may be a more robust/cleaner way of doing this: # Checking the modificationtime of the Thread class in the threading # module >>> import threading >>> import time >>> >>> module_filename = vars()[threading.Thread.__module__].__file__ >>> >>> mtime = os.path.getmtime(module_filename) >>> >>> print time.ctime(mtime) Sun Nov 14 20:29:42 2004 I hope that answer's your question :-) -- Orlando Vazquez From nemesis at nowhere.invalid Wed Jan 19 13:26:38 2005 From: nemesis at nowhere.invalid (Nemesis) Date: Wed, 19 Jan 2005 18:26:38 GMT Subject: [ANN] XPN - X Python Newsreader 0.4.0 released Message-ID: <7k7msc.7m1.ln@orion.homeinvalid> XPN is a multiplatform newsreader written in Python+GTK2. It is unicode compliant and has features like scoring/action rules, configurable attribution lines and random taglines, search facilities and filtered views, import/export newsrc ... You can find it on: http://xpn.altervista.org/index-en.html or http://sf.net/projects/xpn I'd really appreciate every type of feedback. Changes in this release: * v0.4.0: added off-line reading. Now you can download the whole bodies, or mark some article and download their bodies. * v0.4.0: added Keep Article and Watch/Ignore SubThread * v0.4.0: added actions rule, now you can !keep, !watch, !ignore (and so on) your article through rules * v0.4.0: now XPN stores the position and the size of Main Window and Edit Window * v0.4.0: now you can customize the charsets list XPN use to encode your outgoing articles * v0.4.0: improved speed when loading groups list in Groups Window. * v0.4.0: fixed a bug in the binary version that caused a crash trying to subscribe a group * v0.4.0: added Oriental Charsets support (thanks to Python2.4) * v0.4.0: added Global Search, you can search the whole groups and put the results in a virtual group * v0.4.0: added filtered views * v0.4.0: moved to GTK2.4 and Python2.4 * v0.4.0: added a TraceBack viewer and an error logger * v0.4.0: reorganized some menus * v0.4.0: now the background color is changed also on Groups Pane and Headers pane * v0.4.0: added a lot of little features/enhancements * v0.4.0: fixed a lot of bugs -- I'm not a complete idiot - several parts are missing. |\ | |HomePage : http://nem01.altervista.org | \|emesis |XPN (my nr): http://xpn.altervista.org From roy at panix.com Sat Jan 8 00:19:08 2005 From: roy at panix.com (Roy Smith) Date: Sat, 08 Jan 2005 00:19:08 -0500 Subject: how to extract columns like awk $1 $5 References: <487rklcxbidr$.gwsa68us9f3a.dlg@40tude.net> Message-ID: Dan Valentine wrote: > On Fri, 07 Jan 2005 12:15:48 -0500, Anand S Bisen wrote: > > > Is there a simple way to extract words speerated by a space in python > > the way i do it in awk '{print $4 $5}' . I am sure there should be some > > but i dont know it. > > i guess it depends on how faithfully you want to reproduce awk's behavior > and options. > > as several people have mentioned, strings have the split() method for > simple tokenization, but blindly indexing into the resulting sequence > can give you an out-of-range exception. out of range indexes are no > problem for awk; it would just return an empty string without complaint. It's pretty easy to create a list type which has awk-ish behavior: class awkList (list): def __getitem__ (self, key): try: return list.__getitem__ (self, key) except IndexError: return "" l = awkList ("foo bar baz".split()) print "l[0] = ", repr (l[0]) print "l[5] = ", repr (l[5]) ----------- Roy-Smiths-Computer:play$ ./awk.py l[0] = 'foo' l[5] = '' Hmmm. There's something going on here I don't understand. The ref manual (3.3.5 Emulating container types) says for __getitem__(), "Note: for loops expect that an IndexError will be raised for illegal indexes to allow proper detection of the end of the sequence." I expected my little demo class to therefore break for loops, but they seem to work fine: >>> import awk >>> l = awk.awkList ("foo bar baz".split()) >>> l ['foo', 'bar', 'baz'] >>> for i in l: ... print i ... foo bar baz >>> l[5] '' Given that I've caught the IndexError, I'm not sure how that's working. From ods at strana.ru Wed Jan 12 03:23:43 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Wed, 12 Jan 2005 11:23:43 +0300 Subject: os.spawnv & stdin trouble In-Reply-To: <20050111180707.304A41F9268C@mwinf0103.wanadoo.fr> References: <20050111200526.1bd60ebd.ods@strana.ru> <20050111180707.304A41F9268C@mwinf0103.wanadoo.fr> Message-ID: <20050112112343.60ce9e3c.ods@strana.ru> On Tue, 11 Jan 2005 19:08:01 +0100 "Jelle Feringa // EZCT / Paris" wrote: > Using the subprocess module, but still not making any real progress... > I'm trying to make the examples given in the __doc__ work, without any > success I'm afraid, have you had more luck with it? [...] > p = Popen("xform" + " -t 0 8 0 wallo.rad", stdout=PIPE, > shell=True).communicate()[0] > p.stdout > > p = Popen("dir" + " /w", stdout=PIPE, shell=True).communicate()[0] > p.stdout If you want passing parameters via shell (shell=True), than just use os.system. Nevertheless below is correct example of subprocess usage with stdout redirected to file: out_fp = open('wall0.TRANS.rad', 'wb') subprocess.call(['c:\\Radiance\\bin\\xform.exe', '-t', '0', '8', '0', 'wallo.rad'], stdout=out_fp) -- Denis S. Otkidach http://www.python.ru/ [ru] From rittersporn at gmail.com Fri Jan 7 05:47:08 2005 From: rittersporn at gmail.com (rittersporn at gmail.com) Date: 7 Jan 2005 02:47:08 -0800 Subject: Pre/Postconditions with decorators In-Reply-To: References: Message-ID: <1105094828.619317.315340@z14g2000cwz.googlegroups.com> Hi Stephen I have not read anything about the "framehack lambda replacement" yet, but I do compile the pre- and postconditions. Syntax erros e.g. will be raised if the module is compiled. Although I must admit that your code snippets look more like compiled code ;-) Hi Robert thanks for the link to the Ian Bicking blog. Hi George, it would be nice to see how you have tackled the task. Maybe we will have a checker module in Python one day... ;-) Well, I have attached my latest attempt to model pre/postconditions (without "framehack lambda replacement") which does wrap the original function with a class which delegates attribute access. Now I can split my "condition" into pre- and postcondition and the "tracer" prints the original function name. I have also fixed a bug with keyword arguments. Major difference compared to other examples is probably only that I can refer to function arguments by name: class Delegate(object): def __init__(self,function): self.function=function def __getattr__(self,key): return getattr(self.function,key) def condition(pretext,posttext=""): precode=compile(pretext or "True","","eval") postcode=compile(posttext or "True","","eval") # function -> decorated(function) def decorate_condition(function): argcount=function.func_code.co_argcount var=function.func_code.co_varnames[0:argcount] class EvalCond(Delegate): def __call__(self,*args,**kargs): # FIXME: check if "var" always contains ordered list of arguments # map arguments and args_seq=[(argname,args[pos]) for pos,argname in \ enumerate(var) if (argname not in kargs)] # key-arguments to value kargs_seq=[(k,v) for k,v in kargs.iteritems()] environment=args_seq+kargs_seq # precondition assert eval(precode,{},dict(environment)),pretext tmp=function(*args,**kargs) environment2=environment+[('result',tmp)] # postcondition assert eval(postcode,{},dict(environment2)),posttext return tmp return EvalCond(function) return decorate_condition def trace(function): class Trace(Delegate): def __call__(self,*args,**kargs): print "enter function %s with " % \ self.function.func_name,args,kargs result=self.function(*args,**kargs) print "leave function %s with " % \ self.function.func_name,args,kargs return result return Trace(function) def precondition(prgtext): return condition(prgtext) def postcondition(prgtext): return condition("",prgtext) @precondition("number>0 and number<2") @postcondition("result>=0") def sqrt(number): import math return math.sqrt(number) @trace @precondition("len(seq)>0 is not None and str(more)") @postcondition("sum(seq)==result") def my_sum(seq,more): tmp=0 for element in seq: tmp+=element return tmp print sqrt(1.2) print my_sum([1,2,3],more="more") From tjreedy at udel.edu Wed Jan 12 19:34:48 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Jan 2005 19:34:48 -0500 Subject: Why would I get a TypeEror? References: Message-ID: "Peter Hansen" wrote in message news:XOOdnSCB9NmJ-HjcRVn-2w at powergate.ca... > What did you expect the "length" of the integer 3 to be? Perhaps 2 (bits in a minimal binary representation). I once, for maybe a minute, considered proposing this as an overloaded meaning of len, but realized that that would more often mask errors than save time. If case bits(i) is what the OP wants: def bits(i): i = abs(i) b = 0 while i: i >>= 1 b += 1 return b Terry J. Reedy From paschott at no.yahoo.spamm.com Wed Jan 19 14:34:13 2005 From: paschott at no.yahoo.spamm.com (Peter A. Schott) Date: Wed, 19 Jan 2005 19:34:13 GMT Subject: FTPLIB & FTPS or SFTP? Message-ID: <9b9tu0te197u3bmheldg2hsvkbtuivlov6@4ax.com> Does the ftplib support SFTP or FTPS? Is that part of a different module? We have a handful of partners who use FTPS or SFTP and I need to pull/push files to/from them. Thank you for all of your help. -Pete Schott From paschott at no.worldnet.spamm.att.net Mon Jan 17 15:06:31 2005 From: paschott at no.worldnet.spamm.att.net (Peter A. Schott) Date: Mon, 17 Jan 2005 20:06:31 GMT Subject: python to mssql References: <1lmwxbtst8x8x$.10hwcoinem3cs.dlg@40tude.net> Message-ID: <941ou05t4he374tit92pomsj0kf56h8iei@4ax.com> Brane, What are you wanting to know specifically? What is your client machine running? I've started using the Win32 modules to connect using ADODB and that works for me on Windows XP (hopefully 2003 as well, but not tested yet). I pulled those samples from someplace on the net using Google and adapted a couple of times until they worked the way I needed them to. I looked at pymssql and it didn't seem to be updated recently where I felt comfortable. Just my opinion, it may be the best out there. I guess knowing more about what you're looking for would help. -Pete Schott Brane wrote: > can someone please give me some info regarding subject > please advice > regards > brane From theaney at cablespeed.com Mon Jan 17 09:58:18 2005 From: theaney at cablespeed.com (Tim Heaney) Date: Mon, 17 Jan 2005 09:58:18 -0500 Subject: Native widgets for Python References: <41EBC7F3.5050807@web.de> Message-ID: <87oefom7at.fsf@mrbun.watterson> Stephen Thorne writes: > > there's someone writing 'dabo', which is apparently "wxpython but > more python". It looks like dabo uses, not replaces, wxPython http://dabodev.com/about From simoninusa2001 at yahoo.co.uk Wed Jan 19 18:14:06 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 19 Jan 2005 15:14:06 -0800 Subject: Python and Excel References: Message-ID: <1106176446.569712.316040@c13g2000cwb.googlegroups.com> Hmm, sounds interesting, I've always resorted to using CSV (or even HTML!) when exporting to Excel. As far as how to open it up, have a look at creating a project on www.sourceforge.net or just zip it up and bung it on your own website if you have one. I've got the feeling there are also Python-specific repositories too. Or you could just paste the code into a blog or something free like Livejournal. Good luck on the France thing, that's where my folks live now (I'm an Englishman who retreated to the US!) From merkosh at hadiko.de Sun Jan 2 17:57:16 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Sun, 02 Jan 2005 23:57:16 +0100 Subject: UserDict deprecated References: Message-ID: Saturday 01 January 2005 23:34 pm Steven Bethard wrote: [...] > If you implemented the file interface functions yourself, why do you > want to inherit from file? [...] > But just inheriting from list won't make this work, will it? Don't you > want to do something like: [...] Right. I guess the thing I was looking for is an interface specification as in Java's Interfaces. I could write an abstract base class, where all methods just raise NotImplemented(). I don't know wether this is a good idea after all...:/ Thanks Uwe From exarkun at divmod.com Thu Jan 6 10:54:06 2005 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 06 Jan 2005 15:54:06 GMT Subject: Embedding a restricted python interpreter In-Reply-To: <7xbrc2a7zq.fsf@ruckus.brouhaha.com> Message-ID: <20050106155406.25734.561189532.divmod.quotient.3824@ohm> On 06 Jan 2005 07:32:25 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: >Jp Calderone writes: > > A Python sandbox would be useful, but the hosting provider's excuse > > for not allowing you to use mod_python is completely bogus. All the > > necessary security tools for that situation are provided by the > > platform in the form of process and user separation. > > But mod_python is an apache module and runs in the same apache process > with other users' scripts. I am uncertain as to how this differs from mod_php (the alternative discussed in the OP's story). I've been away from PHP for a while, so perhaps mod_php has gained some features of which I am unaware? Jp > -- > http://mail.python.org/mailman/listinfo/python-list > From ville at spammers.com Fri Jan 28 03:06:29 2005 From: ville at spammers.com (Ville Vainio) Date: 28 Jan 2005 10:06:29 +0200 Subject: IPython Article on O'Reilly's ONLamp site References: Message-ID: >>>>> "Jeremy" == Jeremy Jones writes: Jeremy> feedback is welcome. Regardless of what you may think of Jeremy> the article, I hope it encourages everyone to at least try Jeremy> out IPython. IPython has become an indispensible tool in Jeremy> my toolbox. I cannot say enough great things about it. I've said this before, but I'd just like to add that IPython (with the pysh profile) makes a damn fine command prompt for Windows. The loss of job control is not a problem there, because it never was there in the first place. Even if you never use the underlying Python functionality, you can enjoy the Bash-like filename completion (the only way to fly - the windows "4dos-style" completion doesn't cut it for me). I've never really trusted Bash (from cygwin) in Windows, it has always felt very alien. Just install ipython and the "unxutils" package, and windows command prompt suddenly becomes usable. What is essential for me (because I deal with complex source trees) is the persistent "bookmark functionality" for directories (yes, Fernando, this is a shameless plug ;-): Lines starting w/ @POR078 are commands typed by the user. ------- ipython session ------------- @POR078[prj]|22> %bookmark? Manage IPython's bookmark system. %bookmark - set bookmark to current dir %bookmark - set bookmark to %bookmark -l - list all bookmarks %bookmark -d - remove bookmark %bookmark -r - remove all bookmarks You can later on access a bookmarked folder with: %cd -b or simply '%cd ' if there is no directory called AND there is such a bookmark defined. Your bookmarks persist through IPython sessions, but they are associated with each profile. @POR078[testrunner]|24> %bookmark tr @POR078[testrunner]|25> cd /prj/SyncML/doc/ @POR078[doc]|26> %bookmark smldoc @POR078[doc]|27> Exit (IPython exits, I start a new session) @POR078[environmentswitch]|1> cd tr (bookmark:tr) -> C:\prj\testrunner @POR078[testrunner]|3> cd smldoc (bookmark:smldoc) -> C:\prj\SyncML\doc @POR078[doc]|4> -- Ville Vainio http://tinyurl.com/2prnb From aisaac0 at verizon.net Fri Jan 28 13:00:37 2005 From: aisaac0 at verizon.net (David Isaac) Date: Fri, 28 Jan 2005 18:00:37 GMT Subject: extract files from MS-TNEF attachments Message-ID: <95vKd.152$wM.78@trnddc05> I'm looking for Python code to extract files from MS-TNEF attachments. (I'm aware of the C code at http://tnef.sourceforge.net/ ) Thanks, Alan Isaac From rmemmons at member.fsf.org Mon Jan 3 20:56:10 2005 From: rmemmons at member.fsf.org (Rob Emmons) Date: Mon, 03 Jan 2005 19:56:10 -0600 Subject: How do I make Windows Application with Python ? References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> Message-ID: > Well, I programmed a little in MS Visual Studio 2003, and there you have > Console apllication and Windows application (among others). Windows one is > with buttons and other gadgets. So, I want to make applications that > doesn't open console to display result, I want to display it into the > message box. Also, I want to use that application on the computers where > Python isn't installed First there is a good book: Python Prgoramming on Win32, by Hammond & Robinson, O'Reilly is the publisher. I believe one of these guys wrote the python windows extension. Second, on MS Windows you need two python installs, the basic python install, and the python for windows extension (also sometimes call win32all or something like that). These two together give you a great basic set to work with. I've done MS Windows programming with these and they work great. With the win32 extension module -- you can use ActiveX, you can use the standard MS Windows calls, and it also defines a python intepretor mode where it does not open the console window if you name the main program module as .pyw (as opposed to .py). It does other things too. This is all discribed in the book I recommended. Note also, if you don't want to see the console window -- even without use .pyw files, you can tell the launcher to open the console window minimized -- not great but it does work. I believe also if you want to use MS Visual Studio -- Active State sells python programming tools that plug into MS Visual Studio if you want to do that. I've not tried these so I don't know how they work or if they are any good. It's also possible to program on MS Windows so your app is protable to Linux and other systems. You can use Tkinter or wxWidgets (was called wxWindows -- until maybe MS made them change it) to do that. I've used Tkinter before for example, though I think wxWidgets is probalby more of the wave of the future. Others may know. If you want to run the program on other computers not having python, you have two basic choices. One -- what I do, I just made up a python setup CD that installs python, python windows extensions, and the basic libraries I usually use so that it's easy to setup a python environment on other systems. Then I install my code. The other alternative is to use one of the tools that wraps up a python program with the needed executables. Some of these are py2exe, cx-freeze, McMillan Installer, Fractel Mountains, StarKits, UPX, and InnoSetup. I've not used any of these -- and so this list may not be correct/complete. Others may know what's best. There are also some compilers too - pyrex, pysco starkiller, and pypy. Again, I've not used any of these and this is just from some cryptic notes I've taken. So ask others for input. Probabably you want one of the installers rather than the compilers because python compilers are kind of new, but that's just a guess. Hope that helps. Rob From PPNTWIMBXFFC at spammotel.com Mon Jan 31 03:58:54 2005 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Mon, 31 Jan 2005 09:58:54 +0100 Subject: COM on a network drive can't find pywintypes23.dll Message-ID: Hi I have installed Python (2.3.4) on a shared network drive. I use it to run a bunch of application on the workstations (Win2K). Now I am running into the first problem ever. I try to use COM to generate a word-file. It runs fine on my machine (Python installed locally). When I deploy it and start the app on another workstation from the fileserver - it runs but as soon as it comes to the COM part it exits saying: The procedure entry point ?PyWinObject_AsDEVMODE@@YAHPAU_object@@PAPAU_devicemodeA@@H at Z could not be located in the dynamic link library pywintypes23.dll Heck... I copied the files: pythoncom23.dll pywintypes23.dll to about "1000" locations to make it run (Application's dir, Workstation's System Dirs, Fileserver's Python main and bin dir, ...). I tried setting the path on the workstations. But nothing seems to solve the problem. Do you have any proposals how to solve this problem? Thanks in advance, Marco From ncoghlan at iinet.net.au Tue Jan 11 05:24:21 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 11 Jan 2005 20:24:21 +1000 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: <34hmnuF4cvj0uU1@individual.net> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> <34hmnuF4cvj0uU1@individual.net> Message-ID: <41E3A955.6030900@iinet.net.au> Andrey Tatarinov wrote: > afair you told yourself that > > var = where: > > > translates to: > > def unique_name(): > > return > var = unique_name() > > in this case class gets unique_name() function? is it that bad? No, I wasn't thinking clearly and saw problems that weren't there. However, you're right that the semantic definition should include unbinding the unique name after the statement finishes. E.g. for assignments: def unique_name(): return = unique_name() del unique_name > anyway I'd prefer to change semantics deeper. adding new statement-only > scope and adding our suite-definitions there. A new scope essentially *is* a nested function :) My main purpose with the nested function equivalent is just to make the intended semantics clear - whether an implementation actually _does_ things that way is immaterial. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From apardon at forel.vub.ac.be Thu Jan 13 08:26:05 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jan 2005 13:26:05 GMT Subject: Unclear On Class Variables References: Message-ID: Op 2005-01-13, Simon Brunning schreef : > On 13 Jan 2005 07:18:26 EST, Tim Daneliuk wrote: >> I am a bit confused. I was under the impression that: >> >> class foo(object): >> x = 0 >> y = 1 >> >> means that x and y are variables shared by all instances of a class. >> But when I run this against two instances of foo, and set the values >> of x and y, they are indeed unique to the *instance* rather than the >> class. > > I can see why you might think that: > >>>> class Spam(object): > ... eggs = 4 > ... >>>> spam = Spam() >>>> spam2 = Spam() >>>> spam.eggs > 4 >>>> spam2.eggs > 4 >>>> spam.eggs = 2 >>>> spam.eggs > 2 >>>> spam2.eggs > 4 > > But you are being mislead by the fact that integers are immutable. > 'spam.eggs = 2' is *creating* an instance member - there wasn't one > before. Have a look at what happens with a mutable object: > >>>> class Spam(object): > ... eggs = [3] > ... >>>> spam = Spam() >>>> spam2 = Spam() >>>> spam.eggs > [3] >>>> spam2.eggs > [3] >>>> spam.eggs.append(5) >>>> spam.eggs > [3, 5] >>>> spam2.eggs > [3, 5] > Well I find this a confusing behaviour on python's part. The fact that instance.field can mean something different, depending on where in a statement you find it, makes the behaviour inconsistent. I know people in general here are against declarations, but declarations could IMO provide more consistency here and thus more obvious behaviour. -- Antoon Pardon From fperez.net at gmail.com Sun Jan 23 19:47:37 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Sun, 23 Jan 2005 17:47:37 -0700 Subject: Installer made with bdist_wininst segfaulting... Message-ID: Hi all, I am seeking advice/help from those with more win32 experience than myself. I am trying to build a proper win32 installer for IPython, after a user did most of the hard work. For the most part, it's working very well, but I am running into a nasty problem, which took me a few hours to finally understand. This smells to me like a python bug, but I could be wrong. Much googling didn't turn up anything relevant. Here is a brief summary: if the installer file is run from a windows drive which is different from the one where python resides (and hence where ipython will end up), the installer segfaults. No traceback, nothing, just a segfault (well, one of those Windows dialogs asking me to send a binary traceback to Redmond, but not a proper Python traceback). The win32 laptop where I'm testing, for example, has user stuff in the D: drive, and Python installed in C:\Python23. I was running the installer from D:\Temp, and getting this segfault. If I run it from C:\Temp, it works perfectly. I have put the installer here, in case someone else is willing to test this on a different machine: http://amath.colorado.edu/faculty/fperez/tmp/ipython-0.6.9.win32.exe I have narrowed down to a single os.chdir() call in the post-install script. The code is simply: # Lookup path to common startmenu ... d = get_special_folder_path('CSIDL_COMMON_PROGRAMS') + r'\IPython' # Create IPython entry ... if not os.path.isdir(d): os.mkdir(d) directory_created(d) # XXX - The binary installer segfaults here if it was being run from a # different drive than it is trying to change to. In my case, I have # everything in D:, but Python lives in C:, so the chdir() call is going # from D: to C:, and this is crashing things. print "Current dir:",os.getcwd() # dbg print "Going to :",d # dbg os.chdir(d) By forcing a return before the chdir() call, I was able to see that when the source/destination are both on C:, it's all OK, but when the source is in D: and the destination in C:, I get the crash. This is really frustrating, since I'd like to be able to stop distributing .zip sources to Windows users, and would like to be able to provide a proper installer/deinstaller. But having this thing crash if two drives are involved is just not acceptable. Any help from the win32 gurus out there would be much appreciated. For reference, the binary installer linked above was created on a Fedora3 box running pyhton 2.3.4, with the command line: ./setup.py bdist_wininst --install-script=ipython_win_post_install.py Cheers, f From MrJean1 at gmail.com Tue Jan 11 20:48:00 2005 From: MrJean1 at gmail.com (python) Date: 11 Jan 2005 17:48:00 -0800 Subject: readline, rlcompleter In-Reply-To: <1105429869.770262.14360@c13g2000cwb.googlegroups.com> References: <1105429869.770262.14360@c13g2000cwb.googlegroups.com> Message-ID: <1105494480.002007.68390@c13g2000cwb.googlegroups.com> There is a pretty complete (no pun intended) example in the standard cmd module Check file cmd.py in your Python installation .../lib/pythonX.Y/cmd.py, specifically the methods Cmd.preloop() and Cmd.complete(). Another, more elaborate example is in PySH at /Jean Brouwers PS) A version of readline for Windows is here michele.simionato at gmail.com wrote: > This a case where the documentation is lacking. The standard library > documentation > (http://www.python.org/dev/doc/devel/lib/module-rlcompleter.html) gives > this example > try: > import readline > except ImportError: > print "Module readline not available." > else: > import rlcompleter > readline.parse_and_bind("tab: complete") > > but I don't find a list of recognized key bindings. For instance, can I > would like to bind shift-tab to rlcompleter, is that possible? Can I use > function keys? I did various attempt, but I did not succed :-( > Is there any readline-guru here with some good pointers? > Michele Simionato From jbperez808 at wahoo.com Mon Jan 17 22:37:25 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Tue, 18 Jan 2005 11:37:25 +0800 Subject: huygens lands on titan In-Reply-To: <1105704719.374905.239790@f14g2000cwb.googlegroups.com> References: <1105704719.374905.239790@f14g2000cwb.googlegroups.com> Message-ID: <353ejaF4hc5goU1@individual.net> I sure as hell bet it didn't too. Fuzzyman wrote: > John Thingstad wrote: > >>-- >>huygens lands on titan >>Using M2, Opera's revolutionary e-mail client: > > http://www.opera.com/m2/ > > I bet it didn't....... > Regards, > > Fuzzy > http://www.voidspace.org.uk/python/index.shtml > From invalidemail at aerojockey.com Sat Jan 8 01:15:44 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 7 Jan 2005 22:15:44 -0800 Subject: sorting on keys in a list of dicts In-Reply-To: <10tr9ejf05pv660@corp.supernews.com> References: <10tr9ejf05pv660@corp.supernews.com> Message-ID: <1105164944.059936.80960@c13g2000cwb.googlegroups.com> Jeff Shannon wrote: > Jp Calderone wrote: > > > L2 = [(d[key], i, d) for (i, d) in enumerate(L)] > > L2.sort() > > L = [d for (v, i, d) in L2] > > Out of curiosity, any reason that you're including the index? I'd > have expected to just do > > L2 = [(d[key], d) for d in L] > L2.sort() > L = [d for (v, d) in L2] Suppose L is a list of objects that can't be compared (for example, they are dicts that have complex number items) and the keys are not all distinct. If sort tries to compare two equal keys, it'll proceed to compare the objects themselves, which could throw an exception. Stick the index in there, and that possibility is gone. -- CARL BANKS From nick at craig-wood.com Mon Jan 31 08:30:10 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 31 Jan 2005 13:30:10 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <7xzmysqmxk.fsf@ruckus.brouhaha.com> <7xmzuqqn5s.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Actually and surprisingly, that's not really true. Crypto algorithms > are pretty straightforward, so if you examine the code and check that > it passes a bunch of test vectors, you can be pretty sure it's > correct. I was going to write pretty much the same thing. If a security flaw is found in a block cipher (say) it won't be because it has a buffer overflow etc, it will be because the algorithm is flawed. You can't patch up crypto algorithms, you have to throw them away and start again (you can't have two incompatible versions of DES for instance). -- Nick Craig-Wood -- http://www.craig-wood.com/nick From pythongnome at hotmail.com Tue Jan 11 19:56:34 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Wed, 12 Jan 2005 00:56:34 GMT Subject: Game programming in Python In-Reply-To: References: Message-ID: <6B_Ed.4796$C52.3460@newsread2.news.atl.earthlink.net> Mike C. Fletcher wrote: > Lucas Raab wrote: > >> Baza wrote: >> >>> I'm looking for any books or on-line resources on game programming using >>> Python. Does anyone have any advice? >>> -- Computer says, 'no' >>> >>> >> >> www.panda3d.com, www.pygame.org, www.blender3d.com ... > > > http://www.vrplumber.com/py3d.py?category=game > > HTH, > Mike > > ________________________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://www.vrplumber.com > http://blog.vrplumber.com > My apologies. :) From simon.brunning at gmail.com Tue Jan 25 05:28:02 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 25 Jan 2005 10:28:02 +0000 Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) In-Reply-To: <1106590633.15475.3.camel@localhost> References: <1106590633.15475.3.camel@localhost> Message-ID: <8c7f10c605012502281d9c9b29@mail.gmail.com> On Mon, 24 Jan 2005 12:17:13 -0600, Philippe C. Martin wrote: > > I use "__"for private variables because I must have read on net it was > the way to do so - yet this seems to have changed - thanks: > > http://www.network-theory.co.uk/docs/pytut/tut_77.html Nope, that's still the right way to make a member 'really' private. Stephen was pointing out a very common Python idiom - "private by convention", and suggesting that using it would be more appropriate. A member with a single preceding underscore is private by convention. That is to say, there is no mechanism in place to prevent clients of the class accessing these members, but they should consider themselves to have been warned that they do so at their own risk. If you take the back off the radio, the warranty is void. ;-) I (and by inference Stephen) feel that this is a more "Pythonic" approach. Give the programmer the information that they need, but don't try to stop them from doing what they need to do. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From jerf at jerf.org Wed Jan 5 23:26:51 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 05 Jan 2005 23:26:51 -0500 Subject: Concepts RE: Python evolution: Unease References: <20050105002302.542768387.EP@zomething.com> Message-ID: On Wed, 05 Jan 2005 12:15:29 +0300, Roman Suzi wrote: > As for concepts, they are from Generic Programming (by Musser and > Stepanov) and I feel that Python is in position to implement them to the > fullest extent. And IMHO it will be nicer than just Java-like interfaces > or Eiffel's contract approach. > > I can try to write a PEP "Generic Programming Concepts". I'd like to see this. As corey says, sooner rather than later is good. Release Early, Release Often :-) I'm still skeptical on how *most* Generic Programming concepts are an improvement, but while I don't know much about how "concepts" formally work I know I like the name... and that's a start. I'd love to see my skepticism proved wrong. From fperez.net at gmail.com Tue Jan 25 12:49:39 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Tue, 25 Jan 2005 10:49:39 -0700 Subject: Installer made with bdist_wininst segfaulting... References: Message-ID: Thomas Heller wrote: > There are a couple of known bugs in bdist_wininst, and you just reported > another one. All these bugs are related to using the > post_install_script, and show up when either (thats what I currently > remember): > > - the installer is run from a readonly location, > - the installer is run from a different drive (as you reported) > - the installer installs for Python 2.4 > > I will fix these issues in Python 2.3.5, which will probably be out as a > release candidate this week, and in Python 2.4.1. One more small thing I just remembered... In my testing, I noticed the installer, even when it succeeds, leaves little temp files littering the root directory of the drive it was run from. These seem to be the files where stdout is captured, but they should be explicitly removed at the end. Cheers, f From rbt at athop1.ath.vt.edu Mon Jan 24 10:26:33 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 24 Jan 2005 10:26:33 -0500 Subject: urllib2 and proxy question In-Reply-To: <1106575675.520424.155310@f14g2000cwb.googlegroups.com> References: <1106575675.520424.155310@f14g2000cwb.googlegroups.com> Message-ID: Fuzzyman wrote: > urllib2 (under windows) will auto-detect your proxy settings and use > those. > > Normally that's a good thing (I guess), except when it's not ! > > How do I switch off this behaviour ? I'm behind a censoring proxy and > wanting to test things *locally*. IE is set to not use the proxy when > fetching local adresses, but urllib2 ignores that part of the setting > and uses the proxy for everything. > > The only way I can test are changing my IE settings back and forth > every time. Most annoying. > > I can see how to *add* a new proxy to urllib2, but not how to force it > to not use a proxy. I may well be missing something obvious though. > Anyone able to help ? > Regards, > > Fuzzy > http://www.voidspace.org.uk/python/index.shtml > "Alternatively, the optional proxies argument may be used to explicitly specify proxies. It must be a dictionary mapping scheme names to proxy URLs, where an empty dictionary causes no proxies to be used" # Don't use any proxies filehandle = urllib.urlopen(some_url, proxies={}) From wodefey at iun.edu Mon Jan 17 10:21:02 2005 From: wodefey at iun.edu (Bill) Date: 17 Jan 2005 07:21:02 -0800 Subject: Install Python 2.4 on Fedora 3 Core Message-ID: <1105975262.047782.6010@z14g2000cwz.googlegroups.com> I have less than a week experience on linux, so I am a new newbie. Python 2.3 came preinstalled. I installed version 2.4. All seemed to go well except it installed to usr/local? 1. Was it wrong to install when logged in as 'root'? Does it make a difference? 2. I looked in the package editor and there was no way to uninstall 2.3? Should I? If so, how can I? If not,what are the problems, if any, of having both. Thank you for your help. From ncoghlan at iinet.net.au Tue Jan 18 04:10:01 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 18 Jan 2005 19:10:01 +1000 Subject: generator expressions: performance anomaly? In-Reply-To: References: Message-ID: <41ECD269.3050207@iinet.net.au> Raymond Hettinger wrote: > [Delaney, Timothy C] > >>Nick's other suggestion - that genexps propagate __len__ - might >>still be interesting. Of course, it would only be applicable for >>unconditional genexps(i.e. no if clause). > > Length transparency for iterators is not as general as one would expect. I once > spent a good deal of effort exploring where it made sense, and I was surprised > to find that it only rarely works out. Length transparency is an unexpectedly > thorny subject with many dead-ends which precludes a fully general solution such > as that proposed by Nick. > > For a recap of my research, see the docstring for Lib/test/test_iterlen.py . """The situation slightly more involved whenever an object allows length mutation during iteration. """ Ouch. Nice understatement. It's rather unfortunate that we can't make use of the length information even when the source *doesn't* mutate, though. I'll have to think some more to see if I can come up with any concrete ideas for you to shoot down :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From adam at cognitcorp.com Tue Jan 4 22:38:13 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Tue, 04 Jan 2005 22:38:13 -0500 Subject: what is lambda used for in real code? In-Reply-To: References: <1104531721.3724.18.camel@localhost.localdomain> Message-ID: <1104894177.5050.28.camel@localhost.localdomain> On Fri, 2004-12-31 at 22:09, Terry Reedy wrote: > "Adam DePrince" wrote in message > news:1104531721.3724.18.camel at localhost.localdomain... > > In sort, we must preserve the ability to create an anonymous function > > simply because we can do so for every other object type, and functions > > are not special enough to permit this special case. > > Please show me how to create an anonymous type, module, or class, You can create anonymous instances of classes and types. The actual type, module or class .. well, that is another special case that isn't special enough ... but that is somewhat beyond the scope of this thread. I've seen a number of responses similar to this; I feel that the lack of anonymous classes, types and modules are flaws with the language that should be fixed, not used to justify introducing another flaw. It is my humble opinion that a good language design is completely orthogonal. The curse of anonymity in the language can be "cured" at a management/specification level by requiring the use of the name space. The alternative, the removal of anonymous functions, adds a "special case" and dumbs down the language. Personally, I'd like to see Python evolve in the direction of ML instead of Visual Basic. There are actually times when I've wanted anonymous classes. Very often, I've written code that accepts as a parameter, a class. Of course, the code instantiates this class with the expectation that it provides a particular interface. And sometimes, it would have been nice to, in a single invocation of such a function, change a single method of the class before passing it. In a sense, I've written code for which a class or type equivalent to a lambda would actually have been really nice. > especially with an expression. Number, sequences, and dicts have easily > printable values. Functions, like classes and module do not*, so So do lambdas, classes, types, etc. And I've encountered a good many lists and dicts that don't qualify as "easily printable." Quite frankly, it seems a bit capricious to *require* the use of the name space on the basis of the similarity between the repr of the object and line noise. And here is a counter example ... this def fits nicely on one line: Python 2.4 (#1, Dec 27 2004, 15:19:19) [GCC 3.4.1] on linux2 >>> def a( b ): return b+1 ... >>> a( 2 ) 3 >>> > definition names act as a standin and as a pointer to the source code that > produced the object. If functions are not special relative to classes and > modules, which is the grouping they belong with, then we should get rid of > lambda ;-) > > *Now that memory is 'cheap', someone recently proposed that code objects > (and hence functions) get .source attribute. Maybe, someday... The .source attribute could be free from a memory consumption perspective if the source -> byte code conversion is reversible. > > Terry J. Reedy Adam DePrince From sjmachin at lexicon.net Thu Jan 20 23:00:17 2005 From: sjmachin at lexicon.net (John Machin) Date: 20 Jan 2005 20:00:17 -0800 Subject: Unbinding multiple variables In-Reply-To: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> Message-ID: <1106280017.761035.82490@z14g2000cwz.googlegroups.com> Johnny Lin wrote: > Hi! > > Is there a way to automate the unbinding of multiple variables? Say I > have a list of the names of all variables in the current scope via > dir(). Is there a command using del or something like that that will > iterate the list and unbind each of the variables? Yes. It's called "return". From reinhold-birkenfeld-nospam at wolke7.net Sun Jan 9 16:38:43 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 09 Jan 2005 22:38:43 +0100 Subject: else condition in list comprehension In-Reply-To: References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: <34dmj3F4aj2t2U1@individual.net> Matteo Dell'Amico wrote: > Luis M. Gonzalez wrote: >> Hi there, >> >> I'd like to know if there is a way to add and else condition into a >> list comprehension. I'm sure that I read somewhere an easy way to do >> it, but I forgot it and now I can't find it... >> >> for example: >> z=[i+2 for i in range(10) if i%2==0] >> what if I want i to be "i-2" if i%2 is not equal to 0? > > You could use > > [(i-2, i+2)[bool(i%2 == 0)] for i in range(10)] > > or, in a less general but shorter way > > [(i+2, i-2)[i%2] for i in range(10)] > > or even > > [i%2 and i-2 or i+2 for i in range(10)] One should note that the (cond and X or Y) construct only works if X can never produce a false value (such as 0, "", []). In this example, it is okay, but replace 2 with 1 and you will run into trouble for i = 1. Reinhold From johnpote at blueyonder.co.uk Fri Jan 7 08:36:50 2005 From: johnpote at blueyonder.co.uk (John Pote) Date: Fri, 07 Jan 2005 13:36:50 GMT Subject: Python application extending, plugins Message-ID: Hi, Has anyone any thoughts on structuring a program so that it can be extended simply and elegantly by a user who only has a compiled (.pyc) version of the application? I wish to write an application, myApp, that provides a GUI to, amongst other things, a simulator implimented as a class. myApp's simulator may then be extended by more python code to produce what is effectively 'myApp2'. The simulator might then be further extended from myApp2 to myApp3 in a similar manor. Don't think there would be much call, if at all, to go beyond myApp3 level. But who knows! Any thoughts would be appreciated. John Pote From sean_mcilroy at yahoo.com Sat Jan 8 23:40:37 2005 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 8 Jan 2005 20:40:37 -0800 Subject: mysterious buggy behavior Message-ID: While fiddling with a little script I ran into a problem that baffles me completely. Maybe I'm missing something completely obvious, and somebody out there can diagnose the problem at a glance. Anyway, that's the hope. Here's the code (it plays tic tac toe): """ Something goes wrong with the "time saver" section of the function makeMove. The section needs to be there to ensure that the computer makes its move in a reasonable amount of time when it is making the first or the second move. That section of code is so simple that I can't even imagine what could be going wrong with it. """ """ 012 345 678 """ ex,oh,blank = range(3) lines = [(0,3,6),(1,4,7),(2,5,8),(0,1,2),(3,4,5),(6,7,8),(0,4,8),(2,4,6)] def subs(board,player,i): b = board[:] b[i] = player return b def valMove(board): winners = [x for x in (ex,oh) for L in lines if board[L[0]]==board[L[1]]==board[L[2]]==x] if winners: return winners[0]==ex and (+1,None) or (-1,None) if board.count(blank)==0: return (0,None) player = (oh,ex)[board.count(ex)==board.count(oh)] optimal = (min,max)[player==ex] blankIndices = [i for i in range(9) if board[i]==blank] return optimal([(valMove(subs(board,player,i))[0],i) for i in blankIndices]) BOARD = [blank]*9 def clickButton(i): def f(): BOARD[i] = ex (topButtons,midButtons,botButtons)[i//3][i%3]['text'] = 'X' return f def newGame(): BOARD = [blank]*9 for x in topButtons+midButtons+botButtons: x['text'] = '' def makeMove(): i = None ## if i==None: i = valMove(BOARD)[1] BOARD[i] = oh (topButtons,midButtons,botButtons)[i//3][i%3]['text'] = 'O' from Tkinter import * root = Tk() ############################################################### topRow = Frame(master=root) topButtons = [Button(master=topRow,width=1,command=clickButton(i)) for i in range(3)] ############################################################### midRow = Frame(master=root) midButtons = [Button(master=midRow,width=1,command=clickButton(3+i)) for i in range(3)] ############################################################### botRow = Frame(master=root) botButtons = [Button(master=botRow,width=1,command=clickButton(6+i)) for i in range(3)] ############################################################### map(lambda x: x.pack(side=TOP),[topRow,midRow,botRow]) map(lambda x: x.pack(side=LEFT),topButtons + midButtons + botButtons) ############################################################### dummyRow = Frame(master=root) placeHolder = Label(master=dummyRow,text='') dummyRow.pack(side=TOP) placeHolder.pack(side=TOP) ############################################################### ctrlRow = Frame(master=root) computerMoveButton = Button(master=ctrlRow,text='computer move',command=makeMove) newGameButton = Button(master=ctrlRow,text='new game',command=newGame) ctrlRow.pack(side=TOP) computerMoveButton.pack(side=TOP) newGameButton.pack(side=TOP) ############################################################### root.title('tic tac toe') root.mainloop() From fredrik at pythonware.com Mon Jan 17 15:26:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Jan 2005 21:26:39 +0100 Subject: Adjusting the 1024 byte stdin buffer limit References: <1105989047.516986.59990@z14g2000cwz.googlegroups.com> <1105989764.168794.113430@z14g2000cwz.googlegroups.com> Message-ID: "brucoder" wrote: > Currently, when sending a data stream that exceeds 1024 bytes via > stdin, the stream blocks at the 1024th byte. This precludes completion > of the submission of the data stream. you can pass in a buffer size when you open a file: >>> help(open) class file(object) | file(name[, mode[, buffering]]) -> file object | | Open a file. The mode can be 'r', 'w' or 'a' for reading (default), | writing or appending. The file will be created if it doesn't exist | when opened for writing or appending; it will be truncated when | opened for writing. Add a 'b' to the mode for binary files. | Add a '+' to the mode to allow simultaneous reading and writing. | If the buffering argument is given, 0 means unbuffered, 1 means line | buffered, and larger numbers specify the buffer size. | Add a 'U' to mode to open the file for input with universal newline | support. Any line ending in the input file will be seen as a '\n' | in Python. Also, a file so opened gains the attribute 'newlines'; | the value for this attribute is one of None (no newline read yet), | '\r', '\n', '\r\n' or a tuple containing all the newline types seen. | | 'U' cannot be combined with 'w' or '+' mode. | | Note: open() is an alias for file(). or use os.fdopen() to reopen an existing file handle: >>> help(os.fdopen) fdopen(fd [, mode='r' [, bufsize]]) -> file_object Return an open file object connected to a file descriptor. assuming "sending via stdin" means using a pipe, this page explains why all this probably won't matter: http://www.opengroup.org/onlinepubs/7990989799/xsh/write.html (see the "Write requests to a pipe or FIFO" section) From merkosh at hadiko.de Sat Jan 1 16:38:17 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Sat, 01 Jan 2005 22:38:17 +0100 Subject: UserDict deprecated Message-ID: Hi, Why is the UserDict module is deprecated after Python 2.2. The application of it I have in mind is, i.e. multiple inheritance from "file" and "dic" - which is not possible. If I used UserDict I would not need to specify all methods UserDict provides alreay, anyway. Ciao Uwe From danb_83 at yahoo.com Sun Jan 9 12:05:25 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 9 Jan 2005 09:05:25 -0800 Subject: Long strings as function parameters References: <1105288564.441842.13060@c13g2000cwb.googlegroups.com> Message-ID: <1105290325.030128.146490@c13g2000cwb.googlegroups.com> onlyonemc at gmail.com wrote: > I would like to have functions that operate on long strings, 10-100 MB. > In C I would of course pass a pointer to the string for a quick > function call. What is an efficient way to do this in python? > Cheers, In Python, *every* expression is a pointer. This fact is clearest when you look a C-implemented Python functions (which have parameter types and return types of PyObject*), or when using mutable types. >>> class Spam: ... def __init__(self): ... self.foo = 0 ... >>> x = Spam() >>> y = x >>> y.foo = 17 >>> x.foo 17 Compare this to the C code: typedef struct {int foo;} Spam; ... Spam *x, *y; ... y = x; y->foo = 17; printf("%d\n", x->foo); From pdemb at illx.org Sun Jan 2 06:30:17 2005 From: pdemb at illx.org (Peter Dembinski) Date: Sun, 02 Jan 2005 12:30:17 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> <7xsm5kfyse.fsf@ruckus.brouhaha.com> <41d7941f$1_3@127.0.0.1> <7x8y7cjo57.fsf@ruckus.brouhaha.com> Message-ID: <87zmzsax12.fsf@hector.domek> Paul Rubin writes: [...] > I don't understand that. If I see "str x = str(3)", then I know > that x is a string. def foo(x): return str(x) str = foo(x) And now, let's say that foo()'s definition is in another module. It is hard for a programmer to quickly determine the type for str, that's the problem with programming in languages that don't have type declarations. From jwaixs at gmail.com Mon Jan 3 08:35:09 2005 From: jwaixs at gmail.com (Noud Aldenhoven) Date: Mon, 03 Jan 2005 14:35:09 +0100 Subject: removing comments form a file Message-ID: <5b617$41d956df$53e8229a$22273@freeler.nl> Hello everyone, I was wondering how to remove comments away form a file. So that's why I made this script. =============================== #!/usr/bin/env python import sys import string import time helptext = "usage: python rmcomment [oldfile] [newfile] [comment]" def rmcomment(oldfile, newfile, comment): oldfile = open(oldfile, 'r') newfile = open(newfile, 'w') ccount = 0 lcount = 0 for line in oldfile.readlines(): splitline = string.split(line) pstest = 0 fileline = "" for word in splitline: if word[:2] == comment: pstest = -1 ccount += 1 pass elif pstest == -1: pass else: fileline += word + " " if len(fileline) == 0: pass else: newfile.write(fileline + "\n") lcount += 1 print "Done... in %s seconds\nRemoved comment from %s lines\nWrote % lines to %s" % (time.time()-start , ccount, lcount, newfile) raw_input("Push the enter button to quit>") if __name__ == "__main__": if sys.argv[1] == "-h" or sys.argv[1] == "-help": print helptext else: start = time.time() oldfile = sys.argv[1] newfile = sys.argv[2] comment = sys.argv[3] rmcomment(oldfile, newfile, comment) ======================================== This script works fine with standard text files. An example is this one: example.txt: Hello Fuckin' World //how are you doing today //I think it delete this sentence and the next sentence too! But this one not! #Even not this comment end example.txt If I use my script, named rmcomment.py I get this: jwaixs at linux:~/programmeren/python/rmcomment$ cat example.txt Hello Fuckin' World //how are you doing today //I think it delete this sentence and the next sentence too! But this one not! #Even not this comment's jwaixs at linux:~/programmeren/python/rmcomment$ python rmcomment.py example.txt newexample.txt // Done... in 0.00104999542236 seconds Removed comment from 2 lines Wrote 2nes to Push the enter button to quit> jwaixs at linux:~/programmeren/python/rmcomment$ cat newexample.txt Hello Fuckin' World But this one not! #Even not this comment jwaixs at linux:~/programmeren/python/rmcomment$ works fine... but here's my problem. If I use rmcomment.py also the whitelines will be removed. And I don't want that to happen. Here's another example: jwaixs at linux:~/programmeren/python/rmcomment$ cat otherexample.txt //This shows what whitelines are doing here left from me is a nice white line tabs and here left are at least 3 white line tabs //and ofcourse, comments will be deleted jwaixs at linux:~/programmeren/python/rmcomment$ python rmcomment.py otherexample.txt newotherexample.txt // Done... in 0.0011351108551 seconds Removed comment form 2 lines Wrote 2nes to Push the enter button to quit> jwaixs at linux:~/programmeren/python/rmcomment$ cat newotherexample.txt left from me is a nice white line tabs and here left are at least 3 white line tabs jwaixs at linux:~/programmeren/python/rmcomment$ My beautiful whitelines are gone! And I don't want that! I've thaught how to fix this for a time, but I can't make it on my own. Too less programming experiance, I'm afraid. Could someone help me with this problem? Or fix the script or give a hint or something? Thank you at least for reading this post, Noud Aldenhoven The Netherlands (In de beurt bij Nijmegen, voor de nieuwschierigen) ps. Yes, I'm a Dyslextion and can't write correct english. I'm sorry for that. From rkern at ucsd.edu Sun Jan 9 10:06:19 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 09 Jan 2005 07:06:19 -0800 Subject: Python3: on removing map, reduce, filter In-Reply-To: <34ctkpF4b9ijlU1@individual.net> References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> Message-ID: Andrey Tatarinov wrote: > anyway list comprehensions are just syntaxic sugar for > > >>> for var in list: > >>> smth = ... > >>> res.append(smth) > > (is that correct?) > > so there will be no speed gain, while map etc. are C-implemented It depends. Try def square(x): return x*x map(square, range(1000)) versus [x*x for x in range(1000)] Hint: function calls are expensive. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From stephen.thorne at gmail.com Thu Jan 20 22:37:14 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Fri, 21 Jan 2005 13:37:14 +1000 Subject: Unbinding multiple variables In-Reply-To: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> Message-ID: <3e8ca5c80501201937332919d4@mail.gmail.com> On 20 Jan 2005 19:24:43 -0800, Johnny Lin wrote: > Hi! > > Is there a way to automate the unbinding of multiple variables? Say I > have a list of the names of all variables in the current scope via > dir(). Is there a command using del or something like that that will > iterate the list and unbind each of the variables? > > Thanks much! (If anyone posts an answer, if you could also cc your > reply to my email air_jlin at yahoo.com, would be much obliged. Thanks > again!) My immediate reaction is "You never want to do that" If you're doing something along these lines: #some code #create lots of variables #do stuff with those variables # References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> <1104672631.884144.294730@c13g2000cwb.googlegroups.com> Message-ID: <41D8311A.9090009@yahoo.it> mirnazim at gmail.com wrote: >I have started a topic that is really vauge. I knew that this topic is >very general and abstract but I think it turned out to be more general >that I had expected. > >Let me make an attemp at defining "Non-Content Oriented Web >Applications". > >A "Non-Content Oriented Web Application": >(1) will be accessed from web browser(obviously). > >(2) will be developed using 'W3C' and other open standards(STRICTLY, to >ensure compatibility and portablity). > >(3) will expose some kind of functionality to the user, not just some >document to read. > >(4) functionality can be very simple to very complex. > >I sat down to define what I actually mean by "Non-Content Oriented Web >Applications" with a fairly clear idea, But suddenly every thing >vanished from my mind, "OH MY GOD, I AM OUT OF WORDS". I think all of >you have been i such situation at least once. So please help me in >defining these "Non-Content Oriented Web Applications". To give a >example, I think GMAIL comes quite close to what I am talking aout. > > > Well,this is what we are working on,about point 2) 1) ~3) ~4) ,but I really don't think it has something strongly related with gmail. We are using nevow and rdf,mainly.Nevow for rendering pages,and rdf to build them on the fly. Probably,what I find related to your questions in this project is the open server ontology we are trying to build. Eventually ontologies and semantics have nothing to do with python core( :-(( ),but with a good scripting language it's easy to mix semantic net querying with pages ,rendering technical, nevow code. This way functionalities of the service are changed,and built during the service run,just adding triples to the semantic net and changing the contents sticked to its nodes. We hope to have code in the contents of the semantic net soon.This will allow to upload a piece of code ,some templates,together with the right metadatas in the semantic net and see the service implied running around in the pages which URI is matched by the pattern coded in the metadata of the service. It's not clear to me also,but this is how it works:using semantic matching(which can be very complex) to decide the interface to information pieces an URL renders. Last but not least,all the informations ,their logic and the rendering engine end functionalities(templates and their specific code),are distribuited as definition as the reside in the semantic net service.My poor english(and stoned mind). I hope I got something of your lost words,have fun and have a look at www.pytypus.org. Yours From andybak at gmail.com Mon Jan 3 15:24:48 2005 From: andybak at gmail.com (andybak at gmail.com) Date: 3 Jan 2005 12:24:48 -0800 Subject: Ann: CherryPy-2.0-beta released In-Reply-To: <1104774372.943278.302050@f14g2000cwb.googlegroups.com> References: <1104774372.943278.302050@f14g2000cwb.googlegroups.com> Message-ID: <1104783888.664232.72720@f14g2000cwb.googlegroups.com> I'm a great believer that avoiding query strings in URL's is good practise ( http://www.holloway.co.nz/book/9 for good arguments why). How tricky is it to remap URL's to query strings in cherryPy? Also how much does it complicate matters to run cherryPy under an existing webserver? Is any functionality lost? From peter at engcorp.com Tue Jan 11 21:25:01 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 11 Jan 2005 21:25:01 -0500 Subject: appending data to an xml file In-Reply-To: References: Message-ID: Thomas Heller wrote: > I want to append/insert additional data to an xml file. [...] > Better, imo, would be to add the dumped info into a proper xml tag, and > inject it into the original file. Is that (efficiently) possible? My technique, when I can't just strip the root element and have a document fragment consisting of a huge list of the other elements, is just to seek to the end of the file, back up to the beginning of the '', and begin overwriting the file from that point... seems to work nicely, and in most cases since I'm the one who wrote the file in the first place I know that I've written '\n' and can just seek to the end minus 8 bytes (when on Windows, anyway...). -Peter From ptmcg at austin.rr._bogus_.com Thu Jan 20 14:54:50 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 20 Jan 2005 19:54:50 GMT Subject: Overloading ctor doesn't work? References: <35ab8oF4idc25U1@individual.net> <41effd30$1_1@newspeer2.tds.net> Message-ID: "Kent Johnson" wrote in message news:41effd30$1_1 at newspeer2.tds.net... > > Martin H?cker wrote: > > > >> Hi there, > >> > >> I just tried to run this code and failed miserably - though I dunno > >> why. Could any of you please enlighten me why this doesn't work? > > Here is a simpler test case. I'm mystified too: > > from datetime import datetime > > class time (datetime): > def __init__(self, hours=0, minutes=0, seconds=0, microseconds=0): > datetime.__init__(self, 2001, 10, 31, hours, minutes, seconds, microseconds) > > print time(1,2,3,4) # => 0001-02-03 04:00:00 > print time() # => TypeError: function takes at least 3 arguments (0 given) > > > What happens to the default arguments to time.__init__? What happens to the 2001, 10, 31 arguments > to datetime.__init__? > > I would expect the output to be > 2001-10-31 01:02:03.000004 > 2001-10-31 00:00:00.000000 > > Kent I can't explain this behavior, but this version does work (uses datetime.combine instead of ctor) -- Paul from datetime import datetime, date as dt_date, time as dt_time class time_d (datetime): def __new__(cls, *args): # default to no microseconds if len(args)==3: args = args + (0,) if len(args)==4: tmpdate = datetime.today() h, mi, s, ms = args return datetime.combine(tmpdate, dt_time(h,mi,s,ms)) elif len(args)==7: y,m,d,h,mi,s,ms = args return datetime.combine(dt_date(y,m,d), dt_time(h,mi,s,ms)) else: raise TypeError, "wrong number of args" print time_d(2001,10,31,1,2,3,4) print time_d(1,2,3,4) print time_d(1,2,3) From sjmachin at lexicon.net Sun Jan 16 02:01:00 2005 From: sjmachin at lexicon.net (John Machin) Date: 15 Jan 2005 23:01:00 -0800 Subject: How to del item of a list in loop? In-Reply-To: <41ea0a87.979537159@news.oz.net> References: <41ea0a87.979537159@news.oz.net> Message-ID: <1105858860.860419.30900@c13g2000cwb.googlegroups.com> Bengt Richter wrote: > No one seems to have suggested this in-place way yet, > so I'll trot it out once again ;-) > > >>> lst = [1, 2, 3] > >>> i = 0 > >>> for item in lst: > ... if item !=2: > ... lst[i] = item > ... i += 1 > ... > >>> del lst[i:] > >>> lst > [1, 3] Works, but slowly. Here's another that appears to be the best on large lists, at least for removing 1 element. It's O(len(list) * number_to_be_removed). !def method_try_remove(lst, remove_this): ! try: ! while 1: ! lst.remove(remove_this) ! except: ! pass From lbates at syscononline.com Wed Jan 12 18:35:39 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 12 Jan 2005 17:35:39 -0600 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: You don't say how this will be used, but here goes: 1) Read the records and put into dictionary with key of sequence (from header) and data being the sequence data. Use shelve to store the dictionary for subsequent runs (if load time is excessive). 2) Take a look at Gadfly (gadfly.sourceforge.net). It provides you with Python SQL-like database and may be better solution if data is basically static and you do lots of processing. All depends on how you use the data. Regards, Larry Bates Syscon, Inc. Chris Lasher wrote: > Hello, > I have a rather large (100+ MB) FASTA file from which I need to > access records in a random order. The FASTA format is a standard format > for storing molecular biological sequences. Each record contains a > header line for describing the sequence that begins with a '>' > (right-angle bracket) followed by lines that contain the actual > sequence data. Three example FASTA records are below: > > >>CW127_A01 > > TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG > TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA > GCATTAAACAT > >>CW127_A02 > > TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG > TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA > GCATTAAACATTCCGCCTGGGGAGTACGGTCGCAAGATTAAAACTCAAAGGAATAGACGG > >>CW127_A03 > > TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG > TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA > GCATTAAACATTCCGCCTGGG > ... > > Since the file I'm working with contains tens of thousands of these > records, I believe I need to find a way to hash this file such that I > can retrieve the respective sequence more quickly than I could by > parsing through the file request-by-request. However, I'm very new to > Python and am still very low on the learning curve for programming and > algorithms in general; while I'm certain there are ubiquitous > algorithms for this type of problem, I don't know what they are or > where to look for them. So I turn to the gurus and accost you for help > once again. :-) If you could help me figure out how to code a solution > that won't be a resource whore, I'd be _very_ grateful. (I'd prefer to > keep it in Python only, even though I know interaction with a > relational database would provide the fastest method--the group I'm > trying to write this for does not have access to a RDBMS.) > Thanks very much in advance, > Chris > From sese at 263.net Mon Jan 3 04:13:18 2005 From: sese at 263.net (SeSe) Date: Mon, 03 Jan 2005 17:13:18 +0800 Subject: [Twisted-Python] Problem with Echoserver (TCP), Help! In-Reply-To: <1104730160.375967.119070@c13g2000cwb.googlegroups.com> References: <1104730160.375967.119070@c13g2000cwb.googlegroups.com> Message-ID: Thanks. I have disabled my firewall. But still failed. It is a bit strange that echo server UDP works. Only TCP doesn't. Regards, SeSe Kartic wrote: > Hi, > > My experience with Twisted is also limited but let me try to help you. > I tried the same combo as you and it worked well with the following > responses: > receive: Hello, world! > receive: What a fine day it is. > receive: Bye-bye! > connection lost: Connection was closed cleanly. > > I am sure you started the server before the client. > > Do you have some firewall software installed that prevents the client > from connecting to the server? > > Thanks > --Kartic > From sesquile at gmail.com Mon Jan 31 13:41:18 2005 From: sesquile at gmail.com (mh) Date: 31 Jan 2005 10:41:18 -0800 Subject: [ANN] Spike Asset Manager release 0.13 Message-ID: <1107196878.026930.154270@c13g2000cwb.googlegroups.com> Spike Asset Manager (SAM) is an open-source cross-platform framework written in python for probing a system for components and reporting them. It includes a driver file that probes for components commonly found in a LAMPJ stack (Apache, MySQL, PHP, Tomcat, etc). Note that the L in LAMP could be Linux, Solaris, Windows or Mac. SAM can find multiple versions that are installed, query the rpm database and indicate whether components are running. Release 0.13 changes: - Migrate to ElementTree from minidom - Migrate to Cheetah from xsl - Preliminary MacOSX support thanks Matt From http Mon Jan 31 23:20:32 2005 From: http (Paul Rubin) Date: 31 Jan 2005 20:20:32 -0800 Subject: Next step after pychecker References: <41ff0308$0$6503$636a15ce@news.free.fr> Message-ID: <7xis5cq5bj.fsf@ruckus.brouhaha.com> Philippe Fremy writes: > I would like to develop a tool that goes one step further than > pychecker to ensure python program validity. The idea would be to get > close to what people get on ocaml: a static verification of all types > of the program, without any kind of variable declaration. This would > definitely brings a lot of power to python. You know, I've always thought that ML-style type inference is an impressive technical feat, but why is it so important to not use declarations? This is an aspect I've never really understood. From craig at postnewspapers.com.au Fri Jan 28 02:46:15 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 28 Jan 2005 15:46:15 +0800 Subject: Hello In-Reply-To: References: Message-ID: <1106898375.3909.9.camel@albert.localnet> On Thu, 2005-01-27 at 19:39 -0500, g_xo wrote: > Hello everyone, > > I am a python beginner and look forward to learning the language and > working on some interesting projects using it. > > I was wondering if anybody may help me get access to the news group > comp.lang.python I am trying to access it using KNode but I get an > "unable to resolve host name" error. comp.lang.python is gatewayed to this mailing list, and vice versa. You just posted on c.l.p . If you want to access it over NNTP as a newsgroup, rather than receiving it as a mailing list, you just need to ensure you provide your newsreader with a news server that you have access to. Most ISPs provide news servers, often at 'news.ispname.net' if the ISP is 'ispname.net'. You need to get the correct details of which news server to use from your ISP and configure your newsreader to use that. Once your newsread is talking correctly to your ISP's news server, *then* you can subscribe to comp.lang.python. -- Craig Ringer From tonino.greco at gmail.com Fri Jan 21 07:38:50 2005 From: tonino.greco at gmail.com (Tonino) Date: 21 Jan 2005 04:38:50 -0800 Subject: tkinter socket client ? In-Reply-To: <35cae5F4jvrirU1@individual.net> References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> Message-ID: <1106311130.446259.30710@f14g2000cwb.googlegroups.com> thanks for the info - but I really do not want to learn twisted before I can understand Tkinter ;) another thread seems the way - will try that ... Thanks Tonino From ashot at removethismolsoft.com Mon Jan 17 02:19:42 2005 From: ashot at removethismolsoft.com (Ashot) Date: Sun, 16 Jan 2005 23:19:42 -0800 Subject: video analysis with python References: <20050116114407.GE3276@zoran.com> Message-ID: On Mon, 17 Jan 2005 08:08:46 +0100, Alexander 'boesi' B?secke wrote: > Hi > > Am 16.01.2005 12:44:27 schrieb Miki Tebeka: > >> 1. There is PyMedia (http://pymedia.org/) > > Is this library able to extract single images from a video? AFAICS it > can only convert videos from one format to another. But I didn't try it, > I've looked only in the docu. > > Maybe pyVideo (http://www.geocities.com/rtrocca/python/) would be a > solution. But for me the AVIFile-Module doesn't work stable, it > regularly crashes the python-interpreter. > > And there is a library for accessing DirectShow called PyDShowCam. > > cu boesi I haven't tried it yet, but yes its pretty full featured library, there is a tutorial here on extracting images: http://java.sun.com/products/java-media/jmf/2.1.1/solutions/FrameAccess.html -- Ashot Petrosian University of Texas at Austin, Computer Sciences From irmen at -nospam-remove-this-xs4all.nl Tue Jan 18 13:33:32 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 18 Jan 2005 19:33:32 +0100 Subject: ANNOUNCE: Altova ... blah blah blah In-Reply-To: <8u9Hd.344$Jg7.182@fe51.usenetserver.com> References: <8u9Hd.344$Jg7.182@fe51.usenetserver.com> Message-ID: <41ed567c$0$6208$e4fe514c@news.xs4all.nl> Altova Announcements wrote: > Altova Unveils ............. [spam] Well now, I didn't like their products very much already, but this spam has certainly made them drop another few steps down on my scale. Hmpf. --Irmen From ncoghlan at iinet.net.au Thu Jan 13 09:46:04 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 14 Jan 2005 00:46:04 +1000 Subject: else condition in list comprehension In-Reply-To: <34mt3dF4ejn17U1@individual.net> References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> <34mt3dF4ejn17U1@individual.net> Message-ID: <41E689AC.2020001@iinet.net.au> Andrey Tatarinov wrote: >> I presume the point of this is to avoid polluting the local namespace >> with "newval". I further presume you also have plans to do something >> about "i"? ;-) > > no, the point is in grouping definition of newval() with place where it > is used. I'd have said the point was both :) But yeah, unfortunately the 'leaking list comp' problem won't be fixed in the 2.x series due to the compatibility problem. Fortunately, generator expressions didn't inherit the issue. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tim.golden at viacom-outdoor.co.uk Mon Jan 24 06:23:49 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 24 Jan 2005 11:23:49 -0000 Subject: Pointer: CfV de.comp.lang.python Message-ID: <9A28C052FF32734DACB0A288A35339910359E1@vogbs009.gb.vo.local> [Christian Helmbold] | I ask german speaking python programmers to contest the election to | establish the german python newsgroup de.comp.lang.python. It strikes me that this would have been one of the few occasions when it *would* have made sense to write in a language other than English on c.l.py. Although, thinking about it, us non-German speakers wouldn't have known that the post wouldn't apply to us by definition! TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From flaxeater at gmail.com Thu Jan 6 18:42:46 2005 From: flaxeater at gmail.com (flaxeater at gmail.com) Date: 6 Jan 2005 15:42:46 -0800 Subject: wxPython clipboard In-Reply-To: <1105010770.911397.278520@c13g2000cwb.googlegroups.com> References: <1105010770.911397.278520@c13g2000cwb.googlegroups.com> Message-ID: <1105054966.693860.59270@f14g2000cwb.googlegroups.com> Ok well you should look at this module http://www.rutherfurd.net/python/sendkeys/#id1 I then you could take frequent snapshots and use and OCR to find your stuff. Then use the above library to type to the window. From ark at acm.org Mon Jan 17 14:19:19 2005 From: ark at acm.org (Andrew Koenig) Date: Mon, 17 Jan 2005 19:19:19 GMT Subject: Adjusting the 1024 byte stdin buffer limit References: <1105989047.516986.59990@z14g2000cwz.googlegroups.com> Message-ID: "brucoder" wrote in message news:1105989047.516986.59990 at z14g2000cwz.googlegroups.com... > Are there runtime settings that can be used to adjust the default 1024 > byte stdin buffer limit or a buildtime setting in pyconfig.h? I have a > need to pump this up to permit input of a large data block via stdin. What do you think you are being prevented from doing? From aahz at pythoncraft.com Tue Jan 4 10:18:15 2005 From: aahz at pythoncraft.com (Aahz) Date: 4 Jan 2005 10:18:15 -0500 Subject: Unicode universe (was Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)) References: <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> Message-ID: In article <1104849206.111461.70500 at c13g2000cwb.googlegroups.com>, wrote: > >BTW what's the difference between .encode and .decode ? >(yes, I have been living in happy ASCII-land until now ... ;) Here's the stark simple recipe: when you use Unicode, you *MUST* switch to a Unicode-centric view of the universe. Therefore you encode *FROM* Unicode and you decode *TO* Unicode. Period. It's similar to the way floating point contaminates ints. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From steve at holdenweb.com Mon Jan 3 15:55:49 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Jan 2005 15:55:49 -0500 Subject: Python! Is! Truly! Amazing! In-Reply-To: References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: <9niCd.67881$Jk5.63344@lakeread01> Ron Garret wrote: > In article , > jfj wrote: > > >>Ron Garret wrote: >> >>>In article <1104657461.868175.252380 at c13g2000cwb.googlegroups.com>, >>> "Erik Bethke" wrote: >>> >>> >>> >>>>I have NEVER experienced this kind of programming joy. >>> >>> >>>Just wait until you discover Lisp! >>> >>>;-) >> >> >>I've had it with all those lisp posts lately ;-) >> >>There were functional and non-functional programming languages (the >>first being *much* simpler to implement). There is a *reason* people >>chose C over lisp. It's not that we were all blind and didn't see the >>amazingness of lisp. Procedural languages are simply better, and I'm not >>replying to this flamewar. > > > Then neither am I. > > Yes, there's a reason people choose C over Lisp, just as there is a > reason that people choose Windows over OS X, the Ford Taurus over the > Lexus SC400, and Perl over Python. But I'm pretty sure joy isn't that > reason. If joy is part of your quality metric for a programming > language then Lisp is worth a look. (And it costs a lot less than a > Lexus.) Well, in the Computer Programming for Everyone stakes I'm pretty sure that LISP and its derivatives don't stand a chance, simply because of the rebarbative syntax one must use to express even relatively simple algorithms and data structures. While the language has a lot going for it in the hands of an experienced and determined LISPer, the average programmer just isn't going to "get it". regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From vincent at visualtrans.de Thu Jan 13 00:04:04 2005 From: vincent at visualtrans.de (vincent wehren) Date: Thu, 13 Jan 2005 06:04:04 +0100 Subject: py2exe Excludes In-Reply-To: References: Message-ID: Ed Leafe wrote: > I'm trying to make a Windows runtime for Dabo, and I want to exclude > the framework code itself from the exe file, so that people can update > with new releases as they are made. The relevant section of setup.py has: > > setup( > # The first three parameters are not required, if at least a > # 'version' is given, then a versioninfo resource is built from > # them and added to the executables. > version = "0.3.0", > description = "Dabo Runtime Engine", > name = "daborun", > # targets to build > console = ["daborun.py"], > #exclude the actual framework > options = { "py2exe": {"excludes" : ["dabo"]} }, > ) > > Yet the generated library.zip still contains all of the Dabo module > code. Why is this? What am I doing wrong? Just a guess: What happens if you remove everything that's in the "build" directory before running setup.py? There may still be files around from an earlier build that *did* include the Dabo modules. -- Vincent Wehren > > ___/ > / > __/ > / > ____/ > Ed Leafe > http://leafe.com/ > http://dabodev.com/ > From claird at lairds.us Thu Jan 27 09:08:07 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 27 Jan 2005 14:08:07 GMT Subject: Please suggest on the book to follow References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> <1106829519.540737.164210@z14g2000cwz.googlegroups.com> Message-ID: In article <1106829519.540737.164210 at z14g2000cwz.googlegroups.com>, Fuzzyman wrote: >We've only just had Python 2.4. Based on previous experience that means >it will be about 18 months before python 2.5..... > >I learned to program from 'Programming Python'. Particularly the stuff >on Tkinter is very helpful. I don't think you'll have much to >'unlearn', although obviously there is stuff it doesn't cover (like new >style classes). . . . Python is considerate of programmers. While experience with commercial products might lead to an expectation that 2.0 and 2.4 differ greatly, in fact it's quite feasible to learn from books aimed at 1.5 or even before, and have your results work perfectly well under 2.4. From xah at xahlee.org Wed Jan 26 14:28:15 2005 From: xah at xahlee.org (Xah Lee) Date: 26 Jan 2005 11:28:15 -0800 Subject: how to comment out a block of code Message-ID: <1106767695.572974.98920@z14g2000cwz.googlegroups.com> is there a syntax to comment out a block of code? i.e. like html's or perhaps put a marker so that all lines from there on are ignored? thanks. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From Scott.Daniels at Acm.Org Thu Jan 20 10:57:32 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 20 Jan 2005 07:57:32 -0800 Subject: Print to Windows default Printer In-Reply-To: References: Message-ID: <41efd18e$1@nntp0.pdx.net> Tim Golden wrote: > [Samantha] > | I am new to Python and I am having considerable trouble > | trying to print > | (using a simple script) to the default printer rather than the screen. > | Thanks for any help. > | S > > It may be that something here will help you: > > http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html > > Specifically, I think that the section print raw text is > closest to what you're asking (although not necessarily > to what you'll eventually want): > > http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html#win32print > You might be interested in using PDFCreator to save paper during your tests. It is a windows printer driver that creates a PDF file: http://sourceforge.net/projects/pdfcreator/ --Scott David Daniels Scott.Daniels at Acm.Org From ncoghlan at iinet.net.au Tue Jan 11 05:30:29 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 11 Jan 2005 20:30:29 +1000 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: <34frdmF42p2jrU1@individual.net> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <34frdmF42p2jrU1@individual.net> Message-ID: <41E3AAC5.7040703@iinet.net.au> Andrey Tatarinov wrote: > I think using 'with' keyword can cause some ambiguity. for example I > would surely try to write > > >>> x = a+b with self: > >>> b = member > > and using with at the end of block brings more ambiguity: > > >>> stmt1() > >>> stmt2() > >>> with self: > >>> member = stmt3() > > compare to: > > >>> stmt1() > >>> stmt2() > >>> with: > >>> variable = stmt3() > > a way different semantics with just one word added/deleted. Except that for a "with :" block, attributes of the expression must be preceded by a dot: Py> stmt1() Py> stmt2() Py> with self: ... .member = stmt3() The advantages of the 'with' block are that 'self' is only looked up once, and you only need to type it once. The leading dot is still required to disambiguate attribute references from standard name references. Despite that, I think you are right that the ambiguity is greater than I first thought. Correct code is reasonably easy to distinguish, but in the presence of errors it is likely to be unclear what was intended, which would make life more difficult than it needs to be. However, I still agree with Alex that the dual life of "where" outside of Python (as an 'additional definitions' clause, as in mathematics, and as a 'conditional' clause, as in SQL), and the varied background of budding Pythoneers is a cause for concern. 'in' is worth considering, as it is already used by Python at least once for declaring use of a namespace (in the 'exec' statement). However, I suspect it would suffer from ambiguity problems similar to those of 'with' (consider " in " and " in: "). There's also the fact that the statement isn't *really* executed in the inner namespace - any name binding effects are seen in the outer scope, whereas 'exec x in dict' explicitly protects the containing namespace from alteration. So of the four keywords suggested so far ('where', 'with', 'in', 'using'), I'd currently vote for 'using' with 'where' a fairly close second. My vote goes to 'using' because it has a fairly clear meaning ('execute the statement using this extra information'), and doesn't have the conflicting external baggage that 'where' does. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From cdavisNOSP at NOSPstaffmail.ed.ac.uk Thu Jan 13 05:00:08 2005 From: cdavisNOSP at NOSPstaffmail.ed.ac.uk (Cory Davis) Date: Thu, 13 Jan 2005 10:00:08 +0000 Subject: distutils linux script installation broken? In-Reply-To: <1105544059.595961.157780@c13g2000cwb.googlegroups.com> References: <1105535625.443343.326560@z14g2000cwz.googlegroups.com> <1105544059.595961.157780@c13g2000cwb.googlegroups.com> Message-ID: Thanks for the help Chris. I tried the -E option, and also installing as root with no change - the scripts in the bin directory still end up with #!None on the first line. Next step is to reinstall Python 2.4, and if that doesn't work I'll just stick with 2.3.4. Cheers, Cory. Christopher De Vries wrote: > I've got python 2.3.3, 2.4, and 1.5.2 (which came preinstalled) on my > linux box. It's redhat 7.2 (I know... I would upgrade, but it would > void my service contract, so I just install things in /usr/local). You > can check if PYTHONHOME or PYTHONPATH are set, which may somehow be > interfering. I don't have those variables set. If they are set, you > could try running: > > python -E setup.py install > > The -E option should make python ignore those environment variables. > Good luck, I hope this helps. > > Chris > From steven.bethard at gmail.com Mon Jan 10 01:22:27 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 09 Jan 2005 23:22:27 -0700 Subject: Python3: on removing map, reduce, filter In-Reply-To: <1105316438.272475.313670@c13g2000cwb.googlegroups.com> References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> <-7mdndrwD_1qOHzcRVn-qQ@comcast.com> <1105316438.272475.313670@c13g2000cwb.googlegroups.com> Message-ID: beliavsky at aol.com wrote: > Steve Bethard wrote: >> Robert Kern wrote: >>> def square(x): >>> return x*x >>> map(square, range(1000)) >>> >>> versus >>> [x*x for x in range(1000)] >>> >>> Hint: function calls are expensive. >> >> $ python -m timeit -s "def square(x): return x*x" "map(square, range(1000))" >> 1000 loops, best of 3: 693 usec per loop >> >> $ python -m timeit -s "[x*x for x in range(1000)]" >> 10000000 loops, best of 3: 0.0505 usec per loop > > Functions will often be complicated enought that inlining them is not > feasible. True, true. However, list comprehensions still seem to be comparable in speed (at least in Python 2.4): $ python -m timeit -s "def f(x): return x*x" "[f(x) for x in xrange(1000)]" 1000 loops, best of 3: 686 usec per loop $ python -m timeit -s "def f(x): return x*x" "map(f, xrange(1000))" 1000 loops, best of 3: 690 usec per loop Presumably this is because the C code for the byte codes generated by a list comprehension isn't too far off of the C code in map. I looked at bltinmodule.c for a bit, but I'm not ambitious enough to try verify this hypothesis. ;) Steve From swaroopch at gmail.com Fri Jan 28 02:46:48 2005 From: swaroopch at gmail.com (Swaroop C H) Date: Fri, 28 Jan 2005 13:16:48 +0530 Subject: Hello In-Reply-To: <1106898375.3909.9.camel@albert.localnet> References: <1106898375.3909.9.camel@albert.localnet> Message-ID: <351e887105012723467f3eb873@mail.gmail.com> > Most ISPs provide > news servers, often at 'news.ispname.net' if the ISP is 'ispname.net'. > You need to get the correct details of which news server to use from > your ISP and configure your newsreader to use that. Once your newsread > is talking correctly to your ISP's news server, *then* you can subscribe > to comp.lang.python. If you can't find a Usenet server, try news.gmane.org -- Swaroop C H Blog: http://www.swaroopch.info Book: http://www.byteofpython.info From FBatista at uniFON.com.ar Wed Jan 12 17:58:39 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 12 Jan 2005 19:58:39 -0300 Subject: What strategy for random accession of records in massive FAST A file? Message-ID: [Chris Lasher] #- I have a rather large (100+ MB) FASTA file from which I need to #- access records in a random order. The FASTA format is a #- standard format #- for storing molecular biological sequences. Each record contains a #- header line for describing the sequence that begins with a '>' #- (right-angle bracket) followed by lines that contain the actual #- sequence data. Three example FASTA records are below: #- #- >CW127_A01 #- TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG #- TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA #- GCATTAAACAT #- >CW127_A02 #- TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG #- TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA #- GCATTAAACATTCCGCCTGGGGAGTACGGTCGCAAGATTAAAACTCAAAGGAATAGACGG #- >CW127_A03 #- TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG #- TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA #- GCATTAAACATTCCGCCTGGG #- ... I think of two ways. If you have enough memory you could load everything in memory, each record as the element of a list, and then access randomly to the list. If you want to keep the memory usage low, you can parse the file once and store in a list the byte position where the record starts and ends. Then access the list randomly and read each record with seek() and read(). . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Sun Jan 9 10:44:20 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 09 Jan 2005 10:44:20 -0500 Subject: python3: 'where' keyword In-Reply-To: <1gq4ebf.17qqy8dk9ccr6N%aleaxit@yahoo.com> References: <3480qqF46jprlU1@individual.net> <1gq4ebf.17qqy8dk9ccr6N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > AdSR wrote: > > >>I don't know haskell, but it looks SQL-ish to me (only by loose > > > Indeed, the fact that many MANY more people are familiar with SQL than > with Haskell may be the strongest practical objection to this choice of > syntax sugar; the WHERE clause in an SQL SELECT has such wildly > different semantics from Haskell's "where" that it might engender huge > amounts of confusion. I.e., reasoning by analogy with SQL only, one > might reasonably expect that minor syntax variations on: > > print a, b where a = b > > could mean roughly the same as "if a==b: print a, b", rather than > roughly the same as: > > a = b > print a, b > > I wonder if 'with', which GvR is already on record as wanting to > introduce in 3.0, might not be overloaded instead. > IIRC the proposed meaning seems to be most closely related (in my own experience, annyway) to the use of "where" in BCPL (heavens, *that* was a long time ago). I never found that entirely natural either. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From me at privacy.net Sat Jan 1 08:14:23 2005 From: me at privacy.net (Mark Carter) Date: Sat, 01 Jan 2005 13:14:23 +0000 Subject: Which blog tool Message-ID: <41d6a22f$0$42579$ed2619ec@ptn-nntp-reader03.plus.net> I currently use python to automatically summarise a certain newsgroup daily, and post the findings that it makes. Someone has suggested that they would like a to see a blog of the posts. I wondered if there was a python tool/library that could automate the blog postings. Any ideas? Some details: * the summaries are basically just text files * I already have a blog at www.blogger.com (http://markcarterturriff.blogspot.com/), so I would like to use that if possible; although any alternative free one that I can use to achieve my objective would be OK, too. * I do have my own hosted website, which can use perl but not python; but I'd rather use a freebie blog site * the whole thing must be scriptable, because it will run daily. A GUI would therefore likely get in the way. * generating an RSS feed would be nice From fuzzyman at gmail.com Fri Jan 28 05:23:27 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 28 Jan 2005 02:23:27 -0800 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: References: Message-ID: <1106907807.471215.105110@f14g2000cwb.googlegroups.com> Dieter Maurer wrote: > Steven Bethard writes on Tue, 25 Jan 2005 12:22:13 -0700: > > Fuzzyman wrote: > > ... > > > A better (and of course *vastly* more powerful but unfortunately only > > > a dream ;-) is a similarly limited python virutal machine..... > > I already wrote about the "RestrictedPython" which is part of Zope, > didn't I? > Not in this thread. > Please search the archive to find a description... > Interesting. I'd be interested in whether it requires a full Zope install and how easy (or otherwise) it is to setup. I'll investigate. Regards, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > > Dieter From grahamd at dscpl.com.au Thu Jan 27 16:59:24 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 27 Jan 2005 13:59:24 -0800 Subject: Who should security issues be reported to? Message-ID: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> Who are the appropriate people to report security problems to in respect of a module included with the Python distribution? I don't feel it appropriate to be reporting it on general mailing lists. From erikbethke at gmail.com Thu Jan 20 09:42:35 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 20 Jan 2005 06:42:35 -0800 Subject: ElementTree cannot parse UTF-8 Unicode? In-Reply-To: <5861401.FEXqi8ioxF@strongwill.g2ctech> References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> <1106181323.553028.290370@z14g2000cwz.googlegroups.com> <5861401.FEXqi8ioxF@strongwill.g2ctech> Message-ID: <1106232155.502249.95650@c13g2000cwb.googlegroups.com> That was a great clue. I am an idiot and tapped on the wrong download link... now I can read and parse the xml file fine - as long as I create it in XML spy - if I create it by this method: d=wxFileDialog( self, message="Choose a file", defaultDir=os.getcwd(), defaultFile="", wildcard="*.xml", style=wx.SAVE | wxOVERWRITE_PROMPT | wx.CHANGE_DIR) if d.ShowModal() == wx.ID_OK: # This returns a Python list of files that were selected. paths = d.GetPaths() layout = '\n' L1Word = self.t1.GetValue() L2Word = 'undefined' layout += '\n' layout += ' \n' layout += '' open( paths[0], 'w' ).write(layout) I get hung up on the write statement, I am off to look for a a Unicode capable file write I think... -Erik From kent3737 at yahoo.com Wed Jan 26 11:32:37 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Wed, 26 Jan 2005 11:32:37 -0500 Subject: Help With Python In-Reply-To: References: Message-ID: <41f7c39c$1_1@newspeer2.tds.net> Thomas Guettler wrote: > # No comma at the end: > mylist=[] > for i in range(511): > mylist.append("Spam") or just mylist = ["Spam"] * 511 Kent > print ", ".join(mylist) > > Thomas > From cam.ac.uk at mh391.invalid Sun Jan 9 09:33:44 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 09 Jan 2005 14:33:44 +0000 Subject: Recent infoworld column In-Reply-To: References: <41DEEF0F.5000300@nospamyahoo.com> Message-ID: Carlos Ribeiro wrote: > """ > When people talk about the heroes of open source, you tend to hear > such familiar names as Linus Torvalds, Larry Wall, Brendan Eich, Guido > van Rossum, Monty Widenius, Miguel de Icaza, and Rasmus Lerdorf... > """ Of course, I had to look up who Rasmus Lerdorf was... -- Michael Hoffman From bac at OCF.Berkeley.EDU Thu Jan 6 02:44:09 2005 From: bac at OCF.Berkeley.EDU (Brett C) Date: Wed, 05 Jan 2005 23:44:09 -0800 Subject: python-dev Summary for 2004-11-16 through 2004-11-30 Message-ID: <41DCEC49.9090908@ocf.berkeley.edu> python-dev Summary for 2004-11-16 through 2004-11-30 ++++++++++++++++++++++++++++++++++++++++++++++++++++ This is a summary of traffic on the `python-dev mailing list`_ from November 16, 2004 through November 30, 2004. It is intended to inform the wider Python community of on-going developments on the list. To comment on anything mentioned here, just post to `comp.lang.python`_ (or email python-list at python.org which is a gateway to the newsgroup) with a subject line mentioning what you are discussing. All python-dev members are interested in seeing ideas discussed by the community, so don't hesitate to take a stance on something. And if all of this really interests you then get involved and join `python-dev`_! This is the fifty-third summary written by Brett Cannon (Another quarter begins). To contact me, please send email to brett at python.org ; I do not have the time to keep up on comp.lang.python and thus do not always catch follow-ups posted there. All summaries are archived at http://www.python.org/dev/summary/ . Please note that this summary is written using reStructuredText_ which can be found at http://docutils.sf.net/rst.html . Any unfamiliar punctuation is probably markup for reST_ (otherwise it is probably regular expression syntax or a typo =); you can safely ignore it, although I suggest learning reST; it's simple and is accepted for `PEP markup`_ and gives some perks for the HTML output. Also, because of the wonders of programs that like to reformat text, I cannot guarantee you will be able to run the text version of this summary through Docutils_ as-is unless it is from the `original text file`_. .. _PEP Markup: http://www.python.org/peps/pep-0012.html The in-development version of the documentation for Python can be found at http://www.python.org/dev/doc/devel/ and should be used when looking up any documentation on new code; otherwise use the current documentation as found at http://docs.python.org/ . PEPs (Python Enhancement Proposals) are located at http://www.python.org/peps/ . To view files in the Python CVS online, go to http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/ . Reported bugs and suggested patches can be found at the SourceForge_ project page. The `Python Software Foundation`_ is the non-profit organization that holds the intellectual property for Python. It also tries to forward the development and use of Python. But the PSF_ cannot do this without donations. You can make a donation at http://python.org/psf/donations.html . Every penny helps so even a small donation (you can donate through PayPal or by check) helps. .. _python-dev: http://www.python.org/dev/ .. _SourceForge: http://sourceforge.net/tracker/?group_id=5470 .. _python-dev mailing list: http://mail.python.org/mailman/listinfo/python-dev .. _comp.lang.python: http://groups.google.com/groups?q=comp.lang.python .. _Docutils: http://docutils.sf.net/ .. _reST: .. _reStructuredText: http://docutils.sf.net/rst.html .. _PSF: .. _Python Software Foundation: http://python.org/psf/ .. contents:: .. _last summary: http://www.python.org/dev/summary/2004-11-01_2004-11-15.html .. _original text file: http://www.python.org/dev/summary/2004-11-16_2004-11-30.ht ===================== Summary Announcements ===================== PyCon_ is coming up! Being held March 23-25 in Washington, DC, registration is now open at http://www.python.org/pycon/2005/register.html for credit card users (you can pay by check as well; see the general info page for the conference). .. _PyCon: http://www.python.org/pycon/2005/ ========= Summaries ========= --------------------------------------------- Would you like the source with your function? --------------------------------------------- Would you like all functions and classes to contain a __pycode__ attribute that contains a string of the code used to compile that code object? Well, that very idea was proposed. You would use a command-line switch to turn on the feature in order to remove the memory and any performance overhead for the default case of not needing this feature. Some might ask why this is needed when inspect.getsource and its ilk exist. The perk is that __pycode__ would always exist while inspect.getsource is a best attempt but cannot guarantee it will have the source. Beyond a suggested name change to __source__, various people have suggested very different uses. Some see it as a convenient way to save interpreter work easily and thus not lose any nice code snippet developed interactively. Others see a more programmatic use (such as AOP "advice" injection). Both are rather different and led to the thread ending on the suggestion that a PEP be written that specifies what the intended use-case to make sure that need is properly met. Contributing threads: - `__pycode__ extension `__ =============== Skipped Threads =============== - PEP 310 Status - python 2.3.5 release? look for 2.3.5 possibly in January - Current CVS, Cygwin and "make test" - syntactic shortcut - unpack to variably sizedlist mostly discussed `last summary`_ - Python 2.4, MS .NET 1.1 and distutils - Trouble installing 2.4 - Looking for authoritative documentation on packages, import & ihooks no docs exist, but feel free to write some! =) - String literal concatenation & docstrings literal string concatenation only works if the newline separating the strings is not significant to the parser - print "%X" % id(object()) not so nice does 'id' need to return only a positive? No, but it would be nice. - Bug in PyLocale_strcoll - Multilib strikes back - File encodings file.write does not work with Unicode strings; have to decode them to ASCII on your own From amk at amk.ca Fri Jan 21 08:32:56 2005 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 21 Jan 2005 07:32:56 -0600 Subject: PyCon Preliminary Program Announced! References: <20050121000607.DE1261E4010@bag.python.org> <41F061C3.3000802@gmail.com> Message-ID: On Thu, 20 Jan 2005 22:52:13 -0500, Tim Peters wrote: > The web page needs better formatting. In general, there are no more Suggestions for improvement are welcome. Perhaps the Wiki version of the schedule, at http://www.python.org/moin/PyConDC2005/Schedule, may be better. --amk From erikbethke at gmail.com Sun Jan 2 07:20:55 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 2 Jan 2005 04:20:55 -0800 Subject: Python! Is! Truly! Amazing! In-Reply-To: <1104657909.340055.283710@z14g2000cwz.googlegroups.com> References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <1104657909.340055.283710@z14g2000cwz.googlegroups.com> Message-ID: <1104668455.691428.12670@c13g2000cwb.googlegroups.com> somehow lost my j's: www.erikbethke.com/Python/screenshot02.jpg www.erikbethke.com/Python/screenshot03.jpg www.erikbethke.com/Python/screenshot04.jpg www.erikbethke.com/Python/screenshot05.jpg From uche at ogbuji.net Sun Jan 2 01:46:26 2005 From: uche at ogbuji.net (Uche Ogbuji) Date: 1 Jan 2005 22:46:26 -0800 Subject: Any Python XML Data Binding Utilities Avaiable? In-Reply-To: References: Message-ID: <1104648386.567624.274170@c13g2000cwb.googlegroups.com> Sounds like generateDS is closest to what you want: http://www.rexx.com/~dkuhlman/generateDS.html If you can bind from instances only and don't need schema, see Amara Bindery: http://uche.ogbuji.net/tech/4Suite/amara/ Also consider Gnosis Utilities and ElementTree. -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://4Suite.org http://fourthought.com Use CSS to display XML - http://www.ibm.com/developerworks/edu/x-dw-x-xmlcss-i.html Full XML Indexes with Gnosis - http://www.xml.com/pub/a/2004/12/08/py-xml.html Be humble, not imperial (in design) - http://www.adtmag.com/article.asp?id=10286UBL 1.0 - http://www-106.ibm.com/developerworks/xml/library/x-think28.html Use Universal Feed Parser to tame RSS - http://www.ibm.com/developerworks/xml/library/x-tipufp.html Default and error handling in XSLT lookup tables - http://www.ibm.com/developerworks/xml/library/x-tiplook.html A survey of XML standards - http://www-106.ibm.com/developerworks/xml/library/x-stand4/ The State of Python-XML in 2004 - http://www.xml.com/pub/a/2004/10/13/py-xml.html From bulba at bulba.com Thu Jan 6 15:34:23 2005 From: bulba at bulba.com (Bulba!) Date: Thu, 06 Jan 2005 21:34:23 +0100 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <16859.16548.249527.30210@montanaro.dyndns.org> <864d37090501050117761a32e6@mail.gmail.com> Message-ID: On Wed, 05 Jan 2005 17:25:08 -0800, Robert Kern wrote: >> Yes, I know, it can be written by hand. But by this line of logic why >> bother learning VHLL and not just stay with C? >I'm not sure what you mean by "written by hand." I mean the same way as you do mylist.sort() in Python instead of writing the list sorting function yourself in the application / script. >Someone is going to >have to write the functions in the first place. Sure, they can be >written once, well, and placed in the standard library so they don't >have to be *re*written by anyone else again. Well of course - the only point I mean here is getting high-level stuff is one of the main motives of getting into VHLL (aside from issues like automatic memory management, of course). >I still think numarray is a good start for this. It handles more than >just numbers. And RecArray (an array that has different types in each >column, as you seem to require) can be subclassed to add these methods >to it. I have downloaded it, playing with it and like it. I esp. like things like: >>> print a + a [2 4 6] or >>> b.getshape() (4,3) Very Pythonic. :-) However, not all things are generic enough like I meant. That is not to criticize, but merely to point out that the library is for obvious reasons slanted towards numerical work, so e.g. while the following works: .>>> from numarray import transpose .>>> transpose([[1,2],[3,4]]) array([[1, 3], [2, 4]]) ...this doesn't: >>> transpose([('phone1', 12345), ('phone2', 67890)]) Traceback (most recent call last): File "", line 1, in ? [....] TypeError: Expecting a python numeric type, got something else. Why would someone want to do such a thing: suppose he wants 'phone1' and 'phone2' and number records sequenced horizontally instead vertically, while when he read that from a file, such was the file structure. It's a boneheaded example, but you get the idea. It's obvious why that exception happens: in recarray I have to have the same type of the data type in every column, so transpose(recarray) cannot be done. This is not the situation with other builtin Python data types, where whatever with can be mixed, i.e. placed in any "cell" of data type and all the functions will still work as long as the operand type is proper. This is obviously the consequence of numarray being based on the matrices designed for working on numerical data, so it's probably very fast and I'm sure people who use it find it useful. But personally I would happily sacrifice much or even most of that speed for sake of flexibility. Because, sure, I can keep the matrix header with strings separately in a list, do the transformation just on numbers, adjust the list as well - it's not like I'm just lazy to make an additional programming effort, but that eliminates one of the greatest advantages of Python: terseness without foregoing clarity. Yes, now it's probably much harder to do once the simpler things have been done. All I'm saying is that it would be so frigging nice to have it with even richer data structures. >> and clear_ manipulations of rich data structures in Python. Why not >> extend them with flexible tables / matrices / arrays that would work >> in as "Pythonic" ways as dictionaries and lists already do? >Sure. We're working on it! Excellent! Great, I'm really grateful to you all for doing that. Honestly. >Come check out numarray; I think you'll like >it. And if, along the way, you write a CSV-to-RecArray converter, we'd >*love* to include it in the distribution. First I have to learn Python (and programming in general) well enough to produce smth that isn't as bug-infested as a software of certain well-known vendor and that I would not be ashamed of to show to the world. :-) I'm afraid it will take me some time. >I think that a more complete >integration with the other core Python facilities like the csv module >will help numarray become more suited for inclusion into the standard >library. I'm sure people would find it useful. I play with numarray to get the idea how I could apply it in my work. -- It's a man's life in a Python Programming Association. From jbperez808 at wahoo.com Sun Jan 9 04:55:57 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Sun, 09 Jan 2005 17:55:57 +0800 Subject: The best way to do web apps with Python? In-Reply-To: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <34cddlF48eck2U1@individual.net> worzel wrote: > What is the best way to web developemnt with Python? Is there anything > close to PHP style in-page script placement that can create and use > other Python objects? Spyce ( http://spyce.sf.net ) is what you're looking for. I was looking exactly for the same thing as you are - a PHP workalike - and tried around half a dozen or so alternatives before I settled upon Spyce as the best one. If Spyce's [[ and ]] delimiters are not to your liking, you can actually switch to using <% and %> without any problem. Spyce also handles the Python indent issue quite nicely and elegantly, imo, while you can use the free and open source SciTE text editor to separately syntax highlight Spyce source code + Javascript + HTML very nicely (config file tweaking required). > what is the expectataion of Python for this kind of > stuff? Would one use Python for certain other things but turn to PHP for > web apps - or would one use their Python skills in place of PHP? Python can be a full (and superior) replacement for PHP. The only caveat would be third party hosting support. The following post by on the Spyce mailing list (by Andy of Neotitans.com web development) explains why: "One major roadblock to Spyce and other Python server side technologies seeing acceptance on the scale of PHP is the fact that mod_python deployment on 3rd party shared hosting solutions is more complex and involved than mod_php. Apparently, security considerations mean that each mod_python user will need to get their own instance of an Apache server acting as a proxy behind a central instance of an Apache server (which is what's responsible for accepting requests at the shared server's http port). A per-shared user Spyce proxy server approach would likely be more economical (of server resources) and more easily set up than multiple mod_python-enabled Apache server instances. If your hosting solution will permit you to have your own long-running processes (afaik, most won't :-( ), and if they are willing make the necessary httpd.conf mods to pass Spyce page requests over to your own instance of the Spyce proxy server or their .htaccess setup allows you to do that yourself, then you're all set. I'm also happy to report that Spyce CGI works great on any hosting solution that supports CGI and has Python installed. This means that virtually all Linux-based hosting solutions (including those ultra-cheap shared server ones) will support Spyce CGI. It would seem that FastCGI support is probably the hardest to come by." From aleaxit at yahoo.com Thu Jan 6 07:45:09 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 6 Jan 2005 13:45:09 +0100 Subject: Cookbook 2nd ed Credits References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> <41DC613D.1020806@holdenweb.com> Message-ID: <1gpyyi0.7sc9va1t3ze86N%aleaxit@yahoo.com> Steve Holden wrote: ... > > 1: 25 u'Luther Blissett' > > 2: 21 u'Alex Martelli' ... > And I *still* think we deserve to be told the Luther Blissett story ... > > conspiratorial-ly y'rs - steve Martin Elster's post back in Aug '02 already had just about all of the necessary info...: ''' I had just been reading about Luther Blissett, and this name is a sort of umbrella name that is available for anyone that is interested, and that has been used in different "underground" projects and pranks, especially in Italy. ''' Add other well-known facts, such as the fact that Bologna is or was a hotbed of situationist pranks, Umberto Eco is a professor at Bologna University, Umberto Eco's best-known historical novels from "The Name of the Rose" onwards may be interestingly compared with Luther Blissett's "Q", and so forth, and I'm sure you can design a perfectly adequate conspiracy theory. Alex From bill.mill at gmail.com Wed Jan 19 14:46:29 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 19 Jan 2005 14:46:29 -0500 Subject: Zen of Python In-Reply-To: <972ec5bd050119111359e358f5@mail.gmail.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> Message-ID: <797fe3d405011911465ab59acd@mail.gmail.com> The example that occurs to me is that "import smtplib" is better than "import stdlib.inet.services.smtp". Peace Bill Mill bill.mill at gmail.com On Wed, 19 Jan 2005 14:13:47 -0500, Timothy Fitz wrote: > While I agree that the Zen of Python is an amazingly concise list of > truisms, I do not see any meaning in: > > Flat is better than nested. > > I strive for balance between flat and nested. Does anyone have a good > example of where this is applied? (specifically to python, or in > general) > -- > http://mail.python.org/mailman/listinfo/python-list > From beliavsky at aol.com Sat Jan 8 07:47:06 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 8 Jan 2005 04:47:06 -0800 Subject: Another look at language comparisons References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> Message-ID: <1105188426.955508.263030@c13g2000cwb.googlegroups.com> >From the web site: "Why Microsoft can Blow-Off with C#? These people have thought up programming languages Fortran, Prologue, Ada." The author is ignorant. Fortran was invented by IBM in the late 1950s, long before Microsoft existed. Ada was commissioned by the U.S. Department of Defense in the 1970s. The Prolog programming language is not spelled "Prologue". From jaco.smuts at clover.co.za Wed Jan 5 01:28:02 2005 From: jaco.smuts at clover.co.za (Jaco Smuts) Date: Wed, 05 Jan 2005 08:28:02 +0200 Subject: python intergration bus ? In-Reply-To: <1104849906.019872.153800@z14g2000cwz.googlegroups.com> References: <1104849906.019872.153800@z14g2000cwz.googlegroups.com> Message-ID: <41DB88F2.3040305@clover.co.za> Tonino wrote: >Hi, > >Just an interested question - I friend is testing a few JAVA >intergration bus's that will be used to intergrate his companies >services - I was wondering if there was a python intergration bus ? >other than maybe Pyro ? > > > >Thanks >Tonino > > > Hello Tonino There is a Python module (http://www.python.org/other/spread/) for Spread (http://www.spread.org/ ) that is worth looking at. There is also some work on a rpc module using spread. http://pyhacks.suddenthinks.com/spreadrpc/, never worked with this one though. There is a great module for IBM's websphere mq, pymqi ( http://pymqi.sourceforge.net/) by L Smithson. This obviously depends on using the Commercial websphere MQ product though. If web services are an option you can also have a look at Clarence (http://clarens.sourceforge.net) and / or http://pywebsvcs.sourceforge.net/ I've previously stumbled accross some others at sourceforge, but this should get you started. jaco From mail.python.org at bdash.net.nz Thu Jan 27 19:05:11 2005 From: mail.python.org at bdash.net.nz (Mark Rowe) Date: Fri, 28 Jan 2005 13:05:11 +1300 Subject: Question: "load"ing a shared object in python In-Reply-To: References: Message-ID: <2e82e836a9fe632159b03821655404e0@bdash.net.nz> On Jan 28, 2005, at 6:48 AM, Rick L. Ratzel wrote: > Pro Grammer writes: > >> Hello, all, >> I am not sure if this is the right place to ask, but could you kindly >> tell me >> how to "load" a shared object (like libx.so) into python, so that the >> methods in >> the .so can be used? That too, given that the shared object was >> written in c++, >> compiled with g++ ? >> Thanks, >> Pro Grammer > > Will the dl standard library module help you? From the Python docs > at: > > http://docs.python.org/lib/module-dl.html As Simon Brunning notes, ctypes () is a robust alternative to the `dl' module. > Example: > >>>> import dl, time >>>> a=dl.open('/lib/libc.so.6') >>>> a.call('time'), time.time() > (929723914, 929723914.498) A note about this example: the `dl' call returns an integer as that is what the C time function returns. time.time() in Python is implemented in terms of C's gettimeofday, ftime or time depending on the platform. > I'm guessing that there might be some C++ issues, but maybe it's worth > looking into. As far as I am aware, neither dl nor ctypes natively support C++. This is a tricky matter, due to the lack of standards for C++ ABI's covering name mangling and vtable layout etc. See the thread starting at for more information. Regards, Mark Rowe From pierre.barbier at cirad.fr Fri Jan 14 03:41:47 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri, 14 Jan 2005 09:41:47 +0100 Subject: Unclear On Class Variables In-Reply-To: <41e77621$0$19576$636a15ce@news.free.fr> References: <41e77621$0$19576$636a15ce@news.free.fr> Message-ID: <41e7855f$0$31553$626a14ce@news.free.fr> Pierre Barbier de Reuille a ?crit : > Antoon Pardon a ?crit : > >>> Well I find this a confusing behaviour on python's part. The fact >>> that instance.field can mean something different, depending on >>> where in a statement you find it, makes the behaviour inconsistent. >>> >>> I know people in general here are against declarations, but declarations >>> could IMO provide more consistency here and thus more obvious behaviour. >> >> >> >> Well just to show how confusing python can be, the following piece of >> code. >> >> | class Spam: >> | eggs = [2, 3] >> | | | sp1 = Spam() >> | sp2 = Spam() >> | | print sp1.eggs, id(sp1.eggs) >> | print sp2.eggs, id(sp2.eggs) >> | print '--------------------' >> | | sp1.eggs += [4,] >> | >> | print sp1.eggs, id(sp1.eggs) >> | print sp2.eggs, id(sp2.eggs) >> | print '--------------------' >> | >> | Spam.eggs = [3,5] >> | >> | print sp1.eggs, id(sp1.eggs) >> | print sp2.eggs, id(sp2.eggs) >> | print '--------------------' >> >> Which produces: >> >> [2, 3] 1075958860 >> [2, 3] 1075958860 >> -------------------- >> [2, 3, 4] 1075958860 >> [2, 3, 4] 1075958860 >> -------------------- >> [2, 3, 4] 1075958860 >> [3, 5] 1075959084 >> -------------------- >> > > Well ... and could someone explain this behaviour ? > I don't catch it ! > > Pierre Ok, I think I got it ! I speak with friends working with Python too ... It seems that "a += l" if "a" and "l" are lists is equivalent to : a.extend(l) a = a The second line could seem meaningless but it is not ! Indeed, in the example above, the first "sp1.eggs" (the one with the extend) is a class variable but, the second "sp1.eggs" (the one before the "=") is an instance variable ! So, at the end, we append to get sp1.eggs and Spam.eggs references to the same structure. But sp1.eggs is an instance variable of sp1 and no more the class variable. To test that, it's possible to modify slightly the code with : |sp1.eggs += [4,] |del sp1.eggs Then, sp1.eggs still exists !!! But it's again the class variable ... Ok, back to the documentation ... In the doc, there is a special case for the use of "+=" with the class members. IMHO, this should not be !!! But, it says that : ob.a += b is translated into : ob.__setattr__( "a", ob.__getattr__("a").__iadd__(b) ) My opinion is : it would be much more simpler to explain than : a += b <=> a.__iadd__(b); a = a and not give any special case for class members. In both cases, the resulting behaviour is the same, but it would be less confusing. Then, this change of scope of variables in python is very very annoying. Both for new and old programmers (we have both in my lab ...). Well, I hope I got it write this time ... but this is a feature to fear !!! Pierre From apardon at forel.vub.ac.be Mon Jan 17 03:34:59 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Jan 2005 08:34:59 GMT Subject: (objects as) mutable dictionary keys References: Message-ID: Op 2005-01-14, Steve Holden schreef : > Antoon Pardon wrote: > >> Op 2005-01-14, Peter Maas schreef : >> >>>I have summarized the discussion about the usability of lists (and >>>and other mutable types) as dictionary keys and put it into the >>>Python wiki.URL: http://www.python.org/moin/DictionaryKeys. >>> >>>This summary might be used as a reference should the 'mutable >>>dictionary keys' issue come up again in c.l.py. >>> >> >> I had a look and I think you should correct the followingr: >> >> Dictionary lookup with mutable types like lists is a source of >> unpleasant surprises for the programmer and therefore impossible in >> Python. >> > Better, perhaps, to say: > > Dictionary lookup with mutable types like lists can be a > source of unpleasant surprises for the programmer and > therefore not recommended in Python. IOW Python discourages mutable types in any type of container. >> It is not impossible in Python. It may be discouraged but it is not >> impossible since I have already done so. >> > If I discouraged you from shooting yourself in the foot would you do > that too? If I chose not to shoot my self in the foot, it wouldn't be because you discouraged me. It would be because I heard good arguments. What are good arguments or bad and how much weight they have depends on the person and on the circumstances. So a simple rule like: Never use a mutable as a key in a dictionary will sometimes not be the best solution. -- Antoon Pardon From deetsNOSPAM at web.de Tue Jan 18 09:08:44 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 18 Jan 2005 15:08:44 +0100 Subject: generator expressions: performance anomaly? References: <377Hd.77904$Jk5.30235@lakeread01> <354gj7F4etgn8U1@individual.net> <354h9gF4fgsqgU1@individual.net> Message-ID: <354jhnF4gk8l6U1@individual.net> > My thoughts where to let the 'leftmost' section of the expression to be > intact so that any of the dynamic things done to this part, i.e. > replacing time.time with random.random are taken into consideration. > What can be done is to extract the expression into a loopless structure > > lst = list(time.time() for i in xrange(10)) > would be compiled to the bytecode version of: > lst = [time.time(), time.time(), time.time(), time.time() ...] > > Then time.time can do whatever it wants to. It's the (x)range function > that we need to enshure returns the same values in every execution. This > *IS* a useless feature, but I think it's possible to make it work. What makes the leftmost expression different from the iterable returning expression inside the for? The same arguments apply there. -- Regards, Diez B. Roggisch From maxm at mxm.dk Sat Jan 8 14:24:56 2005 From: maxm at mxm.dk (Max M) Date: Sat, 08 Jan 2005 20:24:56 +0100 Subject: Weekly Python Patch/Bug Summary In-Reply-To: References: Message-ID: <41e03383$0$284$edfadb0f@dread12.news.tele.dk> Kurt B. Kaiser wrote: > Remove witty comment in pydoc.py (2005-01-01) > CLOSED http://python.org/sf/1094007 opened by Reinhold Birkenfeld This is not a joke? :-) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From elephantum at dezcom.mephi.ru Mon Jan 10 12:13:25 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Mon, 10 Jan 2005 20:13:25 +0300 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> Message-ID: <34frdmF42p2jrU1@individual.net> Nick Coghlan wrote: > Abstract > -------- > The proposal is to add the capacity for statement local namespaces to > Python. This allows a statement to be placed at the current scope, while > the statement's 'setup code' is indented after the statement:: > > with: > I think using 'with' keyword can cause some ambiguity. for example I would surely try to write >>> x = a+b with self: >>> b = member and using with at the end of block brings more ambiguity: >>> stmt1() >>> stmt2() >>> with self: >>> member = stmt3() compare to: >>> stmt1() >>> stmt2() >>> with: >>> variable = stmt3() a way different semantics with just one word added/deleted. From air_jlin at yahoo.com Mon Jan 24 15:27:45 2005 From: air_jlin at yahoo.com (Johnny Lin) Date: 24 Jan 2005 12:27:45 -0800 Subject: Unbinding multiple variables In-Reply-To: References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> <35bnkeF4jpeetU1@individual.net> <1106334800.868412.27650@f14g2000cwb.googlegroups.com> <41f232b8.1514053864@news.oz.net> Message-ID: <1106598465.731935.237820@z14g2000cwz.googlegroups.com> thanks again for all the help! especially the advice on ideas of tracking down the memory leak :). (sorry for not mentioning it earlier...i had thought deleting everything might be a quick and dirty way short-term fix. :P) best, -Johnny From gandalf at geochemsource.com Fri Jan 21 09:22:48 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Fri, 21 Jan 2005 15:22:48 +0100 Subject: need help on generator... In-Reply-To: <63b5e209.0501210558.686f5c10@posting.google.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> Message-ID: <41F11038.1000903@geochemsource.com> Joh wrote: >hello, > >i'm trying to understand how i could build following consecutive sets >from a root one using generator : > >l = [1,2,3,4] > >would like to produce : > >[1,2], [2,3], [3,4], [1,2,3], [2,3,4] > > Do you mean: [1,2], [2,3], [3,4], [1,2,3], [2,3,4], [1,3,4] (E.g. all elements in the power set except the empty set, the sets with one element and the sets with all elements.) Otherwise, please describe your desired sets in verbal - I cannot see the point. From aurora00 at gmail.com Sun Jan 23 12:00:59 2005 From: aurora00 at gmail.com (aurora) Date: Sun, 23 Jan 2005 09:00:59 -0800 Subject: list unpack trick? References: Message-ID: On Sat, 22 Jan 2005 10:03:27 -0800, aurora wrote: > I am think more in the line of string.ljust(). So if we have a > list.ljust(length, filler), we can do something like > > name, value = s.split('=',1).ljust(2,'') > > I can always break it down into multiple lines. The good thing about > list unpacking is its a really compact and obvious syntax. Just to clarify the ljust() is a feature wish, probably should be named something like pad(). Also there is another thread a few hours before this asking about essentially the same thing. "default value in a list" http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/f3affefdb4272270 From aleaxit at yahoo.com Sun Jan 23 09:46:01 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 23 Jan 2005 15:46:01 +0100 Subject: Reload Tricks References: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> <1gqsb7j.1tbzcqn1f431kdN%aleaxit@yahoo.com> <1106489066.098048.212390@z14g2000cwz.googlegroups.com> Message-ID: <1gqumac.1azcimi14uzz30N%aleaxit@yahoo.com> Kamilche wrote: > Well, I look forward to seeing the new version. I have the old version > of the Python cookbook, it was very useful! I hope the new one is even better -- many more recipes, all updated to Python 2.3 and 2.4. The old one will remain useful for all those who need to keep using older versions of Python, though; to fit more recipes in, the historical discussions of how you did things with Python 1.5.2, 1.6, 2.0 etc have been ruthlessly snipped... Alex From steven.bethard at gmail.com Mon Jan 31 02:11:52 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 31 Jan 2005 00:11:52 -0700 Subject: a Python bug in processing __del__ method ?? In-Reply-To: References: <1107154011.859866.23480@z14g2000cwz.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Baoqiu Cui wrote: > >>The error returned is this: >> >>$ python bug.py >>Exception exceptions.AttributeError: "'NoneType' object has no >>attribute 'population'" in ><__main__.Person instance at 0xa0c9fec>> ignored >> >>However, if I rename variable name 'peter' to something like 'peter1' >>or 'david', the error is gone. Looks to me the >>error only happens to variable name 'peter'. >> >>Does anyone know what is wrong? Is this a bug only on Cygwin? > > it is not a bug, and the documentation has the answer: > > language reference -> index -> __del__ > > http://docs.python.org/ref/customization.html#l2h-175 > > Warning: Due to the precarious circumstances under which __del__() > methods are invoked, exceptions that occur during their execution are > ignored, and a warning is printed to sys.stderr instead. Also, when > __del__() is invoked in response to a module being deleted (e.g., > when execution of the program is done), other globals referenced by > the __del__() method may already have been deleted. For this reason, > __del__() methods should do the absolute minimum needed to > maintain external invariants. > > if you absolutely need to have reliable access to globals, you need to make > sure they're available as instance variables, or are bound in some other way. Along these lines, I think changing your code to: class Person(object): population = 0 def __del__(self): self.__class__.population -= 1 peter = Person() solves the problem. (At least it did for me.) Steve From manatlan_no_s_p_a_m at free.fr Mon Jan 31 17:23:46 2005 From: manatlan_no_s_p_a_m at free.fr (manatlan) Date: Mon, 31 Jan 2005 23:23:46 +0100 Subject: "Mail receiver server" Message-ID: <41feaff2$0$2068$626a14ce@news.free.fr> In an intranet/lan, i'd like to put a "python server script" (which run forever) on a computer A... On another computer B, I'd like to send smtp-email to the computer A ... (send to "user at 126.52.12.12", for example ...126.52.12.12 is the ip address of "B") in fact, i'd like to control "computer A" by sending smtp email from "computer B". What kind of server should i write on computer "B", a smtp server ? a pop server ? (i think i have to make a script which listen on a port, and execute some handlers ... but i don't know how to start) i know python very well, but i dont know anything about smtp/lan if you have a recipe to build this kind of server, it could be good but i'm pretty sure it can be easy to do ... From andre.roberge at gmail.com Sun Jan 23 07:29:22 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 23 Jan 2005 04:29:22 -0800 Subject: finding name of instances created In-Reply-To: References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> <1106397218.724722.172660@c13g2000cwb.googlegroups.com> Message-ID: <1106483362.505871.172050@z14g2000cwz.googlegroups.com> Nick Coghlan wrote: > Andr? wrote: > > So, students will be able to write: > > pete = CreateRobot(2, 3) > > pete.move() > > > > learning about objects and methods. > > > > As for things like > > for robot in robots: > > do stuff > > > > that will be for my use only: drawing robots on the screen, updating > > the 'world' when robots pick stuff up, etc. My intention is that the > > students will use the EXACT python syntax, so that they don't know that > > *I* have given a *name* to their robot(s) behind the scene. > > I have to cut this short; I hope it clarifies my intentions. > > My (and, if I understand him correctly, Jeremy's) concern would be that error > messages like "Robot 'pete' has hit a wall!" would give students the impression > that the robots automatically know their name as a result of the assignment. In > standard Python, that simply isn't true. > It was not my intention to reveal that I had assigned a 'name' to the robot; it was only for internal purpose. (However, see below) > If, instead, CreateRobot looked something like: > > def CreateRobot(street, avenue, name=None): > if name is None: > name = "Robot" + Robot.getNextNumber() > return Robot(street, avenue, name) > > > Then, using a simple assignment: > > pete = CreateRobot(2, 3) > pete.move() > > Would give an error like: > > "Robot1 has hit a wall" That might be an excellent way to solve my problem. > > This could then be used to point out that objects named using assignment don't > know about the names they have been given, and need to be told: > > pete = CreateRobot(2, 3, "Pete") > pete.move() > > "Pete has hit a wall" > > Instead of misleading the students ("objects know what names they have been > given"), you have taught them a powerful truth - objects and the names you give > them via assignment are entirely independent. Good point. > > It also directly addresses the question of aliasing. Think about how Steven's > modified dictionary would react to this code: > > pete = CreateRobot(2, 3) > dad = pete > dad.move() > pete.move() > > Internally, idioms like "for robot in robots" should be entirely unaffected - > the registration of the robot instance with the global list of robots can be > handled by the robot initialisation method. > You make some excellent points. What I implemented (last night) was the "code pre-processing" suggestion. Instead of simply "exec"uting the code, I changed it first so that statements like pete = CreateRobot(2, 3) john = CreateRobot() albert = CreateRobot(colour="blue") get translated to pete = CreateRobot(2, 3, name="pete") john = CreateRobot(name="john") albert = CreateRobot(colour="blue", name="albert") I just checked with: pete = CreateRobot() dad = pete dad.move() pete.move() and I got (I haven't implemented the gui part of dealing with multiple robots) == robot pete move() robot pete move() == which worked the same way as your method would (except with "pete" as a common name instead of "Robot1"). [As an aside, it was an *interesting* experience to learn enough about regular expressions to do this.] Now, after reading your post, I realise that I would have to deal with the problem of figuring out how to handle cases where the users has already given a name to the robot. Your solution takes care of this in a very simple way. Furthermore, I could probably base a lesson around it, about how instances have no name. Thank you very much for your suggestions. Andr? From cookedm+news at physics.mcmaster.ca Thu Jan 13 22:47:24 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Thu, 13 Jan 2005 22:47:24 -0500 Subject: Pyrex-0.9.3: definition mismatch with distutils of Python24 References: <41e6e1c5.8718906@news.muenster.de> Message-ID: mb at muenster.de (Martin Bless) writes: > Now that I've got my extension building machine using the VC++ Toolkit > 2003 up and running I'm keen on using Pyrex (Pyrex-0.9.3, > Python-2.4.0). > > But the definition of the swig_sources() method seems to have changed. > > When I try to build the examples from Pyrex I get a TypeError: > > > c:\Pyrex-0.9.3\Demos> python Setup.py build_ext --inplace > running build_ext > building 'primes' extension > [...] > File "C:\Python24\lib\distutils\command\build_ext.py", line 442, in > build_extension > sources = self.swig_sources(sources, ext) > TypeError: swig_sources() takes exactly 2 arguments (3 given) > > > I can see that Pyrex.Distutils.build_ext.py subclasses > distutils.command.build_ext.build_ext, and the number of arguments of > the swig_sources method seems to have changed. > > Pyrex uses: > > def swig_sources (self, sources): > > whereas the distutils use: > > def swig_sources (self, sources, extension): > > If I just add the "extension" arg to the Pyrex definitions everything > seems to work. But I have to admit that I don't really know what I'm > doing here and I feel sorry I can't contribute more than just > reporting the error. Yep, that's it. Greg must know now, it's been reported a few times. You'll want to change it to def swig_sources(self, sources, extension=None): so that if you use an older python it won't complain about missing arguments. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From newsgroups at jhrothjr.com Sat Jan 8 22:29:47 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 8 Jan 2005 21:29:47 -0600 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <41e09808.360402200@news.oz.net> Message-ID: <10u19a32e5affc1@news.supernews.com> "Bengt Richter" wrote in message news:41e09808.360402200 at news.oz.net... > On Sat, 08 Jan 2005 12:47:52 -0500, Peter Hansen > wrote: > >>Paul Rubin wrote: >>> When Unix was first written, people thought implementing an OS in C >>> was ludicrous. Everyone knew OS's had to be written in assembler. >> >>Actually, when Unix was first written that belief was entirely >>correct, and OSes *did* have to be written in assembler. >> >>That is, pure C did not have the capability to handle all >>that was required. I recall it taking a good decade before it >>became *common* to find C compilers with, for example, @interrupt >>support to let the compiler generate code that properly saved >>all registers and used RTI instead of RTS (or whatever it might >>have been called one one's particular flavour of CPU). >> >>Now, once you added a few tiny interrupt handlers, and some context >>switching (stack manipulation) routines, pretty much everything else >>*could* be done in C, but that doesn't invalidate the point. >> >>I think it's safe to say that none of pure C, pure Lisp, or pure Python >>are really capable of being used as the *sole* language to build >>an operating system. >> >>It's also safe to say that this is a largely irrelevant point. >>It would probably only be of academic interest to try to do >>something like that. Any practical attempt would not think more >>than twice of resorting to a little "glue" in assembler or in >>the form of "canned" byte sequences built by hand and stuck >>into the appropriate places in memory... > Well, usually there's more than one tool in the chain from source > to bootable loader and OS image, even if you are writing in C and > assembler, > and there's usually more to an OS than the bootable image contains. > > So ISTM "writing an OS in " is pretty loose talk ;-) Most people who work in the field know what it means, though. One of the touchstones of language design is whether you can write the compiler and runtime in that language. PyPy is working on that for Python, Squeak Smalltalk is written in Smalltalk and then converted to C for compilation of the runtime. Both of them are completely virtualizable: you can run them (very slowly) under themselves for testing. Given that everything in Python is an object, I see no reason why one couldn't create a set of objects that are appropriate for an operating system kernel and can also be converted cleanly to the operating system subset of C, and write a converter that does it. That's the easy part. The hard part is writing the operating system. Look at the (lack of) progress the GNU HURD project has been making recently. John Roth > > Regards, > Bengt Richter From erwin+usenet at andreasen.org Sun Jan 16 16:19:14 2005 From: erwin+usenet at andreasen.org (Erwin S. Andreasen) Date: Sun, 16 Jan 2005 22:19:14 +0100 Subject: Excel module for Python References: Message-ID: <87brbpdqct.fsf@andreasen.org> Simon Brunning writes: > On Wed, 12 Jan 2005 23:19:44 +0800, sam wrote: >> >> No, I don't use MS windows. I need to generate Excel file by printing >> data to it, just like Perl module Spreadsheet::WriteExcel. > If you need to write out formulae, formratting, that kind of thing, > then I think you'll need to write a 'real' Excel file. I don't have a > clue how to do that - sorry. There's actually an ancient open spreadsheet format called SYLK which is a step above CSV: it allows formatting of data, formulas etc. Google for SYLK to get the rather sparse specification (and skip over the first few links!) If you want to generate "real" Office files from UNIX, another alternative is to automate OpenOffice (which has a COM-like interface too) or generate OO XML files and feed them to OO asking to conver them with a bit of OO macro magic. -- =============================================================== Herlev, Denmark <*> =============================================================== From __peter__ at web.de Thu Jan 6 03:32:35 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 06 Jan 2005 09:32:35 +0100 Subject: No typical loops, and other crazy ideas References: Message-ID: Bulba! wrote: > motivation). I've tried to manipulate the data just in Python > and not in typical loops. One thing that may not be entirely A list comprehension is just a fancy way to write a loop. Resisting the temptation to use it can sometimes improve your code. > [Also, for some reason the advice by another poster, to > use: > > oldl=list(orig) > > instead of: > > oldl=[x for x in orig] > > ..somehow didn't work. The first instruction has produced only empty > lists.] > > > #---------Code follows----------- [...] > #oldl=list(orig) > #newl=list(orig) Because you used the same reader twice newl will always be empty. Peter From pushlinque at hotmail.com Tue Jan 11 23:13:08 2005 From: pushlinque at hotmail.com (Jane) Date: Tue, 11 Jan 2005 23:13:08 -0500 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> <1105497928.471241.13590@z14g2000cwz.googlegroups.com> Message-ID: "La bouche de la v?rit? - D?j? Vu Le Proph?te" wrote in message news:1105497928.471241.13590 at z14g2000cwz.googlegroups.com... > Your Uncle Wally just luuirrrrrrrrrrrrrvs > Monty Python -- especially John Clesse, Eric Idle > & Michael Palin -- very funny !!!!!!!! > > he he he ;-) Believe it or not, we have something in common! I love 'em, too! Jane > From sesquile at gmail.com Mon Jan 31 16:04:03 2005 From: sesquile at gmail.com (mh) Date: 31 Jan 2005 13:04:03 -0800 Subject: [ANN] Spike Asset Manager release 0.13 In-Reply-To: References: <1107196878.026930.154270@c13g2000cwb.googlegroups.com> Message-ID: <1107205443.213015.28550@z14g2000cwz.googlegroups.com> The idea is to have a framework to do this in a semi-crossplatform manner. The framework could be updated to know about apt, portage repositories as well as talk to to the windows registry. Not everyone is running redhat ;) From beliavsky at aol.com Sat Jan 29 09:53:09 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 29 Jan 2005 06:53:09 -0800 Subject: Coding style article with interesting section on white space References: Message-ID: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> Nick Coghlan wrote: > Thought some folks here might find this one interesting. No great revelations, > just a fairly sensible piece on writing readable code :) > > The whole article: > http://www.acmqueue.com/modules.php?name=Content&pa=showpage&pid=271&page=1 > > The section specifically on white space: > http://www.acmqueue.com/modules.php?name=Content&pa=showpage&pid=271&page=3 The suggestions in the cited article, "How Not to Write FORTRAN in Any Language", are reasonable but elementary and can be followed in Fortran 90/95/2003 as well as any other language. What infuriates me is that the author writes as if Fortran has not evolved since the 1960s. It has. To be specific, Fortran 90 (1) allows variable names up to 31 characters long (2) has a free source form where (a) there are no rigid rules about starting code in a certain column (b) white space is significant (3) has a full set of control structures -- goto's are almost never needed More detailed rebuttals of the article are in the archives of the Fortran 90 discussion group at http://www.jiscmail.ac.uk/cgi-bin/webadmin?A1=ind0501&L=comp-fortran-90 -- search for "Fortran bashing". Python looks more like Fortran 90 than one of the curly-brace/semicolon languages, and both languages have modules and array slices. One ought to do a little research before publishing an article. Apparently, many authors and editors are too lazy to do so. From aleaxit at yahoo.com Fri Jan 7 04:15:08 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 10:15:08 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: <1gq0k50.1ooqtco97v2sN%aleaxit@yahoo.com> Bulba! wrote: > Suppose they want to ensure "no forking" or that "bugfixes > and enhancements of original software are given back". > > OK, LGPL is fine for this goal. When you say "they see it Neither LGPL nor GPL can ``ensure "no forking"'', nor can any other open-source license. Alex From fccoelho at gmail.com Sun Jan 9 17:13:28 2005 From: fccoelho at gmail.com (Flavio codeco coelho) Date: 9 Jan 2005 14:13:28 -0800 Subject: Python serial data aquisition Message-ID: Hi, I am using pyserial to acquire data from an A/D converter plugged to my serial port. my hardware represents analog voltages as 12bit numbers. So, according to the manufacturer, this number will be stored in two bytes like this; |-------------bits(1-8)-----------| Byte1: x x x n1 n2 n3 n4 n5 Byte2: x n6 n7 n8 n9 n10 n11 n12 where x is some other information, and nx are the digits of my number. My problem is to how to recover my reading from these bytes, since pyserial gives me a character (string) from each byte... I dont know how to throw away the unneeded bits and concatenate the remaining bits to form a number... Fl?vio Code?o Coelho From steven.bethard at gmail.com Fri Jan 7 18:05:31 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Jan 2005 16:05:31 -0700 Subject: Notification of PEP Updates In-Reply-To: <41df128d.260695390@news.oz.net> References: <41df128d.260695390@news.oz.net> Message-ID: Bengt Richter wrote: > On Sat, 08 Jan 2005 03:28:34 +1000, Nick Coghlan wrote: > > >>I can't recall which thread this came up in, so I'm starting a new one. . . >> >>Barry Warsaw has kindly added a "peps" topic to the python-checkins mailing >>list. If you want to be notified only when PEP's get updated, then subscribe to >>python-checkins and edit your settings to select just the 'peps' topic. > > How does one get to editing one's settings? Go to the bottom of the page http://mail.python.org/mailman/listinfo/python-checkins under "Python-checkins Subscribers", fill in your email address and click "Unsubscribe or edit options". Fill in the "password" field on the next page and click "Log in". The topic option should be near the bottom of the page. Steve From fredrik at pythonware.com Sun Jan 30 02:40:15 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 30 Jan 2005 08:40:15 +0100 Subject: Coding style article with interesting section on white space References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com><1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> Message-ID: beliavsky at aol.com wrote: > The recent "Pystone Benchmark" message says that Python is only 75% as > fast on Linux as on Windows. no, it really only says that the Pystone benchmark is 75% as fast as Linux as on Windows, on the poster's hardware, using his configuration, and using different compilers. From apardon at forel.vub.ac.be Mon Jan 17 06:41:20 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Jan 2005 11:41:20 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-17, Steve Holden schreef : > Antoon Pardon wrote: > [...] >>>"A foolish consistency is the hobgoblin of little minds". Rules are made >>>to be broken. >> >> >> Like only use immutables as dictionary keys. >> > Fair enough, but don;t go advising newbies to do this. How about something like this. Because of the extra precautions one has to take when using mutables as hash keys, we advise newbies to stick with immutable keys until they have gathered enough knowledge and experience to adequatly weight the pro and cons of a mutable key solution against an immutable key solution. -- Antoon Pardon From steven.bethard at gmail.com Wed Jan 12 12:42:06 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 10:42:06 -0700 Subject: property () for Java Programmers ? In-Reply-To: References: Message-ID: michael wrote: > Hi there, > > I am somewhat confused by the following : > > class C(object): > def getx(self): return self.__x > def setx(self, value): self.__x = "extended" + value > def delx(self): del self.__x > x = property(getx, setx, delx, "I'm the 'x' property.") > > So far so good :-) But what to do with this now > > >>>>c = C >>>>c > > > >>>>dir (c) > > ['__class__', '__delattr__', '__dict__', '__doc__', > '__getattribute__', '__hash__', '__init__', '__module__', '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', > '__weakref__', 'delx', 'getx', 'setx', 'x'] > >>>>c.x > > > > > ?????? What can I do with this "property object" now. Well, if you actually want your getx/setx/delx to be called, then you need an *instance* of class C: py> c = C() py> c.x Traceback (most recent call last): File "", line 1, in ? File "", line 2, in getx AttributeError: 'C' object has no attribute '_C__x' py> c.x = "42" py> c.x 'extended42' py> del c.x py> c.x Traceback (most recent call last): File "", line 1, in ? File "", line 2, in getx AttributeError: 'C' object has no attribute '_C__x' Note that I used 'c = C()' instead of 'c = C' as in your code. STeve From elephantum at dezcom.mephi.ru Fri Jan 7 07:31:54 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Fri, 07 Jan 2005 15:31:54 +0300 Subject: embedded scripts debugging Message-ID: <347dpqF45nskbU1@individual.net> Hi all. I have custom resource editor and wish python to be scripting language in it. But I don't want to lose ability of debugging which I currently have implementing all logic in C++. So the question is: Is there suitable library for simple python gui debugger, or may be there are some other techniques for debugging embedded scripts? From dek at pabst.lbl.gov Wed Jan 12 19:19:47 2005 From: dek at pabst.lbl.gov (David E. Konerding DSD staff) Date: Thu, 13 Jan 2005 00:19:47 +0000 (UTC) Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: In article <1105569967.129284.85470 at c13g2000cwb.googlegroups.com>, Chris Lasher wrote: > Hello, > I have a rather large (100+ MB) FASTA file from which I need to > access records in a random order. The FASTA format is a standard format > for storing molecular biological sequences. Each record contains a > header line for describing the sequence that begins with a '>' > (right-angle bracket) followed by lines that contain the actual > sequence data. Three example FASTA records are below: Use biopython. They have dictionary-style classes which wrap FASTA files using indexes. http://www.biopython.org Dave From bulba at bulba.com Thu Jan 6 16:35:31 2005 From: bulba at bulba.com (Bulba!) Date: Thu, 06 Jan 2005 22:35:31 +0100 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 06 Jan 2005 08:39:11 GMT, Roel Schroeven wrote: >> If GPL folks had their way, it would not be possible not to "share" >> _anything_ you create. >That's generally the goal of the Free Software Foundation: they think >all users should have the freedom to modify and/or distribute your code. You have the freedom of having to wash my car then. ;-) >Most people who use the GPL don't feel that way; they think that each >author should have the freedom to choice if and how he chooses to share >code. Whatever they feel, GPL is designed in such a way that essentially is an attempt to extend itself onto all the software in the world. >They just see the GPL as an appropriate way to share their code. And why is that? Suppose they want to ensure "no forking" or that "bugfixes and enhancements of original software are given back". OK, LGPL is fine for this goal. When you say "they see it as appropriate way to share their code", there's nothing in this statement that openly and honestly indicates what is the goal of this method. >> It is widely acknowledged that GPL license has the "viral" aspect of >> extending itself on your software - can you point to closed-source >> licenses that would have this aspect? >Can you point to closed-source licenses that allow using the code *at >all*? Which code? _Their_ code? I.e. written by them? Back then in days of yore I was using C-tree DB library for some time, that came with source - or actually in practical terms "as source". My boss wrote quite a lot of nice C++ wrappings thanks to that (that I didn't bother to use, because I could not be bothered to learn C++ :-). They still sell it that way: http://www.faircom.com/products/ctree/ I don't remember being forbidden to redistribute source code of what _we_ wrote at the company. Just the redistribution of C-tree source code itself was not allowed. Redistribution of the compiled binary with the product was OK (and no royalties were required). >With GPL, you have the choice: either you agree with its terms on >distributing the code and then you can use the code, or you don't agree >with it and you don't use (which is still no worse than closed source). With all due respect, this is a universal statement that applies to all the licenses - obviously, if you don't agree to the terms, you can't use it. However, it's not aboot agreement to conditions per se, this is aboot the freedom of speech, err, this is aboot what those conditions actually are. >Some people call that viral, but I think it's a distortion of the truth. How so? If you combine source of your program with GPLed source, your source no longer can have the license of your choosing - it has to have GPL license, or at least contain the key GPL conditions. Other licenses do not require you to disclose _your_ source. It's a really, really weird world in which having to put "obnoxious advertising clause" is considered as more of imposing yourself on other people than requiring them to disclose your source. This is "money with strings attached" approach. It's just ignored for sake of Grand Goal that few people actually believe into, along the lines "end justifies means". OK, I rambled enough, this group should not degenerate into *.advocacy trash dump. :-) -- It's a man's life in a Python Programming Association. From simon.brunning at gmail.com Fri Jan 7 10:05:44 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Fri, 7 Jan 2005 15:05:44 +0000 Subject: countint words from an input string In-Reply-To: References: Message-ID: <8c7f10c605010707057e5b96a4@mail.gmail.com> On Fri, 7 Jan 2005 15:58:06 +0100, ?ystein Western wrote: > Try to write som code that will get an input string from the user. Futher > more, I'd like to have the program to count all the word the user has > written. > > Startet out like this: > > /------------- > s = raw_input("Write a text line") > print s.split() > /---------------- > > How can I count the words in the split function. print 'You've entered', len(s.split()), 'words.' BTW, though newbie questions are quite welcome here, you might find it beneficial to run through the Python tutorial (at http://docs.python.org/tut/tut.html and included in the standard distribution), and to join the tutor mailing list (at http://mail.python.org/mailman/listinfo/tutor/). -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From removethis.kartic.krishnamurthy at gmail.com Thu Jan 20 20:54:34 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Fri, 21 Jan 2005 01:54:34 GMT Subject: Print a string in binary format In-Reply-To: <1106270502.219126.322790@f14g2000cwb.googlegroups.com> References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> <1106270502.219126.322790@f14g2000cwb.googlegroups.com> Message-ID: neutrino said the following on 1/20/2005 8:21 PM: > Mmm, the output format that I want is like: > 0001110011111111000000001111111100000000.... > > I tried your code on Cygwin under Windows 2000, and on Linux, but it > prints out ASCII characters. > Aha..I guess I posted too soon. You might want to take a look at this cookbook entry: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300 Defines lambdas to convert integer to binary. The one you probably want is - >>> bstr = lambda n, l=16: n<0 and binarystr((2L<>1).lstrip('0')+str(n&1) or '0' >>> bstr(ord('a')) '1100001' --Kartic From boesi.josi at gmx.net Mon Jan 17 02:08:46 2005 From: boesi.josi at gmx.net (Alexander 'boesi' =?ISO-8859-1?Q?B=F6secke?=) Date: Mon, 17 Jan 2005 08:08:46 +0100 Subject: video analysis with python In-Reply-To: <20050116114407.GE3276@zoran.com> References: <20050116114407.GE3276@zoran.com> Message-ID: Hi Am 16.01.2005 12:44:27 schrieb Miki Tebeka: > 1. There is PyMedia (http://pymedia.org/) Is this library able to extract single images from a video? AFAICS it can only convert videos from one format to another. But I didn't try it, I've looked only in the docu. Maybe pyVideo (http://www.geocities.com/rtrocca/python/) would be a solution. But for me the AVIFile-Module doesn't work stable, it regularly crashes the python-interpreter. And there is a library for accessing DirectShow called PyDShowCam. cu boesi -- |?|/?/???\|?| |?|?| |?|/?/???\|????\|????| #1671 : icq-intern http://| / / /?\ | | | | | | / / /?\ | (?) | |??#73628288 : icq-extern smb://| \ \ \_/ | `?? | |__| \ \ \_/ | ? /| ?| boesi111 : aim ftp://|_|\_\___/|_|?|_|____|_|\_\___/|_|?? |_|? i171 : reallife From tim.peters at gmail.com Sun Jan 23 20:20:40 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 23 Jan 2005 20:20:40 -0500 Subject: Weakref.ref callbacks and eliminating __del__ methods In-Reply-To: <41F427EB.3000200@rogers.com> References: <41F427EB.3000200@rogers.com> Message-ID: <1f7befae0501231720428ca3c@mail.gmail.com> [Mike C. Fletcher] > I'm looking at rewriting parts of Twisted and TwistedSNMP to eliminate > __del__ methods (and the memory leaks they create). A worthy goal! > Looking at the docs for 2.3's weakref.ref, there's no mention of whether the > callbacks are held with a strong reference. A callback is strongly referenced from the weakref(s) containing it. > My experiments suggest they are not... i.e. I'm trying to use this pattern: > > class Closer( object ): > """Close the OIDStore (without a __del__)""" > def __init__( self, btree ): > """Initialise the closer object""" > self.btree = btree > def __call__( self, oldObject=None ): > """Regular call via self.close or weakref deref""" > if self.btree: > self.btree.close() > self.btree = None > class BSDOIDStore(oidstore.OIDStore): > def __init__( self, filename, OIDs = None ): > """Initialise the storage with appropriate OIDs""" > self.btree = self.open( filename ) > self.update( OIDs ) > self.close = Closer( self.btree ) > weakref.ref( self, self.close ) > > but the self.close reference in the instance is going away *before* the > object is called. It would really help to give a minimal example of self-contained executable code. I'm not sure how you're using this code, and guessing takes too long. My best brief guess is that it's equivalent to this: >>> class A: pass >>> a = A() >>> def f(*args): ... print "callback called" >>> import weakref >>> weakref.ref(a, f) >>> 2 2 >>> del a -- and the callback isn't called -- The "2" there is important, just because this is an interactive session. The point of it was to stop `_` from holding a reference to the created weakref. In your code weakref.ref( self, self.close ) the weakref itself becomes trash immediately after it's created, so the weakref is thrown away entirely (including its strong reference to self.close, and its weak reference to self) right after that line ends. Of course callbacks aren't *supposed* to be called when the weakref itself goes away, they're supposed to be called when the thing being weakly referenced goes away. So this all looks vanilla and inevitable to me -- the callback is never invoked because the weakref itself goes away long before self goes away. > So, this approach doesn't *seem* to work (the Closer doesn't get > called), so I can gather that the callbacks don't get incref'd (or they > get decref'd during object deletion). I'm pretty sure it's just because there's nothing here to keep the weakref itself alive after it's created. You could try, e.g., self.wr = weakref.ref( self, self.close ) to keep it alive, but things get fuzzy then if self becomes part of cyclic trash. > I can work around it in this particular case by defining a __del__ on > the Closer, but that just fixes this particular instance (and leaves > just as many __del__'s hanging around). I'm wondering if there's a > ready recipe that can *always* replace a __del__'s operation? In the presence of cycles it gets tricky; there's a lot of more-or-less recent words (less than a year old ) about that on python-dev. It gets complicated quickly, and it seems nobody can make more time to think about it. > I know I heard a rumour somewhere about Uncle Timmy wanting to eliminate > __del__ in 2.5 or thereabouts, Python 3 at the earliest. That's the earliest everything nobody can make time for lands <0.5 wink>. > so I gather there must be *some* way of handling the problem generally. The > thing is, weakref callbacks trigger *after* the object is deconstructed, while > __del__ triggers before... > must be something clever I'm missing. > > Throw an old doggie a bone? There are unresolved issues about how to get all this stuff to work sanely. The driving principle behind cyclic-trash weakref endcases right now is "do anything defensible that won't segfault". I'll note that one fairly obvious pattern works very well for weakrefs and __del__ methods (mutatis mutandis): don't put the __del__ method in self, put it in a dead-simple object hanging *off* of self. Like the simple: class BTreeCloser: def __init__(self, btree): self.btree = btree def __del__(self): if self.btree: self.btree.close() self.btree = None Then give self an attribute refererring to a BTreeCloser instance, and keep self's class free of a __del__ method. The operational definition of "dead simple" is "may or may not be reachable only from cycles, but is never itself part of a cycle". Cyclic gc won't call __del__ methods on objects *in* trash cycles, because there's no principled way to know in which order they should be called. But it's perfectly happy to invoke __del__ methods on trash objects reachable only from trash cycles (that are not themselves in a cycle). Applying this consistently can make __del__ methods much easier to live with: it doesn't matter then how many cycles your "real" objects are involved in, or how messy they are. The simple objects with the __del__ methods are not in cycles then, and so the cycles don't create any problems for them. When a weakref and its weak referent are both in cyclic trash, Python currently says "the order in which they die is undefined, so we'll pretend the weakref dies first", and then, as at the start of this msg, the callback is never invoked. The problem this avoids is that the callback may itself be part of cyclic trash too, in which case it's possible for the callback to resurrect anything else in cyclic trash, including the weakly-referenced object associated with the callback. But by hypothesis in this case, that object is also in cyclic trash, and horrible things can happen if a partially destructed object gets resurrected. So the real rule right now is that, if you want a guarantee that a callback on a weakly referenced object gets invoked, you have to write your code to guarantee that the referent becomes trash before its weakref becomes trash. (And note that if you do, the callback necessarily will be alive too, because a weakref does in fact hold a strong reference to its callback.) From rkern at ucsd.edu Wed Jan 12 13:25:12 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 12 Jan 2005 10:25:12 -0800 Subject: complex numbers In-Reply-To: References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: It's me wrote: > "Robert Kern" wrote in message > news:cs1mp9$sg9$1 at news1.ucsd.edu... > >>That's *it*. > > > So, how would you overload an operator to do: > > With native complex support: > > def twice(a): > return 2*a > > print twice(3+4j), twice(2), twice("abc") > > Let's presume for a moment that complex is *not* a native data type in > Python. How would we implement the above - cleanly? The way it's implemented now. See the file Object/complexobject.c for details. Numeric operations on ints, longs, floats, and complex numbers are all implemented using operator overloading. There's nothing special about the complex object. One can even remove it from the language quite easily. Some of the embedded versions of Python have in fact done so. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From hans at zephyrfalcon.org Sun Jan 23 12:28:12 2005 From: hans at zephyrfalcon.org (Hans Nowak) Date: Sun, 23 Jan 2005 12:28:12 -0500 Subject: how to write a tutorial In-Reply-To: <1106472508.591411.40140@c13g2000cwb.googlegroups.com> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > the first paragraph of 9.1 "A Word About Terminology" is epitome of > masturbation. The entire 9.1 is not necessary. > > Large part of 9.2 "Python Scopes and Name Spaces" is again > masturbatory. So I can just take a copy of the tutorial to the bathroom next time. Thanks for the tip, man! -- Hans Nowak http://zephyrfalcon.org/ From claird at lairds.us Fri Jan 14 14:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Fri, 14 Jan 2005 19:08:04 GMT Subject: Integration with java References: Message-ID: In article , Istvan Albert wrote: >Joachim Boomberschloss wrote: > >> the code is already written in Python, using the >> standard libraries and several extension modules > >One thing to keep in mind is that Jython does not >integrate CPython, instead it "understands" python code >directly. So if you have a C extension that works with python >it won't work with Jython. > >My feeling is that if you had a lot of Java code written and >wanted to build on that with python Jython would be a better >fit than vice versa. > >Istvan. There are other possibilities, though, including JPE . I recommend the original poster consider the latter. From nicolas.pourcelot at gmail.com Tue Jan 11 13:14:39 2005 From: nicolas.pourcelot at gmail.com (Nicolas Pourcelot) Date: Tue, 11 Jan 2005 19:14:39 +0100 Subject: exporting from Tkinter Canvas object in PNG Message-ID: <41E4178F.4050804@free.fr> Hello, I'm new to this mailing list and quite to Pyhon too. I would like to know how to export the contain of the Canvas object (Tkinter) in a PNG file ? Thanks :) Nicolas Pourcelot From luismgz at gmail.com Wed Jan 5 23:24:09 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 5 Jan 2005 20:24:09 -0800 Subject: is python more popular than coldfusion? References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dca575$0$14347$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1104985449.245498.215940@z14g2000cwz.googlegroups.com> > by the way, does anybody want to buy any coldfusion books :) I have Sam's Teach Yourself Coldfusion by Charles Mohnike, which I bought in 2001. By this time I used to think that I was learning rocket science the easy way, and thinking about learning php or asp was really scary... these codes looked very complex for my uninitiated eyes. However, It was good for grasping the logic of interacting with a database through sql and making my website dynamic. Soon I realized that finding a cheap CF hosting wasn't easy at all, and I started to read about php. Php is also for web development, but it gave me the basic knowledge to understand programming. However, I wanted to learn a more general purpose language and I don't remember how, I landed in pythonland. Let me tell you that I could learn python basics in just a few hours. Once I got the interpreter running, I couldn't stop! Just get one of the many tutorial available on the web and start playing. YOU'LL SEE IT'S ADDICTIVE. If you want to start from zero, I suggest Josh Cogliati's beginner tutorial. Another good introduction is A Byte of Python (google this), or any of the ones quoted in Python's web site. Learning Python is a good book too (especially the second edition). Enjoy! From sjmachin at lexicon.net Thu Jan 27 22:27:13 2005 From: sjmachin at lexicon.net (John Machin) Date: 27 Jan 2005 19:27:13 -0800 Subject: Why do look-ahead and look-behind have to be fixed-width patterns? In-Reply-To: References: Message-ID: <1106882833.528957.18120@c13g2000cwb.googlegroups.com> inhahe wrote: > Hi i'm a newbie at this and probably always will be, so don't be surprised > if I don't know what i'm talking about. > > but I don't understand why regex look-behinds (and look-aheads) have to be > fixed-width patterns. > > i'm getting the impression that it's supposed to make searching > exponentially slower otherwise > > but i just don't see how. > > say i have the expression (?<=.*?:.*?:).* > all the engine has to do is search for .*?:.*?:.*, and then in each result, > find .*?:.*?: and return the string starting at the point just after the > length of the match. > no exponential time there, and even that is probably more inefficient than > it has to be. But that's not what you are telling it to do. You are telling it to firstly find each position which starts a match with .* -- i.e. every position -- and then look backwards to check that the previous text matches .*?:.*?: To grab the text after the 2nd colon (if indeed there are two or more), it's much simpler to do this: >>> import re >>> q = re.compile(r'.*?:.*?:(.*)').search >>> def grab(s): ... m = q(s) ... if m: ... print m.group(1) ... else: ... print 'not found!' ... >>> grab('') not found! >>> grab('::::') :: >>> grab('a:b:yadda') yadda >>>>>> grab('a:b:c:d') c:d >>> grab('a:b:') >>> From http Sat Jan 22 16:25:10 2005 From: http (Paul Rubin) Date: 22 Jan 2005 13:25:10 -0800 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> <35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fpq0F4mh1ffU1@individual.net> Message-ID: <7xoefhtavd.fsf@ruckus.brouhaha.com> Daniel Bickett writes: > In my (brief) experience with YAML, it seemed like there were several > different ways of doing things, and I saw this as one of it's failures > (since we're all comparing it to XML). YAML looks to me to be completely insane, even compared to Python lists. I think it would be great if the Python library exposed an interface for parsing constant list and dict expressions, e.g.: [1, 2, 'Joe Smith', 8237972883334L, # comment {'Favorite fruits': ['apple', 'banana', 'pear']}, # another comment 'xyzzy', [3, 5, [3.14159, 2.71828, []]]] I don't see what YAML accomplishes that something like the above wouldn't. Note that all the values in the above have to be constant literals. Don't suggest using eval. That would be a huge security hole. From mambuhl at earthlink.net Fri Jan 28 19:09:17 2005 From: mambuhl at earthlink.net (Martin Ambuhl) Date: Fri, 28 Jan 2005 19:09:17 -0500 Subject: what's OOP's jargons and complexities? In-Reply-To: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> Message-ID: <3602hiF4tvskbU1@individual.net> Xah Lee wrote his usual masturbatory crap: Lisp is not topical in 3 of the 5 newsgroups you spewed on. Java is not topical in 5 of the 5 newsgroups you spewed on. Get your head out your butt and post to Java newsgroups if you want and they'll have you. Are you inflicting this crap on the rest of us because the Java people know you to be a troll? Followup-to set to comp.lang.java.advocacy where it might belong. From rnd at onego.ru Tue Jan 4 16:20:18 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 5 Jan 2005 00:20:18 +0300 (MSK) Subject: Optional Static Typing: Part II In-Reply-To: <10tluavnqqufg07@news.supernews.com> References: <10tluavnqqufg07@news.supernews.com> Message-ID: On Tue, 4 Jan 2005, John Roth wrote: >Guido has posted a second blog entry on the optional static typing >initiative. >I like this a lot better than the first. Declarative approach is even more human-oriented than algorithmic one. If Python is to support declarations, let it support declarative programming paradigm with full-blown inference engine . So, why not add some logic approach to type declarations? I hope that "type" is understood in a generic programming way: it will be a big win for Python to provide grounds for GP 'concept' concept ;) Why not? Python program right now are nearer to GP than C++'s. 'Concept' is not mere "interface", but interface + semantic behaviour. And to describe that behaviour logic is needed (right now it could be done with asserts). I propose to skip 'interface' support with Python and go stright to GP concepts :> This way Python will be ahead with innovation and type/interface/concept declarations will not be seen as atavisms but a step forward from OOP. I hope GvR waited so long not implementing interfaces to implement something better, concepts for example ;-) Right now concepts are expressed informally in the docstrings. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From rogerb at rogerbinns.com Tue Jan 18 02:46:33 2005 From: rogerb at rogerbinns.com (Roger Binns) Date: Mon, 17 Jan 2005 23:46:33 -0800 Subject: [ANN] iCalendar package 0.9 References: <41ebd292$0$253$edfadb0f@dread12.news.tele.dk> Message-ID: <9grub2-rvf.ln1@home.rogerbinns.com> "Max M" wrote in message news:41ebd292$0$253$edfadb0f at dread12.news.tele.dk... > http://www.mxm.dk/products/public/ical/ > > Any feedback would be welcome. How well do you cope with the crud that real programs generate? Does it work with the different dialects uses out there? Can it at least identify them? The reason why I ask is this would be useful for BitPim. When I wrote the code for doing vCards, I soon found that there wasn't actually a single program out there on Windows, Linux or Mac that actually generated 100% standards conformant vCards. They generally complied with the spirit, but screwed up character encoding, misspelled fields names, didn't do the right thing when commas and semi-colons were present in values etc. I assume the thing happens with ical. Roger From bill.mill at gmail.com Wed Jan 19 22:33:56 2005 From: bill.mill at gmail.com (Bill Mill) Date: Wed, 19 Jan 2005 22:33:56 -0500 Subject: list item's position In-Reply-To: References: Message-ID: <797fe3d405011919335c6c181f@mail.gmail.com> 2 solutions: In [98]: bars = ["str", "foobaz", "barbaz", "foobar"] In [99]: for bar in bars: ....: if 'bar' in bar and 'baz' in bar: ....: print bar ....: print bars.index(bar) ....: barbaz 2 In [100]: for i in range(len(bars)): .....: if 'bar' in bars[i] and 'baz' in bars[i]: .....: print bars[i] .....: print i .....: barbaz 2 The first one is slow and pretty, the second one is fast and (a bit) ugly. I believe that you should avoid range(len(x)) when you can, but use it when you need to know the index of something without an additional x.index() call. Peace Bill Mill bill.mill at gmail.com On Wed, 19 Jan 2005 22:04:44 -0500, Bob Smith wrote: > Hi, > > I have a Python list. I can't figure out how to find an element's > numeric value (0,1,2,3...) in the list. Here's an example of what I'm doing: > > for bar in bars: > if 'str_1' in bar and 'str_2' in bar: > print bar > > This finds the right bar, but not its list position. The reason I need > to find its value is so I can remove every element in the list before it > so that the bar I found somewhere in the list becomes element 0... does > that make sense? > > Thanks, > > Bob > -- > http://mail.python.org/mailman/listinfo/python-list > From stephane.bronsart at bea.be Fri Jan 28 08:37:38 2005 From: stephane.bronsart at bea.be (StepH) Date: Fri, 28 Jan 2005 14:37:38 +0100 Subject: How to test that an exception is raised ? References: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> Message-ID: <41fa400b$0$2029$6c56d894@feed0.news.be.easynet.net> Thanks for you answer. I'm new to Python (coming from C/C++). > > But i've prob with the 1st test : test_badFile. > > When I run the test, unittest say that no error is Raised. > > But when I run the mps2xml module with a bad file as arg., the exception > > is > > well Raised. > > I assume you don't actually see the exception (you don't see the stack > traceback printed as an output) but you just see your own message > "FileError". That means that the exception was raised and caught by your > try-except statement. Yes, when i'm run mps2xml.py with a bad filename as arg., the IOError is launched and is correctly intercepted. > > > What i'm doing wrong ? > > > > It is because the exception in catched in the mps2xml module ? > > With the above mentioned assumption, that must be it. Once the exception is > caught, it is caught and no other code invoking mps2xml.mps2xml (including > the assertRaises in your test) will see the exception. Do you say that it's not possible to test (using unittest) if an exception is well raised if the tested code catch it ? How to solve this paradoxe ? How to automaticaly test such code ? > > Your mps2xml.mps2xml function should return a value indicating success or > failure or should re-raise the exception. 1./ Cheking error-return value if not a good idea for me, cause this make the code less clear. I don't want a code where i've to test each function return value... 2./ If I re-raise the exception, then how to not show the traceback. My user will became crazy if they view such error msg. > You need a mechanism to let > invoking code know that it was successful or it failed. With a return code, > you should test that and not the exception. The assert you use should work > if you re-raise the exception. > > And BTW, it is a bad idea to use a generic "except" statement like you do. > That catches ALL the exceptions and you will never know if a different > exception than IOError was raised. You should catch only IOError > specifically or any other exception that you may expect. You can add then > an extra "except" statement catching all the other exceptions, but only if > it is essential for your application to handle all exceptions gracefully > instead of just exiting with a stack traceback. It seems that there is 2 school here. I've read a lot on python, and somed 'guru' Python say that it's maybe better to use exception even for case you can "predict", no ? Or i'm completly wrong ? > > > Thanks for your helps. > > > > StepH. > > > > Thanks again. StepH. > > From littlejohn.75 at news.free.fr Fri Jan 28 10:41:49 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 28 Jan 2005 15:41:49 GMT Subject: Dynamic class methods misunderstanding References: Message-ID: <41fa5d3d$0$2024$626a14ce@news.free.fr> Le Fri, 28 Jan 2005 10:20:30 -0500, Bill Mill a ?crit : > Hello all, > > I have a misunderstanding about dynamic class methods. I don't expect > this behavior: > > In [2]: class test: > ...: def __init__(self, method): > ...: self.method = method > ...: self.method() > ...: > > In [3]: def m(self): print self > ...: > > In [4]: test(m) > --------------------------------------------------------------------------- > exceptions.TypeError Traceback (most recent call > last) > > /cygdrive/c/Documents and Settings/Wmill/ > > /cygdrive/c/Documents and Settings/Wmill/ in __init__(self, method) > > TypeError: m() takes exactly 1 argument (0 given) > ----------------------------------------------------------------------------- > > Why doesn't m get the implicit self parameter in the self.method() > call? How would I make it a proper member of the class, so that a > self.method() call would work with the above "m" function? The "def m(self):" was not properly indented. So here, "m" is a module level function, not a method of your class. > > Peace > Bill Mill > bill.mill at gmail.com From ajsiegel at optonline.com Sat Jan 22 09:36:55 2005 From: ajsiegel at optonline.com (Arthur) Date: Sat, 22 Jan 2005 09:36:55 -0500 Subject: Zen of Python References: <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> Message-ID: On 21 Jan 2005 20:32:46 -0800, Paul Rubin wrote: >Of course in that case, since the absence of lexical scope was a wart >in its own right, fixing it had to have been on the radar. So turning >the persistent listcomp loop var into a documented feature, instead of >describing it in the docs as a wart that shouldn't be relied on, >wasn't such a hot idea. Adding lexical scope and listcomps at the >same time might have also been a good way to solve the issue. Most of us go about our business without a fine grained reading of the documentation. I don't think I would be unusual in having learned about listcomp lakkage by tracing a hard to fathom bug to its source. I can't say I understood at that point that for loops *do* leak. But apparently *did* understand intutively that I shouldn't rely on it not doing so. because I chose my local variable names in a way that I couldn't get hurt in any case My intution apparently felt safe in doing otherwise in the vicinity of a list comp, which is how I got burnt. The fact is there was carelessness in the code that surrounded the bug. But it was carelessness of the kind that would, in the absence of list com leakage, have led to an easy to recgnize error message and a quick fix. Nobody likes to hear coulda, shoulda s for done deals. But the issue is an a basic one, in some sense, it seems to me. The question around decorators did not seem too dissimilar. There was those would thought that a better solution to the problem being addressed would most likely naturally present itself further down the road as Python evolved. And that inaction at this time was the best action. Or that a solution should be found that addressed that issue, toigether with related issues, in a way that was less of a "best to to done under the cirucmstances as of now", before a trigger was pulled. woulda, coulda shoulda. Art From reinhold-birkenfeld-nospam at wolke7.net Thu Jan 13 16:43:35 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 13 Jan 2005 22:43:35 +0100 Subject: reference or pointer to some object? In-Reply-To: References: Message-ID: <34o8c7F4ctefqU1@individual.net> Torsten Mohr wrote: > Hi, > >> Could you give us a more concrete use case? My suspicion is that >> anything complicated enough to be passed to a method to be modified will >> probably be more than a simple int, float, str or tuple... In which >> case, it will probably have methods to allow you to update it... > > yes, to be more explicit: I'm quite new to python and i wrote > a small function that does a hexdump of a string. That string > can be quite large, so i suspected a large overhead when the > string would be copied and handed over to the function. It isn't. > But i think my understanding was wrong (though it is not yet > clear). If i hand over a large string to a function and the > function had the possibility to change it, wouldn't that mean > that it is necessary to hand over a _copy_ of the string? > Else, how could it be immutable? You cannot modify a string. Notice that there are no in-place string methods -- str.strip() for example returns a new string. > Thinking about all this i came to the idea "How would i write > a function that changes a string with not much overhead?". Basically, working with very large strings is costly (it saves overhead otherwise). So do make smaller parts and operate on these chunks. > def func(s): > change s in some way, remove all newlines, replace some > charaters by others, ... > return s > > s = func(s) > > This seems to be a way to go, but it becomes messy if i hand over > lots of parameters and expect some more return functions. You can use tuples for that. Automatic tuple packing helps: def func(x, y): # change x, y and generate z return x, y, z x, y, z = func(x, y) > Maybe it is because i did lots of perl programming, but > > func(\$s) looks easier to me. It does, but in fact the problem is not that the string is passed by value, but that the string is not modifiable... Reinhold From mcturra2000 at yahoo.co.uk Tue Jan 4 11:15:57 2005 From: mcturra2000 at yahoo.co.uk (Mark Carter) Date: Tue, 04 Jan 2005 16:15:57 +0000 Subject: How can engineers not understand source-code control? In-Reply-To: <41dabba1$0$47624$ed2619ec@ptn-nntp-reader02.plus.net> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41da713a$0$610$ed2619ec@ptn-nntp-reader03.plus.net> <41dabba1$0$47624$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <41dac13a$0$44959$ed2e19e4@ptn-nntp-reader04.plus.net> Mark Carter wrote: > I'm thinking that the I-Ching is a vast untapped resource for > programming wisdom, plus it makes it funny. Well, carrying on in the same frivilous and some might say off-topic mood, I did a bit of a Google, and found that you can generate your very own I-Ching reading: http://www.grillet.co.uk/iching/ According to the link at: http://www.grillet.co.uk/iching/casting.html "The I Ching is a good guide in taking decisions when you have no rational basis on which to take them." So if your project manager comes out with something like "A pot upturned to empty the decay. The superior one attends to the Way of Heaven.", you'll know whence he's distilling his madness. From stephen.thorne at gmail.com Tue Jan 25 22:33:03 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Wed, 26 Jan 2005 13:33:03 +1000 Subject: Python with no significant whitespace In-Reply-To: <35oh4gF4nvvfoU1@individual.net> References: <35oh4gF4nvvfoU1@individual.net> Message-ID: <3e8ca5c8050125193346f643cc@mail.gmail.com> On Wed, 26 Jan 2005 11:31:18 +0800, mep wrote: > Hi,all > Is there anybody trying to release a modification version to current > python source code with no significant whitespace, say replacing whitespace > by {} > like C or java. I do *NOT* mean whitespace is good or bad, just > want to know. http://logix.livelogix.com/ don't know why you'd bother tho. any competant programmer already indents code exactly like python requires you to. Stephen From steven.bethard at gmail.com Wed Jan 12 17:31:13 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 15:31:13 -0700 Subject: reference or pointer to some object? In-Reply-To: References: Message-ID: Torsten Mohr wrote: > I still wonder why a concept like "references" was not > implemented in Python. I think it is (even if small) > an overhead to wrap an object in a list or a dictionary. > > Isn't it possible to extend Python in a way to use > real references? Or isn't that regarded as necessary? IMHO it's not really necessary. As long as you're passing a mutable object around, when you call one of its methods, the object will be changed. So the only time you'd want a "reference" is if you were passing around an immutable object (e.g. an int, float, str or tuple) and you wanted to change it. The thought of changing an immutable object seems kind of silly to me. ;) Could you give us a more concrete use case? My suspicion is that anything complicated enough to be passed to a method to be modified will probably be more than a simple int, float, str or tuple... In which case, it will probably have methods to allow you to update it... In my case, rather than your original example, which you want to look something like: def func(x): x += 123 x = 5 func(x) I'd just write: x = 5 x += 123 =) Steve From klapotec at chello.at Tue Jan 4 12:07:18 2005 From: klapotec at chello.at (Christopher Koppler) Date: Tue, 04 Jan 2005 17:07:18 GMT Subject: How can engineers not understand source-code control? References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41da713a$0$610$ed2619ec@ptn-nntp-reader03.plus.net> <41dabba1$0$47624$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: On Tue, 04 Jan 2005 15:52:03 +0000, Mark Carter wrote: > ;; This buffer is for notes you don't want to save, and for Lisp evaluation. > ;; If you want to create a file, first visit that file with C-x C-f, > ;; then enter the text in that file's own buffer. Now, _where_ have I seen that before? > I'm thinking that the I-Ching is a vast untapped resource for > programming wisdom, plus it makes it funny. Or haikus, maybe they'd be > good. If only all error messages were like that: Through winter's freezing Nature dies to live again You need to debug -- Christopher 99 bottles of Snakebite on the wall... From fredrik at pythonware.com Sat Jan 22 09:14:26 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 15:14:26 +0100 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com><41EE24F7.7030303@jessikat.fsnet.co.uk><7x1xchlpqv.fsf@ruckus.brouhaha.com><41efeb82$0$27807$9b622d9e@news.freenet.de><41f1a70b$0$25959$9b622d9e@news.freenet.de><7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Martin, do you know more about this? I remember being disappointed > about the decisions since I had done some work on a new block cipher > API and I had wanted to submit an implementation to the distro. But > when I heard there was no hope of including it, I stopped working on > it. "I'll only work on stuff if I'm sure it's going right into the core" isn't exactly a great way to develop good Python software. I recommend the "would anyone except me have any use for this?" approach. From reed at intersiege.com Sat Jan 22 04:18:37 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Sat, 22 Jan 2005 04:18:37 -0500 Subject: introducing a newbie to newsgroups Message-ID: Super Sorry for the extra traffic. ;-) From tmohr at s.netic.de Mon Jan 10 14:38:50 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Mon, 10 Jan 2005 20:38:50 +0100 Subject: Referenz auf Variable an Funktion =?utf-8?b?w7xiZXJnZWJlbj8=?= Message-ID: Hallo, ich m?chte eine Funktion schreiben, der ich eine Referenz auf einen String ?bergeben kann und die dann einige ?nderungen am String vornimmt. In Perl w?rde ich also ein \$string ?bergeben und in der Funktion auf $$string zugreifen. Geht sowas auch in Python? Ich habe von "global" gelesen, das scheint dem was ich suche am n?chsten zu kommen, allerdings trifft es das Problem auch nicht, da ich von einer Unterfunktion aus eine Unterfunktion aufrufen m?chte, also tief verschachtelt. Und global greift nach meinem Verst?ndnis auf den ganz globalen Namensraum zu und nicht auf den der aufrufenden Funktion. Geht sowas vielleicht mit weakref? Danke f?r Tipps, Torsten. From phr at localhost.localdomain Wed Jan 26 07:27:57 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Wed, 26 Jan 2005 12:27:57 GMT Subject: OT References: <35pge0F4pkd7gU1@individual.net> Message-ID: "Diez B. Roggisch" writes: > > Is this a problem with my dns? > > Most probably - he shows up as phr at localhost.localhost for me. It's my news client configuration. Normally I post from a different machine but that one is temporarily down. I haven't bothered to configure this one properly because I didn't expect to have to be using it this long. I don't want to keep posting from this machine for long, so if the other machine is going to stay down, I'll figure out some other alternative. Sorry for this weirdness. --Paul From martin at v.loewis.de Sun Jan 16 06:40:45 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 16 Jan 2005 12:40:45 +0100 Subject: why are some types immutable? In-Reply-To: References: Message-ID: <41ea52bd$0$3354$9b622d9e@news.freenet.de> Torsten Mohr wrote: > reading the documentation (and also from a hint from this NG) > i know now that there are some types that are not mutable. > > But why is it this way? There are various reasons, some apply for some types, and some for others: - immutable objects are hashable - their hash value will not change during their life time (if it is a container, the contained objects also need to be hashable). Mutable types are typically not hashable. A type needs to be hashable to act as a dictionary key. - immutable objects can be shared, allowing the same reference to be used in multiple places. For mutable objects, one often needs to make a copy of the object before storing it. - immutable types can often be implemented more efficiently. For examples, the length of a tuple is fixed, as tuples are immutable. Therefore, memory management for tuples is simpler (they only require one memory block, instead of two, as lists do). - for some types, the expectation of immutability is so common that people would complain massively if they were mutable. This, in particular, applies to numbers - people expect that after x = 7 the variable x keeps the value, and that the "7" object cannot suddenly change its value to 8. > From an overhead point of view i think it is not optimal, > for example for a large string it could be much faster to > have it changed in place, not generating a new one for > every step in a change. For strings, the following points apply; as a net result, the overhead is *less* than it would be if strings were mutable: - strings must be hashable, so they can be used as a dictionary key. If you would modify, say, len.func_name, then newly imported code could not find the len function anymore. It would be possible to solve this by introducing an additional immutable identifier type, but then you would need to create copies of strings (to create identifier object). Many applications might break which currently use strings as dictionary keys. - strings are currently assumed to be shareable. You pass strings to functions which then store the strings in global variables, object attributes, etc. In all these places, copies would need to be made if strings were mutable, since the caller might chose to modify the string afterwards. - immutable strings consume less memory than mutable strings would, because a string is made up of just one memory block. Regards, Martin From steven.bethard at gmail.com Tue Jan 25 19:49:42 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Jan 2005 17:49:42 -0700 Subject: Where can I find Mk4py.dll for python24 ? In-Reply-To: <11e94203.0501251626.7988599b@posting.google.com> References: <11e94203.0501251626.7988599b@posting.google.com> Message-ID: Jose Rivera wrote: > I installed the new release and I have not been able to make work metakit. > > Please give me some help to enjoy metakit and python 24. Repeating your request every 10 minutes is not likely to get you help quicker. On the contrary, it's more likely to make people ignore your threads. Wait patiently, and if someone knows the answer to your question, it's quite likely that they'll answer it. Steve From bokr at oz.net Tue Jan 25 04:57:15 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 25 Jan 2005 09:57:15 GMT Subject: Classical FP problem in python : Hamming problem References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> Message-ID: <41f6162f.1768893674@news.oz.net> On 25 Jan 2005 08:30:03 GMT, Nick Craig-Wood wrote: >Francis Girard wrote: >> def hamming(): >> def _hamming(): >> yield 1 >> hamming2 = hammingGenerators[0] >> hamming3 = hammingGenerators[1] >> hamming5 = hammingGenerators[2] >> for n in imerge(imap(lambda h: 2*h, iter(hamming2)), >> imerge(imap(lambda h: 3*h, iter(hamming3)), >> imap(lambda h: 5*h, iter(hamming5)))): >> yield n >> hammingGenerators = tee(_hamming(), 4) >> return hammingGenerators[3] > >If you are after readability, you might prefer this... > >def hamming(): > def _hamming(): > yield 1 > for n in imerge(imap(lambda h: 2*h, iter(hamming2)), > imerge(imap(lambda h: 3*h, iter(hamming3)), > imap(lambda h: 5*h, iter(hamming5)))): > yield n > hamming2, hamming3, hamming5, result = tee(_hamming(), 4) > return result > >PS interesting thread - never heard of Hamming sequences before! Are the long words really that helpful? def hamming(): def _hamming(): yield 1 for n in imerge(imap(lambda h: 2*h, iter(hg2)), imerge(imap(lambda h: 3*h, iter(hg3)), imap(lambda h: 5*h, iter(hg5)))): yield n hg2, hg3, hg5, result = tee(_hamming(), 4) # four hamming generators return result Regards, Bengt Richter From duncan.booth at invalid.invalid Sun Jan 30 06:28:45 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Jan 2005 11:28:45 GMT Subject: naive doc question References: Message-ID: Gabriel B. wrote: > Is it just me that can't find a full reference in the docs? > > I wanted a list of all the methods of dict for example... where can i > find it? > > Thanks, and sorry if this question is just dumb, i really can't find > it If you want to find out about all the methods of dict then try: lib\pydoc.py dict from a shell prompt, or >>> help(dict) from the interactive interpreter. The catch is that many of the methods that will be shown aren't really relevant to dictionaries, so you will need to ignore the irrelevant ones. Run pydoc interactively ('lib\pydoc.py -g') or as a web-server if you want to get the output as strangely coloured html. e.g. 'lib\pydoc.py -p 8081' then point your browser at 'http://localhost:8081/dict' for help on the dict type. (Pick a different port number if 8081 is used on your machine.) http://localhost:8081/__builtin__ is a good starting point to browse the builtin types, and http://localhost:8081/ will give you an index of all the modules installed on your system. From simon.brunning at gmail.com Thu Jan 13 07:41:39 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Thu, 13 Jan 2005 12:41:39 +0000 Subject: Unclear On Class Variables In-Reply-To: References: Message-ID: <8c7f10c605011304411cf84b79@mail.gmail.com> On 13 Jan 2005 07:18:26 EST, Tim Daneliuk wrote: > I am a bit confused. I was under the impression that: > > class foo(object): > x = 0 > y = 1 > > means that x and y are variables shared by all instances of a class. > But when I run this against two instances of foo, and set the values > of x and y, they are indeed unique to the *instance* rather than the > class. I can see why you might think that: >>> class Spam(object): ... eggs = 4 ... >>> spam = Spam() >>> spam2 = Spam() >>> spam.eggs 4 >>> spam2.eggs 4 >>> spam.eggs = 2 >>> spam.eggs 2 >>> spam2.eggs 4 But you are being mislead by the fact that integers are immutable. 'spam.eggs = 2' is *creating* an instance member - there wasn't one before. Have a look at what happens with a mutable object: >>> class Spam(object): ... eggs = [3] ... >>> spam = Spam() >>> spam2 = Spam() >>> spam.eggs [3] >>> spam2.eggs [3] >>> spam.eggs.append(5) >>> spam.eggs [3, 5] >>> spam2.eggs [3, 5] -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From tim.peters at gmail.com Sun Jan 16 01:42:51 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 16 Jan 2005 01:42:51 -0500 Subject: python mode indentation problem In-Reply-To: <1105842678.044409.270450@z14g2000cwz.googlegroups.com> References: <1105802644.939051.229990@f14g2000cwb.googlegroups.com> <1105842678.044409.270450@z14g2000cwz.googlegroups.com> Message-ID: <1f7befae05011522422fce0cf3@mail.gmail.com> [Xah Lee] ... > ? who the fuck coded the python mode in emacs? The major contributors are listed at the top of python-mode.el. > fuckhead please peruse: > ? http://xahlee.org/UnixResource_dir/writ/responsible_license.html OK, I read it, but have no idea what point you're trying to make here. If, for example, you want to re-release it under a license saying you take financial responsibility for any behavior a user dislikes, be my guest. From fred at adventistcare.org Wed Jan 19 15:52:53 2005 From: fred at adventistcare.org (Sells, Fred) Date: Wed, 19 Jan 2005 15:52:53 -0500 Subject: a question Message-ID: <777056A4A8F1D21180EF0008C7DF75EE0331729D@sunbelt.org> I would use something like cmd = '%s/mos user wmarch, ' % mosbin cmd += 'cd /fa/wm/%s/%s, ' % (jaar, filetype) cmd += ... which reveals that you don't have enough args to satisfy all the %s's -----Original Message----- From: Nader Emami [mailto:emami at knmi.nl] --snip-- I have a long command in Unix and I have to use os.system(cmd) statement. I do the following: cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s, chmod 644 %s' % (mosbin, jaar, filetype, filetype) status = os.system(cmd) This is not very clear, and I have to break this long line in two segment by means of the next character '\' : cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s, \ chmod 644 %s' % (mosbin, jaar, filetype, filetype) But in this case I get a syntax error! I don't know how I can solve this problem. Could somebody tell me about this? With regards, Nader (this -- http://mail.python.org/mailman/listinfo/python-list From robin at SPAMREMOVEjessikat.fsnet.co.uk Wed Jan 19 04:14:31 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Wed, 19 Jan 2005 09:14:31 +0000 Subject: rotor replacement In-Reply-To: <7x1xcidnp1.fsf@ruckus.brouhaha.com> References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> Message-ID: <41EE24F7.7030303@jessikat.fsnet.co.uk> Paul Rubin wrote: > "Reed L. O'Brien" writes: > >>I see rotor was removed for 2.4 and the docs say use an AES module >>provided separately... Is there a standard module that works alike or >>an AES module that works alike but with better encryption? > > > If you mean a module in the distribution, the answer is no, for > political reasons. > .....I'm also missing the rotor module and regret that something useful was warned about and now removed with no plugin replacement. I had understood that this was because rotor was insecure, but you mention politics. Are other useful modules to suffer from politics? What exactly are/were the political reasons for rotor removal? I might add that the source for rotormodule is still easily obtainable and can be compiled trivially as an extension for Python-2.4. Does the Python community take a position on the sources of removed modules? -- Robin Becker From claird at lairds.us Mon Jan 3 11:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Mon, 03 Jan 2005 16:08:03 GMT Subject: How can engineers not understand source-code control? (was: The Industry choice) References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> <41d8417e$0$14596$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: In article <41d8417e$0$14596$ed2619ec at ptn-nntp-reader01.plus.net>, Mark Carter wrote: . . . >Don't start me! Dammit, too late ... > >I've noticed that they have an overwhelming obsession with GUIs, too. >They design wizards for everything. Damn pretty they are, too. Albeit a >bit flakey. They seem to conflate pretty interfaces with good interfaces >and good software. > >I used to joke that since our software wasn't particularly magical, it >didn't need wizards. But I think I just ended up sounding bitter. > >We once had a bit of software that we thought we'd like to turn into a >generic application. The focus on improvements was, predictably enough, >that we should design a GUI that could do anything a client would likely >to want to do. It was my opinion, though, having seen the very >"special-cases" nature required in the original software, that it was >almost impossible to predict exactly how a customer might want the >product tailored. I suggested that what they really needed was a library >(Python would have been good for this, Lisp might have been even better) >that could be extended as required. GUIs second, functionality first. >But hey, what would I know. Fortunately, the whole thing's been put on >the back burner. > >And trying to get through to them why source control makes sense, that >when more than one person works on a project, some form of coordination >is required, that copying and pasting code is evil, and that Excel >probably isn't the hammer for every nail. > >Honestly, I thought (real) engineers were supposed to be clever. Let's provisionally assume ignorance rather than unintelligence, if only on the grounds of parsimony. Sympathetic colleagues are available, by the way, at . While the Wiki remains *very* quiet, at this point, it's still quite young. The subject you raise is precisely at the middle of part of my excitement about Python's prospects. I'll sketch the pertinent propositions: GUIs are the wrong model; true flexibility involves a domain-specific, well-designed "little language". "Scripting languages" were originally "configuration languages"; return to those roots is only healthy. Scientific and engineering software particularly has been in thrall to the GUI, and deserves rejuve- nation with "scripting". Key to the dynamic of dynamic languages is that they make it cheaper to re-write than to re-use, in some carefully limited sense. I've seen the infatuation for Excel (and so on) for years, but never found it at all tempting myself. I mostly just ignore the issue--no, actually, I guess I give them Excel, but show at the same time that they really want the alternative views that I also provide. From the.ech0 at gmail.com Mon Jan 31 19:27:31 2005 From: the.ech0 at gmail.com (ech0) Date: 31 Jan 2005 16:27:31 -0800 Subject: Java Integer.ParseInt translation to python In-Reply-To: References: Message-ID: <1107217651.764967.258100@z14g2000cwz.googlegroups.com> buffer[0] = int(string,16) & 0xff that should work From lkirsh at cs.ubc.ca Sun Jan 30 16:56:36 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Sun, 30 Jan 2005 13:56:36 -0800 Subject: is this sort method the same as the one in python 2.4 In-Reply-To: References: Message-ID: How come you reverse the list twice? And why does this preserve stability? Raymond Hettinger wrote: > "Lowell Kirsh" > >>I'm trying to emulate the sorted() method introduced in python 2.4. The >>only difference is that it takes a sequence as one of its arguments >>rather than being a method of the sequence class. Does my method do the >>same as the sorted()? > > > Almost. This is closer to the mark: > > def sorted(iterable, cmp=None, key=None, reverse=False): > "return a sorted copy of its input" > if sys.version_info >= (2,4): > return sorted(iterable, cmp, key, reverse) > seq = list(iterable) > if reverse: > seq.reverse() # preserve stability > if key is not None: > seq = [(key(elem), i, elem) for i, elem in enumerate(seq)] > seq.sort(cmp) > if key is not None: > seq = [elem for (key, i, elem) in seq] > if reverse: > seq.reverse() > return seq > > > Try it against the tests in Lib/test/test_builtin.py. > > The differences from your version: > * >= 2.4 rather than just > 2.4 > * renamed the parameter to iterable > * handle the case where both cmp and key are defined > * add an enumerated tie breaker to prevent full key comparisons > * preserve by using reverse twice > > The real sorted() does the same thing but is implemented a bit differently. A > custom key wrapper is applied to each object so that only the key value gets > compared (no need for a full tuple with a tie breaker value). > > Raymond Hettinger > > > From skip at pobox.com Wed Jan 5 08:37:25 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 5 Jan 2005 07:37:25 -0600 Subject: Python evolution: Unease In-Reply-To: <864d37090501050117761a32e6@mail.gmail.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <16859.16548.249527.30210@montanaro.dyndns.org> <864d37090501050117761a32e6@mail.gmail.com> Message-ID: <16859.60821.476920.447511@montanaro.dyndns.org> Terry> Numarray has a record array type. If there is not one publicly Terry> available, perhaps you could write a CSV file to record-array Terry> slurper and contribute it to the Recipes site or maybe even the Terry> CSV module. >> >> -1 on putting such a beast into the CSV module, especially if, as it >> seems, it would rely on something outside the core. Carlos> Although I see your point, in the long term it will be required. Carlos> Assuming that Numarray will, at some point in the future, be Carlos> included in the stdlib... why not give these people some help, Carlos> easing the integration? I'm not sure they really need my help. I've never needed Numarray (or Numeric) in my own work. If it's deemed useful I'm sure someone from that community could whip something out in a few minutes. The concepts represented by the csv module are a lot shallower than those represented by Numarray. Skip From http Wed Jan 5 06:49:38 2005 From: http (Paul Rubin) Date: 05 Jan 2005 03:49:38 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> Message-ID: <7x4qhw859p.fsf@ruckus.brouhaha.com> Ville Vainio writes: > To me, this seems to be the job for the Fedora maintainers, not Python > maintainers. If something essential is not in the distro the distro > maintainers have screwed up. I can't parse that. It says two contradictory things. Sentence 2 says that if something essential is not in the (Python) distro then the (Python) distro maintainers have screwed up. Sentence 1 says it's the Fedora maintainer's job to deal with it. Huh? > Paul> The book is very good, but having to go buy a proprietary > Paul> book is the opposite of what self-contained free software > Paul> documentation is supposed to mean. > > I'm not sure the free software documentation is going to evolve to be > more self-contained; the exact opposite is more likely. With software, I don't think you're right. With documentation, I don't have a sense of whether you're right or not, but I hope you aren't right. From jeff at ccvcorp.com Wed Jan 5 16:33:06 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 05 Jan 2005 13:33:06 -0800 Subject: Python 2.4 on Windows XP In-Reply-To: References: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> <10toje56oiebq24@corp.supernews.com> Message-ID: <10ton02dur41v0b@corp.supernews.com> It's me wrote: > In my case, there is *no* error message of any kind. When I run pythonw.exe > from the python23 directory, the screen blinked slightly and goes back to > the command prompt. Right -- pythonw.exe is a console-less interpreter. Having no console, it doesn't have an interactive mode, and since you didn't give it a script to run, it simply started, found nothing to do, and then terminated itself. You need to run idle.pyw, *not* pythonw.exe. The idle.pyw script runs inside the pythonw.exe interpreter, but the latter can't do anything without instructions. Jeff Shannon Technician/Programmer Credit International From josh at yucs.org Tue Jan 11 11:29:01 2005 From: josh at yucs.org (josh at yucs.org) Date: Tue, 11 Jan 2005 11:29:01 -0500 Subject: why not datetime.strptime() ? Message-ID: <20050111162901.GA26246@yucs.org> David M. Cookie writes: > You don't check for errors: an exception being thrown by > PyObject_CallMethod will return obj == NULL. Oops, missed that one. Thanks. > If there's a module in sys.path called time that overrides the stdlib > time, things will fail, and you should be able to catch that. Maybe someone really does want to override the time module, and then we shouldn't get in their way? For example, if someone adds a new field descriptor for nanoseconds to time.strptime, then it'd be nice to have it work with datetime.datetime.strptime as well. Incidentally, this is the way that the rest of datetime does it. > Are you positive those PySequence_GetItem calls will succeed? That > they will return Python integers? Well, without interfaces, I can't be sure :). Throwing an exception is cool (especially if we do allow user implemented time.strptime). -------------- next part -------------- --- Modules/datetimemodule.c.orig 2003-10-20 10:34:46.000000000 -0400 +++ Modules/datetimemodule.c 2005-01-11 10:42:23.000000000 -0500 @@ -3774,6 +3774,47 @@ return result; } +/* Return new datetime from time.strptime(). */ +static PyObject * +datetime_strptime(PyObject *cls, PyObject *args) +{ + PyObject *result = NULL, *obj, *module; + const char *string, *format; + + if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format)) + return NULL; + + if ((module = PyImport_ImportModule("time")) == NULL) + return NULL; + obj = PyObject_CallMethod(module, "strptime", "ss", string, format); + Py_DECREF(module); + + if (obj != NULL) { + int good_timetuple = 1; + if (PySequence_Check(obj) && PySequence_Size(obj) > 6) { + int i; + for (i=0; i <= 6; i++) + if (!PyInt_Check(PySequence_GetItem(obj, i))) + good_timetuple = 0; + } else + good_timetuple = 0; + if (good_timetuple) + result = PyObject_CallFunction(cls, "iiiiiii", + PyInt_AsLong(PySequence_GetItem(obj, 0)), + PyInt_AsLong(PySequence_GetItem(obj, 1)), + PyInt_AsLong(PySequence_GetItem(obj, 2)), + PyInt_AsLong(PySequence_GetItem(obj, 3)), + PyInt_AsLong(PySequence_GetItem(obj, 4)), + PyInt_AsLong(PySequence_GetItem(obj, 5)), + PyInt_AsLong(PySequence_GetItem(obj, 6))); + else + PyErr_SetString(PyExc_ValueError, + "unexpected value from time.strptime"); + Py_DECREF(obj); + } + return result; +} + /* Return new datetime from date/datetime and time arguments. */ static PyObject * datetime_combine(PyObject *cls, PyObject *args, PyObject *kw) @@ -4385,6 +4426,11 @@ PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp " "(like time.time()).")}, + {"strptime", (PyCFunction)datetime_strptime, + METH_VARARGS | METH_CLASS, + PyDoc_STR("strptime -> new datetime parsed from a string" + "(like time.strptime()).")}, + {"combine", (PyCFunction)datetime_combine, METH_VARARGS | METH_KEYWORDS | METH_CLASS, PyDoc_STR("date, time -> datetime with same date and time fields")}, --- Doc/lib/libdatetime.tex.orig 2003-09-06 01:36:56.000000000 -0400 +++ Doc/lib/libdatetime.tex 2005-01-11 11:06:22.699348152 -0500 @@ -624,6 +624,13 @@ ignored. \end{methoddesc} +\begin{methoddesc}{strptime}{date_string, format} + Return the date corresponding to date_string, parsed according + to format. This is equivalent to \code{datetime(*(time.strptime( + date_string, format)[0:7]))}. \exception{ValueError} is raised if + \code{time.strptime()} returns a value which isn't a timetuple. +\end{methoddesc} + Class attributes: \begin{memberdesc}{min} From simonwittber at gmail.com Thu Jan 13 08:58:30 2005 From: simonwittber at gmail.com (Simon Wittber) Date: Thu, 13 Jan 2005 21:58:30 +0800 Subject: why are people still using classic classes? In-Reply-To: References: <7x6522gegg.fsf@ruckus.brouhaha.com> Message-ID: <4e4a11f805011305586f5a5502@mail.gmail.com> > Unfortunately, if we should follow the recent advice about > always using "super()" in the __init__ method, it's hard > to do what you suggest (though it sounds like good advice) > without resorting to extreme ugliness: 'import this' also provides some good advice: "There should be one-- and preferably only one --obvious way to do it." It seems to me that python is not as simple/clean as it once was. It has grown warts, for the sake of backwards compatibility. :( Sw. From http Sat Jan 8 04:54:30 2005 From: http (Paul Rubin) Date: 08 Jan 2005 01:54:30 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> Message-ID: <7xhdlss0tl.fsf@ruckus.brouhaha.com> "Roose" writes: > An OS is NOT an application. It is a completely different kind of program. > Do you guys understand the difference between user and kernel mode? Do you > know what address spaces and hardware interrupts are? Python is not > equipped to handle these things. You would end up doing so much in C > extensions that it could barely be called Python. You'd need some library functions to let Python access device registers and you'd need some low level code to dispatch interrupts into Python code. > I am not trying to be insulting... but unless someone would like to educate > me otherwise, the idea of an OS written in Python is almost ludicrous. Is an OS written in Lisp also ludicrous? Because it's been done. When Unix was first written, people thought implementing an OS in C was ludicrous. Everyone knew OS's had to be written in assembler. > Also I am no threading expert, but I would imagine it would be very hard to > write a task scheduler in Python given that it has the whole GIL thing. (As > I said that isn't my domain of expertise but I'm sure someone here could > expound on that.) The GIL is not part of the Python language. It's just an artifact of one particular implementation. From http Fri Jan 28 02:27:48 2005 From: http (Paul Rubin) Date: 27 Jan 2005 23:27:48 -0800 Subject: Classical FP problem in python : Hamming problem References: <63b5e209.0501210558.686f5c10@posting.google.com> <6PKdnVpD-4f3CGvcRVn-gQ@comcast.com> Message-ID: <7x3bwmggi3.fsf@ruckus.brouhaha.com> Francis Girard writes: > Thank you Nick and Steven for the idea of a more generic imerge. If you want to get fancy, the merge should use a priority queue (like in the heapsort algorithm) instead of a linear scan through the incoming iters, to find the next item to output. That lowers the running time to O(n log k) instead of O(n*k), where k is the number of iterators and n is the length. From bob_smith_17280 at hotmail.com Sun Jan 9 13:41:59 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Sun, 09 Jan 2005 13:41:59 -0500 Subject: windows mem leak In-Reply-To: References: <41XDd.70234$Jk5.40626@lakeread01> <41E06C18.6050407@hotmail.com> Message-ID: Peter Hansen wrote: > Bob Smith wrote: > >> Attached is the code. Run it yourself and see. You too Peter. Be >> gentle with me, this was my first attempt with threads. > > > Thanks, Bob, and I will, but not before you answer some of my > questions. > > I had good reasons to ask them, one of which is that I don't > feel like wasting my time if, for example, you are using an > older version of Python that *did* have a memory leak. 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] > > The most important answers you can provide will be versions, > platform (pretty clearly Linux, but please confirm and give > version), and what "bombs" means and how you are measuring > the memory leak. WinXP Home, Service Pack 2, AMD 1400MHz proc, 256MB Ram Debian Linux Testing (2.4.28 vanilla Kernel) 3GHz P4 proc, 1.5GB Ram > > (I presume you're using a version of nmap that's compiled > for Windows XP then? Yes, I am. > It's certainly not standard. That's a matter of opinion. Nmap works fine on the WinXP machine. > How have > you proven that it is not *that* program which is at fault?) I have not. All I know is that on WinXP, the program uses 100% CPU at times and consumes more Ram than is available (the page file grows to 700 or 800MB). It runs OK for a few hours and then produces a 'not enough resources' error. And, the machine is generally unuserable. On Linux, it has no impact whatsoever on resources. Granted, the Linux machine is much more robust, but one wouldn't expect this great a difference. I can rewrite it so that it's pure Pyhton (no calling nmap) if you think that would be a good idea. Perhaps that would at least remove nmap from the equation. I can run it if you like and take a screen shot of the error. You'll have to give me a few hours though ;) From axel at white-eagle.co.uk Fri Jan 28 08:48:46 2005 From: axel at white-eagle.co.uk (axel at white-eagle.co.uk) Date: Fri, 28 Jan 2005 13:48:46 GMT Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106723545.429728.308620@f14g2000cwb.googlegroups.com> Message-ID: <2prKd.7568$B5.7020@fe1.news.blueyonder.co.uk> In comp.lang.perl.misc Xah Lee wrote: > Following is a tutorial on Python's classes. It is part of a > a-Python-a-day mailing list. As an example, it shows what i mean by > covering the language's functionalities as is, without needing to chalk > up to rocket sciences. If expanded slightly and edited, it can supplant > sections 9.0 to 9.4 of the Python tutorial. Languages Tutorials should > follow this style. It is crap, not a tutorial, but just an aide-memoire for someone who presumably knows the stuff anyway. And keep it where it belongs please. Axel From jhargraveiii at msn.com Sat Jan 22 02:57:00 2005 From: jhargraveiii at msn.com (Jim Hargrave) Date: Sat, 22 Jan 2005 02:57:00 -0500 Subject: embedding jython in CPython... Message-ID: I've read that it is possible to compile jython to native code using GCJ. PyLucene uses this approach, they then use SWIG to create a Python wrapper around the natively compiled (java) Lucene. Has this been done before for with jython? Another approach would be to use JPype to call the jython jar directly. My goal is to be able to script Java code using Jython - but with the twist of using Cpython as a glue layer. This would allow mixing of Java and non-Java resources - but stil do it all in Python (Jython and Cpython). I'd appreciate any pointers to this topic and pros/cons of the various methods. From RajaSrinivasan at hotmail.com Mon Jan 3 15:24:09 2005 From: RajaSrinivasan at hotmail.com (RajaSrinivasan at hotmail.com) Date: 3 Jan 2005 12:24:09 -0800 Subject: Bad Interpreter Message-ID: <1104783849.754892.47560@c13g2000cwb.googlegroups.com> I have seen some previous messages about such a problem. I have this problem but it is not clear what the solution really was. I am running FC2, python 2.3.3 the script i have sock.py runs if i say something like : python sock.py but ./sock.py results in a :bad interpreter error how do i troubleshoot something like this? regards From steve at holdenweb.com Tue Jan 18 09:19:43 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Jan 2005 09:19:43 -0500 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Antoon Pardon wrote: > Op 2005-01-18, Nick Coghlan schreef : [...] > But don't use mutable keys is not a general principle. It is a principle > introduced by the limitations of the python implementations. > Sorry, but it *is* a general principle, adduced from the potential pitfalls available to inexperienced programmers when breaking the principle. > I don't like it when a good rule of thumb because of implementation > limitations is sold as a general principle. > So, since you are so good at nit-picking, perhaps you will explain the difference between "rule of thumb" and "general principle". preferably-in-less-than-three-thousand-words-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From sjmachin at lexicon.net Fri Jan 28 16:22:32 2005 From: sjmachin at lexicon.net (John Machin) Date: 28 Jan 2005 13:22:32 -0800 Subject: py.dll for version 2.2.1 (Windows) References: <1106937199.667357.42040@z14g2000cwz.googlegroups.com> Message-ID: <1106947352.661845.202530@z14g2000cwz.googlegroups.com> mike wrote: > Just recently, my virus checker detected what it called a Trojan Horse > in the py.dll file in the python22 folder. Sorry to come on like the Inquisition, but this _might_ be something of significance to the whole Windows Python community: When was "just recently"? Which virus checker are you using? Did it say which Trojan it had detected? Have you kept a copy of the "py.dll" file? Have you kept a copy of the virus checker's report? Was that the first time you have run that virus checker? If not when was the previous run? > Installation is version > 2.2.1 and I think that it came installed when I bought the PC in > October 2002. > > Does anyone know where I can get a copy of the py.dll file from version > 2.2.1 for Windows (XP) ? > > I looked at www.python.org and do not see a py.dll file in the > self-installation or .tgz versions of 2.2.1 that are posted. That would be because there is no file named "py.dll" in a Windows distribution of Python! You should have Python22.dll -- they all have the major/minor version numbers in the name -- and its size should be about 820Kb. You may like to keep the evidence (if you still have it) -- move the presumably bad file into a folder of its own and rename it to have some extension other than dll -- because targetting a Python installation would appear to be novel and someone may very well be interested in inspecting your file. If you have some good reason to stay with 2.2, then get the _latest_ version of that (2.2.3). Otherwise, install 2.4. Regards, John From klachemin at comcast.net Mon Jan 31 10:09:10 2005 From: klachemin at comcast.net (Kamilche) Date: 31 Jan 2005 07:09:10 -0800 Subject: PyGame not working(?) (was: trouble installing numeric) In-Reply-To: <20050130152208505-0800@news.claremont.edu> References: <20050129232540162-0800@news.claremont.edu> <20050130152208505-0800@news.claremont.edu> Message-ID: <1107183550.798010.327170@z14g2000cwz.googlegroups.com> Are you using Python 2.3? Pygame doesn't work with 2.4, unfortunately. It's the reason I removed 2.4 from my machine. I'll upgrade once PyGame upgrades. From alexrait at gmail.com Fri Jan 28 08:08:20 2005 From: alexrait at gmail.com (alexrait1) Date: 28 Jan 2005 05:08:20 -0800 Subject: Proccess termination Message-ID: <1106917700.730538.80320@f14g2000cwb.googlegroups.com> I use popen.popen2 or popen.popen3 to start a new process and read from it's stdout/ write to it's stdin. But I need a way to know when a process terminates. If it closes it's stdin/stdout, it doesn't mean it has really terminated... And if possible, I would like to see an exception thrown when that happens.. Do you know about a library that provides these tools other then the standard os module... or should I use it otherwise? Thanx Alex Rait. From dbickett at gmail.com Sun Jan 30 21:54:46 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 30 Jan 2005 21:54:46 -0500 Subject: gmail access with python! In-Reply-To: References: Message-ID: <1d6cdae305013018542a71840a@mail.gmail.com> Indeed, here is a detailed help document on GMail POP3 access: http://gmail.google.com/support/bin/answer.py?answer=12103 huh...look at that, they're using python :) Never noticed that before. Anyway, after that you can simply use a standard POP3 module. There's no need to get fancy and use gmail-specific libraries, really. -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ From segphault at sbcglobal.net Tue Jan 25 04:13:56 2005 From: segphault at sbcglobal.net (Ryan Paul) Date: Tue, 25 Jan 2005 09:13:56 GMT Subject: how to call python code from C# References: Message-ID: On Tue, 25 Jan 2005 00:35:04 +0530, paritosh mahana wrote: > Hi all, > How can I call python code from my C# code. One thing is to make an > .exe file of the python program and then try to call it from my C# > code. But I don't like that idea. Is there any other way to do this. > Like making a .dll file from the python code and somehow call it from > C# program.But I couldn't find anything on this topic on the net. > Actually my GUI is in C# and rest part is in python, and i need to > call python from my C# program. Please correct me if I am wrong > anywhere. > thanks > paritosh. This may not be relevant, but if what you are looking for is a way to write a program for .NET with a language that doesnt suck, you might want to look at Boo (http://boo.codehaus.org/). I'm not sure if it can directly use winforms, but you can probably make native .net libraries with it that you can utilize from C#. Boo looks and feels almost exactly like Python, so the learning curve is minimal, and using it is very pleasant. -- SegPhault From chris.lasher at gmail.com Sat Jan 15 17:40:59 2005 From: chris.lasher at gmail.com (Chris Lasher) Date: 15 Jan 2005 14:40:59 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: <1105828859.962224.316320@z14g2000cwz.googlegroups.com> Roy, thank you for your reply. I have BioPython installed on my box at work and have been browsing through the code in there, some of which I can follow, and most of which will take more time and experience for me to do so. I have considered BioPython and databases, and have chosen to forego those routes for the reasons above, here summarized: this script has a limited scope of what I hope it will acheive, and it should be as convenient as possible for the end-user to execute it (even at the expense of convenience to me as the coder). Again, thanks for your input, though. It's very helpful to me to be able to learn from other perspectives that I wouldn't have seen from, myself. From tom at dev.null.daemon.de Mon Jan 10 18:27:11 2005 From: tom at dev.null.daemon.de (Thomas Linden) Date: 11 Jan 2005 00:27:11 +0100 Subject: static compiled python modules References: <87u0pqn5pz.fsf@dev.null.daemon.de> Message-ID: <87d5wcyieo.fsf@dev.null.daemon.de> Nick Coghlan wrote: > http://www.python.org/dev/doc/devel/api/importing.html > Take a look at the last three entries about registering builtin modules. Thanks a lot, it works! regards, Tom From Steven.Bethard at colorado.edu Tue Jan 4 05:22:22 2005 From: Steven.Bethard at colorado.edu (Steven Bethard) Date: Tue, 04 Jan 2005 10:22:22 GMT Subject: why does UserDict.DictMixin use keys instead of __iter__? Message-ID: Sorry if this is a repost -- it didn't appear for me the first time. So I was looking at the Language Reference's discussion about emulating container types[1], and nowhere in it does it mention that .keys() is part of the container protocol. Because of this, I would assume that to use UserDict.DictMixin correctly, a class would only need to define __getitem__, __setitem__, __delitem__ and __iter__. So why does UserDict.DictMixin require keys() to be defined? py> class D(object, UserDict.DictMixin): ... """Simple dict wrapper that implements container protocol""" ... def __init__(self, dict): self.dict = dict ... def __len__(self, key): return len(self.dict) ... def __getitem__(self, key): return self.dict[key] ... def __setitem__(self, key, value): self.dict[key] = value ... def __delitem__(self, key): del self.dict[key] ... def __iter__(self): return iter(self.dict) ... def __contains__(self, key): return key in self.dict ... py> d = D(dict(a=1, b=2)) py> d.clear() Traceback (most recent call last): File "", line 1, in ? File "C:\Program Files\Python\lib\UserDict.py", line 114, in clear for key in self.keys(): AttributeError: 'D' object has no attribute 'keys' py> d.keys() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'D' object has no attribute 'keys' I thought about submitting a patch, but I couldn't think of a way that didn't raise backwards compatibility concerns... Steve [1]http://docs.python.org/ref/sequence-types.html From aleaxit at yahoo.com Sun Jan 23 18:06:01 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 24 Jan 2005 00:06:01 +0100 Subject: Weakref.ref callbacks and eliminating __del__ methods References: Message-ID: <1gqv9il.7udkdu1oqaaqmN%aleaxit@yahoo.com> Mike C. Fletcher wrote: > weakref.ref( self, self.close ) > > but the self.close reference in the instance is going away *before* the > object is called. Uh -- what's holding on to this weakref.ref instance? I guess the weakreference _itself_ is going away right after being created... Alex From http Sat Jan 29 03:01:42 2005 From: http (Paul Rubin) Date: 29 Jan 2005 00:01:42 -0800 Subject: Pystone benchmark: Win vs. Linux (again) References: Message-ID: <7xhdl0ll3t.fsf@ruckus.brouhaha.com> Franco Fiorese writes: > * Windows XP Pro: 16566.7 pystones/second > * Linux (kernel 2.6.9 NPTL): 12346.2 pystones/second > > I have repeated the test, on Linux, also with other distributions and > kernel but a relevant difference still exists with Windows offering a > better performance. > > Is there any way, that you know, to get better performance under Linux? I hate to say this but the Windows C compiler may be beating GCC in output code. Doing anything about it may require a lot of careful profiling and tuning. From ncoghlan at iinet.net.au Mon Jan 24 06:22:32 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 24 Jan 2005 21:22:32 +1000 Subject: delay and force in Python In-Reply-To: <41EE6658.8000409@iinet.net.au> References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> <41EE6658.8000409@iinet.net.au> Message-ID: <41F4DA78.90703@iinet.net.au> Nick Coghlan wrote: > Will Stuyvesant wrote: > >> The program below creates a stream with the numbers 1..995 >> and then filters the stream, keeping only the even numbers, >> and then prints the second number in the stream (implemented >> as the first number of the tail, just like in the 3.5 >> Section in the Wizard book). > > > How's this: > > Py> from itertools import islice > Py> print islice((x for x in xrange(1, 996) if x % 2 == 0), 1, 2).next() > 4 Wouldn't it be nice if this could be spelt: print (x for x in xrange(1, 996) if x % 2 == 0)[2] Well, I just put a patch on SF to enable exactly that: http://www.python.org/sf/1108272 Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From kent3737 at yahoo.com Tue Jan 11 08:13:27 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Tue, 11 Jan 2005 08:13:27 -0500 Subject: [csv module] duplication of end of line character in output file generated In-Reply-To: References: Message-ID: <41e3ceb6$1_3@newspeer2.tds.net> simon.alexandre wrote: > Hi all, > > I use csv module included in python 2.3. I use the writer and encouter the > following problem: in my output file (.csv) there is a duplication of the > end of line character, so when I open the csv file in Ms-Excel a blank line > is inserted between each data line. From the docs for csv.writer(): writer( csvfile[, dialect='excel'[, fmtparam]]) ...If csvfile is a file object, it must be opened with the 'b' flag on platforms where that makes a difference. Windows is a "platform where that makes a difference." So try self.writer = csv.writer(file("Test.csv", "wb")) Kent > > OS: W2k > > Someone has an idea ? > > thanks in advance > > the source code is the following: > > --------------------------------------------------> > import csv > > class CsvDumper: > > def __init__(self): > self.object = > [['la','mb','mc','md'],['ma','mb','mc','md'],['ma','mb','mc','md']] > self.writer = csv.writer(file("Test.csv", "w")) > > def DumpCsvFile(self): > for row in self.object: > self.writer.writerow(row) > > c = CsvDumper() > c.DumpCsvFile() > > From ncoghlan at iinet.net.au Mon Jan 24 06:41:18 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 24 Jan 2005 21:41:18 +1000 Subject: finding name of instances created In-Reply-To: References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> <1106397218.724722.172660@c13g2000cwb.googlegroups.com> Message-ID: <41F4DEDE.6070003@iinet.net.au> Steven Bethard wrote: > That is, you can just keep track of all the names of a Robot in the > Robot object. In the simple case, where there's only one name, you can > display it as such. In the more complicated case, where there's some > aliasing, you can display the multiple aliases. This means you don't > have to teach about aliasing right off the bat, but if a student > accidentally discovers it on their own, the machinery's there to explain > it... Incidentally, this discussion made me realise the real reason why using a lambda to create a named function is evil: Py> def f(): pass ... Py> f.func_name 'f' Py> f = lambda: None Py> f.func_name '' I think I've heard that explanation before, but it never really clicked. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From danperl at rogers.com Fri Jan 28 18:44:14 2005 From: danperl at rogers.com (Dan Perl) Date: Fri, 28 Jan 2005 18:44:14 -0500 Subject: what's OOP's jargons and complexities? References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> Message-ID: "Dan Perl" wrote in message news:U9udnT2lOZ7rUGfcRVn-uA at rogers.com... > Actually, it can be as simple as: > public class test { > public static void main(String[] args) { > String c = new String("a string"+" another one"); > System.out.println(c); > } > } I forgot. It can be even simpler: public class test { public static void main(String[] args) { System.out.println("a string"+" another one"); } } From craig at postnewspapers.com.au Thu Jan 13 14:18:56 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 14 Jan 2005 03:18:56 +0800 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: <1105643936.4001.3.camel@albert.localnet> On Thu, 2005-01-13 at 08:39 +0000, Antoon Pardon wrote: > > At best it would offer new paradigms for existing constructs (violating > > the "there should be one obvious way to do it" zen); at worst it would > > obfuscate the whole language. > > That zen is already broken. Look at the number of answers one gets > if a newbee askes for a ternary operator. I think that a simple > ternary operator or macro's with an official supported macro that > implemented the ternary operator would have been far closer to > the spirit of only having one obvious way than what we have now. And then we have iteration .... (generator expressions, list comprehensions, for loops, ...?) over (sequences, iterators, generators) I happen to be extremely fond of the flexibility this provides, but one obvious way to do it there is not. -- Craig Ringer From zainalam at gmail.com Mon Jan 24 18:56:06 2005 From: zainalam at gmail.com (Quest Master) Date: Mon, 24 Jan 2005 18:56:06 -0500 Subject: Another scripting language implemented into Python itself? Message-ID: <9c35205405012415564654fc85@mail.gmail.com> I am interested in developing an application where the user has an ample amount of power to customize the application to their needs, and I feel this would best be accomplished if a scripting language was available. However, I want to code this application in Python, and I have not yet heard of an implementation of another scripting language into Python. An example of what I mean is this (an implementation of Lua into Ruby -- which I'd prefer not to use): http://ruby-lua.unolotiene.com/ I know C/C++ might be better suited for a task of this kind, but most of the modules in my application which need speed have already been coded in C++. I want to use Python as the "glue" for this project; writing an entire application with a pretty GUI is not fun, as most of you may know from previous experience. So, my question is simply this: is there an implementation of another scripting language into Python? From follower at gmail.com Sun Jan 30 22:30:18 2005 From: follower at gmail.com (Mr Follower) Date: 30 Jan 2005 19:30:18 -0800 Subject: gmail access with python! References: <1107124228.920210.141920@f14g2000cwb.googlegroups.com> Message-ID: <1107142218.468952.190960@z14g2000cwz.googlegroups.com> Did you try the CVS version of libgmail? While none of the "release versions" (i.e. up 0.0.8) currently work, as of a week ago the CVS version handled the two recent modifications to Gmail. --Phil. (Author libgmail) From jason.koch at novasyshealth.com Wed Jan 5 17:45:27 2005 From: jason.koch at novasyshealth.com (Jason Koch) Date: Wed, 05 Jan 2005 16:45:27 -0600 Subject: PIL and ReportsLab error Message-ID: <41DC6E07.60605@novasyshealth.com> Hello, I am trying to produce pdf files from tiffs and I keep getting this error. Does anyone have any tips on this one. I am using the ReportLab package with the PIL. File "C:\Python23\Lib\site-packages\PIL\Image.py", line 309, in _getdecoder raise IOError("decoder %s not available" % decoder_name) IOError: decoder group4 not available Thanks, -- Jason Koch NovaSys Health Jason.Koch at novasyshealth.com Work: 501-219-4444 ext. 608 Work: 1-800-294-3557 ext. 608 Mobile: 501-977-6701 This email and any attachments to it are privileged and confidential and are intended solely for use of the individual or entity to which they are addressed. If the reader of this message is not the intended recipient, any use, distribution, or copying of this communication, or disclosure of all or any part of its content to any other person, is strictly prohibited. If you have received this communication in error, please notify the sender by replying to this message and destroy this message and delete any copies held in your electronic files. Thank you. From danb_83 at yahoo.com Tue Jan 18 02:24:29 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 17 Jan 2005 23:24:29 -0800 Subject: Integration with java References: Message-ID: <1106033069.070545.265310@z14g2000cwz.googlegroups.com> Istvan Albert wrote: > Joachim Boomberschloss wrote: > > > the code is already written in Python, using the > > standard libraries and several extension modules > > One thing to keep in mind is that Jython does not > integrate CPython, instead it "understands" python code > directly. So if you have a C extension that works with python > it won't work with Jython. Also, Jython is several versions behind CPython, so any Python code that uses generators or new-style division won't work either. > My feeling is that if you had a lot of Java code written and > wanted to build on that with python Jython would be a better > fit than vice versa. I agree. From pythongnome at hotmail.com Sun Jan 9 11:11:45 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Sun, 09 Jan 2005 16:11:45 GMT Subject: Old Paranoia Game in Python In-Reply-To: <2005010903390916807%spk00@coxnet> References: <2005010903390916807%spk00@coxnet> Message-ID: <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> Sean P. Kane wrote: > I ported the old (and long since removed) game from the bsd-game pacakge > called, Paranoia, based on the old Paranoia role playing game from C to > Python as a simple exercise in learning the language and pure late night > boredom. Anyways, here it is for anyone looking for a few minutes of > nostalgia. I may get around to posting this at > http://homepage.mac.com/spkane/ or http://www.spkane.org/, but for now > here it is. Improvements or corrections, welcome. > > Thanks, > Sean > Equipment: Red Reflec Armour, Laser Pistol, Laser Barrel (red), > Notebook & Stylus, Knife, Com Unit 1, Jump suit, > Secret Illuminati Eye-In-The-Pyramid(tm) Decoder ring, > Utility Belt & Pouches > =============================================================================== The Illuminati really have infiltrated our society. From noreplyemail at hotmail.com Mon Jan 24 10:27:48 2005 From: noreplyemail at hotmail.com (noreplyemail at hotmail.com) Date: Mon, 24 Jan 2005 15:27:48 +0000 (UTC) Subject: =?iso-8859-1?q?=A4=D1=A4=F4=B3=F2=A4=D1=B4I=ADbA=AEy=A4K=A6=CA?= =?iso-8859-1?q?=A4=D8=B3=E6=A6=EC=A9=D0=B6=A1=A4=C0=AF=B2=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= =?iso-8859-1?q?=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E=2E?= Message-ID: ?????????I?b???@?y???????? ?N?b?|?I???????? ???????q???q?U???n?a?? ???K???K?????N?} ?{???H?G?Q?C?????@???????? ?a???q???p?Z?U?@?? ???????N???? ???V?@?y ???????n???C????,??????80?? ?q???????G?Q?C?? ?u???????H?K,?????H?a, ??????,?????s,?L???}???n?? ???H????,?{???q?????v?????p???u?@.... ???N???q?l?z?????H?????]?A ???O/?~??/???~ ?? : 13556869217 at 163.com ???????|?????^??. ?P???H?p??.. ............................................................................................................................................................................................................................................................................................. From rickard.lind at ntier.se Fri Jan 14 08:07:57 2005 From: rickard.lind at ntier.se (Rickard Lind) Date: Fri, 14 Jan 2005 14:07:57 +0100 Subject: Static executable with shared modules Message-ID: <41E7C42D.8070403@ntier.se> Is there any way to build the python executable statically and still be able to load modules built as shared libraries? I'm trying to run python scripts on a stripped down FreeBSD (4.9) machine which has no shared system libraries so I want to link it statically against libc et al, but it would be nice to still be able to load modules which were built as shared libraries. In particular I have a library for which I've generated a wrapper with swig which I'd like to import. I've googled up and down but can't find anyone who has tried this particular combination. Just adding a -static to the Makefile seems to remove the ability to load shared libraries altogether as I get a "ImportError: Service unavailable" exception. /r From aleaxit at yahoo.com Tue Jan 18 16:11:40 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 18 Jan 2005 22:11:40 +0100 Subject: what would you like to see in a 2nd edition Nutshell? References: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> <8y7h3xsz.fsf@python.net> <1gpkwdy.14p3pn1pgdadfN%aleaxit@yahoo.com> <1105583231.665909.239500@z14g2000cwz.googlegroups.com> Message-ID: <1gqludz.zsr8f0x4iq5cN%aleaxit@yahoo.com> kery wrote: ... > Any schedule for publication of 2nd Ed? I just bought 1st Ed. The 2nd edition Python Cookbook appears to be on-track for PyCon (late March) for the very first ink-on-paper -- probably April in bookstores. The 2nd edition Python in a Nutshell is more doubtful, being just started and all that -- OSCON is a possible target, but it's way too early to say if I'll manage to hit it. In both cases, the 2nd ed is meant to focus on versions 2.3 and 2.4 of Python, while the 1st ed covered all versions up to 2.2 included. So, if you're still interested in using Python 2.2 or older versions, you may want to stock up on 1st editions of Cookbook and Nutshell; if you're only interested in 2.3 and following versions, in the case of the Cookbook waiting 2-3 months for the 2nd ed may be worth it, while, in the case of the Nutshell, I would definitely not recommend a far longer and more uncertain waiting period of 7 months or more. Moreover, the changes in the Nutshell will be less than those in the Cookbook were: the Cookbook has changed way more than 50% of its contents, the Nutshell will change substantially less (according to current plans: I'll be able to give more precise information later this year). Alex From marklists at mceahern.com Wed Jan 19 16:36:47 2005 From: marklists at mceahern.com (Mark McEahern) Date: Wed, 19 Jan 2005 15:36:47 -0600 Subject: Zen of Python In-Reply-To: <972ec5bd050119111359e358f5@mail.gmail.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> Message-ID: <41EED2EF.5080508@mceahern.com> Timothy Fitz wrote: >While I agree that the Zen of Python is an amazingly concise list of >truisms, I do not see any meaning in: > >Flat is better than nested. > >I strive for balance between flat and nested. Does anyone have a good >example of where this is applied? (specifically to python, or in >general) > One example would be using a function instead of a class when a function does the job at the module level. Using the appropriate degree of abstraction/indirection. // m From alessandro.crugnola at gmail.com Thu Jan 27 08:29:32 2005 From: alessandro.crugnola at gmail.com (Alessandro Crugnola) Date: 27 Jan 2005 05:29:32 -0800 Subject: parsing WSDL Message-ID: <6bc0c3c.0501270529.5b9d8e00@posting.google.com> Hi to all. Is there a way, maybe using 4suite, to read a wsdl file and find for every method all the input/output params and their type? From http Sun Jan 9 05:59:19 2005 From: http (Paul Rubin) Date: 09 Jan 2005 02:59:19 -0800 Subject: Pre/Postconditions with decorators References: <1105094828.619317.315340@z14g2000cwz.googlegroups.com> <34814fF43bm4cU1@individual.net> <7x1xcvwkdj.fsf@ruckus.brouhaha.com> Message-ID: <7xfz1ag96g.fsf@ruckus.brouhaha.com> Stephen Thorne writes: > > It should be left on. Leaving it in for development and turning it > > off for production is like wearing a parachute during ground training > > and taking it off once you're in the air. > So we can't use this for a case where we have an extremely large list > then ;). Its an O(n) operation to just call a function that takes a > list of a specific type. The condition should be enforced at the time whenever list itself is mutated. From anon at anon.com Fri Jan 28 18:21:17 2005 From: anon at anon.com (Todd_Calhoun) Date: Fri, 28 Jan 2005 15:21:17 -0800 Subject: Where can I find sample "beginner" programs to study? References: <_6CdnWIOB8AaA2fcRVn-rg@speakeasy.net> Message-ID: Thanks for the great links. The cookbook page has some smaller stuff that looks great. "JanC" wrote in message news:Xns95ECE31EAF7DFJanC at 213.118.32.28... > Todd_Calhoun schreef: > >> I'm trying to learn Python (and programming), and I'm wondering if >> there are any places where I can find small, simple programs to study. > > Try: > > > > -- > JanC > > "Be strict when sending and tolerant when receiving." > RFC 1958 - Architectural Principles of the Internet - section 3.9 From jan.dries at dcube-resource.be Thu Jan 20 02:09:46 2005 From: jan.dries at dcube-resource.be (Jan Dries) Date: Thu, 20 Jan 2005 08:09:46 +0100 Subject: Zen of Python In-Reply-To: References: Message-ID: Luke Skywalker schreef: > On Wed, 19 Jan 2005 14:13:47 -0500, Timothy Fitz > > While I agree that the Zen of Python is an amazingly concise list > > of truisms, I do not see any meaning in: > > For those interested, here's the list: > http://www.python.org/doc/Humor.html#zen Or you just type at the interactive prompt: >>> import this Regards, Jan From reinhold-birkenfeld-nospam at wolke7.net Sun Jan 9 16:22:01 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 09 Jan 2005 22:22:01 +0100 Subject: else condition in list comprehension In-Reply-To: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: <34dljpF491d3uU1@individual.net> Luis M. Gonzalez wrote: > Hi there, > > I'd like to know if there is a way to add and else condition into a > list comprehension. I'm sure that I read somewhere an easy way to do > it, but I forgot it and now I can't find it... > > for example: > z=[i+2 for i in range(10) if i%2==0] > what if I want i to be "i-2" if i%2 is not equal to 0? You'll have to add the condition at the front: z = [(i+2, i-2)[i%2] for i in range(10)] should do what you need. Reinhold From tmohr at s.netic.de Sun Jan 9 12:57:49 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Sun, 09 Jan 2005 18:57:49 +0100 Subject: SuSE 9.1: updating to python-2.4 Message-ID: Hi, along with my distribution SuSE 9.1 came python 2.3.3. I'd like to update to 2.4 now, is this an easy thing to do or will lots of installed modules refuse to work then? Is there an easy way to find out what i need to update? Thanks for any hints, Torsten. From p.s.nuttall at dur.ac.uk Tue Jan 25 13:28:34 2005 From: p.s.nuttall at dur.ac.uk (Peter Nuttall) Date: Tue, 25 Jan 2005 18:28:34 +0000 Subject: [perl-python] 20050125 standard modules In-Reply-To: <5didnV2i-YV_G2vcRVn-iw@rogers.com> References: <1106669614.666772.17750@z14g2000cwz.googlegroups.com> <5didnV2i-YV_G2vcRVn-iw@rogers.com> Message-ID: <200501251828.34550.p.s.nuttall@dur.ac.uk> On Tuesday 25 Jan 2005 17:50, Dan Perl wrote: > I was wrong. He is just crossposting to the newsgroups without having > them as members of the group. > > I wish there was a good way like that to stop these daily postings! > You can just filter on [perl-python] Pete From Marten.Bauer at gmx.net Thu Jan 6 01:48:01 2005 From: Marten.Bauer at gmx.net (Marten Bauer) Date: Thu, 06 Jan 2005 07:48:01 +0100 Subject: Another PythonWin Excel question In-Reply-To: References: Message-ID: <344586F48830bU1@individual.net> It's me wrote: > I followed the example in > http://stompstompstomp.com/weblog/technical/2004-05-20 and learned that to > add a new worksheet to an Excel workbook, you would use the > workbook.Worksheets.Add() method. That works. However, the new worksheet > got added *in front* of the last worksheet I was at. How can I get it to > add *after*? > > Thanks, > > -- > Me > > Hello, I did it yesterday like this way and it works well (part of my code): wb.Worksheets.Add(Count=nrMonths,After=wb.Worksheets(1)) As I read in MSDN you could not write After="sheet1" instead you must use the Object of sheet1 like in my example and it works well in my case. The Count=... statement will create n Sheets after the first worksheet By Marten From danperl at rogers.com Fri Jan 28 18:40:33 2005 From: danperl at rogers.com (Dan Perl) Date: Fri, 28 Jan 2005 18:40:33 -0500 Subject: what's OOP's jargons and complexities? References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> Message-ID: "Xah Lee" wrote in message news:1106953849.915440.134710 at f14g2000cwb.googlegroups.com... > public class test { > public static void main(String[] args) { > String a = new String("a string"); > String b = new String("another one"); > StringBuffer c = new StringBuffer(40); > c.append(a); c.append(b); > System.out.println(c.toString()); > } > } Actually, it can be as simple as: public class test { public static void main(String[] args) { String c = new String("a string"+" another one"); System.out.println(c); } } I will not get into your "history" of the "OOP hype". From http Fri Jan 7 07:12:54 2005 From: http (Paul Rubin) Date: 07 Jan 2005 04:12:54 -0800 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> Message-ID: <7xis6930ah.fsf@ruckus.brouhaha.com> "Anna" writes: > Having taken some calculus (derivatives, limits, some integrals) but > never even heard of lambda calculus, to me, lambda means absolutely > NOTHING. Less than nothing. Lambda calculus is from mathematical logic, but more to the point "lambda" has been the term used in Lisp for this operation since time immemorial. Since the kinds of programmers who want to use anonymous functions have probably been exposed to Lisp at one time or another, "lambda" should not cause any confusion. From petite.abeille at gmail.com Fri Jan 28 19:50:57 2005 From: petite.abeille at gmail.com (PA) Date: Sat, 29 Jan 2005 01:50:57 +0100 Subject: what's OOP's jargons and complexities? In-Reply-To: <3602hiF4tvskbU1@individual.net> References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> <3602hiF4tvskbU1@individual.net> Message-ID: On Jan 29, 2005, at 01:09, Martin Ambuhl wrote: > Xah Lee wrote his usual masturbatory crap: Well... I have to admit that I tremendously enjoyed such "masturbatory crap" (sic). Eagerly looking toward the next installment. Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From newsgroups at jhrothjr.com Thu Jan 13 14:42:39 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 13 Jan 2005 13:42:39 -0600 Subject: python 2.3.4 for windows: float("NaN") throws exception References: <1105629033.442397.124820@c13g2000cwb.googlegroups.com> Message-ID: <10udjqcu1pqsd4@news.supernews.com> wrote in message news:1105629033.442397.124820 at c13g2000cwb.googlegroups.com... > Hi > > my python 2.3.4 for windows refuse to execute line float("NaN"). It > says: > >>>> float("NaN") > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for float(): NaN > > The same line works as expected on Linux and Solaris with python 2.3.4. > Could anybody explain what is possibly wrong here? is it bug or > feature? > > Andrei As others have gently tiptoed around, it's basically the lack of a group of enthusiastic and dedicated volunteers to make it happen. Nobody is really happy with the current situation, but Python is a volunteer effort, and the current set of volunteers isn't really motivated to put in a very large amount of work on something that they think would have relatively little benefit. In other words, if someone wants to dig in and do the work, I'm sure the core developers will look at it favorably - as long as it meets the usual standards for core development, including documentation and maintainability. The bar is lower than it has ever been, by the way. It used to be: It has to work the same way on all supported platforms. Now it's just: it has to work the same on the core platforms, and if anyone else really wants to work on the others, more power to them. John Roth > From phr at localhost.localdomain Wed Jan 26 23:04:38 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Thu, 27 Jan 2005 04:04:38 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: Skip Montanaro writes: > Because good requirements specification is difficult and testing improves > the breed. Better to have the major API changes and bugs taken care of, and > to have its popularity demonstrated *before* it gets into the Python > distribution. The best way to do something isn't always obvious at the > outset. That is sometimes true, but not always. Sometimes the best way is obvious. > If multiple solutions exist in the community, everyone benefits. > The best survive. The worst don't. What's needed here "good enough", not necessarily "the best conceivable", a level of perfection which is perhaps unattainable. > If one implementation is prematurely chosen for inclusion in the > Python distribution, it stifles the vetting process. There have been exactly zero alternative implementations proposed. > Finally, what if, saints be preserved, your whizbang new module is It is not a whizbang module. It is a stripped-down, basic implementation of a well-accepted set of standards that are being used in thousands of other applications in other languages. > included in the core distribution and it's just not as popular as > was first thought? There is demand for it. Look at how this thread started: some crypto user noticed that rotor was gone and wanted to know what to do instead. The issue of whether there's enough desire for a crypto module to warrant including one in the stdlib was decided a long time ago. The proof of that somebody decided to accept the rotor module into the distro. That decision, that enough users want crypto to make having a stdlib module worthwhile, has never been reversed as far as I know. Rather, the specific module (rotor) was withdrawn because it turned out not to do the job on technical grounds. And the decision not to replace it was based on new legal and political concerns that outweighed the technical side, not on thinking that there wouldn't be enough users. > It just winds up as a weight around the maintainers' necks. Once > included in the distribution it's difficult to remove. The rotor module is gone (and good riddance). That's how this thread started, remember? It shows that bogus modules can be removed. Have you ever used a crypto library in a serious way? Which ones have you used? The python-crypto folks (including myself) have used quite a few of them, and after a while one realizes that the usable ones all do pretty much the same stuff. The one we're talking about does about the same stuff that the rest of them do. It does the same stuff listed in PEP 272, although it's organized a little bit differently in order to make supplying multiple cipher primitives more convenient, which the application that drove PEP 272 apparently didn't need to do. Andrew (the author of PEP 272) has said that the different organization is fine. The different organization is similar to what's done internally in OpenSSL, in Peter Gutmann's cryptlib, in GnuPG, and various other successful programs. It's not radical or experimental. It's old hat and low risk. It provides functionality that's missing from the stdlib. > Even rexec and Bastion, which are both known to be inadequate from a > security standpoint, are still in the distribution. They should be removed pronto, just as rotor was removed. Some other ones should be removed too, like SmartCookie. > So, feel free to implement whatever it is you propose. I don't need your permission to do that. What I'm looking for is an indication that it's worth my while, before I spend the effort. > Register it with PyPI, announce it on comp.lang.python.announce, etc. I don't know how to do that, but the folks who care about it are mostly on the python-crypto mailing list, and the module has been discussed at length there and has been well-received. > Support it for awhile. Run it through a couple revisions to fix API > warts and bugs. I already did that with the Python implementation, and did in fact revise the API somewhat based on reviewer feedback. The C implementation would have the exact same API that the reviewers seem to be happy with. > When it's the category king and there is substantial community > support for inclusion, It's already the category king, because there are precisely zero other entrants in the category. If someone else wants to do one and can get it into the stdlib, I will gladly use theirs and stop worrying about mine. > it will be considered. Not according to how I currently interpret Guido's posts to python-dev about it. I read those as saying that no crypto module will be considered for inclusion whether or not it's the category king, because any such module might conflict with crypto regulations in some countries. No matter how much community support or technical perfection it has, it's just won't be included, period. So tell me again what to do after writing and releasing a C module. There's just no reason to write one, if the module can't go into the stdlib. The stdlib has some special requirements but there are existing crypto modules that I'm using and that work just fine outside of the stdlib, even though they don't meet the stdlib's special needs. The only reason to write a special module just to meet the stdlib's special needs is so that the stdlib can use it. > Python is popular in part because of its fairly conservative development > strategy. That goes for the libraries as well as the language itself. Tell me again how rotor got into the distribution. From itsme at yahoo.com Wed Jan 12 13:26:42 2005 From: itsme at yahoo.com (It's me) Date: Wed, 12 Jan 2005 18:26:42 GMT Subject: counting items References: Message-ID: Thanks. May be flatten should be build into the language somehow.... "Paul McGuire" wrote in message news:aKdFd.8991$RW3.7375 at fe1.texas.rr.com... > "It's me" wrote in message > news:ukdFd.10645$5R.2000 at newssvr21.news.prodigy.com... > > Okay, I give up. > > > > What's the best way to count number of items in a list? > > > > For instance, > > > > a=[[1,2,4],4,5,[2,3]] > > > > I want to know how many items are there in a (answer should be 7 - I don't > > want it to be 4) > > > > > I've sure seen a lot of questions about the flattening of lists. I found > this version of flatten somewhere, I thought I got it from the Python > Cookbook but I can't find it now. Perhaps it was posted here on c.l.py. I > *don't* claim authorship, I'm merely an admirer of such a clean-looking > solution. > > def flatten(a): > if not isinstance(a, (tuple,list)): return [a] > if len(a)==0: return [] > return flatten(a[0])+flatten(a[1:]) > > a = [[1, 2, 4], 4, 5, [2, 3], 6, [6], [], 'askjdf'] > > print len(flatten(a)) > > gives the value 10. > > Considering how often this comes up, might there be a place for some sort of > flatten() routine in the std dist, perhaps itertools? > > -- Paul > > From fuzzyman at gmail.com Wed Jan 12 07:42:55 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 12 Jan 2005 04:42:55 -0800 Subject: [Ann] Voidspace Pythonutils Website Change and Updates In-Reply-To: References: Message-ID: <1105533775.886154.194790@z14g2000cwz.googlegroups.com> Blinkin nora... I did... sorry. Better add a redirect *sigh*. Thanks Fuzzy http://www.voidspace.org.uk/python/index.shtml From aleaxit at yahoo.com Sat Jan 22 03:40:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 09:40:36 +0100 Subject: default value in a list References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: <1gqs9gb.1mmtpcit05ruwN%aleaxit@yahoo.com> TB wrote: > Is there an elegant way to assign to a list from a list of unknown > size? For example, how could you do something like: > > >>> a, b, c = (line.split(':')) > if line could have less than three fields? import itertools as it a, b, c = it.islice( it.chain( line.split(':'), it.repeat(some_default), ), 3) I find itertools-based solutions to be generally quite elegant. This one assumes you want to assign some_default to variables in the LHS target beyond the length of the RHS list. If what you want is to repeat the RHS list over and over instead, this simplifies the first argument of islice: a, b, c = it.islice(it.cycle(line.split(':')), 3) Of course, you can always choose to write your own generator instead of building it up with itertools. itertools solutions tend to be faster, and I think it's good to get familiar with that precious modules, but without such familiarity many readers may find a specially coded generator easier to follow. E.g.: def pad_with_default(N, iterable, default=None): it = iter(iterable) for x in it: if N<=0: break yield x N -= 1 while N>0: yield default N -= 1 a, b, c = pad_with_default(3, line.split(':')) The itertools-based solution hinges on a higher level of abstraction, glueing and tweaking iterators as "atoms"; the innards of a custom coded generator tend to be programmed at a lower level of abstraction, reasoning in item-by-item mode. There are pluses and minuses to each approach; I think in the long range higher abstraction pays off, so it's worth the investment to train yourself to use itertools. In the Python Cookbook new 2nd edition, due out in a couple months, we've added a whole new chapter about iterators and generators, since it's such a major subfield in today's Python (as evidenced by the wealth of recipes submitted to Activestate's online cookbook sites on the subject). A couple of recipes have do with multiple unpacking assignment -- one of them, in particular, is an evil hack which peers into the caller's bytecode to find out how many items are on the LHS, so you don't have to pass that '3' explicitly. I guess that might be considered "elegant", for suitably contorted meanings of "elegant"... it's on the site, too, but I don't have the URL at hand. It's instructive, anyway, but I wouldn't suggest actually using it in any kind of production code... Alex From apardon at forel.vub.ac.be Thu Jan 13 06:22:02 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jan 2005 11:22:02 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-01-13, Fredrik Lundh schreef : > Antoon Pardon wrote: > >> Well, it seems that Guido is wrong then. The documentation clearly >> states that an expression is a statement. > > no, it says that an expression statement is a statement. if you don't > understand the difference, please *plonk* yourself. And what else is an expression statement but an expression (list) used as a statement. -- Antoon Pardon From alan.gauld at btinternet.com Sun Jan 2 03:43:52 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Jan 2005 08:43:52 +0000 (UTC) Subject: screen clear question References: <10teqpdvramua3@corp.supernews.com> Message-ID: <8ucft0tf456g07iuuavgu31m6dhrgjbmh3@4ax.com> On Sun, 02 Jan 2005 14:23:07 +0800, Craig Ringer wrote: > On Sun, 2005-01-02 at 11:31, jcollins wrote: > > Is there a command in Python to clear the screen? That is without writing > > multiple blank lines. > > Without knowing what 'screen' you're talking about, it's hard to say. If > you mean clearing a terminal, you can call 'tput clear' or > '/usr/bin/clear' on many UNIX systems; no idea about Windows. On Windows the DOS CLS command will clear a command prompt, it also works for CP/M and VAX terminals too. Finally I think the curses module allows you to clear a window, including the main window - ie the terminal screen. In each case run CLS (or clear) via os.system() But the bottom line is that there is no builtin command because the mechanism is different on each platform. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From ncoghlan at iinet.net.au Fri Jan 7 11:50:58 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 02:50:58 +1000 Subject: Packaging, dependencies and rates of development In-Reply-To: <5r0tt0l1h465t9n7tc0dbgf00crvt3irme@4ax.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com><7x652che6z.fsf@ruckus.brouhaha.com><7x4qhw859p.fsf@ruckus.brouhaha.com><7xk6qrnbum.fsf@ruckus.brouhaha.com><41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <5fGdnfXE0u2qd0DcRVn-iQ@powergate.ca> <5r0tt0l1h465t9n7tc0dbgf00crvt3irme@4ax.com> Message-ID: <41DEBDF2.50301@iinet.net.au> Bulba! wrote: > When you have it ALL in the single distro, released from time > to time, you can easily test it _together_. You don't > get _temporal dependencies between various versions_. > The released, stable distro has the same things on the > same days, and either it all works together or it doesn't. Except that the difference between the distro maintainers' opinion of what is "stable enough" for inclusion, and the updated version of that module which has some stability problems in areas you don't use but fixes a critical bug in the areas you *do* use is always going to be a problem that has to be dealt with. That's one of the reasons numarray hasn't hit the standard library yet - the Python version release and uptake cycle is too slow for the pace of development they currently require. Similarly, this is also part of the reason IDLE went the way of IDLEFork before being merged back in 2.3 - the development outside the core tree let Kurt and everyone else involved get it up to speed more quickly. There's also the fact that monolithic approaches just plain don't scale - imagining that they can is exactly what leads to the version conflicts that bug you so much, since developers assume that they don't need to care about versioning issues, because the packagers will take care of them. In reality, all it does is move the version conflicts currently noticed by end users and make the packagers try to deal with them instead - and for some of the problems, side-by-side installation of multiple version is the only solution, and that's impossible in the general case without the modules in question providing some versioning mechanism. And so, once again, we're left with developers having to worry about dependency issues. For an example of a well-thought out approach to the versioning issue, take a look at the work that was done for the recent wxPython release: http://wiki.wxpython.org/index.cgi/MultiVersionInstalls What would be ideal is if distutils itself was able to offer a standard package versioning system. Then all module developers would have to do is be aware of how to use the distutils versioning system, and installing side-by-side versions of packages would be create straightforward. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From alipolatel at yahoo.com Sun Jan 23 14:30:36 2005 From: alipolatel at yahoo.com (Ali Polatel) Date: Sun, 23 Jan 2005 11:30:36 -0800 (PST) Subject: on the way to find pi! In-Reply-To: Message-ID: <20050123193036.18196.qmail@web61003.mail.yahoo.com> when we change the code that way the programme gets awful slow when I want to calculate say 100 digits or more .Can't we just get the numbers out of there without changing the code radically thus not making the programme sloww? --------------------------------- Do you Yahoo!? Yahoo! Search presents - Jib Jab's 'Second Term' -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Sun Jan 9 20:06:00 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 09 Jan 2005 20:06:00 -0500 Subject: Python3: on removing map, reduce, filter In-Reply-To: <1105316438.272475.313670@c13g2000cwb.googlegroups.com> References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> <-7mdndrwD_1qOHzcRVn-qQ@comcast.com> <1105316438.272475.313670@c13g2000cwb.googlegroups.com> Message-ID: <41E1D4F8.9050103@holdenweb.com> beliavsky at aol.com wrote: > Steve Holden wrote: > No he didn't. I think you will find you are attributing Steven Bethard's comments to me. [...] > > The Numeric and Numarray Python modules have predefined ufunc's that > are essentially elemental functions with one or two arguments. It would > be nice if one could define new ufunc's using only Python code -- I > presume new ones can currently be added by writing C code. > regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From nytimes at swiftdsl.com.au Wed Jan 5 07:16:20 2005 From: nytimes at swiftdsl.com.au (huy) Date: Wed, 05 Jan 2005 23:16:20 +1100 Subject: Python evolution: Unease In-Reply-To: <7xoeg4txrp.fsf@ruckus.brouhaha.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> Message-ID: <41DBDA94.8020708@swiftdsl.com.au> > The Python advocates who claim that Python is well-documented and take > exception to when someone say it isn't. Their idea of "it's > well-documented" seems to be "if there's parts that you think are > poorly documented, feel free to document it". What kind of nonsense > is that? I'm not sure which planet you come from but open source is open source for a reason. IMO gratitude is the only thing which can be given back to the contributors of open source projects not "what you've given me for FREE is not good enough, go back and do a better job (and by the way I don't really know how you can do a better job) so I can make money off your free time". I don't even expect this much from software I pay for. Being a python user (not contributer) for the past few years I personally think the Python docs are GREAT. If it's not in the reference, it can be found in the source (again thank god for open source), if it's not in the source you have google, then google groups then ASPN python cookbook. If you're not smart enough to do this, well learn. It'll help you become a better programmer. Anyone who thinks Python docs suck haven't browsed javadocs lately, or MSDN. > Software advocacy, which Python has an awful lot of, involves > extolling the virtues of a program as it exists in the present. Not > as it could potentially exist if someone hypothetically added a bunch > of work that hasn't yet been done. Python is good software, but its > advocates are making claims that Python itself doesnt live up to. You should be more accurate. Quote "Python is good software, but its advocates are making claims that [you think it] doesnt live up to". I guess everyone is allowed to have their own opinion. > And no, I don't feel a responsibility to do the missing work, since > I'm not the one making those advocacy claims. Good on ya. Huy From ncoghlan at iinet.net.au Sun Jan 23 00:43:43 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 23 Jan 2005 15:43:43 +1000 Subject: list unpack trick? In-Reply-To: References: Message-ID: <41F3398F.9010701@iinet.net.au> aurora wrote: > I am think more in the line of string.ljust(). So if we have a > list.ljust(length, filler), we can do something like > > name, value = s.split('=',1).ljust(2,'') Eh? Py> s.split('=',1).ljust(2,'') Traceback (most recent call last): File "", line 1, in ? AttributeError: 'list' object has no attribute 'ljust' Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From python-url at phaseit.net Sat Jan 15 10:08:16 2005 From: python-url at phaseit.net (Cameron Laird) Date: Sat, 15 Jan 2005 15:08:16 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 15) Message-ID: QOTW: "Python: it tastes so good it makes you hungrier." -- EP "I don't consider 'throws Exception' to be sloppy, I consider it to be programmers voting with their feet." -- Roy Smith The Centre for Epidemiology and Research has released a high-quality suite of Python-based "Network-enabled epidemiology" tools. Among other packages, NetEpi leverages MxDateTime, Albatross, Numeric Python, pyPGSQL, and RPy: http://mail.python.org/pipermail/python-list/2004-December/257928.html Bengt Richter and John Lenton expertly handle binary data, the latter through reliance on mmap: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d9d74e3df5b7495d/ When tackling tedious capabilities like SSL, experts know to leverage the work--Twisted, Medusa, Apache, ...--of others: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e0ae7d7e43dc606 When tackling tedious capabilities like FASTA, experts know to leverage the work--biopython, mmap, gdbm, ...--of others: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/cf9949fce8d51e7e/ So, you're on a desert island, no credit card, no modern OS, nothing but a thin telnet to the universal IP cloud--you can still practice Python: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/c6e33ffbc0726732 twander 3.160 boasts ... well, read for yourself the details of this quite-cool filesystem browser: http://www.tundraware.com/Software/twander No, you do NOT really want XQuery: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/86afefc7cdad4f6d/ Paul McGuire soberly illustrates pyparse's place in programming: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/387915357b5eb524 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. deli.cio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From adijkstra at baandersconsultancy.nl Thu Jan 6 10:57:04 2005 From: adijkstra at baandersconsultancy.nl (Arjen Dijkstra) Date: Thu, 06 Jan 2005 16:57:04 +0100 Subject: File Handling Problems Python I/O In-Reply-To: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> Message-ID: I don't think we can help if you don't post some of your code. Regards, Arjen Josh wrote: > Hi, > > I am having a problem with Python. I am new to Python as a programming > language, but I do have experience in other languages. I am > experiencing strange problems with File handling and wonder if anyone > else has seen this or knows what I am doing wrong. I am simply trying > to open a file for read and iterate through until the end of file. I am > able to do so without a problem, but here's the catch: The open > statement is only working on certain files. I open a simple text file > say file1.txt without any issues, but I change the open statement to > another text file and it error's out stating the file doesn't exist. I > know the code is correct because it worked for the other file. I have > tried both binary and ascii modes to no avail. Any idea why this is > happening? I am running Python 2.3.4 wxPython 2.5.3.1 and SPE as the > IDE on Win2k. Thanks > > Josh > From ianb at colorstudy.com Sun Jan 2 01:37:28 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Sun, 02 Jan 2005 00:37:28 -0600 Subject: Frameworks for "Non-Content Oriented Web Apps" In-Reply-To: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Message-ID: <41D796A8.1090906@colorstudy.com> mirnazim at gmail.com wrote: > There are great Python Web Application Framework. But most of them are > meant for content oriented web apps. > > Is there something that can ease the development of application that > are not content oriented(I call them "NON CONTENT-ORIENTED WEB > APPLICATIONS" because I don't know what else to call them). Maybe you mean "interactive web applications", as opposed to "document-centric" applications? But then, that's what most frameworks are really designed for. > I mean the > applications like, accounting, high volume data entry apps, where > normally GUI clients have ruled. I know very high quality ERP and > similar packages have been implemented in a web based environment. But > problem is that they have been developed with the tools that were > actually meant for content oriented apps like Zope, PHP, etc. Zope I'd say is content-oriented, though with a bit of imagination you can phrase these applications in terms of "content". PHP and many other Python frameworks are process-oriented, meaning that each request just plain executes some code. Which is true of Zope too, but the basic metaphors in Zope are that a request displays the view of some object, which is a little more abstract way of looking at it. > But is there some sort of framework or something that is actually meant > for such web apps,application that make heavy use of forms, have very > high amount of user interaction etc. Do you mean non-traditional web applications, ala gmail? Probably not, I think you are talking about certain framework concerns that most frameworks aspire to in some fashion, but actually achieve to differing degrees. PEAK addresses some of these, but in a UI-neutral way, and it's quite experimental (at least in the perspective of a whole application; as robust as the individual pieces may be, there's no real model for how to use it for a full application). There's other form processing libraries, but they all are experimental in a way. I developed FormEncode, which relates to some of this. Zope 3 has Schemas, which can be used for form generation and validation, and Plone has Archetypes. I don't think there's anything that's a Whole Package, but Zope 3 and Plone/Archetypes might be the closest (depending on what your vision is). > What I am asking here may sound off beat, but I think, in todays world > where web based solutions offers such a flexibility, we really need it. > > I also know that I am to ambiguous, but as is the characteristic of > this wonderful community, talks that start as most abigous, transform > in crystal clear. > > PS: I am a web developer, using PHP for living. I have been playing > with python for a while. I found python is really a cool language(do I > need to say that ;-)) with a really, really impressive collection of > modules and frameworks. While developing a school information system, I > felt the need of such a framework that makes developing of "Non-Content > Oriented Web-Apps" easy. Eh, it just needs some clear direction for *any* kind of web apps, IMHO. But with what you are specifically asking for, I think it's just a Hard Problem that Is Not Yet Solved, though there is work being done and people are attacking it from different directions. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From steve at holdenweb.com Tue Jan 18 10:28:23 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Jan 2005 10:28:23 -0500 Subject: bind error!!!!! In-Reply-To: References: Message-ID: <__9Hd.78969$Jk5.54454@lakeread01> Perrin Aybara wrote: > hi.. > my code was working pretty well until yesterday.suddenly it started > giving me bind error: address already in use. > but i have logged out and again logged in, but still the problem is not solved > can somebody give me solution for this > > thankx > perrin Next time, please ask a slightly smarter question: www.catb.org/~esr/faqs/smart-questions.html I presume you are talking about a socket-based server program? There's a timeout period during which your server port will be left unusable (according to the TCP standards). You can avoid this by setting the socket.SO_REUSEADDR option when you open your server socket. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From aleaxit at yahoo.com Fri Jan 7 04:05:08 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 10:05:08 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> <7xzmzmurte.fsf@ruckus.brouhaha.com> Message-ID: <1gq0jk7.1m8a9h819ckfhfN%aleaxit@yahoo.com> Paul Rubin wrote: > aleaxit at yahoo.com (Alex Martelli) writes: > > Yes, apart from libraries and similar cases (frameworks etc), it's no > > doubt rare for closed-source "end-user packages" to be sold with > > licenses that include source and allow you to "do anything with it". > > > > However, allowing customization (at least for internal use within the > > customer organization), while rare, is far from unheard of. > > There's no obstacle to doing that with GPL'd software either. Absolutely -- as long as you don't redistribute, np. But Roel was not asking about GPL, he was asking about closed-source licenses -- whether any of them "allow using the [[source]] code *at all*" -- and the answer is that, yes, quite a few do, in specifically constrained ways. Alex From no.email at invalid.domain.fr Sat Jan 15 11:54:46 2005 From: no.email at invalid.domain.fr (Nomak) Date: Sat, 15 Jan 2005 17:54:46 +0100 Subject: Pointer or unique id Message-ID: <1q9pydh06wjuk.fexsf964ckya$.dlg@40tude.net> Hello, does python have an equivalent to Java: int Object.hashCode() ? TIA -- Nomak From abkhd at earth.co.jp Mon Jan 17 15:02:58 2005 From: abkhd at earth.co.jp (A.B., Khalid) Date: 17 Jan 2005 12:02:58 -0800 Subject: protecting the python code. References: <1105884196.461107.28120@z14g2000cwz.googlegroups.com> Message-ID: <1105992178.449961.301280@z14g2000cwz.googlegroups.com> nell wrote: > Hi all, > I've developed a testing application in python, and should supply it in > a way that no one (lets say they are regular users) will understand it > and edit it. > The application source is all python but we expose a UI written in C# > that go over all our code and expose to user functions (Indicated with > a special prefix). > So the problem on one hand is protecting the source and make it less > accessible ond on the other hand to make it available for the UI. > 10x in advance You basically have two options: 1. Use Pyrex to compile your application to be used as (a) module(s). 2. Use Pyrex to compile your application and embed Python in it. The first option is probably the easier of the two, and it only requires that you install Pyrex (http://nz.cosc.canterbury.ac.nz/~greg/python/Pyrex/) and that you study the Docs and the Demos in their respective directories. The second option is more involved but is still possible. You need to follow this: http://lists.copyleft.no/pipermail/pyrex/2004-June/000822.html Many people use Pyrex to write Python extensions only. But given the obvious absence of competitors to address the issue of the protecting of python code, for whatever reason, then I think it is safe to say that Pyrex is now in a unique position to address that issue as well. Please be kindly reminded that even py2exe-- although a great undertaking-- is not AFAIK currrently that protective of your code-- not that it ever claimed it is so-- as draging the resulting exe file to your zip archiever will reveal the python code inside your exe file. And so in short: try the Pyrex way. Regards, Khalid From bokr at oz.net Sun Jan 23 04:13:24 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 23 Jan 2005 09:13:24 GMT Subject: list unpack trick? References: <41f35e59.1590759250@news.oz.net> Message-ID: <41f369f7.1593733767@news.oz.net> On Sun, 23 Jan 2005 08:22:36 GMT, bokr at oz.net (Bengt Richter) wrote: >On Sun, 23 Jan 2005 15:43:43 +1000, Nick Coghlan wrote: > >>aurora wrote: >>> I am think more in the line of string.ljust(). So if we have a >>> list.ljust(length, filler), we can do something like >>> >>> name, value = s.split('=',1).ljust(2,'') >> >>Eh? >> >>Py> s.split('=',1).ljust(2,'') >>Traceback (most recent call last): >> File "", line 1, in ? >>AttributeError: 'list' object has no attribute 'ljust' >> > > Python 2.4b1 (#56, Nov 3 2004, 01:47:27) > [GCC 3.2.3 (mingw special 20030504-1)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> help(''.ljust) > Help on built-in function ljust: > > ljust(...) > S.ljust(width[, fillchar]) -> string > > Return S left justified in a string of length width. Padding is > done using the specified fill character (default is a space). > >I should upgrade too ;-) > And learn to read instead of jumping to conclusions ;-/ No ljust for *LIST* objects, D'oh. Regards, Bengt Richter From duncan.booth at invalid.invalid Sat Jan 1 06:46:01 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jan 2005 11:46:01 GMT Subject: what is lambda used for in real code? References: Message-ID: Diez B. Roggisch wrote: > The doc string of _s_item contains a token the metaclass is aware of and > creates a wrapper around _s_item. That works nice on methods, but I found > that properties got bound to their functions _before_ the metaclass kicks > in, so the property wasn't called in the wrapped version, resulting in > errors. Why not improve your metaclass wrapping so it knows about properties and replaces them with properties containing wrapped functions? That way you could avoid having to remember to write special code like this, and surely the whole point of using a metaclass is so that you can extract the special code and leave your class definition as clean as possible. From danb_83 at yahoo.com Fri Jan 21 22:29:07 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 21 Jan 2005 19:29:07 -0800 Subject: pure python code to do modular-arithmetic unit conversions? References: Message-ID: <1106364547.015502.77940@z14g2000cwz.googlegroups.com> Dan Stromberg wrote: > Is there already a pure python module that can do modular-arithmetic unit > conversions, like converting a huge number of seconds into months, > weeks... Use the divmod function. SECONDS_PER_MONTH = 2629746 # 1/4800 of 400 Gregorian years def convert_seconds(seconds): "Return (months, weeks, days, hours, minutes, seconds)." months, seconds = divmod(seconds, SECONDS_PER_MONTH) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) weeks, days = divmod(days, 7) return months, weeks, days, hours, minutes, seconds def to_seconds(months, weeks, days, hours, minutes, seconds): return (((weeks * 7 + days) * 24 + hours) * 60 + minutes) * 60 + \ seconds + months * SECONDS_PER_MONTH >> convert_seconds(10**9) (380, 1, 1, 1, 28, 40) >>> to_seconds(*_) 1000000000 > or a bandwidth measure into megabits/s or gigabits/s or > megabytes/s or gigabytes/s, whatever's the most useful (ala df -h)? def convert_bytes(bytes): PREFIXES = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'] x = bytes for prefix in PREFIXES: if x < 1024: return '%.4g %sB' % (x, prefix) x /= 1024. # No SI prefixes left, so revert to scientific notation return '%.3e B' % bytes >>> convert_bytes(40e9) '37.25 GB' >>> convert_bytes(2048) '2 KB' From bokr at oz.net Mon Jan 24 22:56:38 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 25 Jan 2005 03:56:38 GMT Subject: Question about reading a big binary file and write it into several text (ascii) files References: <1106599472.099182.312130@z14g2000cwz.googlegroups.com> Message-ID: <41f5b8e5.1745011043@news.oz.net> On 24 Jan 2005 12:44:32 -0800, "Albert Tu" wrote: >Hi, > >I am learning and pretty new to Python and I hope your guys can give me >a quick start. > >I have an about 1G-byte binary file from a flat panel x-ray detector; I >know at the beggining there is a 128-byte header and the rest of the >file is integers in 2-byte format. It looks like 16-bit pixels in the 1024*768 images, I assume > >What I want to do is to save the binary data into several smaller files >in integer format and each smaller file has the size of 2*1024*768 >bytes. You could do that, but why duplicate so much data that you may never look at? E.g., why not a class that provides a view of your big file in terms of an image index and returns an efficient array in memory e.g., (untested) import array def getimage(n, f, offset=128): f.seek(offset+n*2*1024*768) return array('H', f.read(2*1024*768)) # 'H' is for unsigned 2-byte integers (check endianness for swap need!) Then usage would be imfile = open('big_file.bin', 'rb') imarray = getimage(23, imfile) And you could get pixel x,y by xpix, ypix = imarray[x+y*1024] # or maybe x*768+y etc. or your could make getimage a method of a class that you intialize with the file and which could maintain an lru cache of images with a particular disk directory as backup, etc. etc. and would provide images wrapped with nice methods to support whatever you are doing with the images. > >I know I can do something like >>>>f=open("xray.seq", 'rb') >>>>header=f.read(128) >>>>file1=f.read(2*1024*768) >>>>file2=f.read(2*1024*768) >>>>...... >>>>f.close() > >Bur I don't them how to save files in integer format (converting from >binary to ascii files) and how to do this in an elegant and snappy way. Best is probably to leave the original format alone, e.g., (untested and needs try/except) this should split the big file into individual image files named file0.ximg .. filen.ximg f = open('xray.seq/, 'rb') header = f.read(128) nfile = 0 while 1: im = f.read(2*1024*768) if not im: break if len(im) != 2*1024*768: print 'broken tail of %s bytes'%len(im); break fw = open('file%s.ximg' % nfile, 'wb') fw.write(im) fw.close() nfile +=1 then you could use getimage above with offset passed as 0 and image number 0, e.g., im23 = getimage(0, open('file23.ximg','rb'), 0) # img 0, offset 0 But then you might wonder about all those separate files, unless you want to put them on a series of CDs where they wouldn't all fit on one. Whatever ;-) You will probably lose in both speed and space if you try to make some kind of ascii disk files. You aren't thinking XML are you??!! For this, definitely ick ;-) > What you want to do will depend on the big picture, which is not apparent yet ;-) > >Please reply when you guyes can get a chance. >Thanks, Sorry to give nothing but untested suggestion, but I have to go, and I will be off line mostly for a while. Regards, Bengt Richter From luke at tatooine.planet Thu Jan 20 01:51:44 2005 From: luke at tatooine.planet (Luke Skywalker) Date: Thu, 20 Jan 2005 07:51:44 +0100 Subject: Zen of Python References: Message-ID: On Wed, 19 Jan 2005 14:13:47 -0500, Timothy Fitz wrote: >While I agree that the Zen of Python is an amazingly concise list of >truisms, I do not see any meaning in: (snip) For those interested, here's the list: http://www.python.org/doc/Humor.html#zen Luke. From flamesrock at gmail.com Wed Jan 5 16:07:17 2005 From: flamesrock at gmail.com (flamesrock) Date: 5 Jan 2005 13:07:17 -0800 Subject: PIL: Quick Question Message-ID: <1104959237.760156.241480@z14g2000cwz.googlegroups.com> Hi, Is there a method (or trick) in the PIL to set to set the alpha channel of a png to zero? I can't find it in the handbook. -thanks From tim.peters at gmail.com Sat Jan 22 23:31:43 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 22 Jan 2005 23:31:43 -0500 Subject: Zen of Python In-Reply-To: <7xfz0uqe1d.fsf@ruckus.brouhaha.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> Message-ID: <1f7befae050122203165bdc5fe@mail.gmail.com> [Tim Peters] >> But at that time, Python didn't have lexical scoping, and it wasn't >> clear that it ever would. So what's the bigger wart? Making >> listcomps exactly equivalent to an easily-explained Python for-loop >> nest, or introducing a notion of lexical scope unique to listcomps, >> hard to explain in terms of the way the rest of the language worked? [Paul Rubin] > Oops, I'd gotten confused and thought lexical scope came first and > listcomps afterwards. If lexical scope came afterwards, then > implementing listcomps as a for-loop at that time makes more sense. Yes, listcomps were introduced in 2.0b1, lexical scoping in 2.1a2 (via explict __future__ request; you couldn't use it freely before 2.2). > Of course in that case, since the absence of lexical scope was a wart > in its own right, fixing it had to have been on the radar. It's unclear why you believe that. There was almost no demand for lexical scoping across the years before lambda was introduced. After lambda, abuses of the default-argument mechanism to carry bindings into lambda bodies became rampant, and that was an ugliness nobody much liked. If a reasonable solution to that alone had been found that didn't require lexical scoping, I expect that's what Python would have wound up with instead. The case for lexical scoping in Python was never compelling, and Guido didn't do anything to add it except (eventually & reluctantly) agree to stay out of Jeremy Hylton's (my Scheme-head friend) way. Without Jeremy's specific involvement, I doubt we'd have lexical scoping today -- no other developer cared enough to implement it. I'm happy it got in, BTW! It's a reasonably useful feature -- but I was happy enough with Python's original 3-level scoping. > So turning the persistent listcomp loop var into a documented feature, instead > of describing it in the docs as a wart that shouldn't be relied on, wasn't such a > hot idea. It did no harm at the time. Morons (hard to distinguish from "clever programmers" at times) always rely on dubious implementation details, and that won't change, documented or not. The current docs say this (language reference manual): In Python 2.3, a list comprehension "leaks" the control variables of each "for" it contains into the containing scope. However, this behavior is deprecated, and relying on it will not work once this bug is fixed in a future release So they've been warned. > Adding lexical scope and listcomps at the same time might have also been a > good way to solve the issue. Find a way to transform just a smidgen of your hindsight into foresight, and you'll get soooooo rich soooooo fast . From python at jayloden.com Thu Jan 20 13:52:45 2005 From: python at jayloden.com (Jay Loden) Date: Thu, 20 Jan 2005 13:52:45 -0500 Subject: What's the best python web-developer's editor In-Reply-To: <41EFFCD9.7060302@wild-flower.co.uk> References: <41EFFCD9.7060302@wild-flower.co.uk> Message-ID: <200501201352.46030.python@jayloden.com> You didn't mention platform, but I'm guessing from the mention of Screem that you're using a Linux platform. ?On Linux I like kwrite and kate (both similar, kate includes some other features like a built in terminal where you can run some commands, ability to support projects, open multiple files tiled to read all the code at once, etc). ?They both use the same editing portion, which has syntax highlighting for Python and html both. ?Because of KDE network transparency, you can edit files over ftp/save to an ftp site. Just in case, I'll recommend my favorite Windows editor for those times when I'm stuck on Windows - Crimson Editor, http://www.crimsoneditor.com Has syntax highlights, and just about every feature I could possibly ask for in an editor. ?I actually missed this app the most when moving to Linux. -Jay On Thursday 20 January 2005 1:47, andy wrote: > Anybody like to comment on which editor they use for python web app > development - for both discrete and mixed python and html code, ?and why? > > I'm comfortable with IDLE (used it for years) but of course it lacks ftp > or webDAV abilities, obviously because it's not intended for that type > of use. > > I've had a look at Screem - and that seems to do python syntax > highlighting, but it dosn't seem to be python syntax aware (unless > there's a hidden option somewhere). ?Although I can live without auto > indent, I'd rather not... > > I'm sure emacs, xemacs, vi, elvis and so on can do the same, but I have > no experience with them for ?heavy python or html coding, nor the time > to trip off down a blind-alley to find out! ?I know Enough Vi To Get > By(tm) but it's by no means my favourite editor. ?Emacs is a complete > mystery to me. > > I guess I *could* use IDLE and Screem together, but that's a clunky > solution! > > all opinions greatfully received, > -andyj From fuzzyman at gmail.com Fri Jan 28 08:01:57 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 28 Jan 2005 05:01:57 -0800 Subject: Who should security issues be reported to? In-Reply-To: <1106911061.429966.303510@f14g2000cwb.googlegroups.com> References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> Message-ID: <1106917317.595640.149010@z14g2000cwz.googlegroups.com> grahamd at dscpl.com.au wrote: > Aahz wrote: > > In article <1106863164.745581.11920 at f14g2000cwb.googlegroups.com>, > > wrote: > > > > > >Who are the appropriate people to report security problems to in > > >respect of a module included with the Python distribution? I don't > > >feel it appropriate to be reporting it on general mailing lists. > > > > There is no generally appropriate non-public mechanism for reporting > > security issues. If you really think this needs to be handled > > privately, do some research to find out which core developer is most > > likely to be familiar with it. Even before you do that, check > > SourceForge to find out whether anyone else has reported it as a bug. > > I find this response a bit dissappointing frankly. Open Source people > make > such a big deal about having lots of people being able to look at > source > code and from that discover security problems, thus making it somehow > making it better than proprietary source code. From what I can see, if > an > Open Source project is quite large with lots of people involved, it > makes it > very hard to try and identify who you should report something to when > there is no clearly identifiable single point of contact for security > related The sourceforge bug tracker *is* the single right place to post such issues. The py-dev mailing list would be a second *useful* place to post such a comment, although not really the right place. The OP seemed to want an individual with whom he could have a private conversation about it. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml > issues. Why should I have to go through hoops to try and track down who > is appropriate to send it to? All you need is a single advertised email > address > for security issues which is forwarded onto a small group of developers > who can then evaluate the issue and forward it on to the appropriate > person. > Such developers could probably do such evaluation in minutes, yet I > have > to spend a lot longer trying to research who to send it to and then > potentially > wait days for some obscure person mentioned in the source code who has > not touched it in years to respond, if at all. Meanwhile you have a > potentially > severe security hole sitting there wating for someone to expliot, with > the > only saving grace being the low relative numbers of users who may be > using > it in the insecure manner and that it would be hard to identify the > actual web > sites which suffer the problem. > > I'm sorry, but this isn't really good enough. If Open Source wants to > say that > they are better than these proprietary companies, they need to deal > with these > sorts of things more professionally and establish decent channels of > communications for dealing with it. > > And yes I have tried mailing the only people mentioned in the module in > question and am still waiting for a response. From petite.abeille at gmail.com Sat Jan 29 07:20:24 2005 From: petite.abeille at gmail.com (PA) Date: Sat, 29 Jan 2005 13:20:24 +0100 Subject: what's OOP's jargons and complexities? In-Reply-To: <1106969295.944274.269570@f14g2000cwb.googlegroups.com> References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> <1106969295.944274.269570@f14g2000cwb.googlegroups.com> Message-ID: On Jan 29, 2005, at 04:28, beliavsky at aol.com wrote: >> Plus, a man which such cinematographic tastes [1] cannot be entirely >> bad :P >> >> http://xahlee.org/PageTwo_dir/Personal_dir/favorite_movies.html > > The site proves he is evil. Grep "Titus" if you have a strong stomach. > I'm sure you did not get that far. I went all the way down with Ms Carrera :P http://xahlee.org/PageTwo_dir/Personal_dir/porn_movies.html At least give him credit for listing Caro's and Jeunet's "La Cit? des enfants perdus": http://www.imdb.com/title/tt0112682/ After all, it's not always easy "Being John Malkovich": http://us.imdb.com/title/tt0120601/ Specially when you are "Leaving Las Vegas". http://us.imdb.com/title/tt0113627/ In any case, these are just "Sex, Lies, and Videotape": http://us.imdb.com/title/tt0098724/ Perhaps getting "Bound" to those "Heavenly Creatures" is too "Exotica" for you? http://us.imdb.com/title/tt0115736/ http://us.imdb.com/title/tt0110005/ http://us.imdb.com/title/tt0109759/ But lets not play "The Crying Game": http://www.imdb.com/title/tt0104036/ This is all "Pulp Fiction" anyway: http://us.imdb.com/title/tt0110912/ Time to "Run Lola Run" to "Brazil": http://us.imdb.com/title/tt0130827/ http://us.imdb.com/title/tt0088846/ Before "Blade Runner" tracks you down: http://us.imdb.com/title/tt0083658/ Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From morphex at gmail.com Wed Jan 5 21:38:52 2005 From: morphex at gmail.com (morphex) Date: 5 Jan 2005 18:38:52 -0800 Subject: Example of using pty to control a process? In-Reply-To: <41dca050$0$64503$a1866201@visi.com> References: <1104976111.041702.255710@c13g2000cwb.googlegroups.com> <41dca050$0$64503$a1866201@visi.com> Message-ID: <1104979132.345765.80630@z14g2000cwz.googlegroups.com> Oh right. I knew about the -b option, but not the -n 1 option (which isn't required on FreeBSD). Thanks, I'll obviously use that instead! :) Regards, Morten From steven.bethard at gmail.com Sat Jan 1 15:45:48 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 01 Jan 2005 20:45:48 GMT Subject: I need some advice/help on running my scripts In-Reply-To: <1104610483.153374.286730@z14g2000cwz.googlegroups.com> References: <1104610483.153374.286730@z14g2000cwz.googlegroups.com> Message-ID: <0_DBd.316444$HA.294361@attbi_s01> Sean wrote: > My problem is that many of the example scripts are run on Linux > machines and I am using Win XP Pro. Here is a specific example of what > is confusing me. If I want to open a file from the dos prompt in some > script do I just write the name of the file I want to open (assuming it > is in the same directory) after the script name? > such as > > c:\some_script.py some_text_file.txt It's unclear to me what you want to do here. If your some_script.py looks like: import sys f = file(sys.argv[1]) then yes, you can call some_script.py as above, and the file will be readable from the 'f' file object. > Does piping work the same way in dos as it does on a linux machine? Mostly: [D:\Steve]$ type test.py import sys for i, line in enumerate(sys.stdin): sys.stdout.write("%i:%s" % (i, line)) [D:\Steve]$ type input.txt A B C D [D:\Steve]$ python test.py < input.txt 0:A 1:B 2:C 3:D [D:\Steve]$ python test.py > output.txt Z Y X ^Z ^Z [D:\Steve]$ type output.txt 0:Z 1:Y 2:X [D:\Steve]$ python test.py < input.txt > output.txt [D:\Steve]$ type output.txt 0:A 1:B 2:C 3:D [D:\Steve]$ type input.txt | python test.py 0:A 1:B 2:C 3:D Note however, that you may run into problems if you don't explicitly call python: [D:\Steve]$ test.py < input.txt Traceback (most recent call last): File "D:\Steve\test.py", line 2, in ? for i, line in enumerate(sys.stdin): IOError: [Errno 9] Bad file descriptor > And last but not least, is there a way to do this all from IDLE? What exactly do you want to do? You can certainly type something like: f = file('input.txt') in IDLE to get access to the 'input.txt' file... Steve From iizogii at gmail.com Tue Jan 18 00:49:48 2005 From: iizogii at gmail.com (Mike McGavin) Date: Tue, 18 Jan 2005 18:49:48 +1300 Subject: Problem parsing namespaces with xml.dom.minidom Message-ID: <41eca38d@clear.net.nz> Hi everyone. I've been trying for several hours now to get minidom to parse namespaces properly from my stream of XML, so that I can use DOM methods such as getElementsByTagNameNS(). For some reason, though, it just doesn't seem to want to split the prefixes from the rest of the tags when parsing. The minidom documentation at http://docs.python.org/lib/module-xml.dom.minidom.html implies that namespaces are supposed to be supported as long as I'm using a parser that supports them, but I just can't seem to get it to work. I was wondering if anyone can see what I'm doing wrong. Here's a simple test case that represents the problem I'm having. If it makes a difference, I have PyXML installed, or at the very least, I have the Debian Linux python-xml package installed, which I'm pretty sure is PyXML. ======== from xml.dom import minidom from xml import sax text = ''' alias Thu Jan 30 15:06:06 NZDT 2003 Nothing ''' # Set up a parser for namespace-ready parsing. parser = sax.make_parser() parser.setFeature(sax.handler.feature_namespaces, 1) parser.setFeature(sax.handler.feature_namespace_prefixes, 1) # Parse the string into a minidom mydom = minidom.parseString(text) # Look for some elements # This one shouldn't return any (I think). object_el1 = mydom.getElementsByTagName("xte:object") # This one definitely should, at least for what I want. object_el2 = mydom.getElementsByTagNameNS("object", 'http://www.mcs.vuw.ac.nz/renata/xte') print '1: ' + str(object_el1) print '2: ' + str(object_el2) ========= Output is: 1: [] 2: [] ========= What *seems* to be happening is that the namespace prefix isn't being separated, and is simply being parsed as if it's part of the rest of the tag. Therefore when I search for a tag in a particular namespace, it's not being found. I've looked through the code in the python libraries, and the minidom.parseString function appears to be calling the PullDOM parse method, which creates a PullDOM object to be the ContentHandler. Just browsing over that code, it *appears* to be trying to split the prefix from the local name in order to build a namespace-ready DOM as I would expect it to. I can't quite figure out why this isn't working for me, though. I'm not terribly experienced with XML in general, so it's possible that I'm just incorrectly interpreting how things are supposed to work to begin with. If this is the case, please accept my apologies, but I'd like any suggestions for how I should be doing it. I'd really just like to be able to parse an XML document into a DOM, and then be able to pull out elements relative to their namespaces. Can anyone see what I'm doing wrong? Thanks. Mike. From jacek.generowicz at cern.ch Tue Jan 11 03:34:50 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 11 Jan 2005 09:34:50 +0100 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <10u5fu3o7v4h9e3@corp.supernews.com> Message-ID: Jeff Shannon writes: > Jacek Generowicz wrote: > > "Anna" writes: > > > >>But first, wouldn't something like: > >> > >>[x+1 for x in seq] > >> > >>be even clearer? > > I'm glad you mentioned that. [...] > > > As to whether it is clearer. That depends. I would venture to suggest > > > that, given a pool of laboratory rats with no previous exposure to > > Python, more of them would understand the map-lambda than the list > > comprehension. > > > I would venture to suggest the exact opposite, that the syntax of a > list comprehension is in itself suggestive of its meaning, while 'map' > and 'lambda' are opaque until you've researched them. In the population of all laboratory rats, I think that the proportion that would understand either form, would be as good as zero. Given a population with previous exposure to computer programming, my money is on the map-lambda version. But this last point is mostly irrelevant. The fact is that you cannot program computers without doing a bit of learning ... and the lambda, map and friends really do not take any significant learning. > Speaking for *this* laboratory rat, at least, map/lambda was always a > nasty puzzle for me and difficult to sort out. But when list comps > were introduced, after reading just a sentence or two on how they > worked, they were completely clear and understandable -- much more so > than map/lambda after many months of exposure. Forgetting about lambda, map, filter and reduce, do you find that you pass callables around in your Python programs, or is this not typically done in your programs? From steve at holdenweb.com Mon Jan 3 09:33:21 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Jan 2005 09:33:21 -0500 Subject: Advice request for project In-Reply-To: References: Message-ID: <41D957B1.3040500@holdenweb.com> John French wrote: > I've been interested in Python for a while now but haven't had an > opportunity to use / learn it. I'm tasked now with a project at work that > might be my first opportunity. > > I have to write a ~75 concurrent user document storage app. that allows > users to scan documents from locally attached scanners and save to a > database for retrieval. I also need to be able to call MS Word with > templates and allow the user to save the file to the database. I think I > understand that I can interface MS COM for these, correct? > > My interest is in using FreeBSD/Postgresql/Python as a back end and a Python > GUI app on the XP workstations. I'm going to end up adding some > non-database functionality to the project in the future that precludes only > using odbc to the database. I'll likely end up with some form of inter-user > messaging being incorporated before it's over. Is it better to write one > server side socket app to handle everything or start via odbc and necessary > server side apps later? If anyone can tell me if this project seems > appropriate to Python and offer suggestions as to an initial architecture, > I'd appreciate it. I'm quite interested in the RAD aspect of the language > but quite lost at the moment. (I did just sign up for the Tutor mailing > list). > It sounds like an ideal project, and either approach would work. The advantage to avoiding ODBC is that you won't experience any non-local driver limitations which might or might not otherwise bite you in the ass (my PostgreSQL experience is rather limited). Look at the Pyrex package to get you started thinking about remote execution and client/server communications. This lets a program on one machine call methods on objects on another machine. I'm sure you'll get other suggestions as well, but that'll get you started thinking pythonically. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From cpghost at cordula.ws Tue Jan 11 10:10:57 2005 From: cpghost at cordula.ws (Cordula's Web) Date: 11 Jan 2005 07:10:57 -0800 Subject: Gecko bindings for Python? Message-ID: <1105456257.275667.6260@f14g2000cwb.googlegroups.com> Hello, I'd like to use the Gecko engine in GTK+ or Qt programs written in Python. Could you recommend a module for this? A tutorial to get started? I didn't find anything useful, but I may have been looking in all the wrong places... :) Thanks, -cpghost. -- Cordula's Web. http://www.cordula.ws/ From fredrik at pythonware.com Mon Jan 24 10:11:43 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 16:11:43 +0100 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> <7xoefhtavd.fsf@ruckus.brouhaha.com> Message-ID: Sion Arrowsmith wrote: > I'm probably not thinking deviously enough here, but how are you > going to exploit an eval() which has very tightly controlled > globals and locals (eg. eval(x, {"__builtins__": None}, {}) ? try this: eval("'*'*1000000*2*2*2*2*2*2*2*2*2") (for more on eval and builtins, see the "Evaluating Python expressions" section here: http://effbot.org/librarybook/builtin.htm ) From craig.howard at earthlink.net Sun Jan 16 14:46:38 2005 From: craig.howard at earthlink.net (Craig Howard) Date: Sun, 16 Jan 2005 14:46:38 -0500 Subject: Executing a script created by the end user Message-ID: <41EAC49E.70209@earthlink.net> I am working on a python project where an object will have a script that can be edited by the end user: object.script If the script is a simple one with no functions, I can easily execute it using: exec object.script But if the object script is a bit more complicated, such as the example below, my approach does not work: def main(): hello1() hello2() def hello1(): print 'hello1' def hello2(): print 'hello2' From apardon at forel.vub.ac.be Wed Jan 19 03:03:43 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Jan 2005 08:03:43 GMT Subject: lambda References: <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-18, David Bolen schreef : > Antoon Pardon writes: > >> Op 2005-01-18, Simon Brunning schreef : >> > On 18 Jan 2005 07:51:00 GMT, Antoon Pardon wrote: >> >> 3 mutating an item in a sorted list *does* *always* cause problems >> > >> > No, it doesn't. It might cause the list no longer to be sorted, but >> > that might or might no be a problem. >> >> Than in the same vain I can say that mutating a key in a dictionary >> doesn't always cause problems either. Sure it may probably make a >> key unaccessible directly, but that might or might not be a problem. > > Well, I'd definitely consider an inaccessible key as constituting a > problem, but I don't think that's a good analogy to the list case. > > With the dictionary, the change can (though I do agree it does not > have to) interfere with proper operation of the dictionary, while a > list that is no longer sorted still functions perfectly well as a > list. I think we are talking past each other. I'm talking about the concept the programmer has in his mind. If the prgrammer has a sorted list in his mind and an element in that list gets mutated that *does* *always* cause problems. I'm not talking about a list in which the elements happen to be in a particular order, but about a list that will be given to algorithms that depend on the list being ordered. > That is, I feel "problems" are more guaranteed with a > dictionary since we have affected base object behavior, whereas sorted > is not an inherent attribute of the base list type but something the > application is imposing at a higher level. But if the program uses one of the buildin sorts, isn't it then obvious that this is an inherent attribute we want to impose? So is sorting a list with mutable object not also more guaranteed to cause problems. So shouldn't we limit the sort algorithms to containers with immutable elements? > For example, I may choose to have an object type that is mutable (and > not worthy for use as a dictionary key) but maintains a logical > ordering so is sortable. I see no problem with sorting a list of such > objects, and then walking that list to perform some mutation to each > of the objects, even if along the way the mutation I am doing results > in the items so touched no longer being in sorted order. The act of > sorting was to provide me with a particular sequence of objects, Personnaly I don't see what the sorting was good for in this case. And I think such programming might be slightly dangerous if you cooperate with other people. They may not understand the particular nature of your mutation and rely on the fact that your list has been sorted to conclude that it still is sorted. > but > aside from that fact, the list continues to perform perfectly well as > a list even after the mutations - just no longer delivering objects in > sorted order. Which may be a problem for those who rely on it. -- Antoon Pardon From eurleif at ecritters.biz Sun Jan 23 20:21:06 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sun, 23 Jan 2005 20:21:06 -0500 Subject: Quoting sql queries with the DB-API In-Reply-To: References: Message-ID: <35j0nlF4nni9gU1@individual.net> snacktime wrote: > I'm used to using the perl DBI and not very familiar with the python > DB-API. I am using PyGreSQL. My question is what is the standard way > to quote strings in sql queries? I didn't see any quoting functions > in the DB-API docs. Is quoting handled internally by the PyGreSQL > module? > > Also, is this a good way to use variables in an insert/update > statement, or is there a better way? > > sql = "insert into test(a,b) values('%s','%s')" % (a,b) > cursor.execute(sql) If you do it like this: sql = "INSERT INTO test(a, b) VALUES(%s, %s)" # no quotes around the %s cursor.execute(sql, (a, b)) Then the quoting will be handled automatically for you. From ncoghlan at iinet.net.au Sun Jan 23 01:02:51 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 23 Jan 2005 16:02:51 +1000 Subject: default value in a list In-Reply-To: <35fordF4llio5U1@individual.net> References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> <1gqs9gb.1mmtpcit05ruwN%aleaxit@yahoo.com> <35fordF4llio5U1@individual.net> Message-ID: <41F33E0B.7080109@iinet.net.au> Reinhold Birkenfeld wrote: >>Why not put these together and put it in itertools, since the requirement seems >>to crop up every other week? >> >> >>> line = "A:B:C".split(":") >> ... >> >>> def ipad(N,iterable, default = None): >> ... return it.islice(it.chain(iterable, it.repeat(default)), N) >> ... >> >>> a,b,c,d = ipad(4,line) >> >>> a,b,c,d >>('A', 'B', 'C', None) > > > Good idea! > > (+1 if this was posted on python-dev!) Please, please Google the python-dev archives before doing so ;) Cheers, Nick. I seem to recall 'tuple unpacking' as the appropriate phrase. . . -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tim.leslie at gmail.com Thu Jan 13 07:00:34 2005 From: tim.leslie at gmail.com (Tim Leslie) Date: Thu, 13 Jan 2005 23:00:34 +1100 Subject: lambda In-Reply-To: References: Message-ID: Because if it takes more than a single line it deserves a name. Also, if you have more than one line in this function, how do you plan to reference it if not by name? Tim On Thu, 13 Jan 2005 20:53:09 +1000, Egor Bolonev wrote: > why functions created with lambda forms cannot contain statements? > > how to get unnamed function with statements? > -- > http://mail.python.org/mailman/listinfo/python-list > From bokr at oz.net Tue Jan 18 18:55:15 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 18 Jan 2005 23:55:15 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: <41ed8c13.1209309354@news.oz.net> On 18 Jan 2005 13:28:00 GMT, Antoon Pardon wrote: >Op 2005-01-18, Nick Coghlan schreef : >> Antoon Pardon wrote: >>> More specific the Decimal class is mutable and usable as dict key. >> >> It's *meant* to be immutable though. The fact that we used __slots__ instead of >> __setattr__ to implement the immutability, so you *can* overwrite the slot >> variables if you really want to is merely an artifact of the current Python >> implementation. >> >> The limited mutability bug will disappear in Python 2.5, so it's not a good >> example of a 'mutable' dict key (especially given that the only way to mutate it >> is to modify private variables directly). >> >> And, as I've stated previously, if the issue of sane mutable keys in >> dictionaries and sets really bugs you so much - implement identity_dict and >> identity_set in C and lobby for their inclusion in the collections module. > >I'm not bugged by its absence in Python. I'm bugged by the attitude >about them. But anyway I'm thinking about implementing a safe dictionary >that will copy whenever it would otherwise allow the risk of mutating a >key. I encourage you to do it. It should be a rich learning experience. My bet is you will discover something about the real requirements of what you are "thinking about implementing" ;-) IANAP, but ISTM that after a certain point, trying to get made-my-point satisfaction in a thread like this is more like OCD symptomatology than n.g. dialog ;-) > >> On the more general point of "don't use mutable objects with non-identity based >> comparisons as dictionary keys", try teaching students for a while (or listen to >> those who have): > >What kind of students? > >I have implemented a hash table when I was a student and its >implementation allowed the use of 'mutable' objects as a key >without a problem. It simply always made copies when appropiate >and didn't allow external access to the keys. So although the >key objects were 'mutable' there was no way a user could accidently >mutate a key. This is word play IMO. What you describe is effectively using the mutables to construct immutable keys for actual use, not using immutable keys. Having the immutable (because of access restriction) constructed keys allows you to check on their consistency with their source any time you want, but that doesn't change the fact that you have created an alternative dictionary implementation with immutable keys made immutable by copying and access restriction. If you update your dictionary when a key no longer matches its source data, you are just deleting an immutable-by-special-means key and entering the associated value in association with a new immutable-by-special-means key. I can produce OCD symptoms too ;-) > >So don't use a mutable as a dictionary key isn't so much a dictionary >limitation in general but a specific limitation of the python implementation. > >And yes I understand, the current implenatation is the result of the >fact that the same dictionaries are used internally for variables in >scopes and attributes in objects and the fact that no copies are >involved gives a boost to performance. But it could be argued that >providing these same dictionaries with those semantics to the users >was a premature optimisation. If you see a sign like +---------------------------------> | WILD GOOSE CHASE THIS WAY -> +-----------------------------> || || \|/ || =o= || /|\ .`.||,..__|_,. Do you feel that you must make sure? The sign painter may only be indicating what his own experience was, after all. But if it was a core developer's experience, it may be prudent to bet on another trail -- unless you have an extremely interesting hunch. Then you should follow your passion and have your own experience, and you may wind up being able to contribute something (even if only an exclamation point on the sign ;-) > >> When stating useful general principles, it is never, ever worth it to get into >> the quibbly little details about exceptions to the principle. If students ask, >> admit that they exist, but point out that the exceptions are rare, and not worth >> worrying about at that point in their learning. > >But don't use mutable keys is not a general principle. It is a principle >introduced by the limitations of the python implementations. That is so in your mind, and it is so given certain interpretations of the words you are using, but to others "mutable keys" may be a contradiction in terms, because they do not use the words in the same sense as you. If you can't see alternative conceptual constructs you are stuck, and if we can't agree on the meaning of words for a given dialog, we won't be communicating very well. The difficulty is getting people to recognize their implicit assumptions and definitions ;-) > >I don't like it when a good rule of thumb because of implementation >limitations is sold as a general principle. People take short cuts in expressing themselves, just as you do. E.g., you say "mutable key" when you really mean a value that will remain constant while you are using it as a dictionary key. The "safe" dictionary that you are "thinking about" will apparently get its "safety" by ensuring that the "mutable key" can't be "mutated" -- or do you want to discuss which copy is the real "key" ;-) (I don't ;-) Regards, Bengt Richter From jack at performancedrivers.com Thu Jan 20 15:01:03 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Thu, 20 Jan 2005 15:01:03 -0500 Subject: building extensions: ming & python mathlink for win32 In-Reply-To: <20050120193521.37C7A2800129@mwinf1007.wanadoo.fr> References: <20050120193521.37C7A2800129@mwinf1007.wanadoo.fr> Message-ID: <20050120200103.GR26167@performancedrivers.com> On Thu, Jan 20, 2005 at 08:38:35PM +0100, Jelle Feringa // EZCT / Paris wrote: > Have been trying to build python extensions from the C libs ming & mathlink. > Same thing goes for Ming (c lib for compiling flas .swf files), such a pity > no disutils script is included in this very powerful library! > ##if you succeeded to build this, please consider sharing it with me! (2.3 > is fine as well!) > This was asked last month (Dec 7th) so I'll just point to my answer then (I don't know if it worked out for the OP or not). Ming seems unmaintained (and the wiki is usually hosed with spam). The setup.py I mention works for me on linux but it still requires copying files around. If you discover how to do it on windows please reply so there won't be a thread in February too *wink* http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/47c878e2d7688324/18a97ab639d034cf -Jack From vze4rx4y at verizon.net Sun Jan 30 18:14:09 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 30 Jan 2005 23:14:09 GMT Subject: is this sort method the same as the one in python 2.4 References: Message-ID: <5TdLd.31$W16.7@trndny07> "Pedro Werneck" > > What about this ? > > > # > if sys.version_info >= (2,4): > def sorted(iterable, *args, **kwds): > seq = list(iterable) > seq.sort(*args, **kwds) > return seq > # > > It worked against the TestSorted in lib/test/test_builtins.py The key= and reverse= parameters were introduced to list.sort() in Py2.4. Consequently, the above code won't provide the desired functionality in Py2.3 and prior. Raymond Hettinger From __peter__ at web.de Mon Jan 17 11:43:44 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Jan 2005 17:43:44 +0100 Subject: pychecker - sets.Set need to be overridden References: Message-ID: Istvan Albert wrote: > if I have this code: > > import sets > > class Foo: > x = sets.Set() > > then pychecker says: > > test.py:4: Methods (__cmp__, __hash__) in sets.Set need to be overridden > in a subclass > > I don't get this message. What is it trying to say, and why? The minimal example is actually import sets sets.Set() The Set class has implementations for __cmp__() and __hash__() that unconditionally raise an exception. pychecker assumes that these methods are "abstract", i. e. meant to be overriden by a subclass, and warns that you are instantiating an abstract base class, while the intention of the Set class author was to make Sets "uncomparable" and unhashable by overriding the corresponding superclass methods. Peter From jriveramerla at yahoo.com Tue Jan 25 19:22:24 2005 From: jriveramerla at yahoo.com (Jose Rivera) Date: 25 Jan 2005 16:22:24 -0800 Subject: Where can I find Mk4py.dll for Python24? Message-ID: <11e94203.0501251622.760339c3@posting.google.com> Hi I changed for python24 and the only thing missed is metakit for python24. Thanks From steve at holdenweb.com Mon Jan 31 08:01:46 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 08:01:46 -0500 Subject: variable declaration In-Reply-To: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> Message-ID: <41FE2C3A.2050001@holdenweb.com> Alex Martelli wrote: > Alexander Zatvornitskiy > wrote: > > >>Hello All! >> >>I'am novice in python, and I find one very bad thing (from my point of >>view) in language. There is no keyword or syntax to declare variable, like >>'var' in > [...] There are zillions of languages -- use another one. [...] > If Python doesn't fit YOUR brain, for example because your brain is > ossified around a craving for the declaration of variables, then, unless > you're specifically studying a new language just for personal growth > purposes, I think you might well be better off with a language that > DOES, at least until and unless your brain changes by other means. > > > Alex I think we should all remember that Python isn't for everyone, and least of all for those with little knowledge of Python and preconceptions about what Python *should* be like. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From mike at hobbshouse.org Fri Jan 7 11:34:48 2005 From: mike at hobbshouse.org (Michael Hobbs) Date: Fri, 07 Jan 2005 16:34:48 -0000 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: <10tteh884ivk6c9@corp.supernews.com> David Brown wrote: > Hello. I recently came across a free operating system called Unununium (or > something like that) and it was developed in Python and Assembly. > > Now, I have been looking for a way to make an operating system for a long > long time and the only possibilities I could find were C++ and assembly. The problem when using Python instead of C for OS development is that C was *specifically designed* to create an OS, while Python was designed for completely different purposes. If you want to write an OS, it would be wise to use a language that is suited for that purpose. If you dislike C so much and prefer Python so much more, your first step should be to design a Python dialect that is more appropriate for writing OS's. (I know that you mentioned C++, not C, but I decided to setup C as a straw-man to make my argument.) - Mike From flamesrock at gmail.com Mon Jan 3 21:23:52 2005 From: flamesrock at gmail.com (flamesrock) Date: 3 Jan 2005 18:23:52 -0800 Subject: Howto Extract PNG from binary file @ 0x80? In-Reply-To: References: <1102753727.706459.105920@f14g2000cwb.googlegroups.com> <1104797038.407042.32580@z14g2000cwz.googlegroups.com> <1104802606.806575.178870@c13g2000cwb.googlegroups.com> Message-ID: <1104805432.215537.31490@z14g2000cwz.googlegroups.com> omg, it works!! thankyou!!!!! and thankyou again, Frederick for the original code! I've discovered a weird thing when changing header = infile.read(8) to header = infile.read(4): For some reason, the extracted png image is the exact same size as the savegame archive (10.1 megs.) When reading 8bytes, its closer to ~200kb. Any clue as to why that is? -thanks #import struct # #def pngcopy(infile, outfile): # # # copy header # header = infile.read(8) # if header != "\211PNG\r\n\032\n": # raise IOError("not a valid PNG file") # outfile.write(header) # # # copy chunks, until IEND # while 1: # chunk = infile.read(8) # size, cid = struct.unpack("!l4s", chunk) # outfile.write(chunk) # outfile.write(infile.read(size)) # outfile.write(infile.read(4)) # checksum # if cid == "IEND": # break # # #infile = open("mysimcityfile.sc4", "rb") #infile.seek(96) ###print (infile.read(4)) #outfile = open("myimage.png", "wb") #pngcopy(infile, outfile) #outfile.close() #infile.close() (http://simcitysphere.com/peachville.sc4) From a at a.invalid Wed Jan 26 18:54:26 2005 From: a at a.invalid (Timo Virkkala) Date: Wed, 26 Jan 2005 23:54:26 GMT Subject: python without OO In-Reply-To: <1106716951.060290.253010@z14g2000cwz.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> Message-ID: This guy has got to be a troll. No other way to understand. -- Timo Virkkala From crabak at acm.org Sun Jan 30 12:24:50 2005 From: crabak at acm.org (Cesar Rabak) Date: Sun, 30 Jan 2005 15:24:50 -0200 Subject: what's OOP's jargons and complexities? References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> <1107060381.623163.19850@z14g2000cwz.googlegroups.com> <873bwjj8fe.fsf@thalassa.informatimago.com> Message-ID: <41FD1862.9050804@acm.org> Pascal Bourguignon escreveu: > "Larry" writes: > > >>Xah Lee wrote: >> >>>in computer languages, often a function definition looks like this: >> >>> xah at xahlee.org >>> http://xahlee.org/PageTwo_dir/more.html >> >>Your ideas are original, insightful and simply reflect incredibly deep >>creative genius. I have read your work and I want to hire you for >>highly classified work in software design and philosophical writing. >>Would you possibly be available to meet with me in my secret mountain >>compound to discuss terms? >> >>Larry > > > You forgot to mention the coordinates of your secret mountain compound: > > 28 deg 5 min N, 86 deg 58 min E > Pascal!! You spoiled a carefully kept Larry's secret. . . now it will have to change his compound. . . From ncoghlan at iinet.net.au Fri Jan 7 12:32:37 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 03:32:37 +1000 Subject: sorting on keys in a list of dicts In-Reply-To: <1105117539.30384.46.camel@rasputin.localnet> References: <10tr9ejf05pv660@corp.supernews.com> <1105117539.30384.46.camel@rasputin.localnet> Message-ID: <41DEC7B5.1020407@iinet.net.au> Craig Ringer wrote: > Well, that's several hundred more words than were probably required, but > I hope I made sense. Remarkably similar to what I just posted. . . I guess numeric 2-tuples are just too good to pass up when discussing sorting :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From robin at SPAMREMOVEjessikat.fsnet.co.uk Wed Jan 19 19:08:49 2005 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Thu, 20 Jan 2005 00:08:49 +0000 Subject: rotor replacement In-Reply-To: References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> Message-ID: <41EEF691.20706@jessikat.fsnet.co.uk> Nick Craig-Wood wrote: > Robin Becker wrote: > >> Paul Rubin wrote: >> >>>"Reed L. O'Brien" writes: >>> >>> >>>>I see rotor was removed for 2.4 and the docs say use an AES module >>>>provided separately... Is there a standard module that works alike or >>>>an AES module that works alike but with better encryption? >>> >>> >>>If you mean a module in the distribution, the answer is no, for >>>political reasons. >>> >> >> .....I'm also missing the rotor module and regret that something useful >> was warned about and now removed with no plugin replacement. >> >> I had understood that this was because rotor was insecure, but you >> mention politics. Are other useful modules to suffer from politics? >> ... > Presumably he is talking about crypo-export rules. In the past strong > cryptography has been treated as munitions, and as such exporting it > (especially from the USA) could have got you into very serious > trouble. well since rotor is a german (1930's) invention it is a bit late for Amricans (Hollywood notwithstanding) to be worried about its export > However I believe those restrictions have been lifted (the cat having > been let out of the bag somewhat ;-), and its easy to do this for open > source encryption software. A wade through > -- Robin Becker From tech at gpao.cc Mon Jan 31 10:07:32 2005 From: tech at gpao.cc (Olivier Noblanc ATOUSOFT) Date: Mon, 31 Jan 2005 16:07:32 +0100 Subject: import directory error Message-ID: <41fe49b5$0$2168$8fcfb975@news.wanadoo.fr> Hello, When i want to import a .py fire from another subdirectory i make import inc/setupxml but that make me an error message. A man tell me to put a dot but that doesn't work. Can you help me ? Thanks. From http Mon Jan 31 00:59:25 2005 From: http (Paul Rubin) Date: 30 Jan 2005 21:59:25 -0800 Subject: python and gpl References: Message-ID: <7xmzuqgmv6.fsf@ruckus.brouhaha.com> John Hunter writes: > The question is: does shipping a backend which imports a module that > links with GPL code make some or all of the library GPL. Literally speaking, no, not automatically, any more than driving a car makes you into a licensed driver if you weren't one already. But if you weren't licensed, then you've broken the law by driving the car. So your question should be: 1) is shipping that backend one of the things you need the GPL to license you to legally do, and 2) if so, does the GPL in fact give you that license? If you're asking in terms of legal enforcement, the answer is 1) maybe and 2) almost certainly not. I think it's better to ask in terms of the GPL's spirit. I would say that it's not in the GPL's spirit and that GPL die-hards would consider that use objectionable, though they might make exceptions for specific cases (so it doesn't hurt to ask). Some authors who use the GPL are less strict about how they interpret it, so again, the friendly thing to do is ask the author. * If a backend module somebackend does import somelib where somelib is a python wrapper of GPL code, is somebackend GPLd? It's GPL'd if you GPL it. If you don't GPL it, then distributing it it may be a GPL violation that could get you taken to court. I believe the FSF's view is that it is fact a violation; however, the courts have not yet established this. The law doesn't have a black-and-white boundary. It's more like a fractal. The only way to find out what a court will decide is to actually try a case there. Rather than try to probe how closely you can dance around the boundaries of the GPL, you might just ask the author of the GPL'd library whether what you want to do is ok with him or her. If s/he says no and you do it anyway, you're both inviting trouble over the possible infringement, and also inviting people to try to use your code in ways you don't like. Since the free software movement depends on a spirit of cooperation, I think it's best to avoid trying to press too hard against the boundaries of anyone's licenses. http://www.gnu.org/licenses/gpl-faq.html From rbt at athop1.ath.vt.edu Mon Jan 24 10:07:44 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 24 Jan 2005 10:07:44 -0500 Subject: Memory Usage In-Reply-To: References: Message-ID: Peter Hansen wrote: > rbt wrote: > >> Would a Python process consume more memory on a PC with lots of memory? >> >> For example, say I have the same Python script running on two WinXP >> computers that both have Python 2.4.0. One computer has 256 MB of Ram >> while the other has 2 GB of Ram. On the machine with less Ram, the >> process takes about 1 MB of Ram. On the machine with more Ram, it uses >> 9 MB of Ram. >> >> Is this normal and expected behavior? > > > It's probably not normal if this is *really* the memory usage, but > I would expect to see such behaviour, given how difficult it is > to measure *actual* memory usage. How are you measuring it? > Just by looking at the Mem Usage column in the Task Manager? > > -Peter That's right. I look at that column. Should I measue mem usage in some other way? From deetsNOSPAM at web.de Tue Jan 11 10:15:19 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 11 Jan 2005 16:15:19 +0100 Subject: Python serial data aquisition References: <41e1b833$1_3@omega.dimensional.com> Message-ID: <34i5cjF499h0nU1@individual.net> > It all looks pretty god but there is a couple of things I still don't > understand, 1) in Steve's solution (which seems equivalent to your > own), he does the masking, shifts by seven, and then sums the two > numbers while you, instead of summing, use a logical or. How can these > operations be equivalent? or are they? Is the logical or equivalent > to a concatenation? No, but look at this: 111000 + 000111 = 111111 111000 | 000111 = 111111 Adding and or are yielding the same results as long as at least one of the bits combined is zero. By shifting the appropriate number of bits and thus clearing the lower ones and "anding" the second argument with 0x7f, this is ensured for the whole numbers. > > 2) why 7? why do we have shift 7 bits? is that so the 8th bit on byte > one is aligned with the first bit on the second byte? Because of the specification you gave - look at the Byte2 spec closely. -- Regards, Diez B. Roggisch From aahz at pythoncraft.com Thu Jan 13 01:01:18 2005 From: aahz at pythoncraft.com (Aahz) Date: 13 Jan 2005 01:01:18 -0500 Subject: why are people still using classic classes? References: Message-ID: In article , Simon Wittber wrote: > >Is there a legitimate use for classic classes that I am not aware of? >Is there a project to specifically migrate standard library classes to >new-style classes? Exceptions, in addition to the other excellent reasons you've been provided. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From asda at sdarta.com Wed Jan 5 08:09:54 2005 From: asda at sdarta.com (worzel) Date: Wed, 5 Jan 2005 21:09:54 +0800 Subject: is python more popular than coldfusion? References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41dbe722$0$23057$5a62ac22@per-qv1-newsreader-01.iinet.net.au> How seriuosly do folk take the TIOBE index? Is it a good way to ague what you should be keeping up to speed with or just a 'vague' guide? "Premshree Pillai" wrote in message news:mailman.189.1104927428.22381.python-list at python.org... > On Wed, 5 Jan 2005 19:59:21 +0800, worzel wrote: >> >> >> >> is python more popular than coldfusion? > > I don't know if Coldfusion _was_ ever more "popular" than Python, but > Python is definitely more "popular" _now_. > > This might be of some help: http://www.tiobe.com/tpci.htm > >> >> I realsie that is a very general question as one thing does not directly >> relate to the other. My issue is that I am ditching coldfusion due to >> there >> being next to no work for it, and I am thinking of taking on python as a >> second language to java in the hope of improving my resume. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > > -- > Premshree Pillai > http://www.livejournal.com/~premshree From mefjr75 at hotmail.com Tue Jan 25 18:40:06 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 25 Jan 2005 15:40:06 -0800 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> Message-ID: <1106696406.515575.84540@z14g2000cwz.googlegroups.com> Wrap your head around Python, don't wrap the Python around your head! This is NOT Java, or C++ or C , it IS Python. Davor wrote: > (note, I am not an experienced developer, nor the > others I'll be working with (even though some think they are:-)) Don't worry we didn't get confused, it was quite clear ;) Mostly you are just so off base I just say go *READ* and write more Python, look at the standard library. You will only see one or two levels of inheritance as the norm and it is not that difficult. Also you are telling me you don't have an OO problem, you have a problem with your managment and communication skills. > so I prefer preemptively dealing with issue of everyone showing off their OO > design skills) Work on that micro-management just a little bit more, that gets the code flowing ;) hth, M.E.Farmer From bokr at oz.net Tue Jan 11 03:18:11 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 11 Jan 2005 08:18:11 GMT Subject: Python serial data aquisition References: Message-ID: <41e384d0.552090624@news.oz.net> On 9 Jan 2005 14:13:28 -0800, fccoelho at gmail.com (Flavio codeco coelho) wrote: >Hi, > >I am using pyserial to acquire data from an A/D converter plugged to >my serial port. > >my hardware represents analog voltages as 12bit numbers. So, according >to the manufacturer, this number will be stored in two bytes like >this; > |-------------bits(1-8)-----------| >Byte1: x x x n1 n2 n3 n4 n5 >Byte2: x n6 n7 n8 n9 n10 n11 n12 > >where x is some other information, and nx are the digits of my number. > >My problem is to how to recover my reading from these bytes, since >pyserial gives me a character (string) from each byte... I dont know >how to throw away the unneeded bits and concatenate the remaining >bits to form a number... > The others have shown how to recover a 12 bit positive value 0 through 4095, but if the number is signed, and you want the signed value, you'll have to find out how signed numbers are represented. An offset is common, in which case you would subtract 2048 (2**11). If it's two's complement by some chance, you'll want (I think -- untested ;-) to do num -= 2*(num&2048) instead of always num -= 2048 If you need speed in converting large strings of byte pairs, you could convert pairs of bytes with the array module ('H' for unsigned 2-byte numbers) and use the resulting 16-bit numbers as indices into another array of final values prepared beforehand with redundant information that will accomplish the effect of masking and shifting and adjusting sign. If you need this speed, volunteers will magically appear. Maybe even if you don't ;-) Regards, Bengt Richter From jeff at ccvcorp.com Tue Jan 25 17:54:01 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 25 Jan 2005 14:54:01 -0800 Subject: Tuple slices In-Reply-To: <1106669254.838248.317170@z14g2000cwz.googlegroups.com> References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> <1106669254.838248.317170@z14g2000cwz.googlegroups.com> Message-ID: <10vdj4s9ib19fe3@corp.supernews.com> George Sakkis wrote: > An iterator is perfectly ok if all you want is to iterate over the > elements of a view, but as you noted, iterators are less flexible than > the underlying sequence. The view should be (or at least appear) > identical in functionality (i.e. public methods) with its underlying > sequence. So, what problem is it, exactly, that you think you'd solve by making tuple slices a view rather than a copy? As I see it, you get the *possibility* of saving a few bytes (which may go in the other direction) at a cost of complexity and speed. You have greater dependence of internal objects on each other, you can't get rid of the original tuple while any slice views of it exist, you gain nothing in the way of syntax/usage simplicity... so what's the point? To my mind, one of the best things about Python is that (for the most part) I don't have to worry about actual memory layout of objects. I don't *care* how tuples are implemented, they just work. It seems to me that you're saying that they work perfectly fine as-is, but that you have a problem with the implementation that the language tries its best to let you not care about. Is this purely abstract philosophy? Jeff Shannon Technician/Programmer Credit International From gandalf at geochemsource.com Wed Jan 26 08:06:25 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Wed, 26 Jan 2005 14:06:25 +0100 Subject: execute python code from db In-Reply-To: References: Message-ID: <41F795D1.3020708@geochemsource.com> robert wrote: >Hello, > >Anybody knows if it's possible to execute python code from an db. > >db=MySQLdb.connect(host="localhost",user="r",passwd="j",db="v") > >c=db.cursor() >c.execute("""SELECT * FROM table > WHERE id = %s""", (id,)) > >for python_code in c.fetchall(): > execute (python_code) > >Maybe feed python with stdin??. > > http://docs.python.org/lib/built-in-funcs.html Look for these: compile exec eval execfile Also the statement exec: http://docs.python.org/ref/exec.html#l2h-562 I also recommend to look at the documentation of "global","globals" before you try to use them. Best, Laci 2.0 From holywill at gmail.com Mon Jan 17 19:01:15 2005 From: holywill at gmail.com (Will) Date: Tue, 18 Jan 2005 13:01:15 +1300 Subject: PUG in Melbourne Australia? In-Reply-To: <_gQGd.122103$K7.32923@news-server.bigpond.net.au> References: <_gQGd.122103$K7.32923@news-server.bigpond.net.au> Message-ID: <11a4311705011716013ea770b9@mail.gmail.com> Hi , On Mon, 17 Jan 2005 14:50:34 GMT, Emiliano Molina wrote: > Does anyone here know if there is a Python Users Group in Melbourne > Australia? I'm from NZ, but the closest thing to what you're after that I know of is over at Ozzope - Zope in Australia (Zope being built in Python). Have a look at http://www.ozzope.org and you'll find a couple of contacts there who'll be able to refine your search even further. HTH, Will :) ** From the shameless propaganda file: Need a Saatchi-quality copywriter, art director and concepts person, without their price tag? If so, email me and I'll send you the URL of my website. ** From steven.bethard at gmail.com Thu Jan 27 14:16:06 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 12:16:06 -0700 Subject: Question about 'None' In-Reply-To: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: flamesrock wrote: > The statement (1 > None) is false (or any other value above 0). Why is > this? What code are you executing? I don't get this behavior at all: py> 100 > None True py> 1 > None True py> 0 > None True py> -1 > None True py> -100 > None True > (The reason I ask is sortof unrelated. I wanted to use None as a > variable for which any integer, including negative ones have a greater > value so that I wouldn't need to implement any tests or initializations > for a loop that finds the maximum of a polynomial between certain x > values. Anything is greater than nothing, no?) Yup, that's the behavior I get with None. Steve From a at b.c Tue Jan 25 16:19:01 2005 From: a at b.c (Pro Grammer) Date: Tue, 25 Jan 2005 23:19:01 +0200 Subject: Question: "load"ing a shared object in python Message-ID: Hello, all, I am not sure if this is the right place to ask, but could you kindly tell me how to "load" a shared object (like libx.so) into python, so that the methods in the .so can be used? That too, given that the shared object was written in c++, compiled with g++ ? Thanks, Pro Grammer From ajikoe at gmail.com Wed Jan 26 10:46:11 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 26 Jan 2005 07:46:11 -0800 Subject: access private field in python 2.4 Message-ID: <1106754371.637295.82160@z14g2000cwz.googlegroups.com> Hello, I'm new to python, How can I access private field in python. thanks From steve at holdenweb.com Fri Jan 14 11:40:13 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 11:40:13 -0500 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> Message-ID: <41E7F5ED.1010403@holdenweb.com> Antoon Pardon wrote: > Op 2005-01-13, hanz schreef : > >>Antoon Pardon wrote: >> >>>So if I have a call with an expression that takes more than >>>one line, I should assign the expression to a variable and >>>use the variable in the call? >> >>Yes, that's sometimes a good practice and can clarify >>the call. >> >> >>>But wait if I do that, people will tell me how bad that it >>>is, because it will keep a reference to the value which >>>will prevent the garbage collector from harvesting this >>>memory. >> Of course, unless that reference is in the global scope of the __main__ module its lifetime will be transient anyway. If the reference is stored in a function's local variable then unless its value is returned from the function it will become available for garbage collection when the function returns. >>Nobody will tell you that it's bad. > > > Sorry, someone already did. If I recall correctly it > was Alex Martelli. > "A foolish consistency is the hobgoblin of little minds". Rules are made to be broken. Besides which, if you don't understand the language environment, rules alone will do you very little good. Try to focus a little more on principles and a little less on minutiae. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From steven.bethard at gmail.com Wed Jan 19 04:03:07 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 19 Jan 2005 02:03:07 -0700 Subject: generator expressions: performance anomaly? In-Reply-To: References: <377Hd.77904$Jk5.30235@lakeread01> <41ED1C0F.4030800@holdenweb.com> <41eda453.1215517842@news.oz.net> <41edcc68.1225778626@news.oz.net> <_NCdnVV_I9UrZHDcRVn-og@comcast.com> Message-ID: Stephen Thorne wrote: > On Tue, 18 Jan 2005 23:09:57 -0700, Steven Bethard > wrote: > >>@with_consts(i=1, deftime=time.ctime()) >>def foo(x, y=123, *args, **kw): >> return x*y, kw.get('which_time')=='now' and time.ctime() or deftime >> >>Then you don't have to mix parameter declarations with locals definitions. >> >>[1] I have no idea how implementable such a decorator would be. I'd >>just like to see function constants declared separate from arguments >>since they mean such different things. > > > (untested) > > def with_constant(**constants_kwargs): > def decorator(f) > def closure(*arg, **kwargs): > kwargs.update(constants_kwargs) > return f(*arg, **kwargs) > return closure > return decorator This doesn't quite work because it still requires that f take the constants as parameters: py> def with_constant(**constants_kwargs): ... def decorator(f): ... def closure(*arg, **kwargs): ... kwargs.update(constants_kwargs) ... return f(*arg, **kwargs) ... return closure ... return decorator ... py> @with_constant(x=1) ... def f(y): ... return x + y ... py> f(1) Traceback (most recent call last): File "", line 1, in ? File "", line 5, in closure TypeError: f() got an unexpected keyword argument 'x' I screwed around for a while with: ctypes.pythonapi.PyFrame_LocalsToFast(ctypes.py_object(frame), 0) which will let you propagate updates made to frame.f_locals, but only if you don't *add* any locals to the frame, as far as I can tell: py> def f(x=1): ... frame = sys._getframe() ... frame.f_locals["x"] = 2 ... print x ... py> f() 1 py> def f(x=1): ... frame = sys._getframe() ... frame.f_locals["x"] = 2 ... ctypes.pythonapi.PyFrame_LocalsToFast( ... ctypes.py_object(frame), 0) ... print x ... py> f() 2 py> def f(x=1): ... frame = sys._getframe() ... frame.f_locals["y"] = 2 ... ctypes.pythonapi.PyFrame_LocalsToFast( ... ctypes.py_object(frame), 0) ... print y ... py> f() Traceback (most recent call last): File "", line 1, in ? File "", line 6, in f NameError: global name 'y' is not defined Steve From bokr at oz.net Thu Jan 20 02:53:25 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 20 Jan 2005 07:53:25 GMT Subject: delay and force in Python References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> Message-ID: <41ef61f0.1329594776@news.oz.net> On Wed, 19 Jan 2005 23:53:28 +1000, Nick Coghlan wrote: [...] >> Something else: this crashes with a "maximum recursion reached" >> . print stream_enumerate_interval(1,998) >> >> while this does not crash >> . print stream_enumerate_interval(1,900) >> this means Python has a maximum of something like 900 >> recursions? > >The CPython implementation is limited by the stack size allocated by the C >runtime library. The exact recursion limit is platform dependent, but something >around 1000 sounds fairly normal. > ISTM you forgot something ;-) (I.e., that 1000 is only a default value (don't know if same on all platforms)). >>> import sys >>> help(sys.setrecursionlimit) Help on built-in function setrecursionlimit in module sys: setrecursionlimit(...) setrecursionlimit(n) Set the maximum depth of the Python interpreter stack to n. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. The highest possible limit is platform- dependent. Regards, Bengt Richter From kartic.krishnamurthy at gmail.com Mon Jan 3 00:29:20 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 2 Jan 2005 21:29:20 -0800 Subject: [Twisted-Python] Problem with Echoserver (TCP), Help! In-Reply-To: References: Message-ID: <1104730160.375967.119070@c13g2000cwb.googlegroups.com> Hi, My experience with Twisted is also limited but let me try to help you. I tried the same combo as you and it worked well with the following responses: receive: Hello, world! receive: What a fine day it is. receive: Bye-bye! connection lost: Connection was closed cleanly. I am sure you started the server before the client. Do you have some firewall software installed that prevents the client from connecting to the server? Thanks --Kartic From zathras at thwackety.com Sat Jan 8 15:24:36 2005 From: zathras at thwackety.com (Michael Sparks) Date: Sat, 08 Jan 2005 20:24:36 +0000 Subject: Another look at language comparisons References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> Message-ID: <41dfbcb1$0$60694$ed2e19e4@ptn-nntp-reader04.plus.net> Pierre Quentel wrote: > http://khason.biz/blog/2004/12/why-microsoft-can-blow-off-with-c.html I almost didn't look at this, but I'm glad I did - quite a fun comparison, nicely arbitrary and reminds me of RFC in a similar vein :) Michael. From cochrane at physics.uq.edu.au Thu Jan 20 22:43:36 2005 From: cochrane at physics.uq.edu.au (Paul Cochrane) Date: 20 Jan 2005 19:43:36 -0800 Subject: [ANN] PyScript 0.5 released Message-ID: <61de6b8e.0501201943.3cbc9ec3@posting.google.com> PyScript is a python module for producing high quality postscript graphics. Rather than use a GUI to draw a picture, the picture is programmed using python and the PyScript objects. Some of the key features are: * All scripting is done in python, which is a high level, easy to learn, well developed scripting language. * All the objects can be translated, scaled, rotated, ... in fact any affine transformation. * Plain text is automatically kerned. * You can place abritrary LaTeX expressions on your figures. * You can create your own figure objects, and develop a library of figure primitives. * Output is publication quality. LICENSE: Released under the GPL The major change in this release is a complete rewrite of the Path object. The internals have completely changed and there have been some incompatible changes with previous versions but it's now much closer to what was envisaged for the object. There have also been many bug fixes and minor other improvements. For details see the PyScript web page: pyscript.sourceforge.net.

        PyScript 0.5 - a python module for producing high quality postscript graphics; rather than use a GUI to draw a picture, the picture is programmed using python and the pyscript objects. (10-Jan-05) -- paultcochrane at users.sourceforge.net From ola.natvig at infosense.no Tue Jan 25 03:36:55 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Tue, 25 Jan 2005 09:36:55 +0100 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: Message-ID: <72dhc2-8pe.ln1@pluto.i.infosense.no> Roy Smith wrote: > In article , > Quest Master wrote: > > >>I am interested in developing an application where the user has an >>ample amount of power to customize the application to their needs, and >>I feel this would best be accomplished if a scripting language was >>available. However, I want to code this application in Python, and I >>have not yet heard of an implementation of another scripting language >>into Python. >> >>An example of what I mean is this (an implementation of Lua into Ruby >>-- which I'd prefer not to use): http://ruby-lua.unolotiene.com/ >> >>I know C/C++ might be better suited for a task of this kind, but most >>of the modules in my application which need speed have already been >>coded in C++. I want to use Python as the "glue" for this project; >>writing an entire application with a pretty GUI is not fun, as most of >>you may know from previous experience. >> >>So, my question is simply this: is there an implementation of another >>scripting language into Python? > > > Python *is* a scripting language. Why not just let your users write > Python modules which you them import and execute via some defined API? There are examples of XML used for application configuration and in template systems, I don't know how much power you intend to give your users, but if it boils down to simple display logic and some small 'macro' calls to a predefined API, you could make some kind of tagged language for that implementing basic flowcontroll functionality, allowing function calling and definition. You could look at wxWidgets/wxPython's XRC format, which are a XML tagged format that are used to customize layout of wx forms. But I don't think there are a implemented any fully usable scripting languages like that in Python. But it should not be to much work if you don't need many functions. -- -------------------------------------- Ola Natvig infoSense AS / development From tmohr at s.netic.de Sun Jan 9 11:37:58 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Sun, 09 Jan 2005 17:37:58 +0100 Subject: use a file as a database, access rights References: <1105286813.666599.207230@c13g2000cwb.googlegroups.com> Message-ID: Hi, sorry for being unclear and thanks for your answers. Yes, i'd like to use a flat-file database AND access rights. One way i thought of would be to handle the access rights in the script that i write. But to let some other module handle it would also be great. If for example i could embed some SQL database and tell it to store all its tables in ONE FILE it would be quite easy to do. I want to write that application cross-platform, at least Win32 AND Linux. Best regards, Torsten. > Torsten, > > Please explain the environment you are planning to use - Operating > System, whether you have full control of the machine that runs the > database, how many users?. > > If you are using Windows and if your needs are simple, you can use > Access as it has some simple access control that can be setup. > > Also, the part about "database would store all its data in a file" is > not very clear. Are you wanting to use a flat-file database and also > have security implemented in it? If you are on linux/*BSD machine, > consider using a real database. > > Fine access control can be implemented in your application (e.g. only > the creator of a record and his/her superiors can edit it, all others > view it) > > Please send more details to receive useful recommendations. > Thanks, > --Kartic From andersjm at inbound.dk Tue Jan 4 17:33:23 2005 From: andersjm at inbound.dk (Anders J. Munch) Date: Tue, 4 Jan 2005 23:33:23 +0100 Subject: Speed ain't bad References: <0189t05r3226bkp5e1vtmp0gd6odcsf2qp@4ax.com> <41d6a39b$0$33656$edfadb0f@dread16.news.tele.dk> <1104784526.014246.13300@z14g2000cwz.googlegroups.com> Message-ID: <41db19cb$0$223$edfadb0f@dread11.news.tele.dk> "John Machin" wrote: > 1. Robustness: Both versions will "crash" (in the sense of an unhandled > 2. Efficiency: I don't see the disk I/O inefficiency in calling 3. Don't itemise perceived flaws in other people's postings. It may give off a hostile impression. > 1. Robustness: Both versions will "crash" (in the sense of an unhandled > exception) in the situation where zfdir exists but is not a directory. > The revised version just crashes later than the OP's version :-( > Trapping EnvironmentError seems not very useful -- the result will not > distinguish (on Windows 2000 at least) between the 'existing dir' and > 'existing non-directory' cases. Good point; my version has room for improvement. But at least it fixes the race condition between isdir and makedirs. What I like about EnvironmentError is that it it's easier to use than figuring out which one of IOError or OSError applies (and whether that can be relied on, cross-platform). > 2. Efficiency: I don't see the disk I/O inefficiency in calling > os.path.isdir() before os.makedirs() -- if the relevant part of the > filesystem wasn't already in memory, the isdir() call would make it > so, and makedirs() would get a free ride, yes/no? Perhaps. Looking stuff up in operating system tables and buffers takes time too. And then there's network latency; how much local caching do you get for an NFS mount or SMB share? If you really want to know, measure. - Anders From frans.englich at telia.com Sat Jan 8 16:22:43 2005 From: frans.englich at telia.com (Frans Englich) Date: Sat, 8 Jan 2005 21:22:43 +0000 Subject: Documenting data members Message-ID: <200501082122.43151.frans.englich@telia.com> Hello, I have a custom module which among others contains a dictionary, acting as a "constant". I want to document it, but no matter what I do, it doesn't show up in `pydoc`. For example, the following doesn't work: """ A dictionary of the namespaces. """ xmlns = { ... } or xmlns = { """ A dictionary of the namespaces. """ ... } Bottom line: how do I document data members? I also have another documentation question: In a module which I install, the file starts with a comment containing a license header, to then be followed by a Python documentation string("""this module ..."""). The problem is that in pydoc, I get the uninteresting license header as documentation, instead of the doc string. I want to have the license header at the top. Is this somehow fixable? That the doc string, instead of the license header, shows up in pydoc despite the latter being first in the file? Cheers, Frans From annaraven at gmail.com Mon Jan 10 10:07:08 2005 From: annaraven at gmail.com (Anna) Date: 10 Jan 2005 07:07:08 -0800 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: References: <3480qqF46jprlU1@individual.net><41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> Message-ID: <1105369628.887672.82860@c13g2000cwb.googlegroups.com> +1 I really like the idea of this. It removes all my objections to lambdas, and replaces it with something clear and readable. I look forward to seeing what comes of it. Anna From siona at chiark.greenend.org.uk Tue Jan 25 07:38:50 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 25 Jan 2005 12:38:50 +0000 (GMT) Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) References: Message-ID: Jeremy Bowers wrote: > [ ... ] the Python community, and in general the dynamic language >community, has become increasingly confident that private variables don't >solve *real* problems. Years of writing and maintaining others' C++ and Java code (plus one year of maintaining Python code and rather more writing) has led me to believe that there is no justification for truly private variables. "protected" yes, I can see the argument for, but denying derived classes full access to your inner workings just leads to clumsier (less readable and more bug-prone) implementations derivations. (The same applies to Java's "final".) And it's based on the hubris that you are a better programmer than anyone who might want to extend your class and can forsee all circumstances in which it might be subclassed. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From phr at localhost.localdomain Mon Jan 24 17:10:23 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Mon, 24 Jan 2005 22:10:23 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.bro Message-ID: "Fredrik Lundh" writes: > have you tried this, or are you just making things up to be able to > continue the argument? (hint: it doesn't work; python portability > means that it's fairly easy to write programs that run on multiple > platforms, not that they will run on all available platforms without > porting and testing). As an app writer I want to publish code that runs on multiple platforms without needing special attention from the end user, and preferably without needing special platform-specific attention from me. If you want to use the words "Python portability" to mean something weaker than that, that's ok, but I'm trying to accomplish something better. I've written lots of Python code that uses the sha module without my needing to worry about the target platform, so that shows the goal can be met. I'm aiming for an aes/des module that's as convenient for app writers and end users as the sha module is. So now I know what you think "Python portability" means. What do you think "batteries included" means? From "yardholler\" at Nospam,charter.net> Sat Jan 15 07:08:46 2005 From: "yardholler\" at Nospam,charter.net> (Misty) Date: Sat, 15 Jan 2005 06:08:46 -0600 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: <_I7Gd.12337$8q6.12047@fe05.lga> Lucas Raab wrote: > Jane wrote: > >> wrote in message >> news:1105495569.479185.166340 at z14g2000cwz.googlegroups.com... >> >>> python.org = 194.109.137.226 >>> >>> 194 + 109 + 137 + 226 = 666 >>> >>> What is this website with such a demonic name and IP address? What >>> evils are the programmers who use this language up to? >>> >> >> Some people have too much time on their hands... >> >> Jane >> >> > > Better get some ointment for that burn!! From fredrik at pythonware.com Mon Jan 17 12:05:59 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Jan 2005 18:05:59 +0100 Subject: how to stop google from messing Python code References: <1105620098.878376.110250@z14g2000cwz.googlegroups.com><1105704548.146263.229220@f14g2000cwb.googlegroups.com> <1105953885.661245.27570@c13g2000cwb.googlegroups.com> Message-ID: Fuzzyman wrote: >> if you have internet access, you have NNTP access. gmane.org provides access >> to more than 6,500 mailing lists via NNTP, including all relevant Python forums. > > Not if you're behind a censoring proxy that blocks everything except > http. This is a situation many people find themselves in. If you have HTTP-only access, you don't have Internet access. But even if you have HTTP-only access, you can use gmane's various web interfaces. (Had you visited the site, you'd known this already) From daniel at bowettsolutions.com Tue Jan 25 15:55:26 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Tue, 25 Jan 2005 20:55:26 +0000 Subject: MySQLdb In-Reply-To: <351e8871050125125434eb6d2@mail.gmail.com> References: <41F6AF8A.3040102@bowettsolutions.com> <351e8871050125125434eb6d2@mail.gmail.com> Message-ID: <41F6B23E.6010904@bowettsolutions.com> Swaroop C H wrote: >On Tue, 25 Jan 2005 20:43:54 +0000, Daniel Bowett > wrote: > > >>I have just started playing around with MySQLdb for a project I am planning. >> >>As a test I have written a script that executes 3000 insert statements >>on a table. The table contains 10 fields with a mix of text and numbers >>- its a product table for a website eg UPC, ProductName, Price etc. >> >>The problem I have is that it takes just over two minuted to execute the >>3000 insert statements which seems really slow! I am running it on a >>machine with a 1.5 Ghz Pentium M Processor and Gig Of Ram. I dont think >>the machine is to blame for the speed because during execution the >>processor sits at about 10% and there is loads of free RAM. >> >> > >I think a better option is to have the rows in a text file and then >use `mysqlimport` or 'load data infile' SQL[1] > >[1]: http://dev.mysql.com/doc/mysql/en/load-data.html > > > I remember using that a while ago when I dabbled with mysql so I think thats a potential solution. With my current solution I get full error logging with each row i try to insert. Will mysqlimport fail completeley if one row fails? From matthew_shomphe at countrywide.com Fri Jan 21 13:43:43 2005 From: matthew_shomphe at countrywide.com (Matt) Date: 21 Jan 2005 10:43:43 -0800 Subject: Configuring Python for Tk on Mac In-Reply-To: References: Message-ID: <1106333023.891552.106530@z14g2000cwz.googlegroups.com> I googled around and it looks like it might be a permissions error: http://mail.python.org/pipermail/pythonmac-sig/2002-November/006809.html I don't have a Mac, tho', so I have no idea if it works... HTH From Kevin.Smith at sas.com Tue Jan 18 11:54:56 2005 From: Kevin.Smith at sas.com (Kevin Smith) Date: 18 Jan 2005 16:54:56 GMT Subject: One-Shot Property? Message-ID: <20050118115456510-0500@braeburn.themorgue.org> I have many cases in my code where I use a property for calculating a value on-demand. Quite a few of these only need to be called once. After that the value is always the same. In these properties, I set a variable in the instance as a cached value and return that value on subsequent calls. It would be nice if there was a descriptor that would do this automatically. Actually, what would be really nice is if I could replace the property altogether and put the calculated value in its place after the first call, but the property itself prevents me from doing that. Is this possible? -- Kevin Smith Kevin.Smith at sas.com From dwt23 at hotmail.com Thu Jan 20 16:43:05 2005 From: dwt23 at hotmail.com (=?ISO-8859-1?Q?Martin_H=E4cker?=) Date: Thu, 20 Jan 2005 22:43:05 +0100 Subject: Overloading ctor doesn't work? In-Reply-To: <41f010b5$1_1@newspeer2.tds.net> References: <35ab8oF4idc25U1@individual.net> <41effd30$1_1@newspeer2.tds.net> <41f010b5$1_1@newspeer2.tds.net> Message-ID: <35amupF4h5oevU1@individual.net> > Ah, right. The light turns on... > > datetime is immutable so overriding the constructor doesn't change the > constructed object. You have to override __new__ instead. > http://www.python.org/2.2.1/descrintro.html#__new__ Ahhh! Thanks a bunch, now this makes things much clearer. Thanks again! cu Martin -- Reach me at spamfaenger (at) gmx (dot) net From golux at comcast.net Tue Jan 18 03:38:52 2005 From: golux at comcast.net (Stephen Waterbury) Date: Tue, 18 Jan 2005 03:38:52 -0500 Subject: Advice to a Junior in High School? In-Reply-To: <1106034944.793262.19950@z14g2000cwz.googlegroups.com> References: <1106034944.793262.19950@z14g2000cwz.googlegroups.com> Message-ID: <41ECCB1C.6040400@comcast.net> collegebabe2004 wrote: > wow! Aren't we getting ahead of ourselves? ... Well I'm like "yuhhh!" Like, you know, Japanese ... oh I am *so* shur! From jloden at toughguy.net Mon Jan 17 12:47:01 2005 From: jloden at toughguy.net (Jay Loden) Date: Mon, 17 Jan 2005 12:47:01 -0500 Subject: Central New Jersey PIG Meeting -- Python Interest Group In Princeton PIG/IP In-Reply-To: <1105976215.038859.72730@z14g2000cwz.googlegroups.com> References: <1105976215.038859.72730@z14g2000cwz.googlegroups.com> Message-ID: <200501171247.01796.jloden@toughguy.net> Are visitors welcome? I just happen to be in NJ, and I would like to attend my first PIG/IP Also, are you related in any way to LUG/IP? -Jay On Monday 17 January 2005 10:36, drjonfox at gmail.com wrote: > Central New Jersey PIG Meeting -- Python Interest Group In Princeton > PIG/IP > > PIG/IP will hold its first meeting on Jan 19, 2005 at the Lawrenceville > Library (Room #3). Jon Fox will speak about Python's 2.4 release and > then open discussion about Python will be encouraged. > > When: > Wednesday, January 19, 2005 at 7:00 PM > > Where: > Mercer County Library Lawrenceville Branch > 2751 Brunswick Pike > Lawrenceville, NJ 08648 > 882-9246 > Map and directions at http://www.lugip.org/meeting/location/ > > For more information about this group > http://python.meetup.com/156/ > or email > Jon Fox at drjonfox at gmail.com From hancock at anansispaceworks.com Mon Jan 24 20:06:39 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Mon, 24 Jan 2005 19:06:39 -0600 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: Message-ID: <200501241906.39865.hancock@anansispaceworks.com> On Monday 24 January 2005 03:40 pm, Fredrik Lundh wrote: > have you tried this, or are you just making things up to be able to continue > the argument? (hint: it doesn't work; python portability means that it's fairly > easy to write programs that run on multiple platforms, not that they will run > on all available platforms without porting and testing). I don't know, they come pretty close. Problems with portability in pure-python modules have been almost non-existent for me. I almost never test on the Windows platform, but I know some of my code is being used by Windows users. And I guess I won't start, really, because I haven't heard any complaints about it breaking. I *did* have a few problems with Zope packages running on FreeBSD, bizarrely enough, given that it's in the "POSIX" family of OSs, and therefore seems very similar on the surface. And, well, I'm sorry Mr. Lundh, but your PIL module actually is something of a pain to install still. The OP is right about that. Usually worth it, but I don't like the fact that that pain is being passed on to the end-user of my software. The fact that you got all snide and refused to work with me when I asked for a copy of the autoconf sources to try to fix the problem didn't make me too happy, either. So, naturally, I just dropped it. I'm in no position to pick it up now -- just don't need it badly enough now (AFAIK it's unchanged still -- lately I've been using the Debian package though, so I don't have to worry about it). I know that you don't want PIL to go into the core, of course, but I'm pretty sure that problem would've needed fixing, if it were to be introduced. Small problem, trivial to fix, but that's what bothers me about it. Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From eric_brunel at despammed.com Mon Jan 3 09:52:10 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 03 Jan 2005 15:52:10 +0100 Subject: cosmetic Tkinter question In-Reply-To: References: Message-ID: <41d95a46$0$17838$8fcfb975@news.wanadoo.fr> Sean McIlroy wrote: > I've got a bunch of Frames, all packed into the root window with > side=TOP, and in each Frame I've got a Checkbutton packed with > side=LEFT. I expected the Checkbuttons to be flush with the left edge > of the window, but they're not, and it looks a little gross. How do I > get them to align? The standard behaviour for frames is to adapt to their contents, and packing them with side=TOP without any other option will center them in their container. So you have a few solutions to your problem: - use the anchor option when packing the frames; setting anchor=W should do what you want - use fill=X when packing the frames, as Harold said. This expands the frame to the whole width of its container, so this should align the check-buttons (if it doesn't work, add the option expand=1 to force the frame to be wider than its contents) A silly question BTW: why do you use frames? If you have only check-buttons in them, you do not need them: from Tkinter import * root = Tk() for i in range(0, 101, 20): b = Checkbutton(root, text='Option %s' % i) b.pack(side=TOP, anchor=W) root.mainloop() HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From newsgroups at jhrothjr.com Fri Jan 7 18:46:59 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 7 Jan 2005 17:46:59 -0600 Subject: "A Fundamental Turn Toward Concurrency in Software" References: Message-ID: <10tu7s9tjnbur81@news.supernews.com> "aurora" wrote in message news:opsj84xwpo6yt6e7 at news.cisco.com... > Hello! > > Just gone though an article via Slashdot titled "The Free Lunch Is Over: A > Fundamental Turn Toward Concurrency in Software" > [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that the > continous CPU performance gain we've seen is finally over. And that future > gain would primary be in the area of software concurrency taking advantage > hyperthreading and multicore architectures. > > Perhaps something the Python interpreter team can ponder. Well, yes. However, it's not as bad as it looks. I've spent a good part of my professional life with multiprocessors (IBM mainframes) and I have yet to write a multi-thread program for performance reasons. All of those systems ran multiple programs, not single programs that had to take advantage of the multiprocessor environment. Your typical desktop is no different. My current system has 42 processes running, and I'd be willing to bet that the vast majority of them aren't multi-threaded. There are a relatively small number of places where multi-threading is actually useful; many programmers will never run into an application where they need to use it. I think it would be a good idea for the Python team to address decent support for multiprocessors, but I hardly think it is a crisis. John Roth From __peter__ at web.de Mon Jan 24 07:41:52 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Jan 2005 13:41:52 +0100 Subject: delay and force in Python References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> <41EE6658.8000409@iinet.net.au> Message-ID: Nick Coghlan wrote: >> Py> print islice((x for x in xrange(1, 996) if x % 2 == 0), 1, 2).next() >> 4 > > Wouldn't it be nice if this could be spelt: > > print (x for x in xrange(1, 996) if x % 2 == 0)[2] > > Well, I just put a patch on SF to enable exactly that: > http://www.python.org/sf/1108272 I like it. Of course you always have to bear in mind that one giant leap for a list could be _many_ small steps for an iterator. Peter From maxm at mxm.dk Wed Jan 5 16:44:09 2005 From: maxm at mxm.dk (Max M) Date: Wed, 05 Jan 2005 22:44:09 +0100 Subject: smtp question In-Reply-To: References: Message-ID: <41dc5f5d$0$289$edfadb0f@dread12.news.tele.dk> Philippe C. Martin wrote: > Hi, > > I am testing the smtp module and have the following question: > > in the code below (taken from net sample) prior to adding the "Subject:" > field, the email client found the "From" and the "To". Without the > "Subject:" field on I get this: > > Email client = Evolution: the "From" field is blank > Email client = KMail: the "To" field is blank > > Any clue ? It' very easy to create email messages with the email module. >>> from email.Message import Message >>> fromaddr = 'maxm at mxm.dk' >>> to = 'maxm at mxm.dk' >>> msg = Message() >>> msg['Subject'] = 'From Python' >>> msg['From'] = fromaddr >>> msg['To'] = to >>> body = "This is the message content" >>> msg.set_payload(body) Thats all. Though some smtp servers needs a Date header too, to work. >>> from time import gmtime, strftime >>> msg['Date'] = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) Sending the message via the smtp module is even simpler. >>> import smtplib >>> server = smtplib.SMTP('localhost') >>> server.sendmail(fromaddr, [to], msg.as_string()) >>> server.quit() -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From tdelaney at avaya.com Thu Jan 13 17:46:29 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 14 Jan 2005 09:46:29 +1100 Subject: sorted (WAS: lambda) Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE025202A5@au3010avexu1.global.avaya.com> Terry Reedy wrote: > No, not same difference. A list method would only operate on lists, > as is true of all list methods. Being a function lets it work for > any iterable, as is true of any function of iterable. Big > difference. And consistent. One could argue though that it should > have been put into itermethods module instead of builtins. Definitely not. iter*tools* is primarily for functions that take iterators and *return* iterators i.e. don't use memory proportional to the length of the iterator. OK - so there are one or two exceptions, but their presense there has been strongly justified (and nowhere else seems appropriate - for example, itertools.tee). Tim Delaney From no at spam.invalid Mon Jan 24 15:15:07 2005 From: no at spam.invalid (Russell E. Owen) Date: Mon, 24 Jan 2005 12:15:07 -0800 Subject: Configuring Python for Tk on Mac References: Message-ID: In article , martyn_quick at yahoo.co.uk (Martyn Quick) wrote: >On my desk here at work I have a Mac G4 running Mac OS X v10.2.8. > >When I go into a terminal and type "python" up comes a nice python >interface and all seems great. However when I type "import Tkinter" >I'm greeted by the following error.... Assuming you are running MacPython from ... Install Aqua Tcl/Tk as another poster suggested. Run Applications/MacPython.../Package Manager and install Tkinter. Or if your MacPython is out of date, you may just want to download and install the current version. If Tcl/Tk is already installed then I think it will install Tkinter automatically (but if not, use Package Manager). If you are running some other python, please tell us more about it. (If it's fink python, install the version that includes Tkinter support, but this runs on X11 instead of Aqua). -- Russell From rnd at onego.ru Tue Jan 4 12:46:47 2005 From: rnd at onego.ru (Roman Suzi) Date: Tue, 4 Jan 2005 20:46:47 +0300 (MSK) Subject: Lambda as declarative idiom (was RE: what is lambda used for in real code?) In-Reply-To: <6vyCd.617042$wV.607079@attbi_s54> References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> <6vyCd.617042$wV.607079@attbi_s54> Message-ID: On Tue, 4 Jan 2005, Steven Bethard wrote: >Roman Suzi wrote: >> On Mon, 3 Jan 2005, Steven Bethard wrote: >> >> >>>Roman Suzi wrote: >>> >>>>I wish lambdas will not be deprecated in Python but the key to that is >>>>dropping the keyword (lambda). If anybody could think of a better syntax for >>>>lambdas _with_ arguments, we could develop PEP 312 further. >>> >>>Some suggestions from recent lambda threads (I only considered the ones >>>that keep lambda as an expression): >> >> Wow! Is there any wiki-page these could be put on? > >It's now on: > >http://www.python.org/moin/AlternateLambdaSyntax > >and I added Bengt Richter's and your recent suggestions. Hmmm... what if we kill two rabbits in one blow: lambda will be even more implicit, if we just mark parameters by a back-quote while using PEP 312 convention: (:f(`a) + o(`b) - o(`c)) (:`x * `x) (:x) (:x.bar(*`a, **`k)) Not sure about default args: ((fun(x=x, a=a, k=k): x(*a, **k)) for x, a, k in funcs_and_args_list) Maybe this needs to be done with closures. Otherwise I think Python interpreter is quite capable to determine which parameters the function has... Only their order become a problem. Probably, ","-s could be used there: (`a,`b,`c : f(`a) + o(`b) - o(`c)) The whole expressions could be quoted: `(x, y, z) meaning a parameter with such structure. >Steve > Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From deetsNOSPAM at web.de Thu Jan 13 07:32:36 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 13 Jan 2005 13:32:36 +0100 Subject: Iteration over two sequences References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> <34kvs0F4bqiviU1@individual.net> Message-ID: <34n82lF4dec78U1@individual.net> My example is somewhat flawed because it assigns a and b the values of the iteration - so in the end, b is 'c', and only setting a to [1,2] will show your results. Use c and d for the variables in the for-statments, and things work as expected. -- Regards, Diez B. Roggisch From fuzzyman at gmail.com Fri Jan 14 07:09:08 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 14 Jan 2005 04:09:08 -0800 Subject: how to stop google from messing Python code In-Reply-To: <1105666406.272397.170730@c13g2000cwb.googlegroups.com> References: <1105620098.878376.110250@z14g2000cwz.googlegroups.com> <1105666406.272397.170730@c13g2000cwb.googlegroups.com> Message-ID: <1105704548.146263.229220@f14g2000cwb.googlegroups.com> Xah Lee wrote: > gmane is great! its renaming of newsgroups is quite a headache. > i found that comp.lang.python corresponds to gmane.comp.python.general. > do you know which one corresponds to comp.lang.perl.misc? > there's no .misc or .general... > > -- > i thought there a strick like preceding a line by -- or something that > prevents google from reformating the post. > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html I guess that most people use google to post to newsgroups is that they don't have nntp access. Telling htem to use a newsreader is facetious and unhelpful. Google strips leading whitespace. Putting *anything* before indentation stops the formatting getting messed up. It doesn't stop long lines being wrapped of course. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From ncoghlan at iinet.net.au Sun Jan 16 06:05:59 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 16 Jan 2005 21:05:59 +1000 Subject: How to del item of a list in loop? In-Reply-To: <1105836175.289357.158650@z14g2000cwz.googlegroups.com> References: <34rvjqF4f6l70U1@individual.net> <34s7omF4emdsaU1@individual.net> <1105836175.289357.158650@z14g2000cwz.googlegroups.com> Message-ID: <41EA4A97.5020000@iinet.net.au> John Machin wrote: > Nick Coghlan wrote: >>The effbot's version is still going to be faster though: >> lst = [x for x in lst if x != 2] > > > Have you measured this? Nope. I'm going purely on the fact that it is O(n), and the in-place modification will always be worse than that. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steve at holdenweb.com Fri Jan 14 17:14:28 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 17:14:28 -0500 Subject: query python env In-Reply-To: References: Message-ID: Michael Hoffman wrote: > David Bear wrote: > >> How does one query the python environment, ie pythonhome > > > sys.prefix > > > pythonpath > > sys.path > >> etc. > > [...] I suspect rather that the OP is looking for os.environ, as in: [sholden at headrat sholden]$ ENVAR=value [sholden at headrat sholden]$ export ENVAR [sholden at headrat sholden]$ python Python 2.2.1 (#1, Aug 30 2002, 12:15:30) [GCC 3.2 20020822 (Red Hat Linux Rawhide 3.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ["ENVAR"] 'value' regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From cwilbur at mithril.chromatico.net Wed Jan 26 04:39:26 2005 From: cwilbur at mithril.chromatico.net (Charlton Wilbur) Date: Wed, 26 Jan 2005 09:39:26 GMT Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106723545.429728.308620@f14g2000cwb.googlegroups.com> Message-ID: <87ekg8zgcz.fsf@mithril.chromatico.net> >>>>> "XL" == Xah Lee writes: XL> I've used the Python tutorial's chapter on class as XL> an example. I've indicated that proper tutorial should be XL> simple, covering just common cases, be self-contained, and be XL> example based. "Correct" is not in your list of criteria. Big surprise, that. Followups set appropriately. Charlton -- cwilbur at chromatico dot net cwilbur at mac dot com From tom.willis at gmail.com Fri Jan 28 08:52:09 2005 From: tom.willis at gmail.com (Tom Willis) Date: Fri, 28 Jan 2005 08:52:09 -0500 Subject: win32com/makepy question In-Reply-To: <9A28C052FF32734DACB0A288A3533991035A06@vogbs009.gb.vo.local> References: <9A28C052FF32734DACB0A288A3533991035A06@vogbs009.gb.vo.local> Message-ID: Wow Thanks!!!! I didn't even know about the gencache that's is exactly what I was hoping for. On Fri, 28 Jan 2005 09:06:15 -0000, Tim Golden wrote: > [Tom Willis] > > | It seems in COM late binding is something that should be > | avoided if possible. > | > | Because python seems to be really good at doing thing dynamically I'm > | wondering why no one has figured out how to make the functionality in > | makepy fire automagically when you need it. > > I (nearly) always use win32com.client.gencache.EnsureDispatch. There > are a few occasions when it refuses to play, and then I'm back to > Dispatch. > > > import win32com.client > > word = win32com.client.gencache.EnsureDispatch ("Word.Application") > # > # does the same as Dispatch ("Word.Application") but does > # the makepy stuff first if it needs to. > # > > > > TJG > > ________________________________________________________________________ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > ________________________________________________________________________ > -- > http://mail.python.org/mailman/listinfo/python-list > -- Thomas G. Willis http://paperbackmusic.net From martinnitram at excite.com Wed Jan 19 03:04:42 2005 From: martinnitram at excite.com (martinnitram at excite.com) Date: 19 Jan 2005 00:04:42 -0800 Subject: safest way to kill a thread In-Reply-To: References: <1106106497.429643.307440@f14g2000cwb.googlegroups.com> <1106115159.200989.60870@c13g2000cwb.googlegroups.com> Message-ID: <1106121882.809441.12670@z14g2000cwz.googlegroups.com> Great thank for your helping. Should the 'daemonic' flag at setDaemon() function set to 1/TRUE or 0/FALSE to do such action? limodou wrote: >I think only those threads which invoked with setDaemon() method will >exit, and others will not, as the main program exit. From steve at holdenweb.com Sat Jan 29 20:40:30 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 29 Jan 2005 20:40:30 -0500 Subject: Hey, get this! [was: import from database] In-Reply-To: References: Message-ID: Peter Otten wrote: > Steve Holden wrote: > > >>This is even stranger: it makes it if I import the module a second time: > > > [second import seems to succeed] > > Maybe you are experiencing some version confusion? What you describe looks > much like the normal Python 2.3 behaviour (with no import hook involved) > whereas you seem to operate on the 2.4 library. > A partially initialized module object is left behind in sys.modules and seen > by further import attempts. > I agree that this is 2.3-like behavior, but Python cannot lie ... sholden at dellboy ~/Projects/Python/dbimp $ python Python 2.4 (#1, Dec 4 2004, 20:10:33) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> > $ cat arbitrary.py > > import not_there > > def f(): > print "you ain't gonna see that" > > $ python > Python 2.3.3 (#1, Apr 6 2004, 01:47:39) > [GCC 3.3.3 (SuSE Linux)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import arbitrary > > Traceback (most recent call last): > File "", line 1, in ? > File "arbitrary.py", line 2, in ? > import not_there > ImportError: No module named not_there > >>>>import arbitrary >>>>arbitrary.f() > > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'f' > > > I have no experience with import hooks, but for normal imports that has been > fixed in Python 2.4: > > $ py24 > Python 2.4 (#5, Jan 4 2005, 10:14:01) > [GCC 3.3.3 (SuSE Linux)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import arbitrary > > Traceback (most recent call last): > File "", line 1, in ? > File "arbitrary.py", line 2, in ? > import not_there > ImportError: No module named not_there > >>>>import arbitrary > > Traceback (most recent call last): > File "", line 1, in ? > File "arbitrary.py", line 2, in ? > import not_there > ImportError: No module named not_there > > > Peter > $ cat arbitrary.py import not_there def f(): print "you ain't gonna see that" sholden at dellboy ~/Projects/Python/dbimp $ python Python 2.4 (#1, Dec 4 2004, 20:10:33) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import arbitrary Traceback (most recent call last): File "", line 1, in ? File "arbitrary.py", line 1, in ? import not_there ImportError: No module named not_there >>> import arbitrary Traceback (most recent call last): File "", line 1, in ? File "arbitrary.py", line 1, in ? import not_there ImportError: No module named not_there >>> Yup, looks like 2.4 (despite this funny cygwin stuff, could that make a difference). Let me try it under Windows [ferkle, ferkle ...] Does the same thing there. This problem also seems to depend what's already loaded. I wrote a program to write a test program that looks like this: import dbimp dbimp.install() print "Trying aifc" try: import aifc except: print "%Failed: aifc" print "Trying anydbm" try: import anydbm except: print "%Failed: anydbm" print "Trying asynchat" try: import asynchat except: print "%Failed: asynchat" ... import dbimp dbimp.install() print "Trying aifc" try: import aifc except: print "%Failed: aifc" print "Trying anydbm" try: import anydbm except: print "%Failed: anydbm" print "Trying asynchat" try: import asynchat except: print "%Failed: asynchat" The two platforms give expectedly close results. I'm storing compiled code, so a version incompatibility would be a problem, I agree, but I have checked the program that loaded the database, and loaded it again from the Windows source rather than the CygWin source, just to see whether there were any unnoticed platform dependencies. The results were exactly the same using either library, and Windows and Cygwin showed only minor variations. exhaustCyg24.txt:%Failed: bsddb.dbtables exhaustCyg24.txt:%Failed: bsddb.test.test_all exhaustCyg24.txt:%Failed: bsddb.test.test_associate exhaustCyg24.txt:%Failed: bsddb.test.test_basics exhaustCyg24.txt:%Failed: bsddb.test.test_compat exhaustCyg24.txt:%Failed: bsddb.test.test_dbobj exhaustCyg24.txt:%Failed: bsddb.test.test_dbshelve exhaustCyg24.txt:%Failed: bsddb.test.test_dbtables exhaustCyg24.txt:%Failed: bsddb.test.test_env_close exhaustCyg24.txt:%Failed: bsddb.test.test_get_none exhaustCyg24.txt:%Failed: bsddb.test.test_join exhaustCyg24.txt:%Failed: bsddb.test.test_lock exhaustCyg24.txt:%Failed: bsddb.test.test_misc exhaustCyg24.txt:%Failed: bsddb.test.test_queue exhaustCyg24.txt:%Failed: bsddb.test.test_recno exhaustCyg24.txt:%Failed: bsddb.test.test_thread exhaustCyg24.txt:%Failed: tzparse exhaustWin24.txt:%Failed: bsddb.dbtables exhaustWin24.txt:%Failed: bsddb.test.test_all exhaustWin24.txt:%Failed: bsddb.test.test_associate exhaustWin24.txt:%Failed: bsddb.test.test_basics exhaustWin24.txt:%Failed: bsddb.test.test_compat exhaustWin24.txt:%Failed: bsddb.test.test_dbobj exhaustWin24.txt:%Failed: bsddb.test.test_dbshelve exhaustWin24.txt:%Failed: bsddb.test.test_dbtables exhaustWin24.txt:%Failed: bsddb.test.test_env_close exhaustWin24.txt:%Failed: bsddb.test.test_get_none exhaustWin24.txt:%Failed: bsddb.test.test_join exhaustWin24.txt:%Failed: bsddb.test.test_lock exhaustWin24.txt:%Failed: bsddb.test.test_misc exhaustWin24.txt:%Failed: bsddb.test.test_queue exhaustWin24.txt:%Failed: bsddb.test.test_recno exhaustWin24.txt:%Failed: bsddb.test.test_thread exhaustWin24.txt:%Failed: pty exhaustWin24.txt:%Failed: rlcompleter exhaustWin24.txt:%Failed: tzparse As a workaround I can for the moment just omit everything that show the least suspicion of not working from the database, but I'd really rather know what's failing. If you have any clues I'd be grateful. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From peter at engcorp.com Sat Jan 8 13:05:48 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Jan 2005 13:05:48 -0500 Subject: "A Fundamental Turn Toward Concurrency in Software" In-Reply-To: <10tu7s9tjnbur81@news.supernews.com> References: <10tu7s9tjnbur81@news.supernews.com> Message-ID: John Roth wrote: > I have yet to write a multi-thread program for performance reasons. If we include in the set of things covered by the term "performance" not only throughput, but also latency, then I suspect you actually have written some multithreaded programs for "performance" reasons. *I* certainly have: that's easily the reason for threading in 95% of the cases I've dealt with, and I suspect those of many others. -Peter From martin at v.loewis.de Thu Jan 20 12:46:12 2005 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 20 Jan 2005 18:46:12 +0100 Subject: xml parsing escape characters In-Reply-To: <41efe52f$0$6220$e4fe514c@news.xs4all.nl> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efb72d$1_2@newspeer2.tds.net> <41efe52f$0$6220$e4fe514c@news.xs4all.nl> Message-ID: <41efee5d$0$11622$9b622d9e@news.freenet.de> Irmen de Jong wrote: > The unescaping is usually done for you by the xml parser that you use. Usually, but not in this case. If you have a text that looks like XML, and you want to put it into an XML element, the XML file uses < and >. The XML parser unescapes that as < and >. However, it does not then consider the < and > as markup, and it shouldn't. Regards, Martin From fumanchu at amor.org Mon Jan 31 11:12:09 2005 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 31 Jan 2005 08:12:09 -0800 Subject: variable declaration Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33982F2@exchange.hqamor.amorhq.net> Alex Martelli wrote: > If Python doesn't fit YOUR brain, for example because your brain is > ossified around a craving for the declaration of variables, > then, unless > you're specifically studying a new language just for personal growth > purposes, I think you might well be better off with a language that > DOES, at least until and unless your brain changes by other means. *shudder* Once a VB coder, always a VB coder? Whatever your first shop uses, you're stuck with for life? Again, I say *shudder*. Bah. Nothing teaches you a new language like having your job depend upon it. People who study languages merely for "personal growth" learn 50% of the syntax and 1% of the concepts, and then fritter that learning away on inconsequential newsgroups the world over. Alex Z, keep using and learning Python. Let it change your brain. Robert Brewer MIS Amor Ministries fumanchu at amor.org From matippc at gmail.com Sat Jan 15 14:50:41 2005 From: matippc at gmail.com (matippc at gmail.com) Date: 15 Jan 2005 11:50:41 -0800 Subject: LOOK AT THIS!! Message-ID: <1105818641.933566.15950@f14g2000cwb.googlegroups.com> I swear it works! I just did it, and it worked!!! Instructions: Please read this over completely. It is extremely powerful and will pay you very well. This is not MLM or a ponzi scheme or gifting. All funds come from the company's advertisers so You Pay Nothing! -- not one penny. The company pays you to promote it -- you don't pay them. It doesn't take any money to start, and takes only 5-10 minutes to set up. It can pay nearly $350,000 at NO Cost to You except a little time. The Details: Carefully follow the instructions below...and hopefully you may be willing to give it a chance...after all the opportunity is totally FREE...nothing out of your pocket now or ever! You will make $100 in the next (3) minutes if you want it... WITHOUT SPENDING A DIME! This will cost YOU NOTHING! - HONEST! "Yeah right," you say. You get $100 just for joining and the referral potential earnings is STAGGERING! You will NEVER SEND MONEY, NEVER SPEND anything and NEVER ASK FOR MONEY, but you will make THOUSANDS! Just follow the steps below. * * * THREE STEP PROCESS * * * Read Very Carefully & Take Your Time for Accuracy Listed below are three e-mail addresses & sign-up URLs. (1) First, sign-up at RichMails.com - Under the first (1st) ID and You'll get $100 just for joining. [You can't use AOL for this. I would suggest free www.Yahoo.com or another email account you might have.] So Click on the #1 Position's url and Sign-up. (2) Next, send an e-mail to the #3 - third person on the list and put in subject line: "I signed up under #1" (3) Now, Copy and paste this letter into a file. Delete the person in the #1 position of this letter. Move the other two URLs - UP to #1 & #2 positions respectively, and INSERT YOUR information at the BOTTOM, in the #3 position. Please be sure you copy or type YOUR e-mail and your new RichMails sign up URL correctly and the other 2 addresses also! Replace your own name where mine now is. FINAL STEP Send this ad until you have 3 responses saying they signed up under #1. That's it, only 3 responses, not 6 or 10 or 20, (just 3)! Of course, you can mail more and make more, too! When your address gets to the #1 position, you will have (27) people signed up under you! Not bad, but ONLY THE BEGINNING. A short (very short) time later, each of those 27 people will have 27 people signed up under them which equals 729, and so on. RichMails pays you for everyone who subscribes under you for three levels, and it adds up fast! They make their money from the advertisers. See calculations below...Here's how the payout works: Your own sign-up $100 First level is 27 X $25 referral 675 Second level is 729 X $25 referral 18,225 Third level is 19,683 X $25 referral 492,075 Here is the list of names: #1: http://www.RichMails.net/cgi-bin/signup.cgi?r=tangirl1042000 at yahoo.com #2: http://www.RichMails.com/cgi-bin/signup.cgi?r=windblade20 at hotmail.com #3: http://www.RichMails.com/cgi-bin/signup.cgi?r=matippc at gmail.com Mail to me with the subject: (I have signed up under #1) TO: matippc at gmail.com A WORD OF CAUTION: "IF YOU CHEAT, YOU LOSE"! And, the people above you, know it! This is the reason you would lose: It must go through all (3) levels to work! The Money builds up and goes to you! If you type your information in the #1 position, you will only make, maximum, $75! Once you have your page set up, simply advertise it everywhere and anywhere( spamfree or course) and watch your income e-x-p-l-o-d-e- Don't forget funding your favorite charity! See ya at the Top!! May you be richly Blessed Sincerely, Matt.- From sp1d3rx at gmail.com Wed Jan 12 10:40:36 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 12 Jan 2005 07:40:36 -0800 Subject: Excel module for Python In-Reply-To: References: Message-ID: <1105544436.518262.183240@c13g2000cwb.googlegroups.com> that's easy. Just make an html file of your data, using tables and save it as a "*.xls" and excel will think it's an excel file. From donn at drizzle.com Sat Jan 1 13:39:01 2005 From: donn at drizzle.com (Donn Cave) Date: 1 Jan 2005 12:39:01 -0600 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> Message-ID: <41d6ee45$1_2@127.0.0.1> Quoth Hans Nowak : | Paul Rubin wrote: | |> You should write unit tests either way, but in Python you're relying |> on the tests to find stuff that the compiler finds for you with Java. | | As I wrote on my weblog a while ago, I suspect that this effect is | largely psychological. You jump through hoops, declaring types all over | the place, checking exceptions, working around the language's | limitations, etc. So when your code compiles, it *feels* safer. Like | you're at least part of the way towards ensuring correctness. All that | work must be good for *something*, right? Never mind that when writing | unit tests for a dynamic language, you don't check for these things at | all. How often do you explicitly check types in Python unit tests? | IMHO, when using a dynamic language, you don't need most of the checks | that Java, C# and their ilk force upon you. I have been fooling around with strongly, statically typed languages for a couple of years, in my spare time - Objective CAML, Haskell, O'Haskell. This is a little different experience than what you two are talking about - I don't think Java, C# and their ilk are quite as rigorous, nor do they use type inference - but as much as it would probably gag an FP enthusiast to say this, the basic idea is the same. I can only believe that if you think the benefit of static typing is psychological, either something is very different between the way you and I write programs, or you're not doing it right. For me, the effect is striking. I pound out a little program, couple hundred lines maybe, and think "hm, guess that's it" and save it to disk. Run the compiler, it says "no, that's not it - look at line 49, where this expression has type string but context requires list string." OK, fix that, iterate. Most of this goes about as fast as I can edit, sometimes longer, but it's always about structural flaws in my program, that got there usually because I changed my mind about something in midstream, or maybe I just mistyped something or forgot what I was doing. Then, when the compiler is happy -- the program works. Not always, but so much more often than when I write them in Python. Now you may repeat here that we all must make thorough unit testing a cornerstone of our Python programming, but don't tell me that the advantage of static typing is psychological. It does substantially improve the odds that a program will be correct when it runs, because I have seen it happen. If unit testing does so as well, then obviously there will be some redundancy there, but of course only where you actually have complete coverage from unit testing, which not everyone can claim and I'm sure even fewer really have. And like the man said, you're doing that work to find a lot of things that the compiler could have found for you. Donn Cave, donn at drizzle.com From foo at bar.com Mon Jan 17 17:58:24 2005 From: foo at bar.com (Steve Menard) Date: Mon, 17 Jan 2005 17:58:24 -0500 Subject: Integration with java (Jpype vs. JPE) In-Reply-To: References: <34s5krF4c85d5U1@individual.net> Message-ID: Istvan Albert wrote: > Cameron Laird wrote: > >> Someone really ought to include a couple of sentences to that effect >> on the front page of . > > > Now I remember visiting this site, but never understood how it > actually worked. Examples such as: > > from jpype import * > startJVM("d:/tools/j2sdk/jre/bin/client/jvm.dll", "-ea") > java.lang.System.out.println("hello world") > shutdownJVM() > > in three different versions are the only code examples > that to show "complete" working snippets. I'm still > clueless as to how would one say share a list between > python and java. > > Istvan. > > I am sorry you find the site so confusing ... perhpas I shold post a more complete example in a prominent location ... To asnwer your question more fully, the jpype-specific cide is only for looking up the Classes and startting/stopping the environment. For everything else, Java objects and classes are used as regular Python objects. In version 0.4.x, the API mostly remain Java's. This means some of the basic magic python methods have been mapped to java equivalent (like __str__ mapped to toString() and __eq__ mapped to equals()). If you have any questions, feel free to post them on the feedback list on sourceforge. I check it every day and I try to answer as quickly as possible. Steve, aka devilwolf on sourceforge, maintainer of JPype From luisXX_lupe2XX at netvisaoXX.pt Thu Jan 20 14:10:08 2005 From: luisXX_lupe2XX at netvisaoXX.pt (Luis P. Mendes) Date: Thu, 20 Jan 2005 19:10:08 +0000 Subject: xml parsing escape characters In-Reply-To: <41efedf2$0$11622$9b622d9e@news.freenet.de> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efedf2$0$11622$9b622d9e@news.freenet.de> Message-ID: <35adg4F4jgvpnU1@individual.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I would like to thank everyone for your answers, but I'm not seeing the light yet! When I access the url via the Firefox browser and look into the source code, I also get: <DataSet> ~ <Order> ~ <Customer>439</Customer> ~ </Order> </DataSet> should I take the contents of the string tag that is text and replace all '<' with '<' and '>' with '>' and then read it with xml.minidom? how to do it? or should I use another parser that accomplishes the task with no need to replace the escaped characters? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFB8AIQHn4UHCY8rB8RAuw8AJ9ZMQ8P3c7wXD1zVLd2fe7MktMQwwCfXAND EPpY1w2a3ix2s2vWRlzZ43U= =bJQV -----END PGP SIGNATURE----- From koko9991 at compuserve.de Thu Jan 6 11:38:55 2005 From: koko9991 at compuserve.de (Konrad Koller) Date: Thu, 06 Jan 2005 16:38:55 GMT Subject: curses is not imported under Linux (and Python 2.4) Message-ID: <41dd65bd.785984171@news.compuserve.de> import curses produces the ImportError: No module named _curses ("from _curses import *" in line 15 in __init__.py) Of course imp.find_module ("_curses") reports the same error. How can I make use of the curses package for writing a Python script with curses? From rupole at hotmail.com Wed Jan 19 01:10:14 2005 From: rupole at hotmail.com (Roger Upole) Date: Wed, 19 Jan 2005 01:10:14 -0500 Subject: Window capture using WM_PRINT and Python References: <41ed7017$0$23339$7a628cd7@news.club-internet.fr> Message-ID: <41edfa52$1_2@127.0.0.1> Do you get any kind of traceback when you start a process that way? There's not much info to go on. Sys.argv parameters are passed as strings. You'll need to do an int() on them before you can use them as handles. Also, not all handles are portable between processes. Your device context handle might not be valid even if you make it an int. hth Roger "arN" wrote in message news:41ed7017$0$23339$7a628cd7 at news.club-internet.fr... > Hi ! > > I'm a Java developper and I wish to make a capture of an offscreen window > (on WinXP). It's not possible in Java, so I use a python script and > WM_PRINT, but it doesn't seem to work. > > Could someone have a look at my script and give me any advise ? > > TIA > > -- > Arnaud > my python script : python snap.py GraphicalContext_handle image_handle > -------------------------------------------------------------------------------------------------- > snap.py : > " > import win32api, win32con, sys > > win32api.SendMessage(sys.argv[2], win32con.WM_PAINT, sys.argv[3], 0) > win32api.SendMessage(sys.argv[2], win32con.WM_PRINT, sys.argv[3], > win32con.PRF_CHILDREN | win32con.PRF_CLIENT | win32con.PRF_OWNED) > " > > ------------------------------------------------------------------------------------------------ > snippet from Snapshot.java : > " > public static Image snapshot(Composite bean) { > GC gc = new GC(bean); > final Image image = new Image (null, bean.getBounds().width, > bean.getBounds().height); > String commmand = "python snap.py " + gc.handle + " " + image.handle; > > Runtime rt = Runtime.getRuntime(); > try { > Process p = rt.exec(command); > } catch (.....) > > gc.dispose(); > return image; > } > " ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From golux at comcast.net Thu Jan 6 10:36:43 2005 From: golux at comcast.net (Stephen Waterbury) Date: Thu, 06 Jan 2005 10:36:43 -0500 Subject: Developing Commercial Applications in Python In-Reply-To: <87pt0iegga.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> <87pt0iegga.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: <41DD5B0B.6070901@comcast.net> Nick Vargish wrote: > eeykay at gmail.com writes: > >>Can somebody there to point me any good commercial applications >>developed using python ? > > Python is used in several games ... Also see Python Success Stories: http://pythonology.org/success A notable example is Verity's search engine -- see http://python.oreilly.com/news/PythonSS.pdf Steve From b at b.b Mon Jan 10 13:10:13 2005 From: b at b.b (Roose) Date: Mon, 10 Jan 2005 18:10:13 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> <7xu0ppyjjg.fsf@ruckus.brouhaha.com> Message-ID: <9yzEd.9081$wZ2.6859@newssvr13.news.prodigy.com> "Paul Rubin" wrote in message news:7xu0ppyjjg.fsf at ruckus.brouhaha.com... > "Roose" writes: > > Are you actually going to answer any of my questions? Let's see > > this "JavaScript task scheduler" you have written! > > I wrote it at a company and can't release it. It ran inside a > browser. There was nothing terribly amazing about it. Obviously the > tasks it scheduled were not kernel tasks. Do you know how Stackless > Python (with continuations) used to work? That had task switching, > but those were not kernel tasks either. Well, then of course you know I have to say: An OS does not run inside a browser. There's a sentence I never thought I'd utter in my lifetime. So that is an irrelevant example, since it obviously isn't a task scheduler in the context of this thread. Anyway, this argument is going nowhere... I will admit that people have pointed out things here that are interesting like the attempts to embed Python in a kernel. But the point was that the OP was looking for an easier way to write an OS, and thought that might be to do it in Python, and I think I gave some good guidance away from that direction. That is mostly what I care about. These other arguments are academic, and of course I am not trying to stop anyone from trying anything. When I we see real working example, then we will all have a better idea of what the problems are, and how much of it can realistically be implemented in an interpreted language. Frankly I don't think that will come for about 10 years if ever, but hey prove me wrong. From cpl.19.ghum at spamgourmet.com Wed Jan 26 03:55:22 2005 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Wed, 26 Jan 2005 08:55:22 +0000 (UTC) Subject: py2exe problem References: <41f7213c$0$2343$a1866201@visi.com> Message-ID: Grant Edwards > LookupError: no codec search functions registered: can't find encoding > Googling for the error message will find you the answer. http://starship.python.net/crew/theller/moin.cgi/Py2Exe carries within "encodings" and "encodings again" receipes to get it working. A software development system which REALLY solves the encodings problem WITHOUT creating a swarm of new ones could would challange even my devotedness to Python :)))) Harald From philippecmartin at sbcglobal.net Tue Jan 25 21:11:57 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Tue, 25 Jan 2005 20:11:57 -0600 Subject: Crypto in Python: (Was: What's so funny? WAS Re: rotor replacement) Message-ID: <1106705517.7317.21.camel@localhost> >In the USA, it's pretty simple, you just send an email to an address >at the BXA telling them what you're exporting. >See http://www.bxa.doc.gov/Encryption for info. I wish it were so :-) So far getting the agreement for my product has taken two months of work (http://www.bis.doc.gov/encryption/) .... I hope to get a positive response this week (wish me luck!) Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From beliavsky at aol.com Fri Jan 28 22:28:15 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 28 Jan 2005 19:28:15 -0800 Subject: what's OOP's jargons and complexities? References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> Message-ID: <1106969295.944274.269570@f14g2000cwb.googlegroups.com> PA wrote: > Plus, a man which such cinematographic tastes [1] cannot be entirely > bad :P > > http://xahlee.org/PageTwo_dir/Personal_dir/favorite_movies.html The site proves he is evil. Grep "Titus" if you have a strong stomach. I'm sure you did not get that far. From BOOGIEMANPN at YAHOO.COM Sun Jan 2 15:52:42 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Sun, 2 Jan 2005 21:52:42 +0100 Subject: How to make executable file ? Message-ID: Just how to make *.exe file from python code ?? I typed this : a, b = 0, 1 while b < 1000: print b, a, b = b, a+b and saved it as pyt.txt Now, how do I make pyt.exe file ??? I want to run it on windows where isn't installed python. From rkern at ucsd.edu Tue Jan 11 18:16:56 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 11 Jan 2005 15:16:56 -0800 Subject: complex numbers In-Reply-To: References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: It's me wrote: > You are focusing on computational type applications of complex numbers. For > those, you can do it with any languages - including machine language. It's > just a matter of how much headache you want. > > For instance, when constructing "software lego parts" (such as the > Matlab/Simulink type), it's very annoying that you need to know what kind of > signal comes in and goes out. In Malab/Simulink, for instance, you specify > that the signal is of the "inherit" type (meaning you don't care what type > it is - just process it). In Python, it's of type "duck", just pass it > on...I don't need to care if it's real or complex. I don't need to devise > yet another overloaded operator or function whenever I encounter a situation > where the native language doesn't handle. I'm not sure what you're talking about here. Python's complex numbers are implemented with operator overloading. Python's integers are implemented with operator overloading for that matter. The only difference between having complex numbers in the standard library (analogous to Math::Complex, if I'm reading these posts correctly; I don't use Perl) and having complex numbers in the language, per se, is the syntactical support: >>> 5.0+1.j versus >>> complex(5, 1) That's *it*. Okay, on reflection, there's a little bit more to it: since complex objects come as part of the interpreter, writing C extensions that use complex objects is a little simpler. You don't have to include special header files and make sure the correct module is imported before using complex objects in the C code (like you have to do with Numeric, for example). -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From nick at craig-wood.com Fri Jan 21 05:30:02 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 21 Jan 2005 10:30:02 GMT Subject: Overloading ctor doesn't work? References: <35ab8oF4idc25U1@individual.net> Message-ID: Martin H?cker wrote: > Now I thought, just overide the ctor of datetime so that year, month and > day are static and everything should work as far as I need it. > > That is, it could work - though I seem to be unable to overide the ctor. :( > > Why is that? Its a bug! http://sourceforge.net/tracker/index.php?func=detail&aid=720908&group_id=5470&atid=105470 However its been fixed in a recent Python 2.3. (I was bitten by the same thing which used to fail but now works after an upgrade of python 2.3!) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jeff at ccvcorp.com Mon Jan 24 20:38:21 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon, 24 Jan 2005 17:38:21 -0800 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: Message-ID: <10vb8cve125v0b0@corp.supernews.com> Roy Smith wrote: > In article , > Quest Master wrote: > >>So, my question is simply this: is there an implementation of another >>scripting language into Python? > > Python *is* a scripting language. Why not just let your users write > Python modules which you them import and execute via some defined API? Because you cannot make Python secure against a malicious (or ignorant) user -- there's too much flexibility to be able to guard against every possible way in which user-code could harm the system. Parsing your own (limited) scripting language allows much better control over what user-code is capable of doing, and therefore allows (at least some measure of) security against malicious code. To the O.P.: Yes, people have implemented other languages in Python. For example, I believe that Danny Yoo has written a Scheme interpreter in Python (Google tells me it should be at http://hkn.eecs.berkeley.edu/~dyoo/python/pyscheme but I'm getting no response from that host right now), but I don't know whether Scheme counts as a scripting language. ;) However, if you're using a fully-featured language for these user scripts, you'll probably have the same security issues I mentioned for Python. Unless you really need that level of features, you may be better off designing your own limited language. Check into the docs for pyparsing for a starter... Jeff Shannon Technician/Programmer Credit International From esj at harvee.org Tue Jan 18 16:53:54 2005 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 18 Jan 2005 16:53:54 -0500 Subject: anydbm biasing Message-ID: I have a preference for gdbm when building DBM based dictionaries but have found I cannot count on it being there all the time. Therefore, I have created this little tidbit which you call before opening your anydbm database to bias the preference towards gdbm instead of dbhash: # bias DBM towards gdbm if at all possible. def bias_anydbm(): """bias anydbm to gdbm""" try: _mod = __import__("gdbm") except ImportError: pass else: # and other words, if you can import gdbm, make it the default anydbm._defaultmod = _mod usage: bias_anydbm() open_DBM = anydbm.open(DBM_path, 'c') if you have gdbm enabled, it will use that otherwise it will default to the search list in anydbm. obviously, this can be used to bias anydbm to meet your own preferences ---eric From gurpreet.sachdeva at gmail.com Thu Jan 13 08:14:35 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Thu, 13 Jan 2005 18:44:35 +0530 Subject: pyPgSQL giving error! Message-ID: I am using Redhat 9.0/python2.3. I installed pyPgSQL-2.4.tar.gz and it was successfull. Now when I am trying to import that module, I got: Python 2.3.3 (#1, Jan 11 2005, 15:24:09) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from pyPgSQL import PgSQL Traceback (most recent call last): File "", line 1, in ? File "pyPgSQL/PgSQL.py", line 391, in ? from libpq import * File "pyPgSQL/libpq/__init__.py", line 23, in ? from libpq import * ImportError: No module named libpq I tried googling also but couldn't get the answere. Please help... ~Garry From spamfranke at web.de Fri Jan 14 11:51:52 2005 From: spamfranke at web.de (neophyte) Date: 14 Jan 2005 08:51:52 -0800 Subject: import keyword behaviour - performance impact if used multiple times? References: <41a87cd9$0$25779$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1105721512.379401.266490@c13g2000cwb.googlegroups.com> Nick Coghlan wrote: > > Is > > this something to do with system modules being singletons? > > They aren't singletons in the GoF design pattern sense. However, Python's import > machinery operates in such a way that it takes effort to get multiple version of > the same module into memory at the same time (it *can* be done, but you have to > work at it). Given that this is exactly what I want, how can you do it? From fumanchu at amor.org Fri Jan 7 16:37:07 2005 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 7 Jan 2005 13:37:07 -0800 Subject: Exception report library Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398134@exchange.hqamor.amorhq.net> Ian Bicking wrote: > I've been using one of several systems to catch unexpected exceptions > and log them (e.g., write to a file, display on web page, email me, > etc). But many are built into a particular system, or have an > interesting but incomplete set of features. E.g., many web > frameworks have exception reporters (and the stdlib includes cgitb), > but I want to handle non-web exceptions in the same way as exceptions > from web requests, and that's not generally easy. ... > I feel like there must be something out there, since every Python > programmer has to deal with this sort of thing to some degree...? I feel that way, too, but haven't found it. I broke my webapp framework out of my ORM late last year, and quickly realized how small the core framework really is (22k, versus 250k for the web bits). Features like the logging handler could be provided as separate modules, rather than built into the Application object, and I've been meaning to get around to that. If we could put our many heads together, I think this would be doable for the stdlib. Here are the pieces of the framework, by the way, which might also benefit from some standardization (I was thinking about them all at once): 1. Thread-safe application state 2. Logging (+ exception handling) 3. Configuration data (reading from various sources) 4. Registry of Workers for getting things done on a schedule, possibly recurring 5. Registry of startup/shutdown functions 6. Registry of active user interfaces I think the first three are all good candidates for a standard. If we had a standard, thread-safe Application object, the rest could be registerable plugins for that. You'd basically register callbacks for app.startup and .shutdown methods to iterate over. Robert Brewer MIS Amor Ministries fumanchu at amor.org From jdhunter at ace.bsd.uchicago.edu Tue Jan 25 12:35:37 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 25 Jan 2005 11:35:37 -0600 Subject: ANN: matplotlib-0.71 Message-ID: matplotlib is a 2D graphics package that produces plots from python scripts, the python shell, or embeds them in your favorite python GUI -- wx, gtk, tk, fltk currently supported with qt in the works. Unlike many python plotting alternatives is written in python, so it is easy to extend. matplotlib is used in the finance industry, web application servers, and many scientific and enginneering disciplines. With a large community of users and developers, matplotlib is approaching the goal of having a full featured, high quality, 2D plotting library for python. http://matplotlib.sourceforge.net What's new in matplotlib 0.71 numerix refactor The organization of the numerix module was refactored to be mindful of namespaces. See http://matplotlib.sf.net/API_CHANGES. pylab no longer overrides the built-ins min, max, and sum, and provides amin, amax and asum as the numerix/mlab versions of these. pylab defines __all__ to prevent surprises when doing from pylab import *. To see the complete list of symbols provided >>> import matplotlib.pylab >>> matplotlib.pylab.__all__ contour zigzag bug fixed Thanks Nadia for the blood, sweat and tears, and Dominique for the report. contour colormaps Contour now uses the current colormap if colors is not provided, and works with colorbars. See examples/contour_demo2.py colorbar enhancements Horizontal colorbars supported with keyword arg orientation='horizontal' and colorbars can be placed in an arbitrary axes with keyword arg cax. accents in mathtext Added accents to mathtext: \hat, reve, \grave, ar, cute, ilde, ec, \dot, \ddot. All of them have the same syntax, eg to make an overbar you do ar{o} or to make an o umlaut you do \ddot{o}. The shortcuts are also provided, eg: "o 'e \`e \~n \.x \^y . See examples/accent_demo.py fixed super/subscript parsing in mathtext Widowed superscripts now work, eg r'$^12 m{CO}$' little bugs and enhancements Plugged some memory leaks in wx and image module, fixed x,y args in contour, added latex symbol kappa, fixed a yticklabel problem under change in clim, fixed colorbar number of color bug, fixed set_clip_on bug, reverted pythoninspect in tkagg, fixed event handling bugs, fixed matlab-compatible load function, exposed vbox attr in FigureManagerGTK. Downloads at http://matplotlib.sourceforge.net JDH From sjmachin at lexicon.net Sun Jan 16 00:46:21 2005 From: sjmachin at lexicon.net (John Machin) Date: 15 Jan 2005 21:46:21 -0800 Subject: generator expressions: performance anomaly? Message-ID: <1105854381.117059.59940@c13g2000cwb.googlegroups.com> Please consider the timings below, where a generator expression starts out slower than the equivalent list comprehension, and gets worse: >python -m timeit -s "orig=range(100000)" "lst=orig[:];lst[:]=(x for x in orig)" 10 loops, best of 3: 6.84e+004 usec per loop >python -m timeit -s "orig=range(200000)" "lst=orig[:];lst[:]=(x for x in orig)" 10 loops, best of 3: 5.22e+005 usec per loop >python -m timeit -s "orig=range(300000)" "lst=orig[:];lst[:]=(x for x in orig)" 10 loops, best of 3: 1.32e+006 usec per loop >python -m timeit -s "orig=range(100000)" "lst=orig[:];lst[:]=[x for x in orig]" 10 loops, best of 3: 6.15e+004 usec per loop >python -m timeit -s "orig=range(200000)" "lst=orig[:];lst[:]=[x for x in orig]" 10 loops, best of 3: 1.43e+005 usec per loop >python -m timeit -s "orig=range(300000)" "lst=orig[:];lst[:]=[x for x in orig]" 10 loops, best of 3: 2.33e+005 usec per loop Specs: Python 2.4, Windows 2000, 1.4GHz Athlon chip, 768Mb of memory. Background: There was/is a very recent thread about ways of removing all instances of x from a list. /F proposed a list comprehension to build the result list. Given a requirement to mutate the original list, this necessitates the assignment to lst[:]. I tried a generator expression as well. However while the listcomp stayed competitive up to a million-element list, the genexp went into outer space, taking about 20 times as long. The above timeit runs show a simpler scenario where the genexp also seems to be going quadratic. Comments, clues, ... please. TIA, John From Serge.Orlov at gmail.com Tue Jan 11 18:17:43 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 11 Jan 2005 15:17:43 -0800 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> <1105451779.544442.204920@f14g2000cwb.googlegroups.com> <34itatF4d4i9kU1@individual.net> Message-ID: <1105485463.864628.76040@c13g2000cwb.googlegroups.com> Leif K-Brooks wrote: > Serge.Orlov at gmail.com wrote: > > So is the support of Unicode in virtually every computer language > > because they don't support ... digits except 0..9. > > Hex digits aren't 0..9. > You're right, I forgot about hex. But that's boring :) How about Hebrew numerals which are present in Unicode? Serge. From irmen at -nospam-remove-this-xs4all.nl Sun Jan 9 11:52:25 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 09 Jan 2005 17:52:25 +0100 Subject: Long strings as function parameters In-Reply-To: <1105288564.441842.13060@c13g2000cwb.googlegroups.com> References: <1105288564.441842.13060@c13g2000cwb.googlegroups.com> Message-ID: <41e16148$0$6220$e4fe514c@news.xs4all.nl> onlyonemc at gmail.com wrote: > I would like to have functions that operate on long strings, 10-100 MB. > In C I would of course pass a pointer to the string for a quick > function call. What is an efficient way to do this in python? Err, just pass the string to the function? In Python, all function arguments are passed by (object)reference. So if you are afraid that Python passes your 50Mb string object /by value/ (thus creating a copy): it doesn't. --Irmen From http Fri Jan 21 01:23:24 2005 From: http (Paul Rubin) Date: 20 Jan 2005 22:23:24 -0800 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> Message-ID: <7x1xcfwbab.fsf@ruckus.brouhaha.com> Reinhold Birkenfeld writes: > For those of you who don't know what YAML is: visit http://yaml.org/! > You will be amazed, and never think of XML again. Well, almost. Oh please no, not another one of these. We really really don't need it. From zuerich at hebeler.net Thu Jan 27 07:48:28 2005 From: zuerich at hebeler.net (Felix Hebeler) Date: Thu, 27 Jan 2005 13:48:28 +0100 Subject: how to pass attribute name via sys.argv Message-ID: <41f8e31a$1@idnews.unizh.ch> Hi all, I am doing some Python scripting for a while, but I'm not too deep into it yet. So I have a problem I can't solve. I need to call an object attribute: value = object.attrName[0] the problem is, that the attribute name can only be specified at runtime. So what I have is something like >>> attrName = sys.argv[1] >>> attrName 'cellsize' and I need to pass it on so I can call value = object.cellsize[0] Can this be done using Python? Thanks for any hints Cheers Felix From nszabolcs at gmail.com Thu Jan 27 11:19:14 2005 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 27 Jan 2005 08:19:14 -0800 Subject: On benchmarks, heaps, priority queues In-Reply-To: <1106835562.598569.211370@c13g2000cwb.googlegroups.com> References: <1106835562.598569.211370@c13g2000cwb.googlegroups.com> Message-ID: <1106842754.010427.74630@c13g2000cwb.googlegroups.com> hello nice benchmarks some time ago i've also done some benchmarking i sorted 100000 random int with differrent heap implementations, bisect module and with list.sort() I know that heaps are not for sorting, but i tested their performance with sorting back then. my results (sorting algo / time): myheap: (my dummy heap implementation with non-standard comparison) 4.08311503909 heapdict: (my heapdict able to update/delete arbitrary items: heap[key]=value) 5.11007613686 priodict: (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117228) 4.96804296435 pyheapq: (heapq from py 2.3) 2.37830548956 cheapq: (heapq from py 2.4) 0.375011378197 sort: (list.sort) 0.118014529543 bisect: (bisect module) 3.88104577077 i didn't made many benchmarks but bisect is not so fast with larger amount of data (if i saw well your PQ0 implementation used bisect) it's not scaleable (not even O(nlog(n)) !!!! because inserting in a python list is not O(1)) however for small amount of data bisect is the fastest if i used 10 times more data every algorithm scaled well except for bisect: myheap: 50.6242882263 heapdict: 67.465409454 priodict: 71.5018580555 pyheapq: 30.9821771082 cheapq: 6.41072844834 sort: 1.58179548464 bisect: 785.215063469 nsz From roy at panix.com Sun Jan 2 17:58:55 2005 From: roy at panix.com (Roy Smith) Date: Sun, 02 Jan 2005 17:58:55 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> <7xsm5kfyse.fsf@ruckus.brouhaha.com> <41d7941f$1_3@127.0.0.1> <7x8y7cjo57.fsf@ruckus.brouhaha.com> <87zmzsax12.fsf@hector.domek> <87pt0na5zf.fsf@hector.domek> <87llbba55t.fsf@hector.domek> Message-ID: "Terry Reedy" wrote: > None has been reserved because there is no known good use for overriding > it. Should I infer from the above that there's a known bad use? > True and False will be reserved someday. I remember a lisp I used many years ago. If you tried to rebind nil, you got an error message -- in latin! From zanesdad at bellsouth.net Wed Jan 26 15:26:57 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Wed, 26 Jan 2005 15:26:57 -0500 Subject: when self-absorbed narcissists discover usenet [ was: how to write a tutorial ] In-Reply-To: <41F7F520.8040706@po-box.mcgill.ca> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106723545.429728.308620@f14g2000cwb.googlegroups.com> <41F7F520.8040706@po-box.mcgill.ca> Message-ID: <41F7FD11.8090800@bellsouth.net> Brian van den Broek wrote: > Terry Reedy said unto the world upon 2005-01-26 14:08: > >> Xah the arrogant wrote, among other things, > > > > >> However, there are several errors in the above that would mislead a >> Python learner. I advise any such to ignore Xah's writings. >> >> Terry J. Reedy > > > Hi all, > > here's a thought: > > There isn't any doubt that these 'tutorials' are generally unwelcome > and unhelpful. Numerous people have kindly taken the time to flag some > of the problems. So much so that any competent google of the archives > would quickly reveal the group consensus on their instructional merit. > > I submit that continued corrections and advice of this sort are > counter-productive. I understand the good intentions behind the > corrections. (Indeed, my own level of Python-fu is such that it is > possible that I might have been mislead the 'tutorials' without these > corrections; I thus appreciate the correctors' efforts.) But, such > corrections are troll-food and make it unlikely that the 'game' of > posting such tutorials will soon loose its magical power to amuse the > OP. They all but ensure that there will be more such 'tutorials' to > correct. I couldn't agree with you more. *However*, when the person posting is self-absorbed to the extent that he doesn't realize that others exist and don't give a crap about their wishes or discomforts, it puts you in a "damned if you do, damned if you don't" situation. I honestly think that we're stuck with the inane ramblings of Xah Lee regardless of whether we feed his trolling or ignore him. But I do think that responding to him in order to preach some sense into him is futile. He is right about everything and can't be swayed by the likes of us mere mortals. So, ignore him, post responses for the benefit of others out there, entertain yourself by pointing out to yourself and others his folly, but don't waste your time replying back to him and trying to talk sense. Like I said, we're stuck with him. Jeremy From bday at jvncomm.com Tue Jan 25 13:16:48 2005 From: bday at jvncomm.com (Bernie) Date: 25 Jan 2005 10:16:48 -0800 Subject: __deepcopy__ without recursive copies? Message-ID: <1106677008.086803.76270@c13g2000cwb.googlegroups.com> #!/usr/bin/env python import sys import copy ''' How to define __deepcopy__ with out causing recursive calls to copies of self? Bernie Day 01/25/05 I was using deepcopy on DeviceManager and this worked well. When I defined __deepcopy__, so I could have a handle to the children of the Master device Manager I got into trouble. I see that there is a method using a dic to limit this, but I can't seem to get it to work. This is not the code I was using but should represent it well. Thanks! ''' class DeviceManager: def __init__(self,devFile): DevFile = open(devFile) devList = [Device(line) for line in DevFile] #etc, etc... def __deepcopy__(self): miniMe = copy.deepcopy(self) miniMe.devList = tuple(devList) return miniMe class Device: def __init__(self,line): self.copyies = [] #do something with line here def __deepcopy__(self): miniMe = copy.deepcopy(self) self.copyies.append(miniMe) return miniMe DevMan1 = DeviceManager(devfile) devMan2 = copy.deepcopy(DevMan1) From asmirnov1234567890 at yahoo.com Thu Jan 13 10:10:33 2005 From: asmirnov1234567890 at yahoo.com (asmirnov1234567890 at yahoo.com) Date: 13 Jan 2005 07:10:33 -0800 Subject: python 2.3.4 for windows: float("NaN") throws exception Message-ID: <1105629033.442397.124820@c13g2000cwb.googlegroups.com> Hi my python 2.3.4 for windows refuse to execute line float("NaN"). It says: >>> float("NaN") Traceback (most recent call last): File "", line 1, in ? ValueError: invalid literal for float(): NaN The same line works as expected on Linux and Solaris with python 2.3.4. Could anybody explain what is possibly wrong here? is it bug or feature? Andrei From aleaxit at yahoo.com Wed Jan 5 13:25:37 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 5 Jan 2005 19:25:37 +0100 Subject: Python evolution: Unease References: Message-ID: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> Carlos Ribeiro wrote: ... > > - IDE: Better than what? Than IDLE? Than Eclipse? Than SPE? Than Pythonwin? > > I would like to seee Eric3, with some polish & opensourced on Win > (which means solving the Qt licensing problem). Perhaps someone could > convince Trolltech to release a special Qt Win version just for it > (Eric3). Eclipse is also an interesting approach. I love eric3, but if you're an eclipse fan, look at enthought's "envisage" IDE -- it seems to me that it has superb promise. > wish I could simply plug & play DBAPI modules in a totally seamlessly > way. Anyone who tried know how far are we of this dream. If you manage to get there, you'll start fighting against the different dialects of SQL supported by the various back-ends, as is well known by anybody who tried, say, ODBC or ADO, which do manage good plug&play of their components but still can't solve the real hard one:-( Alex From ajsiegel at optonline.com Tue Jan 25 21:06:11 2005 From: ajsiegel at optonline.com (Arthur) Date: Tue, 25 Jan 2005 21:06:11 -0500 Subject: Another scripting language implemented into Python itself? References: <0juic2-68k.ln1@lairds.us> Message-ID: On Tue, 25 Jan 2005 23:08:06 GMT, claird at lairds.us (Cameron Laird) wrote: >In article , >Terry Reedy wrote: > . > . > . >>worrying about Python security seems superfluous. Why worry, for instance, >>about os.unlink when the user can just do the same much easier in a text or >>gui shell? > . > . > . >It's an apt question--and one with several answers. I'll >hint at the range by observing that part of security has >to do with prevention not of malicious acts, but of common >mistakes. I entirely agree with you that it's crucial to >think of wider context, and whether a particular choice's >costs are worth its benefits. As long as we include the cost of treating adults as children, and take it seriously as the kind of cost it is, I'm OK. I think Terry's point covers a wide range of the real world situations. Though certainly not all. My "real" life is in the mid-market business world, not as a geometry software developer. And I see a sort of hysteria descending, in this realm on this subject. Of theY2k ilk, but with actually, it seems to me, less substance. Family businesses out on the limb, as a business, in a myriad of ways - because they are after all in business, focusing on remote scenarios because they are somehow becoming convinced that is what business people do (they don't), and demoralizing folks in the process. Folks who know that if they wanted to hurt this business they could have done so a hundred times in a hundred ways over the years. But it wouldn't be by screwing with their computer system because they wouldn't know how. So isn't it funny that is what the boss is so concerned about - all of a sudden? (They always knew they were smarter then him. More proof) Art From rkern at ucsd.edu Thu Jan 6 21:18:20 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 06 Jan 2005 18:18:20 -0800 Subject: Excluded and other middles in licensing In-Reply-To: <75r0b2-ohg.ln1@lairds.us> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> <75r0b2-ohg.ln1@lairds.us> Message-ID: Cameron Laird wrote: > In article <1gpz9qx.vmv8hav17z8qN%aleaxit at yahoo.com>, > Alex Martelli wrote: > . > . > . > >>One last reflection -- I believe there are or used to be some programs >>written by people no doubt of very good will, distributed with all >>sources and often with no profit motive at all, which are NOT open >>source because they include in the license some restrictive clause, such >>as "no military use", "no use by organizations which perform testing of >>cosmetics on animals", or something of that kind. These would be >>examples of closed-source software which DO allow ALMOST any kind of use >>-- any EXCEPT the specific one the authors dislike so intensely. >> >>While most people may not think of such programs as "closed source", >>they most definitely ARE: the definition of open source is very strict >>about this aspect. >> >> >>Alex > > > With my mathematical background, I'm consistent about calling > these "non-open" rather than "closed". I don't insist others > adopt my nomenclature ... I'm with Cameron on this one. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From premshree.pillai at gmail.com Wed Jan 5 15:08:32 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Thu, 6 Jan 2005 01:38:32 +0530 Subject: is python more popular than coldfusion? In-Reply-To: <86d5wjps6q.fsf@guru.mired.org> References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <1104933800.156835.91350@f14g2000cwb.googlegroups.com> <86d5wjps6q.fsf@guru.mired.org> Message-ID: On Wed, 05 Jan 2005 13:54:53 -0600, Mike Meyer wrote: > beliavsky at aol.com writes: > > >>is python more popular than coldfusion? > > For your specific purpose of learning a language to get a job, I > > suggest visiting the site http://mshiltonj.com/sm/categories/languages/ > > , where it appears that Python is mentioned about as often as Fortran > > or Ada in job listings at dice.com . Apart from Java, two languages in > > demand are C++ and Visual Basic. C++ may be easier to learn along with > > Java since the syntax is similar, but VB is a very easy language to > > learn and use. > > SQL is also in pretty high demand in the places I watch. Problem is, Umm, but SQL is not a _programming_ language. If you're job requires DB stuff, knowledge of SQL would probably be a requisite, but SQL alone, of course, won't do much good. > they usually want *specific* SQL variants, so it's a fragmented > market. > > -- > Mike Meyer http://www.mired.org/home/mwm/ > Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From http Fri Jan 14 02:52:57 2005 From: http (Paul Rubin) Date: 13 Jan 2005 23:52:57 -0800 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: <7xllaw1m7a.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > So, precisely how should one go about cleanly embedding something that > cares about whitespace into a context which doesn't care in the > slightest? Treat the macro like a function call whose arguments are thunks made from the macro arguments, or something like that. There's been some discussions about it on clpy in the past, by people more into this stuff than I am. From ptmcg at austin.rr._bogus_.com Wed Jan 12 13:34:54 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 12 Jan 2005 18:34:54 GMT Subject: Refactoring; arbitrary expression in lists References: Message-ID: "Frans Englich" wrote in message news:mailman.576.1105553330.22381.python-list at python.org... > > As continuation to a previous thread, "PyChecker messages", I have a question > regarding code refactoring which the following snippet leads to: > > > > runner.py:200: Function (detectMimeType) has too many returns (11) > > > > > > The function is simply a long "else-if" clause, branching out to > > > different return statements. What's wrong? It's simply a "probably ugly > > > code" advice? > > > > That is also advice. Generally you use a dict of functions, or some other > > structure to lookup what you want to do. > > More specifically, my function looks like this: > > #-------------------------------------------------------------- > def detectMimeType( filename ): > > extension = filename[-3:] > basename = os.path.basename(filename) > > if extension == "php": > return "application/x-php" > > elif extension == "cpp" or extension.endswith("cc"): > return "text/x-c++-src" > # etcetera Since the majority of your tests will be fairly direct 'extension "XYZ" means mimetype "aaa/bbb"', this really sounds like a dictionary type solution is called for. Still, you might have some desire to do some order-dependent testing. Here are two ideas - the first iterates over a list of expressions and resulting types, the other uses a dictionary lookup. -- Paul import os extToMimeMap = [ ('"php"', "application/x-php"), ('"cpp" or extension.endswith("cc")', "text/x-c++-src"), ('"xsl"', "text/xsl"), ] def detectMimeType1( filename ): extension = filename[-3:] basename = os.path.basename(filename) for exp,mimetype in extToMimeMap: if eval("extension=="+exp): return mimetype # do other non-extension-related tests here if basename.find( "Makefile" ) != -1: return "text/x-makefile" else: raise NoMimeError extToMimeDict = { "php": "application/x-php", "cpp": "text/x-c++-src", "xsl": "text/xsl", } def detectMimeType2( filename ): extension = filename[-3:] basename = os.path.basename(filename) # check for straight extension matches try: return extToMimeDict[extension] except KeyError: pass # do more complex extension and other non-extension-related tests here if extension.endswith("cc"): return extToMimeDict["cpp"] if basename.find( "Makefile" ) != -1: return "text/x-makefile" raise NoMimeError for detectMimeType in (detectMimeType1, detectMimeType2): for s in ("a.php","z.acc","Makefile","blork.xsl"): print s,"->",detectMimeType(s) From adsr at poczta.onet.pl Fri Jan 7 15:04:28 2005 From: adsr at poczta.onet.pl (AdSR) Date: Fri, 07 Jan 2005 21:04:28 +0100 Subject: python3: 'where' keyword In-Reply-To: <3480qqF46jprlU1@individual.net> References: <3480qqF46jprlU1@individual.net> Message-ID: Andrey Tatarinov wrote: > Hi. > > It would be great to be able to reverse usage/definition parts in > haskell-way with "where" keyword. Since Python 3 would miss lambda, that > would be extremly useful for creating readable sources. > > Usage could be something like: > > >>> res = [ f(i) for i in objects ] where: > >>> def f(x): > >>> #do something I don't know haskell, but it looks SQL-ish to me (only by loose association). And it's not that unpythonic - it resembles >>> res = [x for x in sequence if x.isOk()] > or > > >>> print words[3], words[5] where: > >>> words = input.split() Here's a shorter version: >>> print input.split()[3:5:2] (Does it qualify as obfuscated Python code? :) ) > - defining variables in "where" block would restrict their visibility to > one expression > > - it's more easy to read sources when you know which part you can skip, Yes, I like the readability of it, too. > compare to > > >>> def f(x): > >>> #do something > >>> res = [ f(i) for i in objects ] > > in this case you read definition of "f" before you know something about > it usage. When I first read your post, I thought "Well, just one more of those Py3k ideas that appear on c.l.py every day." But as I look at the latter example, I think you have just scratched my itch. The same thing has bugged me more than once in my code. I think this idea is of the same kind as the @decorator syntax. Guido moved an operation to a point in the code where it was more visible. You moved an operation to a more local context where (pun not intended) it really belongs. I'm usually rather conservative about Python syntax (@decorators, absolute/relative imports, if-else operator), but this one could appear in Python tomorrow and that would be too far in the future for me ;) Cheers, AdSR From reinhold-birkenfeld-nospam at wolke7.net Thu Jan 20 12:09:13 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Thu, 20 Jan 2005 18:09:13 +0100 Subject: What YAML engine do you use? Message-ID: <35a6tpF4gmat2U1@individual.net> Hello, I know that there are different YAML engines for Python out there (Syck, PyYaml, more?). Which one do you use, and why? For those of you who don't know what YAML is: visit http://yaml.org/! You will be amazed, and never think of XML again. Well, almost. Reinhold From sjmachin at lexicon.net Sun Jan 2 21:43:25 2005 From: sjmachin at lexicon.net (John Machin) Date: 2 Jan 2005 18:43:25 -0800 Subject: Calling Function Without Parentheses! References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> <1104718215.795501.83450@f14g2000cwb.googlegroups.com> Message-ID: <1104720205.691929.263460@c13g2000cwb.googlegroups.com> Dan Bishop wrote: > Kamilche wrote: > > What a debug nightmare! I just spent HOURS running my script through > > the debugger, sprinkling in log statements, and the like, tracking > down > > my problem. > > > > I called a function without the ending parentheses. I sure do WISH > > Python would trap it when I try to do the following: > > MyFunc > > > > instead of: > > > > MyFunc() > > You're a former Pascal programmer, aren't you? ;-) > > In Python, it's not an error, because you can do things like: > > >>> def simpson(f, a, b): > ... "Simpson's Rule approximation of the integral of f on [a, b]." > ... return (b - a) * (f(a) + 4 * f((a + b) / 2.0) + f(b)) / 6.0 > ... > >>> simpson(math.sin, 0.0, math.pi) # Note that math.sin is a function > 2.0943951023931953 In Python, it's not an error, because functions are first class citizens. The OP's problem is evaluating an expression and then doing SFA with the result. Pychecker appears to be able to make the distinction; see below: C:\junk>type simpson.py import math def simpson(f, a, b): return (b - a) * (f(a) + 4 * f((a + b) / 2.0) + f(b)) / 6.0 print simpson(math.sin, 0.0, math.pi) C:\junk>python simpson.py 2.09439510239 C:\junk>pychecker simpson.py C:\junk>c:\python24\python.exe c:\python22\Lib\site-packages\pychecker\checker.py simpson.py Processing simpson... 2.09439510239 Warnings... None From ncoghlan at iinet.net.au Fri Jan 7 11:21:41 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 02:21:41 +1000 Subject: Please Contribute Python Documentation! In-Reply-To: <16861.60868.409947.889215@montanaro.dyndns.org> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> <16861.60868.409947.889215@montanaro.dyndns.org> Message-ID: <41DEB715.1040100@iinet.net.au> Skip Montanaro wrote: > Fred Drake releases new development versions of the docs frequently > (typically once every month or two). I normally use the development docs > instead of the regular ones for my day-to-day work. They are available > here: > > http://www.python.org/dev/doc/devel/ > > It's useful to check to see the most current status of the docs. The only > thing more current is the source in CVS. Although, when working this way, and Python's behaviour seems to contradict the documentation, don't forget to check the docs specific to your version of Python before submitting a bug report :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From craig at postnewspapers.com.au Mon Jan 3 06:06:38 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Mon, 03 Jan 2005 19:06:38 +0800 Subject: emulating an and operator in regular expressions In-Reply-To: References: Message-ID: <1104750397.26918.1.camel@rasputin.localnet> On Mon, 2005-01-03 at 08:52, Ross La Haye wrote: > How can an and operator be emulated in regular expressions in Python? > Specifically, I want to return a match on a string if and only if 2 or more > substrings all appear in the string. For example, for a string s = 'Jones > John' and substrings sg0 = 'Jones' and sg1 = 'John', I want to return a > match, but for substrings sg0 = 'Jones' and sg2 = 'Frank' I do not want to > return a match. Because the expression 'A and B' is logically equivalent to > 'not (not A or not B)' I thought I could try something along those lines, > but can't crack it. My first thought would be to express your 'A and B' regex as: (A.*B)|(B.*A) with whatever padding, etc, is necessary. You can even substitute in the sub-regex for A and B to avoid writing them out twice. -- Craig Ringer -- Craig Ringer From http Tue Jan 4 22:49:27 2005 From: http (Paul Rubin) Date: 04 Jan 2005 19:49:27 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> Message-ID: <7xr7l0h6wo.fsf@ruckus.brouhaha.com> Peter Hansen writes: > The key distinction is that "well-documented" is clearly > a judgment call, a personal opinion, No it's not. If a program has significant modules with complicated public API's and no documentation, it's poorly documented in an absolute sense. A well-documented program includes docs for all the public API's. > So those who claim Python is well-documented are the ones who > should improve the documentation, but those claiming that > the documentation is poor should feel no responsibility to > make the improvements? Yes, precisely so. Like if someone says "I've written this fantastic math package, it's fast and accurate and solves every problem perfectly, let's start a newsgroup about how to convince our PHB's to use it and why it's so much better than every other math package that's ever been written", and I try the package and it says that 2+2=5 and I report that bug, I've made a constructive comment and have no further responsibility. I've also shown that the program doesn't live up to its claims and people wanting to do real work with it should watch out. If the developers want to keep making the grand claims, they should fix the bug. If they want to say "this package is technically cool but gets some answers wrong, maybe you don't want to do anything serious with it but it's fun to play with", that's different. But there's a constant current in clpy of "Python is great for everything, our PHB's should all embrace it, it supports protocols X, Y, and Z and is great for that kind of application" when those protocols turn out to be only half-implemented, or "it's well-documented" when the manual turns out to be only half-complete. And the responses I see sound almost like "2+2=5 is an accurate answer, and if you think it's not close enough, it's open source, so fix it". If you want to see a really well-done (at least in parts, and also poorly documented but not making claims to the contrary) Python program, take a look at Twisted Matrix. It reimplements any number of features that are already in Python. An early version of the docs explained the reason. It said something like "it may look like we're re-inventing the wheel, but we have no choice, since the existing wheel is square and made of glue". > Does this make any sense to you? To me, *this* is the nonsense. I don't see any nonsense. People who make claims about a program are the ones responsible for the truth of the claims. Saying anyone else is responsible is bizarre. From FBatista at uniFON.com.ar Thu Jan 6 10:46:45 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 6 Jan 2005 12:46:45 -0300 Subject: PyAr - Python Argentina 5th Meeting, Thursday, January 13th Message-ID: The Argentinian Python User Group, PyAr, will have its fifth meeting this Thursday, January 13th at 7:00pm. Please see http://pyar.decode.com.ar/Wiki/ProximaReunion for details (in Spanish.) Agenda ------ Despite our agenda tends to be rather open, this time we would like to cover these topics: - Planning of our first sprint: we actually have two main subjects: Messages Queues Manager with interfaces for SMTP (e-mail), SMPP (SMS) and MM7 (MMS); and Genetic Algorithms. - Website organization & content - Means of promoting the group's activities, in order to increase our member base. Where ----- We're meeting at Hip Hop Bar, Hip?lito Yirigoyen 640, Ciudad de Buenos Aires, starting at 19hs. We will be in the back room, so please ask the barman for us. About PyAr ---------- For more information on PyAr see http://pyar.decode.com.ar (in Spanish), or join our mailing list (Also in Spanish. For instructions see http://pyar.decode.com.ar/Members/ltorre/listademail) We meet on the second Thursday of every month. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Thu Jan 27 08:14:02 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 27 Jan 2005 08:14:02 -0500 Subject: import hook, overwrite import? In-Reply-To: <1106756209.188804.270160@c13g2000cwb.googlegroups.com> References: <1106756209.188804.270160@c13g2000cwb.googlegroups.com> Message-ID: Kartic wrote: > Hi Torsten, > > If you want to use other methods to import (other than good ole file > system), yes, you can create an importer class and register it as an > importer module, that import will use to search and import. > > For example, it is possible to use zip imports (this functionality is > already builtin) to import from a zip archive. > py>>> import zlib # required > py>>> import sys > py>>> sys.path.append('/location/to/zippedmodules.zip') > py>>> import testzip > py>>> testzip.__file__ > '/location/to/zippedmodules.zip/testzip,py' > > To generally do it, you have to: > 1. Create a class that provides a load_module method that returns a > module type. > 2. Install your class as a hook using > sys.path_hooks.append(your_importer_class) > > Please take a look at the imp module : > http://docs.python.org/lib/module-imp.html for a complete description > on accessing the import internals. There is also a simple example in > this section. > > Is this is what you are looking for? > > Thanks, > --Kartic > PS: This about how much I know...the more I find out, I will share :-) > I will just chime in to say I too am looking for information in this area. I hope to put some sort of BoF or Open Space event together for people wishing to learn about (and teach about) the import system from PEP 302 at PyCon this year. Early bird registration rates are still available today and tomorrow! regards Steve From steve at holdenweb.com Mon Jan 10 20:06:59 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Jan 2005 20:06:59 -0500 Subject: Port blocking In-Reply-To: References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> <34f8ovF47d783U1@individual.net> <34fdf6F4a7t7uU1@individual.net> Message-ID: Ville Vainio wrote: >>>>>>"Mark" == Mark Carter writes: > > > Mark> Mark Carter wrote: > >> Paul Rubin wrote: > > >>> Usually you wouldn't run a public corba or pyro service over > >>> the internet. You'd use something like XMLRPC over HTTP port > >>> 80 partly for the precise purpose of not getting blocked by > >>> firewalls. > > Mark> I'm not sure if we're talking at cross-purposes here, but > Mark> the application isn't intended for public consumption, but > Mark> for fee-paying clients. > > Still, if the consumption happens over the internet there is almost > 100% chance of the communication being prevented by firewalls. > > This is exactly what "web services" are for. > I teach the odd security class, and what you say is far from true. As long as the service is located behind a firewall which opens up the correct holes for it, it's most unlikely that corporate firewalls would disallow client connections to such a remote port. Web services are for offering services despite the fact that the corporate firewall managers are valiantly trying to stop unknown services from presenting to the outside world (and my immediately preceding post tells you what I think of that idea). The situation is analogous to connecting to web servers running on non-standard ports (8000 and 8080 are traditional favorites, but firewalls very rarely accord them any special treatment). Most firewall configurations allow fairly unrestricted outgoing connections, limiting rules to sanity checking of addresses to ensure nobody inside the firewall is address spoofing. Incoming connections are usually limited to specific combinations of port number and IP address known to be legitimate corporate services to the external world. Firewalling web services effectively is just an additional pain for the network manager. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From rnd at onego.ru Tue Jan 4 07:25:56 2005 From: rnd at onego.ru (Roman Suzi) Date: Tue, 4 Jan 2005 15:25:56 +0300 (MSK) Subject: Lambda as declarative idiom (was RE: what is lambda used for in real code?) In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> Message-ID: On Mon, 3 Jan 2005, Steven Bethard wrote: > Roman Suzi wrote: > > I wish lambdas will not be deprecated in Python but the key to that is > > dropping the keyword (lambda). If anybody could think of a better syntax for > > lambdas _with_ arguments, we could develop PEP 312 further. > > Some suggestions from recent lambda threads (I only considered the ones > that keep lambda as an expression): > > ***** Args Before Expression ***** > > Nick Coghlan: def-to syntax [1] > (def (a, b, c) to f(a) + o(b) - o(c)) > (def (x) to x * x) Wow! Is there any wiki-page these could be put on? By the way, I think to satisfy least-surprise principle, our declarative idiom must be compatible with type declarations GvR is planning for Python 3.0. This way Python will have ONE style for declarations, be it type declarations, logical declarations or database-queries, etc. This means, that there is a need for a LISP's quote, when code is only written and parsed but may be processed not only by Python interpreter itself but by any user-made interpreter. For example, type-checker, cursor.execute, lazy-Python-subinterpreter, DOM-manipulator etc. I do not know how it could be done syntactically, but it could be done if thought about long enough. Lambdas is one of the ways, arguably not the most pleasant one for a "quote". Maybe this is too outlandish, but I see lambdas as a "quote" mechanism, which presents a possibility to postpone (precisely control, delegate) evaluation. That is, an ovehead for lambda must be much lower but at the same time visible to the programmer: d = a + (lambda x, y: x+ y)(3, 4) if this expression is to be viewed in hypotetical syntax-highlighting editor, "(lambda x, y: x+ y)" need to be painted with another color than the rest of the expression, as it represents defining part of the expression, not the part which is being evaluated right away. What if we deprecate ` in it's repr() function and reserve it for inline lambdas (for Python 3.0, of course): d = a + (` x, y: x+y) (3, 4) Thus, implicit lambdas will be one more symbol, e.g. (`: None) instead of (: None) What does Guido think? ;) Sincerely yours, Roman A.Suzi -- - Petrozavodsk - Karelia - Russia - mailto:rnd at onego.ru - From peter at engcorp.com Thu Jan 13 10:30:24 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 10:30:24 -0500 Subject: python 2.3.4 for windows: float("NaN") throws exception In-Reply-To: <1105629033.442397.124820@c13g2000cwb.googlegroups.com> References: <1105629033.442397.124820@c13g2000cwb.googlegroups.com> Message-ID: asmirnov1234567890 at yahoo.com wrote: > my python 2.3.4 for windows refuse to execute line float("NaN"). It > says: > >>>>float("NaN") > > Traceback (most recent call last): > File "", line 1, in ? > ValueError: invalid literal for float(): NaN > > The same line works as expected on Linux and Solaris with python 2.3.4. > Could anybody explain what is possibly wrong here? is it bug or > feature? Differences in the underlying platform/C library. No difference here with similar platforms. -Peter From EP at zomething.com Sun Jan 23 11:27:49 2005 From: EP at zomething.com (EP) Date: Sun, 23 Jan 2005 08:27:49 -0800 Subject: File objects? - under the hood question In-Reply-To: <20050118225310.1939807216.whereU@now.com> References: <20050119034955.75129.qmail@web50306.mail.yahoo.com> <20050118225310.1939807216.whereU@now.com> Message-ID: <20050123082749.1511901297.EP@zomething.com> > My brain-teaser: What I'd like to do is read the last ~2K of a large > number of large files on arbitrary servers across the net, without > having to read each file from the beginning (which would be slow and > resource inefficient)... > Proper googling would have revealed that HTTP 1.1 includes a Range Request. My bad. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html Before I reinvent the wheel (and make it a little squarer than it has to be) has anyone seen a "cookbook" recipe for adding the HTTP 1.1 range request to a urllib urlopener (or something similar)? From fredrik at pythonware.com Sun Jan 23 18:56:59 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 00:56:59 +0100 Subject: [perl-python] 20050121 file reading & writing References: <1106395060.211314.54530@f14g2000cwb.googlegroups.com> Message-ID: Erik Max Francis wrote: >> To do this efficiently on a large file (dozens or hundreds of megs), you should use the >> 'sizehint' parameter so as not to use too much memory: >> >> sizehint = 0 >> mylist = f.readlines(sizehint) > > It doesn't make any difference. .readlines reads the entire file into memory at once. except when it doesn't: readlines([sizehint]) Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (possibly after rounding up to an internal buffer size) are read. Objects implementing a file-like interface may choose to ignore sizehint if it cannot be implemented, or cannot be implemented efficiently. >>> f = open("ot.xml") >>> s = f.readlines(1000) >>> len(s) 157 >>> f = open("ot.xml") >>> s = f.readlines() >>> len(s) 48560 From ed at leafe.com Mon Jan 3 21:11:16 2005 From: ed at leafe.com (Ed Leafe) Date: Mon, 3 Jan 2005 21:11:16 -0500 Subject: Is it possible to open a dbf In-Reply-To: <41D9790C.4080907@skynet.be> References: <0F3Ad.3192$5R.2578@newssvr21.news.prodigy.com> <7xy8fjywar.fsf@ruckus.brouhaha.com> <41D9790C.4080907@skynet.be> Message-ID: On Jan 3, 2005, at 11:55 AM, Helmut Jarausch wrote: > I've been using > http://www.fiby.at/dbfpy/ > without any problems including writing/modifying dbf files. The problem, of course, is that there is no single DBF format. The only product out there that still uses DBFs, Visual FoxPro, supports 3 separate and incompatible formats: 2.x, 3.0, and later. What's more, the later versions introduced new data types, so even those are not compatible with older formats. Because VFP has not fallen off the face of the earth, but instead has continued to thrive, it has added things such as auto-increment fields and BLOB support that were never even envisioned by the folks at JPL when they created Vulcan. As a result, there is no single DBF reader that can read all DBF files. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From danperl at rogers.com Wed Jan 5 13:52:06 2005 From: danperl at rogers.com (Dan Perl) Date: Wed, 5 Jan 2005 13:52:06 -0500 Subject: Cookbook 2nd ed Credits References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> <1gpxjfg.thnaf0oys6jrN%aleaxit@yahoo.com> Message-ID: "Alex Martelli" wrote in message news:1gpxjfg.thnaf0oys6jrN%aleaxit at yahoo.com... > Dan Perl wrote: > >> "Alex Martelli" wrote in message >> news:1gpvtjk.3jf7dc1cch7yfN%aleaxit at yahoo.com... >> > Premshree Pillai wrote: >> >> Btw, is there a comprehensive list of ALL contributors put up >> >> anywhere? >> > >> > Not yet -- do you think I should put it up on my website? >> >> Updating the status of the recipes on the web site would be nice. > > Please take this up with Activestate guys -- I have no say on what > happens on the website they own, nor any special status there. I was under the impression that the status on the website reflects whether the recipes are approved or rejected for the book (with a few more states added: new, deferred, pending). I gather now from your reply that there is no connection between that status and the book. Okay then, I am adding my vote to posting the list of all the contributors. I still think that the ActiveState website is an appropriate place to do that, as they also have the recipes. Actually, what is the exact relationship between the recipes on the website and the recipes published in the book? If not on the ActiveState website, then posting the list to another website would be good too. Even if the list is not absolutely final and may be changed later (a disclaimer to that effect would suffice). I have two recipes submitted (for which I got permission requests) and I am curious. BTW, I sent an email to pythoncookbook at activestate.com earlier today, before I even saw this thread in c.l.p. I haven't received a reply from them yet. Dan > > Alex From steven.bethard at gmail.com Tue Jan 25 14:22:13 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Jan 2005 12:22:13 -0700 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) Message-ID: Fuzzyman wrote: > Cameron Laird wrote: > [snip..] > >>This is a serious issue. >> >>It's also one that brings Tcl, mentioned several >>times in this thread, back into focus. Tcl presents >>the notion of "safe interpreter", that is, a sub- >>ordinate virtual machine which can interpret only >>specific commands. It's a thrillingly powerful and >>correct solution to the main problem Jeff and others >>have described. > > A better (and of course *vastly* more powerful but unfortunately only > a dream ;-) is a similarly limited python virutal machine..... Yeah, I think there are a lot of people out there who would like something like this, but it's not quite clear how to go about it. If you search Google Groups, there are a lot of examples of how you can use Python's object introspection to retrieve "unsafe" functions. I wish there was a way to, say, exec something with no builtins and with import disabled, so you would have to specify all the available bindings, e.g.: exec user_code in dict(ClassA=ClassA, ClassB=ClassB) but I suspect that even this wouldn't really solve the problem, because you can do things like: py> class ClassA(object): ... pass ... py> object, = ClassA.__bases__ py> object py> int = object.__subclasses__()[2] py> int so you can retrieve a lot of the builtins. I don't know how to retrieve __import__ this way, but as soon as you figure that out, you can then do pretty much anything you want to. Steve From steve at holdenweb.com Fri Jan 14 16:53:30 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 16:53:30 -0500 Subject: why are people still using classic classes? In-Reply-To: <10udbgqh32a2901@corp.supernews.com> References: <10udbgqh32a2901@corp.supernews.com> Message-ID: Michael Hobbs wrote: > Simon Wittber wrote: > >>I've noticed that a few ASPN cookbook recipes, which are recent >>additions, use classic classes. >> >>I've also noticed classic classes are used in many places in the >>standard library. >> >>I've been using new-style classes since Python 2.2, and am suprised >>people are still using the classic classes. >> >>Is there a legitimate use for classic classes that I am not aware of? >>Is there a project to specifically migrate standard library classes to >>new-style classes? > > > I'm guessing that the biggest contributor to the continued prevalence > of classic classes is the official Python Tutorial: > http://docs.python.org/tut/node11.html#SECTION0011300000000000000000 > > I came into Python around the 2.2 timeframe and used the tutorial as > my starting point. I had often read people referring to "classic > classes" but assumed that it was some old pre-2.2 thing that I need > not worry about. For the longest time, I had assumed that I was using > new style classes because I created them exactly as prescribed in the > 2.2 tutorial (which still hasn't changed for 2.3 or 2.4). > > Now, classic classes are my habit and I see no compelling reason to > put in the effort to change my habits. > Since the only effort is the addition of __meta class__ = type at the head of your modules you could probably automate this without breaking too much code. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From tonino.greco at gmail.com Fri Jan 21 01:25:52 2005 From: tonino.greco at gmail.com (Tonino) Date: 20 Jan 2005 22:25:52 -0800 Subject: tkinter socket client ? Message-ID: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> I have been looking through the previous posts - but with my lack of knowledge on the whole tkinter subject - I have no clue what to look for ... SO - can anyone please help with this ...? I have a python server that when it gets a connection from a client - it sends data back - quite a bit of it - in discreet parts - around 1024 byte chunks ... I have created a tkinter client that makes a simple connect to the server. What I have a problem with is I need the client to write all the data to the Text() widget created in the GUI client - the Text() widget is created as : self.text=Text(self.center_frame,background='white') scroll=Scrollbar(self.center_frame) self.text.configure(yscrollcommand=scroll.set) self.text.pack(side=LEFT, fill=BOTH, expand=YES) scroll.pack(side=RIGHT,fill=Y) self.center_frame.pack(side=RIGHT, expand=YES, fill=BOTH) I have a button with "Connect" written on it that connects to the server by calling : HOST = 'localhost' PORT = 9000 global s for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: s = socket.socket(af, socktype, proto) except socket.error, msg: s = None continue try: s.connect(sa) except socket.error, msg: s.close() s = None continue break if s is None: print 'could not open socket' self.quitButtonClick NOW - HOW do I get the server's sent data to continuiosly print in the Text() widget ? Many thank Tonino From steve at holdenweb.com Thu Jan 6 08:50:44 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Jan 2005 08:50:44 -0500 Subject: Python evolution: Unease In-Reply-To: References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1104830276.579755.133870@f14g2000cwb.googlegroups.com> <7x652dk0gh.fsf@ruckus.brouhaha.com> <1104831798.408560.228940@c13g2000cwb.googlegroups.com> Message-ID: <41DD4234.6070807@holdenweb.com> Aahz wrote: > In article <1104831798.408560.228940 at c13g2000cwb.googlegroups.com>, > wrote: > >>Maybe a PSF grant would help? I guess this has been considered ... > > > The first three PSF grants were all in some way not directly related to > changing the core language. One was for a library, one for improving > Jython, and one for improving docs. Giving the PSF more money increases > the chances for additional work. I would, however, like to make the point that the Foundation is much more likely to fund work that actually gets proposed for a grant, since the officers don't generally have the time to inspire teams and promote specific topics. So if a bunch of like-minded people wanted to get together to propose a specific set of changes, it would then at least be possible to consider such changes for funding. There's also a lot of good work that goes on unfunded, of course, and I wouldn't like to see the grants process subvert such public-spirited efforts in any way. So there's nothing to stop a bunch of like-minded individuals proposing changes anyway, through the existing process. Lastly, the Foundation has only just started to make grants, and so we need a little time to see how the existing projects go before we can evaluate the success or failure of the process (at least on the existing projects, whose outcomes may or may not be related to the grant process). regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From brianr at liffe.com Thu Jan 13 08:05:16 2005 From: brianr at liffe.com (brianr at liffe.com) Date: Thu, 13 Jan 2005 13:05:16 +0000 Subject: [perl-python] 20050112 while statement References: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> Message-ID: "Xah Lee" writes: > # here's a while statement in python. > > a,b = 0,1 > while b < 20: > print b > a,b = b,a+b > > --------------- > # here's the same code in perl > > ($a,$b)=(0,1); > while ($b<20) { > print $b, "\n"; > ($a,$b)= ($b, $a+$b); > } That python code produces a syntax error: File "w.py", line 3 print b ^ IndentationError: expected an indented block So, not the same then! (As a matter of interest, is this sequence of posts intended to demonstrate ignorance of both languages, or just one?) -- Brian Raven If you write something wrong enough, I'll be glad to make up a new witticism just for you. -- Larry Wall in <199702221943.LAA20388 at wall.org> From roccomoretti at hotpop.com Thu Jan 27 12:13:23 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Thu, 27 Jan 2005 11:13:23 -0600 Subject: ANN: Tao Scripting Language 0.8.5 beta released! In-Reply-To: References: Message-ID: Limin Fu wrote: > Dear all, > > I am glad to announce in this mailing list that the lastest version > of a new scripting language has come out. Since you chose to announce it in this mailing list/newsgroup, may I suggest that a comparison with Python is in order? Since it is a new scripting language, I'm not suggesting a language war, but rather a simple statement of how Tao differs from Python, and what "itch" you were trying to scratch when you designed your new language. Basically, how does your design philosophy differ from that of Guido? Where did you go left when Python went right? (Congrats on beating the technical challenge of designing and implementing a programming language - now's your chance to sell us on it. :-) From FBatista at uniFON.com.ar Mon Jan 10 11:18:22 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 10 Jan 2005 13:18:22 -0300 Subject: Writing huge Sets() to disk Message-ID: [Martin MOKREJ?] #- I have sets.Set() objects having up to 20E20 items, #- each is composed of up to 20 characters. Keeping Are you really sure?? #- How can I write them efficiently to disk? To be more exact, I think that there's some mistake here. At least you'll need a disk of 34694 EXABYTES!!! . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kartic.krishnamurthy at gmail.com Sun Jan 9 11:06:53 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 9 Jan 2005 08:06:53 -0800 Subject: use a file as a database, access rights In-Reply-To: References: Message-ID: <1105286813.666599.207230@c13g2000cwb.googlegroups.com> Torsten, Please explain the environment you are planning to use - Operating System, whether you have full control of the machine that runs the database, how many users?. If you are using Windows and if your needs are simple, you can use Access as it has some simple access control that can be setup. Also, the part about "database would store all its data in a file" is not very clear. Are you wanting to use a flat-file database and also have security implemented in it? If you are on linux/*BSD machine, consider using a real database. Fine access control can be implemented in your application (e.g. only the creator of a record and his/her superiors can edit it, all others view it) Please send more details to receive useful recommendations. Thanks, --Kartic From jan.dries at dcube-resource.be Mon Jan 17 11:39:57 2005 From: jan.dries at dcube-resource.be (Jan Dries) Date: Mon, 17 Jan 2005 17:39:57 +0100 Subject: Integration with java (Jpype vs. JPE) In-Reply-To: References: <34s5krF4c85d5U1@individual.net> Message-ID: <41EBEA5D.6070800@dcube-resource.be> Istvan Albert wrote: > Now I remember visiting this site, but never understood how it > actually worked. Examples such as: > > from jpype import * > startJVM("d:/tools/j2sdk/jre/bin/client/jvm.dll", "-ea") > java.lang.System.out.println("hello world") > shutdownJVM() > > in three different versions are the only code examples > that to show "complete" working snippets. I'm still > clueless as to how would one say share a list between > python and java. A while ago there was a thread in c.l.p about using JPype to access JMS from within Python. IIRC someone then contributed a more elaborate real life example of how to do this. Search Google Groups for more details. Regards, Jan From peter at engcorp.com Tue Jan 18 13:38:59 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 18 Jan 2005 13:38:59 -0500 Subject: Print to Windows default Printer In-Reply-To: References: Message-ID: Samantha wrote: > I am new to Python and I am having considerable trouble trying to print > (using a simple script) to the default printer rather than the screen. > Thanks for any help. Please show some example code, and explain in more detail what you are trying to do. There are perhaps *dozens* of different ways to do printing under Windows, and we can't guess which approach you are trying, nor which might be suitable for your needs. -Peter From http Sat Jan 22 08:01:15 2005 From: http (Paul Rubin) Date: 22 Jan 2005 05:01:15 -0800 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> <1gqsayh.th49i518ixczeN%aleaxit@yahoo.com> <7xpszxljra.fsf@ruckus.brouhaha.com> Message-ID: <7x4qh9pqhw.fsf@ruckus.brouhaha.com> "Fredrik Lundh" writes: > > Some languages let you say things like: > > for (var x = 0; x < 10; x++) > > do_something(x); > > and that limits the scope of x to the for loop. > > depending on the compiler version, compiler switches, IDE settings, etc. Huh? I'm not sure what you're talking about. From JoshuaACohen at gmail.com Thu Jan 6 13:00:02 2005 From: JoshuaACohen at gmail.com (Josh) Date: 6 Jan 2005 10:00:02 -0800 Subject: File Handling Problems Python I/O In-Reply-To: References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> Message-ID: <1105034402.428393.283930@c13g2000cwb.googlegroups.com> He is the function where I am making the call. If I change the open statment to another file, say "c:\test.txt", a file I know exists, it will error out stating the file does not exist. Thanks Josh def GetStartVars(self): try: DOWNFILE = open("c:\fixes.txt","r") except IOError: print "Failed to open file." else: counter = 1 while 1: theline = DOWNFILE.readline() if not theline: break print theline counter = counter + 1 print counter DOWNFILE.close() From ncoghlan at iinet.net.au Tue Jan 25 21:42:37 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 12:42:37 +1000 Subject: string.atoi and string.atol broken? In-Reply-To: References: Message-ID: <41F7039D.504@iinet.net.au> Peter Otten wrote: > Mike Moum wrote: > > >>s.atoi('4',3) should result in 11 >> >>s.atoi('13',4) should result in 31 >> >>s.atoi('12',4) should result in 30 >> >>s.atoi('8',4) is legitimate, but it generates an error. >> >>Is this a bug, or am I missing something obvious? > > > You and atoi() seem to disagree about the direction of the conversion, and > atoi() wins :-). It converts a string representation of a number into the > corresponding integer. The second parameter specifies in what base this > string is given. > You seem to want something like > > import string > > def itoa(n, base): > assert 2 <= base <= 16 > if n < 0: > digits = ["-"] > n = -n > else: > digits = [] > while n: > n, m = divmod(n, base) > digits.append(string.hexdigits[m]) > digits.reverse() > return "".join(digits) > > if __name__ == "__main__": > assert itoa(4, 3) == "11" > assert itoa(13, 4) == "31" > assert itoa(12, 4) == "30" > assert itoa(8, 4) == "20" Huh - you remind me that I forgot to put the "show_base" Bengt and I came up with into the ASPN cookbook. . . Py> def show_base(val, base, min_digits=1, complement=False, ... digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"): ... if base > len(digits): raise ValueError("Not enough digits for base") ... negative = val < 0 ... val = abs(val) ... if complement: ... sign = "" ... max = base**min_digits ... if (val >= max) or (not negative and val == max): ... raise ValueError("Value out of range for complemented format") ... if negative: ... val = (max - val) ... else: ... sign = "-" * negative ... val_digits = [] ... while val: ... val, digit = divmod(val, base) ... val_digits.append(digits[digit]) ... result = "".join(reversed(val_digits)) ... return sign + ("0" * (min_digits - len(result))) + result ... Py> show_base(10, 2) '1010' Py> show_base(-10, 2) '-1010' Py> show_base(10, 2, 8) '00001010' Py> show_base(-10, 2, 8) '-00001010' Py> show_base(10, 2, 8, complement=True) '00001010' Py> show_base(-10, 2, 8, complement=True) '11110110' Py> show_base(10, 16, 2, complement=True) '0A' Py> show_base(-10, 16, 2, complement=True) 'F6' Py> show_base(127, 16, 2, complement=True) '7F' Py> show_base(-127, 16, 2, complement=True) '81' Py> show_base(255, 16, 2, complement=True) 'FF' Py> show_base(-255, 16, 2, complement=True) '01' Py> show_base(256, 16, 2, complement=True) Traceback (most recent call last): File "", line 1, in ? File "", line 10, in show_base ValueError: Value out of range for complemented format Py> show_base(-256, 16, 2, complement=True) '00' Py> -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steve at holdenweb.com Tue Jan 18 09:29:15 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Jan 2005 09:29:15 -0500 Subject: generator expressions: performance anomaly? In-Reply-To: References: <354esdF4fouh0U1@individual.net> Message-ID: Antoon Pardon wrote: > Op 2005-01-18, Diez B. Roggisch schreef : > >>>Something else I was thinking about. I think it would be nice if the >>>python compilor could figure out whether a genexp in a list or tuple >>>expression always generates the same list or tuple and then instead >>>of generating code would generate the list or tuple in place. >> >>This won't ever happen in python - at least not in python otherwise similar >>to the one we know... >> >>The thing you're after is known as "common subexpression elemination" and >>can only be done in purely functional languages. While that certainly is an >>interesting property of a language, it e.g. forbids functions like >>time.time() - a too huge paradigm shift for python. >> > > > I don't see how generating byte code for a = 9; when seeing the > expression a = 3 + 6, would be a problem for non-functional > languages. > > I agree that things like [time.time() for i in xrange(10)] shouldn't > be pregenerated and that the problem is more complicated as I thought. > > But during compilation the compilor could do an anlysis of the code > do determine whether there are side effects or not. If the compilor > then would store a code in the byte code for functions that are > guaranteed side-effect free and only pregenerated objects generated > by expressions with no side-effect, some common subexpression > elimination could be done even in a non-functional language. > Indeed, and it has been, which is a matter of well-recorded history. Constant folding has been used since the early Fortran compilers. But you've already stated that the problem is more complicated than you thought. I presume you are already prepared to bail on any function that calls into external modules or extensions, since clearly nothing can be known about their behaviors vis a vis side effects. Python is *designed* as a dynamic language. I wish you would embrace this aspect rather than continually trying to shoehorn it into a static straitjacket. Efficiency is good. Flexibility is better. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From spam at nospam.org Wed Jan 26 23:09:04 2005 From: spam at nospam.org (Erik Johnson) Date: Wed, 26 Jan 2005 21:09:04 -0700 Subject: Where can I find Mk4py.dll for python24 ? References: <11e94203.0501251626.7988599b@posting.google.com> Message-ID: <41f86753$1@nntp.zianet.com> I don't know what metakit or the file you are looking for is, but a simple search on google turns up the following article where a guy built it for Python 2.2 and was willing to mail that to people. Try contacting him: http://www.equi4.com/pipermail/metakit/2002-March/000560.html HTH, -ej "Jose Rivera" wrote in message news:11e94203.0501251626.7988599b at posting.google.com... > I installed the new release and I have not been able to make work metakit. > > Please give me some help to enjoy metakit and python 24. > > Thanks From steve at holdenweb.com Tue Jan 25 12:54:40 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 25 Jan 2005 12:54:40 -0500 Subject: Import from database In-Reply-To: <1106587145.067483.14710@z14g2000cwz.googlegroups.com> References: <1106587145.067483.14710@z14g2000cwz.googlegroups.com> Message-ID: Kartic wrote: > Steve, > > I believe you have to put ntpath, macpath and posixpath in the module > database for os.path to work. > > I tried it with zipimporter builtin and I got the same traceback till I > added ntpath.py to my zip file. (Of course, I renamed the original > ntpath to _ntpath so that the original did not get imported) > Thanks, > --Kartic > I'm not sure I understand, as I am currently relying on the system implementations of any modules that happen to be loaded before my code picks up. As to what's in the database SELECT * FROM `module` WHERE modName LIKE '%path%' shows that I have macpathm macurlpath, ntpath, nturlpath, os2emxpath and posixpath all there (but, as I say, I've already executed the standard modules by the time anything of mine gets to run). If I alter my test program to: import dbimp, sys if __name__ == "__main__": dbimp.install() k = sys.modules.keys() k.sort() for kk in k: print kk #import bsddb.db import a.b.c.d import bsddb then I get as output MySQLdb MySQLdb.MySQLdb ... MySQLdb.types UserDict __builtin__ __main__ _codecs _locale _mysql _mysql_exceptions _sre array cPickle codecs copy copy_reg db dbimp ... mx.Misc mx.Misc.LazyModule new nt ntpath os os.path re ... zipimport Accepted *db* found a in db load_module: a a loaded: pkg: 1 found a.b in db load_module: a.b a.b loaded: pkg: 1 found a.b.c in db load_module: a.b.c a.b.c loaded: pkg: 1 found a.b.c.d in db load_module: a.b.c.d a.b.c.d loaded: pkg: 0 found bsddb in db load_module: bsddb found weakref in db load_module: weakref weakref loaded: pkg: 0 Traceback (most recent call last): File "test.py", line 11, in ? import bsddb File "/c/steve/Projects/Python/dbimp/dbimp.py", line 49, in load_module exec code in module.__dict__ File "db:bsddb", line 62, in ? File "/usr/lib/python2.4/os.py", line 133, in ? from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep, ImportError: No module named path In other words, the os module is /already/ in sys.smodules, as is os.path, yet the interpreter is complaining (I presume) that os.path is not a module. I don't even know *why* os is being executed a second time. I can only assume it's being imported as some other name like "bsddb.os" and some element of the import system is actually doing an import rather than refusing to guess. I presume I need to control the import process more closely to make sure that this import attempt is rejected, but I can't see how to do that. regards Steve From jeff at ccvcorp.com Tue Jan 11 15:50:38 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 11 Jan 2005 12:50:38 -0800 Subject: python3: 'where' keyword In-Reply-To: <7xpt0ciekk.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> <7xllb2f3z4.fsf@ruckus.brouhaha.com> <1105355380.040837.189270@c13g2000cwb.googlegroups.com> <7xis65a5w6.fsf@ruckus.brouhaha.com> <1105357839.696387.309900@c13g2000cwb.googlegroups.com> <7xr7kt314a.fsf@ruckus.brouhaha.com> <1105364925.848973.73080@c13g2000cwb.googlegroups.com> <7xllb1jsdz.fsf@ruckus.brouhaha.com> <7xpt0ciekk.fsf@ruckus.brouhaha.com> Message-ID: <10u8emr2iaa5k03@corp.supernews.com> Paul Rubin wrote: > Steve Holden writes: > >>[...] and if you think that >>newbies will have their lives made easier by the addition of ad hoc >>syntax extensions then you and I come from a different world (and I >>suspect the walls might be considerably harder in mine than in yours). > > I'm saying that many proposals for ad hoc extensions could instead be > taken care of with macros. Newbies come to clpy all the time asking > how to do assignment expressions, or conditional expressions, or > call-by-reference. Sometimes new syntax results. Lots of times, > macros could take care of it. Personally, given the requests in question, I'm extremely thankful that I don't have to worry about reading Python code that uses them. I don't *want* people to be able to make up their own control-structure syntax, because that means I need to be able to decipher the code of someone who wants to write Visual Basic as filtered through Java and Perl... If I want mental gymnastics when reading code, I'd use Lisp (or Forth). (These are both great languages, and mental gymnastics would probably do me good, but I wouldn't want it as part of my day-to-day requirements...) Jeff Shannon Technician/Programmer Credit International From michele.simionato at gmail.com Tue Jan 4 10:29:14 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 4 Jan 2005 07:29:14 -0800 Subject: Python evolution: Unease In-Reply-To: References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1104830276.579755.133870@f14g2000cwb.googlegroups.com> <7x652dk0gh.fsf@ruckus.brouhaha.com> <1104831798.408560.228940@c13g2000cwb.googlegroups.com> Message-ID: <1104852554.684821.297400@f14g2000cwb.googlegroups.com> Aahz: > The first three PSF grants were all in some way not directly related to > changing the core language. One was for a library, one for improving > Jython, and one for improving docs. Giving the PSF more money increases > the chances for additional work. Here is the link you forgot to post ;-) http://www.python.org/psf/grants/ The one about the docs seems more about teaching scientists how to use Python. Michele Simionato From cepl at surfbest.net Sat Jan 1 14:33:02 2005 From: cepl at surfbest.net (cepl at surfbest.net) Date: 1 Jan 2005 11:33:02 -0800 Subject: Python equivalent of script(1) Message-ID: <1104607982.132310.181560@c13g2000cwb.googlegroups.com> Is there anything like script(1) for python interactive sessions. From script(1) manpage: Script makes a typescript of everything printed on your terminal. It is useful for students who need a hardcopy record of an interactive session as proof of an assignment, as the typescript file can be printed out later with lpr(1). If the argument file is given, script saves all dialogue in file. If no file name is given, the typescript is saved in the file typescript. In my case I wouldn't like to use it as a proof of anything, but I want to get a script accessing a library system in my school -- it means many attempts to play with urllib. I would prefer to do it in an interactive session, but then I would love to have a record of all what I've done, so I can edit this record into final script. Thanks for any hint, Matej Cepl From ville at spammers.com Tue Jan 11 02:47:41 2005 From: ville at spammers.com (Ville Vainio) Date: 11 Jan 2005 09:47:41 +0200 Subject: Port blocking References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> <34f8ovF47d783U1@individual.net> <34fdf6F4a7t7uU1@individual.net> Message-ID: >>>>> "Steve" == Steve Holden writes: >> >>> Usually you wouldn't run a public corba or pyro service over >> >>> the internet. You'd use something like XMLRPC over HTTP port >> >>> 80 partly for the precise purpose of not getting blocked by >> >>> firewalls. Mark> I'm not sure if we're talking at cross-purposes here, but Mark> the application isn't intended for public consumption, but Mark> for fee-paying clients. >> Still, if the consumption happens over the internet there is almost >> 100% chance of the communication being prevented by firewalls. >> This is exactly what "web services" are for. Steve> I teach the odd security class, and what you say is far Steve> from true. As long as the service is located behind a Steve> firewall which opens up the correct holes for it, it's most Steve> unlikely that corporate firewalls would disallow client Steve> connections to such a remote port. Yes, but "clients" might also act as servers, e.g. when they register a callback object and expect the "server" to invoke something later on. This is possible (and typical) with CORBA at least. ORBs can use the same client-initiated connection for all the traffic, but this is probably somewhere in the gray area. -- Ville Vainio http://tinyurl.com/2prnb From grante at visi.com Wed Jan 26 18:26:55 2005 From: grante at visi.com (Grant Edwards) Date: 26 Jan 2005 23:26:55 GMT Subject: exclude binary files from os.walk References: <41f8167b$0$8648$a1866201@visi.com> Message-ID: <41f8273f$0$8001$a1866201@visi.com> On 2005-01-26, Larry Bates wrote: > There's no definitive way of telling a file is "non-ascii". > Bytes in a binary file define perfectly good ascii characters. As long as bit 7 is a 0. Traditional ASCII only allows/defines the values 0x00 through 0x7f. If that's what is meant by "ASCII", then a file containting bytes greater than 0x7F is not ASCII. If all bytes are 0x7F or below, the file _may_ be ASCII, but there's now way to tell if it _is_ ASCII unless you ask the creator of the file. It could be Baudot or some other encoding that doesn't use bit 7. Or, it could just be binary data that happens to have bit 7 == 0. > We could be of more help, if you would take the time to > explain a little about what you are trying to do. Yup. -- Grant Edwards grante Yow! Now, let's SEND OUT at for QUICHE!! visi.com From claudio.grondi at freenet.de Thu Jan 27 10:32:13 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 27 Jan 2005 15:32:13 -0000 Subject: Tao Scripting Language 0.8.5 beta released! References: Message-ID: <35scaqF4sqpqnU1@individual.net> Dear Limin, Tao Script with its 300 KByte of code is so small, that one just must love it forgiving all its baby troubles. After changes (see below) to the code in taoModule.cpp necessary because my compiler claimed repeated definition of 'ref' e.g. in the section: if(TaoReference *ref2a=inNameSpace->findDataShared(name) ){ myData[name]=ref2a; outNameSpace->nsData[name]=ref2a; }else{ TaoShareRefer*ref2b=new TaoShareRefer(); myData[name]=ref2b; outNameSpace->nsDataShared[name]=ref2b; outNameSpace->nsData[name]=ref2b; } I was able to compile the code with Microsoft Visual C++ .NET 2003 on W2K (create an empty .NET project, add all source code files, compile and be happy :-) Trying the examples provided on the homesite of Tao Script which run ok as they are, I found, that print("### \n") failes due to the way the Lexer works beeing not able to proper handle string literals. One just can't probably use any of "#'" "//" "/*" in strings because the lexer strips the comments before it analyses the source to handle content of the string literals. Hope this comment helps you to continue the well done work on it. I had fun with it because of its size, so from my point of view please try to keep the project as small as possible, so that it remains easy to check out the entire code. Maybe it is even a good idea to keep the problem with the strings as a "feature" in order to keep the Lexer as simple as possible? Best regards Claudio "Limin Fu" schrieb im Newsbeitrag news:mailman.1426.1106825698.22381.python-list at python.org... > Dear all, > > I am glad to announce in this mailing list that the lastest version > of a new scripting language has come out. > > Welcome to try it out. > > Comments are welcome. > > Suggestions are appreciated. > > ======================= > Here are some details: > ======================= > > Design Goals: > 1. Simple and efficient. > 2. Integrate nice features of other languages whenever possible. > > Implementation language: C++ with STL. > > Designer: Fu Limin > Email: fu [dot] limin [dot] tao [at] gmail.com > > Key features have been supported: > > 1. Dynamic-typing variables, supporting complex data structures > such as array/list, hash/dictionary and matrix etc. > > 2. Object-oriented programming ( multi-inheritance not supported > yet ). > > 3. Basic string regular expression matching. > > 4. Automatic garbage collection capable of collecting cyclically > referenced objects. > > 5. Numeric data types: complex number and matrix, and their basic > operations. > > 6. Convenient namespacing and dynamic creation of subroutines and > classes. > > 7. Dynamic loading of C/C++ modules ( not complete, but enough for > playing with it ^_^ ). > > 8. An embedded tiny XML parser. > > ToBeDone: > More string operations, multi-inheritance of classes, improvements > on C/C++ module loading, more on regular expression matching and > possible optimizations etc. > > Documentation: > > http://taoscript.sourceforge.net/brief_tao.php > > Sample scripts: > > http://taoscript.sourceforge.net/sample.php > > Download: > http://taoscript.sourceforge.net/downloads.php > > Best regards, > > Limin > > -- > Homepage for Tao Language: > http://taoscript.sourceforge.net > > Tao Language project at sourceforge.net: > http://sourceforge.net/projects/taoscript From stian at soiland.no Sun Jan 16 12:32:35 2005 From: stian at soiland.no (Stian Soiland) Date: Sun, 16 Jan 2005 18:32:35 +0100 Subject: How can I get the names of the files in a directory? In-Reply-To: References: Message-ID: <9C61660E-67E4-11D9-90E4-000D934525B6@soiland.no> P? 15. jan 2005 kl. 16:16 skrev .removethis.: > >>> import glob > >>> from os.path import isfile > >>> print filter(isfile, glob.glob('/tmp/*')) # can use patterns Nice example of when filter() is better than list comprehension. [f for f in glob.glob("/tmp/*") if isfile(fi)] is a bit too verbose, the iteration is a totally uninteresting part here. -- Stian S?iland Trondheim, Norway http://www.soiland.no/ =/\= From sjmachin at lexicon.net Tue Jan 18 16:47:39 2005 From: sjmachin at lexicon.net (John Machin) Date: 18 Jan 2005 13:47:39 -0800 Subject: Fuzzy matching of postal addresses In-Reply-To: <1106033765.623338.184170@f14g2000cwb.googlegroups.com> References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> <1106033765.623338.184170@f14g2000cwb.googlegroups.com> Message-ID: <1106084858.987989.35210@z14g2000cwz.googlegroups.com> John Machin wrote: > Ermmm ... only remove "the" when you are sure it is a whole word. Even > then it's a dodgy idea. In the first 1000 lines of the nearest address > file I had to hand, I found these: Catherine, Matthew, Rotherwood, > Weatherall, and "The Avenue". > Partial apologies: I wasn't reading Skip's snippet correctly -- he had "THE ", I read "THE". Only "The Avenue" is a problem in the above list. However Skip's snippet _does_ do damage in cases where the word ends in "the". Grepping lists of placenames found 25 distinct names in UK, including "The Mythe" and "The Wrythe". Addendum: Given examples in the UK like "Barton in the Beans" (no kiddin') and "Barton-on-the-Heath", replacing "-" by space seems indicated. From duncan.booth at invalid.invalid Mon Jan 17 08:25:54 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jan 2005 13:25:54 GMT Subject: Writing huge Sets() to disk References: Message-ID: Martin MOKREJ? wrote: > Duncan Booth wrote: >> Almost anything you do copies references. > > > But what does this?: > > x = 'xxxxx' Copies a reference to the existing string 'xxxxx' and stores the new reference in the variable x. If its a global variable then this will involve creating a new reference to the existing string 'x' and storing both references in the globals() dictionary for the module. > a = x[2:] Creates a new string by slicing the one reference by x, then creates a new reference to the string and stores it in the variable 'a' (as above), then releases the first reference to the new string. > b = z + len(x) Creates a new reference to 'z'; creates a new reference to 'x', creates a new reference to 'len', calls the function (which involves creating and releasing a tuple), releases the references to 'len' and 'x', invokes the add operator, releases the reference to 'z', then creates a new reference to the result while storing it in the variable 'b'. The result of the addition could be a new object, or it may just be a new reference created to an existing object. > dict[a] = b If 'dict' is a variable of type 'dict' (and its a bad idea to use the type name as the variable name), then this creates new references to each of 'a' and 'b' and stores them in the object 'dict'. As I said, almost everything you do involves creating and releasing references to existing objects. >> >> The member variables are all still accessible as member variables >> until you run your loop at the end to clear them, so no way could >> Python release them. > > OK, I wanted to know if there's some assignment using a reference, > which makes the internal garbage collector not to recycle the memory, > as, for example, the target dictionary still keeps reference to the > temporary dictionary. > So long as the object is still accessible it won't be free. You aren't making anything new reference the temporary dictionary, but so long as the old references are still there it can't free the memory. >> >> Even if they are Shelf objects, I see no reason here why you have to > > I gathered from previous discussion it's faster to use bsddb directly, > so no shelve. > Until you know that speed of accessing the file is a problem, I would go for the simple to use solution. At present there is no evidence that the speed of accessing the file is going to be a problem: your problems seem to stem from excessive memory use which means that page faults are likely to swamp everything else as far as execution time is concerned. >> What on earth is the point of an explicit call to __add__? If Guido >> had meant us to use __add__ he woudn't have created '+'. > > To invoke additon directly on the object. It's faster than letting > python to figure out that I sum up int() plus int(). It definitely > has helped a lot when using Decimal(a) + Decimal(b), where I got rid > of thousands of Decimal(__new__), __init__ and I think few other > methods of decimal as well - I think getcontext too. > The same point as above: it is most unlikely that these additions are going to make a noticeable difference to the running time, so leave them as easy to read additions until you have profiled the code and determined that they really are a hotspot that needs optimisiing. The less time you spend optimising prematurely, the sooner you get a program that meets your needs. >> tuple of your values then you don't have to use split or cast the >> strings > > bsddb creaps on me that I can store as a key or value only a string. > I'd love to store tuple. > >>>> import bsddb >>>> _words1 = bsddb.btopen('db1.db', 'c') >>>> _words1['a'] = 1 > > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.3/bsddb/__init__.py", line 120, in __setitem__ > self.db[key] = value > TypeError: Key and Data values must be of type string or None. > >>>> > > How can I record a number then? Either by wrapping your database access in code which converts the values to/from string, or by using a package which already does that (such as shelve). > > Can I use the mmap() feature on bsddb or any .db file? Most of the > time I do updates, not inserts! I don't want to rewrite all the time > 300MB file. I want to update it. What I do need for it? Know the > maximal length of a string value keept in the .db file? Can I get rid > of locking support in those huge files? Dont worry about it, updates won't rewrite the entire file. > > Definitely I can improve my algorithm. But I believe I'll always have > to work with those huge files. The point of using something like a bsddb file is that you get a system which will do the hard work for you of figuring out which bits to keep in memory and which bits to leave on disc. The sort of processing you showed, which updates the database in a random order but probably doesn't access every record should work well with a bsddb file. The code you show is dumping the contents of the temporary dictionary into the database then clearing the dictionary. Why are you waiting until the dictionaries occupy 300Mb before doing this. What happens to the runtime if you clear out the dictionaries when they occupy 30Mb or 3Mb? Questions about what will run fastest are almost impossible to answer without actually timing the results on some realistic data. Dumping the dictionaries frequently when they are comparatively small will result in higher runtime overheads since you will be updating some keys much more often, but you save by reducing the working set of your process. If your working set gets too large then expect massive increases in runtime, so it will be worth making sure that you aren't hitting this point before you consider any other optimisations. From luke at tatooine.planet Tue Jan 11 19:08:31 2005 From: luke at tatooine.planet (Luke Skywalker) Date: Wed, 12 Jan 2005 01:08:31 +0100 Subject: Windows GUIs from Python References: Message-ID: On Tue, 11 Jan 2005 22:15:36 +0100, Thomas Heller wrote: >Well, venster. Although it is most certainly alpha. But with some >work... Thx, I'll keep an eye on it. http://venster.sourceforge.net/ Luke. From eino at iki.fi Tue Jan 11 09:45:03 2005 From: eino at iki.fi (=?ISO-8859-1?Q?Eino_M=E4kitalo?=) Date: Tue, 11 Jan 2005 16:45:03 +0200 Subject: Python 2.4 and os.open question? Message-ID: <41e3e670$0$20038$39db0f71@news.song.fi> I just test in Windows XP with Python 2.4 I'd like to create a file with exclusive flag. If file exist I try to use it, if not I'd like to create it. Python (and underlying library) works differently with/without O_EXCL flag. Is this okay. How I should use this. Has somebody manual :-) ? Eino M?kitalo see scenarios (1 without flag ) (2 with flag) Scenario 1: To create file if it's not available this works ok >>> aa=os.open("c:\\temp\\a.txt",os.O_RDWR|os.O_CREAT) >>> os.close(aa) >>> aa=os.open("c:\\temp\\a.txt",os.O_RDWR|os.O_CREAT) >>> os.close(aa) Scenario 2: But if you try to do same with O_EXCL then it does not use same logic??? >>> aa=os.open("c:\\temp\\a.txt",os.O_RDWR|os.O_EXCL|os.O_CREAT) >>> os.close(aa) >>> aa=os.open("c:\\temp\\a.txt",os.O_RDWR|os.O_CREAT) Traceback (most recent call last): File "", line 1, in OSError: [Errno 17] File exists: 'c:\\temp\\a.txt' From jbperez808 at wahoo.com Wed Jan 12 02:44:10 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Wed, 12 Jan 2005 15:44:10 +0800 Subject: a new Perl/Python a day In-Reply-To: References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> <87r7ku3pwq.fsf@mithril.chromatico.net> <34ism6F4athpcU1@individual.net> Message-ID: <34k2q9F4bitrcU1@individual.net> Bob Smith wrote: > With terms such as "blabbering Unix donkeys" and "sloppy perl monkeys" I would say that the monkey-mind is indeed one that is enamoured with obfuscation and complicated gadgetry for its own sake. Ever wonder why no one has ever considered using the phrase "Zen of Perl"? (yes, it sounds completely off-kilter) ... or why 'Perl monkey' is an oft-heard term whereas 'Python monkey' just doesn't seem to be appropriate? From kent3737 at yahoo.com Thu Jan 20 12:33:49 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Thu, 20 Jan 2005 12:33:49 -0500 Subject: xml parsing escape characters In-Reply-To: <41efe52f$0$6220$e4fe514c@news.xs4all.nl> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efb72d$1_2@newspeer2.tds.net> <41efe52f$0$6220$e4fe514c@news.xs4all.nl> Message-ID: <41efe914_3@newspeer2.tds.net> Irmen de Jong wrote: > Kent Johnson wrote: > [...] > >> This is an XML document containing a single tag, , whose >> content is text containing entity-escaped XML. >> >> This is *not* an XML document containing tags , , >> , etc. >> >> All the behaviour you are seeing is a consequence of this. You need to >> unescape the contents of the tag to be able to treat it as >> structured XML. > > > The unescaping is usually done for you by the xml parser that you use. Yes, so if your XML contains for example <not a tag> and you parse this and ask for the *text* content of the tag, you will get the string "" but it's still *not* a tag. If you try to get child elements of the element there will be none. This is exactly the confusion the OP has. > > --Irmen From arobert at townisp.com Wed Jan 5 11:03:02 2005 From: arobert at townisp.com (Andrew Robert) Date: Wed, 05 Jan 2005 11:03:02 -0500 Subject: How to make executable file ? In-Reply-To: References: Message-ID: <10to3sve2nburaf@corp.supernews.com> BOOGIEMAN wrote: > Just how to make *.exe file from python code ?? > I typed this : > > a, b = 0, 1 > while b < 1000: > print b, > a, b = b, a+b > > and saved it as pyt.txt > > Now, how do I make pyt.exe file ??? > I want to run it on windows where isn't installed python. You may want to try cx_freeze. Details on it can be found at http://starship.python.net/crew/atuining/cx_Freeze/ Binaries are available for Linux and Windows. Alternately, source code is available if you need to compile it for a different platform. -- Thank you, Andrew Robert E-mail: arobert at townisp.com Ur: http://shardservant.no-ip.info From jfine at pytex.org Tue Jan 11 13:40:12 2005 From: jfine at pytex.org (Jonathan Fine) Date: Tue, 11 Jan 2005 18:40:12 +0000 Subject: What could 'f(this:that=other):' mean? References: <41DC52CA.5070104@pytex.org> <10toomjdjcs5v21@corp.supernews.com> <41DCE28B.70806@pytex.org> <10tr8eo5skqo2a3@corp.supernews.com> <41DF05DC.9060004@pytex.org> Message-ID: <41E41D8C.9060701@pytex.org> Nick Coghlan wrote: > If the caller is meant to supply a namespace, get them to supply a > namespace. > > def f(ns1, ns2): > print ns1['a'], ns1['b'], ns2['a'], ns2['b'] > > f(ns1 = dict(a=1, b=2), ns2 = dict(a=3, b=4)) > > Hey, where's Steve? Maybe his generic objects should be called > namespaces instead of bunches. . . > > def f(ns1, ns2): > print ns1.a, ns1.b, ns2.a, ns2.b > > f(ns1 = namespace(a=1, b=2), ns2 = namespace(a=3, b=4)) Basically, there are three main possibilities. f_1(ns1=dict(a=1, b=2), ns2=dict(a=3, b=4)) f_2(ns1_a=1m, ns1_b=2, ns2_a=3, ns2_b=4) f_3(ns1:a=1m, ns1:b=2, ns2:a=3, ns2:b=4) f_3 is the suggested extension to Python. f_3 is similar to f_2 for the caller of f_3. f_3 is similar to f_1 for the implementor of f_3. Nick points out that a key issue is this: Is the user meant to supply arguments belonging to a namespace? I'm not, at this time, wishing to promote my suggestion. If I were, I would be well advised to find usage cases. Rather, I simply wish to point out that the f(this:that=other) syntax may have uses, other than optional static typing. And this I've done. So for me the thread is closed. Jonathan From artyprog at wanadoo.fr Sun Jan 23 10:39:48 2005 From: artyprog at wanadoo.fr (salvatore) Date: Sun, 23 Jan 2005 16:39:48 +0100 Subject: PSE : Python Servlet Engine configuration Message-ID: <41f3c55e$0$25811$8fcfb975@news.wanadoo.fr> Hello, Is there someone who use PSE ? I have a strange problem, i don't see how pse.conf is managed. Indeed althoug I make modifications on it nothind is take in account. I have also erases it !!! and PSE doesn't claim anything !!! Can someone help me ? Regards Salvatore From bvanzant at ironport.com Tue Jan 4 20:26:38 2005 From: bvanzant at ironport.com (Bob Van Zant) Date: Tue, 04 Jan 2005 17:26:38 -0800 Subject: modpython, apache and windows In-Reply-To: <41DB3F0A.2010706@tiscali.co.uk> References: <41DB3F0A.2010706@tiscali.co.uk> Message-ID: <1104888398.29610.123.camel@localhost.localdomain> Fortunately most of the Python-for-the-web implementations do not follow closely to the PHP paradigm of web-based programming. There are some, like PSP, that more closely model what PHP does. It is not uncommon to have something like index.py which does hardly anything except fire up a framework that takes care of parsing the rest of the URI and passing control over to the proper script. Using some relatively cryptic features of Apache you can hide the fact that everything goes through index.py (mod_rewrite). You might be interested in the Aquarium web framework (http://aquarium.sf.net). It provides a very flexible, mature framework for developing web applications including a session manager, a form validation library and a form generation "widget" among many other things. The documentation on the official aquarium site is fairly cryptic but I have written a few more intro documents at http://bob.norcalttora.com including an example excerpt of an httpd.conf file that will configure mod_python to work with Aquarium including the previously mentioned apache rewrite rules. I have never tried to get this working in windows but if you get it working I'd be very interested in seeing what changes you had to make. I'm willing to help you along the way. Not really sure how else to help you at this point. The index.py that you had working was probably on the right track. -Bob On Wed, 2005-01-05 at 01:12 +0000, Sam wrote: > Hi All, > > I am interested in learning python since I am hearing more and more > about python for use in web development > > I am starting out on python, with knowledge of PHP some perl > > my current hurdle is setting up either apache 1 or 2 with python 2.3.3 I > have installed modpython fine > > which informed me that I need to make some configuration changes to > httpd.conf > > I have not had it working yet, searches on the web give conflicting > suggestions and so far has confused me > > some forums mention spyce and serving .spy files > > so far I one explanation worked in that a .py file was parsed but I had > to set the name of the actual file within apache.conf > this seems strange > > thanks in advance >> SS > > > -- > No virus found in this outgoing message. > Checked by AVG Anti-Virus. > Version: 7.0.298 / Virus Database: 265.6.7 - Release Date: 30/12/2004 > From boomberschloss at yahoo.com Tue Jan 18 11:03:57 2005 From: boomberschloss at yahoo.com (Joachim Boomberschloss) Date: Tue, 18 Jan 2005 08:03:57 -0800 (PST) Subject: Integration with java (Jpype vs. JPE) Message-ID: <20050118160357.30843.qmail@web53105.mail.yahoo.com> Thanks for the info. I understand now the background and possibilities, but would like to refine my query: As I see it, writing a hybrid Java/Python application faces approximately three possibilities: (i) write the core in Java and do some scripting with Jython, (ii) write independent code in Java and in Python, and integrate using JPype (or similar), using Python also as a glue layer, (iii) write independent code in Java and in Python, and integrate using a neutral technology. Since much of the code in my project is already written, I am considering options ii and iii. This is how I perceive the work required in each case: Option ii would enable writing independent packages in Python and Java, and will require a glue layer in Python consisting of general administration and wrappers around Java packages written using JPype. I don't yet have a clear perception of how difficult it would be to make such wrappers, or to put my faith in JPype at this stage. Option iii would also enable writing independent packages in Python and Java, but its glue layer will be distributed between Python and Java using Jython and Pyro (I chose Pyro because it works in both CPython and Jython, and can be used to communicate between them). This would (to the best of my understanding) enable a smoother interface between Java and Python, but will probably complicate somewhat the glue layer, both because it would use networking to communicate, and because it would probably involve taking special measures to overcome the differences between CPython and Jython (since the glue layer will need to run on both of them). Joe. --- Cameron Laird wrote: > In article <34s5krF4c85d5U1 at individual.net>, > Jon Perez wrote: > >Can someone summarize in a nutshell what is the > >difference between JPype and JPE? > > JPE's the original. It provided more functionality > than JPype has > achieved so far, I believe (though that could change > any day). I > think no one now maintains JPE. > > Someone really ought to include a couple of > sentences to that effect > on the front page of . > -- > http://mail.python.org/mailman/listinfo/python-list > __________________________________ Do you Yahoo!? The all-new My Yahoo! - What will yours do? http://my.yahoo.com From itsme at yahoo.com Wed Jan 12 11:30:04 2005 From: itsme at yahoo.com (It's me) Date: Wed, 12 Jan 2005 16:30:04 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: Precisely. One have to convert complex number into vectors, and vector of complex numbers into vector of vectors, list of complex numbers into list of vectors, ...., you get the idea. And my code no longer look like the equation I have on paper... Like I said, I've travelled down that path before with C++ and Modelica. It gets ugly. Anyway. "Antoon Pardon" wrote in message news:slrncu9mmo.1r6.apardon at rcpc42.vub.ac.be... > Op 2005-01-12, It's me schreef : > > > > "Robert Kern" wrote in message > > news:cs1mp9$sg9$1 at news1.ucsd.edu... > >> > >> That's *it*. > > > > So, how would you overload an operator to do: > > > > With native complex support: > > > > def twice(a): > > return 2*a > > > > print twice(3+4j), twice(2), twice("abc") > > > > Let's presume for a moment that complex is *not* a native data type in > > Python. How would we implement the above - cleanly? > > > I suppose in the same way as (graphic) points and vectors can be > implemented cleanly. > > A few years back I had written a Vector class in python, just > to get an understanding of how things worked. It worked without > a problem with your twice function. > > > >>> Vec(1.0,2.0) > Vector[1.0, 2.0] > >>> def twice(a): > ... return 2 * a > ... > >>> twice(Vec(1.0,2.0)) > Vector[2.0, 4.0] > >>> > > > I suppose what can be done with a vector class could have been > done with a complex class should complex numbers not have been > native to python. > > -- > Antoon Pardon From jb2410 at columbia.edu Wed Jan 12 15:36:30 2005 From: jb2410 at columbia.edu (Jonah Bossewitch) Date: Wed, 12 Jan 2005 15:36:30 -0500 Subject: human readable IPTC field names Message-ID: Hi, I am using PIL's IptcImagePlugin to extract the IPTC tags from an image file. I was able to successfully retrieve the tags from the image (thanks!), but the results are keyed off of cryptic tuples. I found the lookup codes here - http://demo.imagefolio.com/demo/ImageFolio31_files/skins/cool_blue/images/iptc.html, but I was wondering if these existed anywhere in the code. Would it make sense to include a label lookup on these keys? Maybe as a dictionary or a properties file alongside the IptcImagePlugin? I am not sure if these field names are standard, but named lookups off of keys would be much more readable does such a lookup table exist? Does it make sense to include with the IptcImagePlugin? I would be willing to work on this if anyone was interested. thanks, Jonah ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Jonah Bossewitch Technology and Programmer Analyst ccnmtl.columbia.edu jb2410 at columbia dot edu ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From fredrik at pythonware.com Thu Jan 20 04:38:56 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jan 2005 10:38:56 +0100 Subject: why are these not the same? References: Message-ID: Lowell Kirsh wrote: > On a webpage (see link below) I read that the following 2 forms are not the same and that the > second should be avoided. They look the same to me. What's the difference? > def functionF(argString="abc", argList = None): > if argList is None: argList = [] > ... > > def functionF(argString="abc", argList=None): > argList = argList or [] > ... "is None" tests for None, "argList or" tests for a false value. None is false, but many non-None objects are also false. "should be avoided" sounds like overly zealous advice to me; use the latter form if you understand it. From irmen at -nospam-remove-this-xs4all.nl Tue Jan 18 13:36:41 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Tue, 18 Jan 2005 19:36:41 +0100 Subject: Integration with java (Jpype vs. JPE) In-Reply-To: References: Message-ID: <41ed5739$0$6208$e4fe514c@news.xs4all.nl> Joachim Boomberschloss wrote: > Option iii would also enable writing independent > packages in Python and Java, but its glue layer will > be distributed between Python and Java using Jython > and Pyro (I chose Pyro because it works in both > CPython and Jython, and can be used to communicate > between them). Please note that currently it is not possible to use Pyro as a server in Jython. Only as a client. Also; last time I checked there were some bugs in the Jython compiler that were triggered by Pyro's code (parts of it would give a compile error). See http://www.razorvine.net/python/PyroAndJython --Irmen From fredrik at pythonware.com Mon Jan 31 11:28:18 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 31 Jan 2005 17:28:18 +0100 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1107188359.375703.110590@f14g2000cwb.googlegroups.com> Message-ID: Michael Tobis wrote: > Also, the assertion that "Python has no declarations whatsoever" is no > longer obviously true. In the 2.4 decorator syntax, a decorator line is > not executable that's a nice theory, but since the decorator line is executed by the inter- preter, it's a little weak. From duncan.booth at invalid.invalid Fri Jan 14 08:53:43 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Jan 2005 13:53:43 GMT Subject: porting C code References: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> <0NidnetRONZTgHrcRVn-oQ@powergate.ca> Message-ID: Lucas Raab wrote: > Sorry, the third "byte" is what I meant. As for code samples, I hope the > following will work: > > typedef unsigned long int word32 ; > void mu(word32 *a) > { > int i ; > word32 b[3] ; > > b[0] = b[1] = b[2] = 0 ; > for( i=0 ; i<32 ; i++ ) > { > b[0] <<= 1 ; b[1] <<= 1 ; b[2] <<= 1 ; > if(a[0]&1) b[2] |= 1 ; > if(a[1]&1) b[1] |= 1 ; > if(a[2]&1) b[0] |= 1 ; > a[0] >>= 1 ; a[1] >>= 1 ; a[2] >>= 1 ; > } > > a[0] = b[0] ; a[1] = b[1] ; a[2] = b[2] ; > } > > The "a[#]" and "b[#]" are the parts that are giving me trouble. So far as I can tell, the function takes an array of 3 32bit values, reverses the order of the bits in each value, and swaps the first and last elements of the array. All of this seems to be being done in an attempt to make the process as obscure and inefficient as possible both by using meaningless names, and by doing both operations simultaneously. To convert this to Python I might try something like: rev2 = [ 0, 0x02, 0x01, 0x03 ] rev4 = [ (lo|hi<<2) for lo in rev2 for hi in rev2 ] rev8 = [ (lo|hi<<4) for lo in rev4 for hi in rev4 ] def rev32(n): '''Reverse the low 32bits of an integer''' return (rev8[(n>>24)&0xff]| (rev8[(n>>16)&0xff]<<8)| (rev8[(n>>8)&0xff]<<16)| (rev8[n&0xff]<<24)) def mu(a): '''Reverse the bit order of a list of 32bit integers while also reversing the list itself''' return [rev32(n) for n in reversed(a)] print [hex(n) for n in mu([0x10203040, 0x50607080, 0x90a0b0c0])] Although if 'a' really is just being used as a 96 bit integer I could add a 96 bit variant of the reversal function and use it directly: def rev96(n): '''Reverse the low 96bits of an integer''' return rev32(n>>64)|(rev32(n>>32)<<32)|(rev32(n)<<64) print hex(rev96(0x102030405060708090a0b0c0L)) From maxm at mxm.dk Wed Jan 5 05:09:32 2005 From: maxm at mxm.dk (Max M) Date: Wed, 05 Jan 2005 11:09:32 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) In-Reply-To: <1104892737.215470.34590@c13g2000cwb.googlegroups.com> References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> <1104892737.215470.34590@c13g2000cwb.googlegroups.com> Message-ID: <41dbbc8d$0$290$edfadb0f@dread12.news.tele.dk> Carl Banks wrote: > Also, note that there are some encodings unrelated to Unicode. For > example, try this: > > . >>> "abcd".encode("base64") > This is an encoding between two byte strings. Yes. This can be especially nice when you need to use restricted charsets. I needed to use unicode objects as Zope ids. But Zope only accepts a subset of ascii as ids. So I used: hex_id = u'INBOX'.encode('utf-8').encode('hex') >>494e424f58 And I can get the unicode representation back with: unicode_id = id.decode('hex').decode('utf-8') >>u'INBOX' Tn that case id.decode('hex') doesn't return a unicode, but a utf-8 encoded string. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From elbertlev at hotmail.com Wed Jan 12 17:40:11 2005 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: 12 Jan 2005 14:40:11 -0800 Subject: encryption/decryption help References: Message-ID: <1105569611.087888.58330@c13g2000cwb.googlegroups.com> For the problem described pycrypto is the best solution. Blowfish is simple and secure. The method you want to use is called "security by obscurity". But chances are very high that the "homebrewed" scheme you will invent will not stand any serious crytoatack. First of all: both sides (sender and receiver) have to agree on the session key used. And this is the most "dangerous" exchange. Sure you can hard coded the key on both sides, but periodically you have to change them. I was facing similar problem: had to secure legacy Inet server. I started with stunnel (worked great, but was a little bit sluggish). Then I figured out how to implement IPSEC (both sides were W2K) and this was the safiest solution. Sorry but it does not involve Python :( From newsgroups at jhrothjr.com Sun Jan 9 08:50:15 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sun, 9 Jan 2005 07:50:15 -0600 Subject: Getting rid of "self." References: <1gq4ery.1v79c2t9lsfinN%aleaxit@yahoo.com> Message-ID: <10u2dlj4p45psf0@news.supernews.com> "Alex Martelli" wrote in message news:1gq4ery.1v79c2t9lsfinN%aleaxit at yahoo.com... > BJ?rn Lindqvist wrote: > >> I think it would be cool if you could refer to instance variables >> without prefixing with "self." I know noone else thinks like me so > > Some do -- Kent Beck's excellent book on TDD-by-example has a specific > grouse against that in the chapter where he develops the unittest module > (in Python). But that's how comes Kent is a _Smalltalk_ programmer > rather than a _Python_ programmer, see?-) And of course, the reason it's possible in Smalltalk but not in Python is that Smalltalk requires the declaration of instance variables. Also Smalltalk does not have things like module variables and builtins. The interpreter knows exactly what every name references, which isn't true in Python. John Roth > > > Alex From aleaxit at yahoo.com Wed Jan 5 08:25:37 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 5 Jan 2005 14:25:37 +0100 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> Message-ID: <1gpx56v.yb9ubn188tj2yN%aleaxit@yahoo.com> Dave Brueck wrote: ... > No, not at all - I'm just trying to better understand what you mean. Words > like "generic" and "concepts" don't yet have a widely recognized, strict > definition in the context of programming. If somebody has assigned some > specific definition to them, that's great, it's just not universal yet so > references and additional explanations are helpful. Googling for "generic programming" (with the quotes) gets 100,000 + hits. The first couple pages of hits, at least, seem to all be speaking about exactly the same thing. The terminology appears to be settled enough that Oxford's St Anne College feels they can organize a "Summer School on Generic Programming", Nottingham University a "Workshop on Generic Programming", etc, etc, without fearing ambiguity. "Generic" by itself is one thing, but when we specifically mention "Generic programming" I do not really see the ambiguity. Same for "concepts" -- by itself it's too wide, to the point that it means nothing, but put it next to "generic programming" and the resulting 26.000 hits seem to be mostly speaking about the very same thing, in as much as one can tell from the first few pages of hits, "a concept is defined as a family of abstractions that are all related by a common set of requirements" to quote Musser. Exactly what extra support Roman would want from Python for 'concepts', beyond that offered by, say, C++, I'm not sure. Protocols, interfaces and design-by-contract are other terms often used to try and capture pretty similar issues. As far as I know the C++ community is unique in routinely formalizing some PERFORMANCE requirements (pragmatics ahoy!-) as part of their approach to generic programming -- but that's just an important cultural issue, the LANGUAGE itself, C++ as it stands, offers no way to say "this has O(N) perfrmance"... this kind of thing still goes in comments, and in clauses in standardization documents. When I say that a "protocol" includes pragmatics as well as syntax and semantics, that's part of what I mean, in a handwaving kind of sense. The *interface* to a Python dictionary/mapping includes a set of methods with certain signatures; it expresses little beyond "syntax" issues. The *semantics* of it include axioms that could and perhaps should be formalized to define the connectedness among the methods, e.g. a long list of things such as "for any x acceptable as a key and y acceptable as a value into d, ...: d[x] = y assert x in d del d[x] assert x not in d d[x] = y z = d[x] assert z is y and so on, and so forth". The kind of things one would write in a unit test... except that unit tests don't include universal quantifiers of the form "for any x such that";-). Finally, the *pragmatics* of a Python dictionary include "accessing d[x] is pretty darn fast" although no doubt that could (I dunno if it should) be formalized further. As to how a "dictionary CONCEPT" might differ from a "dictionary PROTOCOL", I'm not sure. They both should include syntax (interface), semantics (behavior specs), and perhaps a sprinkling of pragmatics -- such as, O(...) performance specs for some operations, but mostly stuff that's harder to formalize, such as, say: x = malloc(N); x = realloc(x, M): when N is very very large, and M is MUCH smaller than N, SHOULD, pragmatically, make some memory available for other uses (as opposed to leaving it all in the block allocated for x) -- the kind of things that don't get into formalized standards because handwaving is disliked there, but can make a programmer's life miserable nevertheless (as this very issue does with today's Python, which relies on these pragmatics in a spot or two, and MacOSX' standard C library, which ignores them...). Alex From http Mon Jan 10 21:45:16 2005 From: http (Paul Rubin) Date: 10 Jan 2005 18:45:16 -0800 Subject: OT: MoinMoin and Mediawiki? Message-ID: <7x6524d6pv.fsf@ruckus.brouhaha.com> I need to set up a wiki for a small group. I've played with MoinMoin a little bit and it's reasonably straightforward to set up, but limited in capabilities and uses BogusMarkupConventions. I want to use it anyway because I need something running right away and I don't want to spend a whole lot of time messing with it. In the larger world, though, there's currently One True wiki package, namely Mediawiki (used by Wikipedia). Mediawiki is written in PHP and is far more complex than MoinMoin, plus it's database backed, meaning you have to run an SQL server as well as the wiki software itself (MoinMoin just uses the file system). Plus, I'll guess that it really needs mod_php, while MoinMoin runs tolerably as a set of cgi's, at least when traffic is low. I'll say that I haven't actually looked at the Mediawiki code, though I guess I should do so. What I'm getting at is I might like to install MoinMoin now and migrate to Mediawiki sometime later. Anyone have any thoughts about whether that's a crazy plan? Should I just bite the bullet and run Mediawiki from the beginning? Is anyone here actually running Mediawiki who can say just how big a hassle it is? There are actually two wikis I want to run, one of which I need immediately, but which will be private, low traffic and stay that way. The other one will be public and is planned grow to medium size (a few thousand active users), but which I don't need immediately. I definitely want the second one to eventually run Mediawiki. I can probably keep the first one on MoinMoin indefinitely, but that would mean I'm eventually running two separate wiki packages, which gets confusing. From dmerrillq at usaq.netq Sat Jan 8 12:12:41 2005 From: dmerrillq at usaq.netq (Dave Merrill) Date: Sat, 8 Jan 2005 12:12:41 -0500 Subject: Installing IPython on win2k Message-ID: Hi, I'm new to python, and ipython, but not to programming, having trouble getting ipython installed on windows 2000, python 233. Any help would be much appreciated; I'm sure I'm being some basic flavor of dense... First downloaded and installed PythonWin, readline and ctypes. They're all pretty clearly here and working, because I can run PythonWin, and from there, importing readline and ctypes works. Then downloaded ipython-0.6.6.zip and unzipped it. When I double-click setup.py, I get only a brief wait cursor; nothing else happens, and importing ipython as a test fails. I tried moving the whole unzipped dir to site-packages, no difference. Both files in the scripts dir, ipython and pycolor, have no filename extension, which seems odd to my newbie eye. I tried renaming them to .py, still no difference. My apologies for this basic question, and my no doubt ignorant flailing about. Very much looking forward to getting this working. Thanks, Dave Merrill From brianobush at gmail.com Fri Jan 14 10:32:06 2005 From: brianobush at gmail.com (brianobush at gmail.com) Date: 14 Jan 2005 07:32:06 -0800 Subject: Class initialization from a dictionary, how best? References: <1105677379.632236.17020@z14g2000cwz.googlegroups.com> <41e7b80e.827352389@news.oz.net> Message-ID: <1105716725.996023.255800@c13g2000cwb.googlegroups.com> Yes, my examle here is a tiny part of a larger more complex issue. My application is an DOM XML parser that is reading attributes one at a time. My class that I am creating is used elsewhere and must have certain arguments for those uses to continue working. So, I seem to be left with creating an intermediate object. Before, I was simply creating an object: t = Test() for attr_name in mapping.keys(): setattr(t, attr_name, value_from_source) This I feel was ellegant, efficient and clear. However, what I have now works but is not clear. BTW, t1 is just for example and was just being printed Thanks, Brian From jdhunter at ace.bsd.uchicago.edu Wed Jan 19 17:12:01 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 19 Jan 2005 16:12:01 -0600 Subject: [OT] Good C++ book for a Python programmer In-Reply-To: ("Philippe C. Martin"'s message of "Wed, 19 Jan 2005 17:58:23 GMT") References: <1106136496.719185.87850@c13g2000cwb.googlegroups.com> Message-ID: >>>>> "Philippe" == Philippe C Martin writes: Philippe> I suggest you google 'C++ tutorial' Regards, Stroustup's "The C++ Programming Language" is the best C++ book I've read. It is at a fairly high level, and I already had read several C++ books before reading it, so it may be tough sledding. But I would try this first since you are an experienced programmer and know OO concepts, and if it fails to satisfy try something lighter. Unfortunately, I didn't like any of the other kinder, gentler overview books I read on C++, so can't really recommend anything along those lines, though I'm sure they are out there. JDH From itsme at yahoo.com Tue Jan 11 17:51:59 2005 From: itsme at yahoo.com (It's me) Date: Tue, 11 Jan 2005 22:51:59 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> <6-Cdnfjyqs6coXncRVnyuA@pipex.net> Message-ID: "Big and Blue" wrote in message news:6-Cdnfjyqs6coXncRVnyuA at pipex.net... > It's me wrote: > > > > I am very happy that Python included *native* complex number > > support. > > And I have always been happy that FORTRAN supports them. > > > I really like Python's notion of having just one data type: the duck. > > So have you considered using Python for your problem? > Yes, over the holiday, I wrote a somewhat complex program using Python - just so I can apply what I have learned so far. It's a joy to use. I was able to finished the program in a fraction of the time it used to take me in Fortran (and later C). From aorfanakos at gmail.com Sun Jan 30 14:47:18 2005 From: aorfanakos at gmail.com (Aggelos I. Orfanakos) Date: 30 Jan 2005 11:47:18 -0800 Subject: Regarding exception handling Message-ID: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> Hello. In a program, I want to ensure that a socket closes (so I use try ... finally), but I also want to catch/handle a socket exception. This is what I have done: try: try: s = ... # socket opens # various code ... except socket.error, x: # exception handling finally: s.close() # socket closes Is there a more "elegant" or "proper" way to do this? Or the above code is OK? Thanks in advance. From yyusenet at yahoo.com Sun Jan 30 09:58:26 2005 From: yyusenet at yahoo.com (YYusenet) Date: Sun, 30 Jan 2005 07:58:26 -0700 Subject: [perl-python] sending email In-Reply-To: <1107041765.890014.112530@c13g2000cwb.googlegroups.com> References: <1107041765.890014.112530@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: [snip] > > The first two has glaring problems. I'm sorry i forgot what they ^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^ > are. ^^^^ [snip] How can you complain about *Mail::Mailer* and *Mail::Send* when you don't even know what they are? -- k g a b e r t (at) x m i s s i o n (dot) c o m From nightmarch at gmail.com Mon Jan 24 04:18:05 2005 From: nightmarch at gmail.com (nightmarch) Date: Mon, 24 Jan 2005 17:18:05 +0800 Subject: Why can't use cursor.nextset() in adodbapi package? Message-ID: <31d9b15c050124011863ee32a5@mail.gmail.com> I want use crsr.nextset() , But I got errors like following: >>> connStr = "Provider=MSDAORA.1;Password=jmpower;User ID=jmpower;Data Source=jmgis_agps3;Persist Security Info=True" >>> import adodbapi >>> conn= adodbapi.connect( connStr ) >>> crsr = conn.cursor() >>> sql = "select * from wjtmp" >>> crsr.execute(sql) >>> rec = crsr.fetchone() >>> crsr.nextset() Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\Lib\site-packages\adodbapi\adodbapi.py", line 711, in nextset rsTuple=self.rs.NextRecordset() File "", line 2, in NextRecordset File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 251, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) com_error: (-2147352567, '\xb7\xa2\xc9\xfa\xd2\xe2\xcd\xe2\xa1\xa3', (0, 'ADODB.Recordset', 'Current provider does not support returning multiple recordsets from a single execution.', 'C:\\WINNT\\HELP\\ADO210.CHM', 0, -2146825037), None) Why? thanks From aleaxit at yahoo.com Fri Jan 7 06:05:08 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 12:05:08 +0100 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> Message-ID: <1gq0oyv.1ko371t1a7y8eyN%aleaxit@yahoo.com> Terry Reedy wrote: ... > Even though I currently only have 80 megs (about the minimum one can You probably mean 80 gigs. You can get smaller disks, say 30 gigs, in entry-point laptops. But for a few dozen megs I think you'd have to go for solid-state "disks", say USB keys with flash memory -- while 128 megs is around the minimum one can easily find in shops, there are plenty of smaller cuts, such as 64 or even 32 megs, sold e.g. as part of other gadgets such as mice, remote-control receivers, &c. > serious stuff is obsolete. (My first hard disk was 5 or 10 megs.) A Here I suspect you do mean megs -- 5 and 10 megs were indeed the sizes of the first affordable "winchester" hard-disks 20/25 years ago. Alex From google at trisko.net Mon Jan 24 15:37:30 2005 From: google at trisko.net (mtrisko) Date: 24 Jan 2005 12:37:30 -0800 Subject: Python Developers Wanted Message-ID: <1106599050.050364.267690@c13g2000cwb.googlegroups.com> Textura LLC is currently looking to hire experienced Python software developers. We are a new and quickly growing business process service provider based in the Lake Forest/Lake Bluff, IL area. We are a very well funded company, we have launched our services, and we are experiencing explosive sales growth. The management team include the former global COO for PwC Consulting and a number of other very experienced executives. Our primary customer service offering is based in Python. We have major additional functionality to add to our current offering, and plans to refactor and rearchitect our systems architecture to support future requirements. We're looking for developers with a well-rounded technical skillset, and experience developing complex, high volume business systems. Desirable technology skills include: * Programming in Python, C/C++, and Java * Web application development using Linux, Apache, Webware, SQLObject, Reportlab, and J2EE technologies * Database programming with PostgreSQL, DB2, and Oracle * Web services and enterprise application integration experience The ideal candidate would have the following qualifications: * BA/BS in CS or equivalent experience * A minimum of 3 years of software development experience, using formal development methods * Experience developing robust, secure, scalable, high volume, commercial-grade systems * Financial and business workflow development experience * Expertise with all phases of the software development lifecycle, including requirements analysis, design, coding, testing, implementation, and support * Excellent verbal and written communication skills * Skills working in a collaborative team environment You can expect a fast-paced, fun, and challenging work environment, great people to work with, and a competitive salary with significant bonus potential. If you are qualified and interested, please send your resume to the e-mail address below: Michael Trisko Chief Technology Officer Textura LLC http://www.texturallc.com E-mail contact: mtrisko (at) texturallc.com From erikbethke at gmail.com Thu Jan 20 09:20:46 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 20 Jan 2005 06:20:46 -0800 Subject: ElementTree cannot parse UTF-8 Unicode? In-Reply-To: References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> <5861401.FEXqi8ioxF@strongwill.g2ctech> Message-ID: <1106230846.455765.7310@c13g2000cwb.googlegroups.com> There is something wrong with the physical file... I d/l a trial version of XML Spy home edition and built an equivalent of the korean test file, and tried it and it got past the element tree error and now I am stuck with the wxEditCtrl error. To build the xml file in the first place I had code that looked like this: d=wxFileDialog( self, message="Choose a file", defaultDir=os.getcwd(), defaultFile="", wildcard="*.xml", style=wx.SAVE | wxOVERWRITE_PROMPT | wx.CHANGE_DIR) if d.ShowModal() == wx.ID_OK: # This returns a Python list of files that were selected. paths = d.GetPaths() layout = '\n' L1Word = self.t1.GetValue() L2Word = 'undefined' layout += '\n' layout += ' \n' layout += '' open( paths[0], 'w' ).write(layout) d.Destroy() So apprantly there is something wrong with physically constructing the file in this manner? Thank you, -Erik From me at privacy.net Tue Jan 11 18:52:32 2005 From: me at privacy.net (Dan Sommers) Date: 11 Jan 2005 18:52:32 -0500 Subject: CGI, anydbm.open() and linux file permissions References: Message-ID: On Tue, 11 Jan 2005 15:16:53 -0800 (PST), Derek Basch wrote: > Hello, > I have a CGI script which uses anydb.open() to create a DBM. However I get this > traceback: > /usr/lib/python2.3/bsddb/__init__.py in > hashopen(file='/var/www/bp/predictor/tools.dbm', flag='c', mode=438, > pgsize=None, ffactor=None, nelem=None, cachesize=None, lorder=None, hflags=0) > 190 if ffactor is not None: d.set_h_ffactor(ffactor) > 191 if nelem is not None: d.set_h_nelem(nelem) > 192 d.open(file, db.DB_HASH, flags, mode) > 193 return _DBWithCursor(d) > 194 > d = , d.open = , file = > '/var/www/bp/predictor/tools.dbm', global db = '/usr/lib/python2.3/lib-dynload/_bsddb.so'>, db.DB_HASH = 2, flags = 65, mode = > 438 > DBAccessError: (13, 'Permission denied') > args = (13, 'Permission denied') > The permissions on the CGI script (/usr/lib/cgi-bin/evaluator.py) are: > -rwxr-xr-x 1 bpeters bpeters 2446 Jan 11 14:42 evaluator.py > and the permissions on the target DBM creation directory > (/var/www/bp/predictor/) are: > drwxr-xr-x 2 bpeters bpeters 4096 Jan 11 14:45 predictor > Can anyone tell me what I need to do to allow the CGI script to create the DBM > in the target directory? That is short of changing everything to root. Chances are that for security reasons your script probably runs as user "nobody" or another special user ID set up specifically for running CGI scripts (rather than your user id). Check your web server's documentation, or render the output of sys.getuid, sys.geteuid, sys.getgid, and sys.getedig. One solution is to open up the permissions of /var/www/bp/predictor; a better solution is to change its owner to whatever user ID runs your script. HTH, Dan -- Dan Sommers Never play leapfrog with a unicorn. From jmeile at hotmail.com Wed Jan 26 04:29:34 2005 From: jmeile at hotmail.com (Josef Meile) Date: Wed, 26 Jan 2005 10:29:34 +0100 Subject: how to ncurses on win32 platform In-Reply-To: <3nkds3kzc9mp.18yfed1y3vo9d$.dlg@40tude.net> References: <3nkds3kzc9mp.18yfed1y3vo9d$.dlg@40tude.net> Message-ID: <41F762FE.2090302@hotmail.com> Hi Brane, I was wondering about the same thing some days ago. I found the following alternatives: * Curses for Windows for Python (It was previously mentioned on a follow-up. there are some missing features): http://flangy.com/dev/python/curses/ * PDCurses (It looks promissing): http://pdcurses.sourceforge.net/ * The Console Module: http://www.effbot.org/zone/console-handbook.htm * Windows CONsole I/O for Python: http://newcenturycomputers.net/projects/wconio.html Please note that I haven't tested any of the mentioned packages, so, I don't know if they are really a good replacement for ncurses, so, it's up-to-you to test them. Regards, Josef From http Sun Jan 2 02:17:24 2005 From: http (Paul Rubin) Date: 01 Jan 2005 23:17:24 -0800 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> <7xsm5kfyse.fsf@ruckus.brouhaha.com> <41d7941f$1_3@127.0.0.1> Message-ID: <7x8y7cjo57.fsf@ruckus.brouhaha.com> "Donn Cave" writes: > Yes, it would be really weird if Python went that way, and the > sort of idle speculations we were reading recently from Guido > sure sounded like he knows better. But it's not like there aren't > some interesting issues farther on downstream there, in the compare > function. cmp(), and str() and so forth, play a really big role in > Python's dynamically typed polymorphism. It seems to me they are > kind of at odds with static type analysis I don't understand that. If I see "str x = str(3)", then I know that x is a string. From jgrahn-nntq at algonet.se Fri Jan 7 05:24:49 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 7 Jan 2005 10:24:49 GMT Subject: Locale confusion Message-ID: [Long posting due to the examples, but pretty simple question.] I'm sitting here with a Debian Linux 'Woody' system with the default Python 2.2 installation, and I want the re module to understand that re.compile(r'\W+'. re.LOCALE) doesn't match my national, accented characters. I don't quite understand how the locale module reasons about these things, and Python doesn't seem to act as other programs on my system. Bug or my mistake? Here's my environment: frailea> env |grep -e LC -e LANG LC_MESSAGES=C LC_TIME=C LANG=sv_SE LC_NUMERIC=C LC_MONETARY=C frailea> locale LANG=sv_SE LC_CTYPE="sv_SE" LC_NUMERIC=C LC_TIME=C LC_COLLATE="sv_SE" LC_MONETARY=C LC_MESSAGES=C LC_PAPER="sv_SE" LC_NAME="sv_SE" LC_ADDRESS="sv_SE" LC_TELEPHONE="sv_SE" LC_MEASUREMENT="sv_SE" LC_IDENTIFICATION="sv_SE" LC_ALL= This seems to indicate that $LANG acts as a fallback when other things (e.g. LC_CTYPE isn't defined) and that's also what the glibc setlocale(3) man page says. Works well for me in general, too. However, consider this tiny Python program: frailea> cat foo import locale print locale.getlocale() locale.setlocale(locale.LC_CTYPE) print locale.getlocale() When I paste it into an interactive Python session, the locale is already set up correctly (which is what I suppose interactive mode /should/ do): >>> import locale >>> print locale.getlocale() ['sv_SE', 'ISO8859-1'] >>> locale.setlocale(locale.LC_CTYPE) 'sv_SE' >>> print locale.getlocale() ['sv_SE', 'ISO8859-1'] >>> When I run it as a script it isn't though, and the setlocale() call does not appear to fall back to looking at $LANG as it's supposed to(?), so my LC_CTYPE remains in the POSIX locale: frailea> python foo (None, None) (None, None) The corresponding program written in C works as expected: frailea> cat foot.c #include #include int main(void) { printf("%s\n", setlocale(LC_CTYPE, 0)); printf("%s\n", setlocale(LC_CTYPE, "")); printf("%s\n", setlocale(LC_CTYPE, 0)); return 0; } frailea> ./foot C sv_SE sv_SE So, is this my fault or Python's? I realize I could just adapt and set $LC_CTYPE explicitly in my environment, but I don't want to capitulate for a Python bug, if that's what this is. BR, Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From evan at tokenexchange.com Tue Jan 18 17:59:06 2005 From: evan at tokenexchange.com (Evan Simpson) Date: Tue, 18 Jan 2005 16:59:06 -0600 Subject: macros In-Reply-To: References: Message-ID: <41ED94BA.5060506@tokenexchange.com> Jeremy Bowers wrote: > You know, Guido might as well give in now on the Macro issue. If he > doesn't come up with something himself, apparently we'll just hack > bytecode. Ah, hacking bytecode isn't where it's at anymore. These days, you use the compiler package and munge the AST. Hygenic! That said, the big brake on macros implemented either of these ways is the fact that the source still has to be syntactically valid python. You can make a macro FOOBAR that works in these ways: x = FOOBAR(some, arguments) # Pseudo-function if FOOBAR: a.suite # Pseudo-'if' statement { FOOBAR: expr } # Pseudo-throwaway dict ...but not these: FOOBAR: a.suite # Suite that explicity depends on FOOBAR for meaning x = a FOOBAR b # expression with pseudo-keyword What we need is a generic suite statement, something like: gensuite ::= [decorators] "do:" suite ...where the suite is treated like the body of an anonymous function that is called and discarded immediately after it is defined. In other words, the code @f2 do: pass ...is roughly equivalent to: @f2 def (): pass () del Then we could abuse the heck out of it by perverting the AST of @FOOBAR do: stuff That's never going to happen, tho. Cheers, Evan @ 4-am From jtauber at jtauber.com Sat Jan 8 15:04:29 2005 From: jtauber at jtauber.com (jtauber) Date: 8 Jan 2005 12:04:29 -0800 Subject: losing CGI variables in os.environ in Python 2.4 Message-ID: <1105214669.441236.181820@c13g2000cwb.googlegroups.com> Did something change between 2.3 and 2.4 that would affect os.environ being populated with CGI variables when using the BaseHTTPServer/CGIHTTPServer? I received a bug report from someone trying to run my wiki/blog software, Leonardo[1] under Python 2.4 on Windows 2000. I was able to reproduce the problem under Python 2.4 on Windows XP Pro but confirmed that it worked fine under Python 2.3. Simply printing out os.environ at the point things like PATH_INFO are extracted by Leonardo revealed that os.environ contained no CGI-related variables when run under Python 2.4 but did contain them under 2.3 I can't see in the code for the http server modules that anything changed in this area. Am I missing something? Thanks in advance. James Tauber http://jtauber.com/blog/ [1] http://jtauber.com/leonardo From tonino.greco at gmail.com Tue Jan 18 04:13:12 2005 From: tonino.greco at gmail.com (Tonino) Date: 18 Jan 2005 01:13:12 -0800 Subject: Socket and Tkinter Problem In-Reply-To: References: Message-ID: <1106039592.561686.190810@c13g2000cwb.googlegroups.com> hi, was wondering if you ever got a reply ? Did you mannage to sort this out ? I am wanting todo the same thing - just have a window that connects to a port and displays the data it receives from that port in the window? Thanks Tonino From frans.englich at telia.com Mon Jan 17 13:52:00 2005 From: frans.englich at telia.com (Frans Englich) Date: Mon, 17 Jan 2005 18:52:00 +0000 Subject: Assigning to self In-Reply-To: <200501171845.46766.frans.englich@telia.com> References: <200501171845.46766.frans.englich@telia.com> Message-ID: <200501171852.00073.frans.englich@telia.com> On Monday 17 January 2005 18:45, Frans Englich wrote: > The line 'self = me'(scary..) doesn't really > work for the attribute attr; the attribute exists on line 21, but it fails > when yo() tries to access it. Typo; line 21 is yo(). I ment line 18, the print statement in __init__. Cheers, Frans From abigail at abigail.nl Fri Jan 28 03:12:30 2005 From: abigail at abigail.nl (Abigail) Date: 28 Jan 2005 08:12:30 GMT Subject: [perl-python] 20050127 traverse a dir References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> <1106875259.426213.252030@z14g2000cwz.googlegroups.com> Message-ID: Timo Virkkala (a at a.invalid) wrote on MMMMCLXVIII September MCMXCIII in : @@ The Flow wrote: @@ > Do you want to be taken seriously? @@ > First, stop posting. @@ > Second, learn perl. @@ > Third, learn python. @@ @@ No. Second, learn Python. Third, learn Perl (optional). :) Just leave the third option out. Let him learn Python. We don't want him. ;-) Abigail -- sub f{sprintf'%c%s',$_[0],$_[1]}print f(74,f(117,f(115,f(116,f(32,f(97, f(110,f(111,f(116,f(104,f(0x65,f(114,f(32,f(80,f(101,f(114,f(0x6c,f(32, f(0x48,f(97,f(99,f(107,f(101,f(114,f(10,q ff))))))))))))))))))))))))) From gh at ghaering.de Thu Jan 13 08:27:48 2005 From: gh at ghaering.de (Gerhard Haering) Date: Thu, 13 Jan 2005 14:27:48 +0100 Subject: Debian says "Warning! you are running an untested version of Python." on 2.3 In-Reply-To: References: Message-ID: <20050113132748.GA17117@mylene.ghaering.de> On Thu, Jan 13, 2005 at 12:56:38PM -0000, Alex Stapleton wrote: > Whenever I run python I get > > "Warning! you are running an untested version of Python." > > prepended to the start of any output on stdout. [...] ROFL. Are you using testing, sid or experimental? I expect overzealous patching from Debian developers, but this is the worst I've heard of. To look what's going on and how to fix it, you could try to download the sources with "apt-get source ...", which will give you the standard Python tarball + the Debian patches. Then you can look into the Debian patches wtf they're doing there. -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From peter at engcorp.com Thu Jan 6 16:33:23 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Jan 2005 16:33:23 -0500 Subject: Really OT (was Re: OT: spacing of code in Google Groups) In-Reply-To: <1gpzgcv.1a4vagsqm9b69N%aleaxit@yahoo.com> References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> <1gpzgcv.1a4vagsqm9b69N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Peter Hansen wrote: >>This "cat equivalent" thing is a red-herring. I can rarely type more > > I tried offering a red herring to my cat to check this out, and, sure > enough, she indignantly refused it and miaowed loudly for less smelly > food. So, you may have a point here. Going totally off-topic (except for those who define anything that ridicules Bill Gates as inherently on-topic), just as I read your reply I saw the following two "related" articles as I was reading some news online: On red herrings (and silly Bill screwing up another demo): http://www.redherring.com/Article.aspx?a=11118&hed=Glitz%2C+glitches+and+Gates+at+CES§or=Profiles&subsector=Companies On cats (bouncing dead ones, anyway): http://yahoo.reuters.com/financeQuoteCompanyNewsArticle.jhtml?duid=mtfh79805_2005-01-06_17-20-03_n06358600_newsml (My reticular formation must be working fine today...) -Peter From pierre.barbier at cirad.fr Fri Jan 21 07:52:18 2005 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Fri, 21 Jan 2005 13:52:18 +0100 Subject: map in Python In-Reply-To: <1106310327.213874.305660@f14g2000cwb.googlegroups.com> References: <1106310327.213874.305660@f14g2000cwb.googlegroups.com> Message-ID: <41f0fa9d$0$25624$626a14ce@news.free.fr> You have three ways to do what you want : First wayt is to use lambda. Then, you want to write : >>> map(lambda x: re.sub("[a-z]", "", x), test) Second is to use regular named function : >>> def remove_letters( s ): ... re.sub("[a-z]", "", s) >>> map(remove_letters, test) A third way would be to use the "pseudo-currying" described there : http://www.python.org/moin/PythonDecoratorLibrary In fact, you need a small generalisation : >>> class curried(object): ... def __init__(self, func, *a, **kw): ... self.func = func ... self.args = a ... self.kwords = kw ... def __call__(self, *a, **kw): ... args = self.args + a ... kwords = dict(self.kwords) ... kwords.update(kw) ... if len(args)+len(kwords) < self.func.func_code.co_argcount: ... return curried(self.func, *args, **kwords) ... else: ... return self.func(*args, **kwords) The difference is you can handle the kwords with that version ! Then you want to write this : >>> curried_sub = curried(re.sub) >>> map(curried_sub("[a-z]", "", count=0), test) My opinion is : the simplest and best solution more "pythonic" is the second one ! The third one is interesting but work only for functions written in Python ! (Hopefully the re.sub function is written in Python). The biggest problem with the first one is that lambda are planned to disappear in future Python versions ... Pierre Stu a ?crit : > I have recently switched over to Python from Perl. I want to do > something like this in Python: > > @test = ("a1", "a2", "a3"); > map {s/[a-z]//g} @test; > print @test; > > However, I take it there is no equivalent to $_ in Python. But in that > case how does map pass the elements of a sequence to a function? I > tried the following, but it doesn't work because the interpreter > complains about a missing third argument to re.sub. > > import re > test = ["a1", "a2", "a3"] > map(re.sub("[a-z]", ""), test) > print test > Thanks in advance. > > Regards, > Stuart > From EP at zomething.com Wed Jan 5 03:23:02 2005 From: EP at zomething.com (EP) Date: Wed, 5 Jan 2005 00:23:02 -0800 Subject: Python evolution: Unease In-Reply-To: References: Message-ID: <20050105002302.542768387.EP@zomething.com> Roman wrote: > Maybe OP doesn't yet fully comprehend the ways of Python universe? > > Don't misinterpret this response. I know it was a rambling. But > *maybe* you > > have something to contribute to Python development, even good ideas > only and > > no work. > > > > . Facundo Am I selling Snake Oil? Here's my observation, which must be taken with the grain of salt that I am simply not a smart nor seasoned enough programmer to understand some of the considerations for the new language features. It's over my head - there, I said it. What I do have is a "forest" instead of an "in the trees" perspective, and from a forest view I see a lot of defensiveness about Python's hypothetical shortcomings. No one needs be defensive, Python is an amazing programming language, and everyone involved with its development, evolution, support and codebase ought to feel quite good about it. So there should be a lot of clapping each other on the shoulder and the clinking of beer bottles in toasts. The next morning we get up, we ought to look at our bed mate and think over some coffee whether this is someone who will be our lifelong friend, or if we want it to be much more than that. Because taking it to the next level, to it's ultimate potential, is not a linear exercise and requires non-linear thinking, strategy, and execution (and no doubt greater commitment.) It would not be ground breaking for me to assert that undertakings reach plateaus as they grow in magnitude and scope. A company, for example, must re-invent itself several times on the way to greatness from the couple folks gathered around the kitchen table, and this is not just at low levels. Companies reach plateaus, for example, around points like $1 billion in annual revenue -- to keep growing and get to, let's say, $5 billion, they have to re-invent themselves with a new and greater vision. It would be easy to miss this with our heads buried in code, or with our minds occupied with either the defense of Python or a debate about what a "concept" is. [tongue in cheek] I use Python everyday; I've liked it from the first five minutes, and I like it more all the time. I hope it is always maintained because it would be a shame to ever lose such a powerful and joyful tool. I also think Python affords a view of what might be great things in the distance, but perhaps the journey required to get there is more like crossing an ocean than simply walking down the road. Not knowing how to cross the ocean doesn't mean there isn't milk and honey on the other side, nor that the journey should be written off; but there is no guarantee that Python is the right vehicle to get us there, and if it is it may need to grow organic gills. I'm of two minds, that (1) Python is perfect as is and (2) that "it" needs radical (non-linear) improvements in development environment, documentation, and execution speed to reach its potential in terms of application and acceptance. Where and how far the community wants to take Python would be something to figure out before debating what needs to be changed about it, if there is a desire to take it to a potential on a new level. Python: it tastes so good it makes you hungrier. Eric Pederson - - - - - - - - - - - - - - Perfect indifference and assuming one perceives the "real world" are the essential lies against the natural universe - a "leftist" - - - - - - - - - - - - - - From j.p.t.j.berends at [N0SP4M].nl Thu Jan 6 09:31:22 2005 From: j.p.t.j.berends at [N0SP4M].nl (J Berends) Date: Thu, 06 Jan 2005 15:31:22 +0100 Subject: sorting on keys in a list of dicts Message-ID: Suppose I have a list of dictionaries and each dict has a common keyname with a (sortable) value in it. How can I shuffle their position in the list in such way that they become sorted. Maybe I am doing it wrongly and you would say: why don't you get yourself a (slimmed-down) implementation of a database class. But then please guide me on the right path without having to install a xxSQL server for my multiplatform code. From missiplicity at yahoo.com Tue Jan 25 15:28:20 2005 From: missiplicity at yahoo.com (missiplicity at yahoo.com) Date: 25 Jan 2005 12:28:20 -0800 Subject: Question Regarding SocketServer Message-ID: <1106684900.771730.218060@f14g2000cwb.googlegroups.com> Hi, I am newbie to Python language and am taking my baby steps. I am using Python2.4 from ActiveState on W2K. I am trying to create a simple SocketServer program. Just adding the following 2 lines of code in the program result in the errors given below: import SocketServer print "SocketServer imported" Running the above cause the following errors Traceback (most recent call last): File "TestServer3.py", line 2, in ? import SocketServer File "C:\Python24\lib\SocketServer.py", line 8, in ? - AF_INET{,6}: IP (Internet Protocol) sockets (default) AttributeError: 'module' object has no attribute 'StreamRequestHandler' I actually had more code to get the server running (actually it runs on Linux), but it was throwing up errors on Windows, so I stripped it down to the bare minimum to see where I am having an issue. I dont understand why this is happening. Can someone point to me what I am doing wrong or what is wrong with my configuration. Thanks, Kris From steve at holdenweb.com Fri Jan 21 17:20:54 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Jan 2005 17:20:54 -0500 Subject: Tuple size and memory allocation for embedded Python In-Reply-To: References: Message-ID: Jinming Xu wrote: > Hi Folks, > > Python seems unstable, when allocating big memory. For example, the > following C++ code creates a tuple of tuples: > > PyObject* arCoord = PyTuple_New(n); > double d = 1.5; > for(int i=0; i { > PyObject* coord = PyTuple_New(2); > PyTuple_SetItem(coord,0, PyFloat_FromDouble(d));//x > PyTuple_SetItem(coord,1, PyFloat_FromDouble(d));//y > PyTuple_SetItem(arCoord,i, coord); > } > > When the n is small, say 100, the code works fine. when n is big, say > 10,000, Python has trouble allocating memory, saying: > > "Exception exceptions.IndexError: 'tuple index out of range' in 'garbage > collection' ignored > Fatal Python error: unexpected exception during garbage collection > Aborted" > > Could anyone please give me some insight or a fix for this? > > Thanks in advance for your answer. > I'm going to guess that the problem is related to incorrect reference counts. I don't see any IncRefs in there. It seems probable that the program will work until you make n high enough to trigger a garbage collection sweep, then memory your program still regards as allocated is garbage collected by Python and reused. Ugly :-P Python is pretty stable, so it's usually best to suspect our own code unless you're heavily into using the C API (which I'm not, so feel free to ignore me). regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From sharidas at zeomega.com Tue Jan 25 08:53:47 2005 From: sharidas at zeomega.com (Satchidanand Haridas) Date: Tue, 25 Jan 2005 19:23:47 +0530 Subject: DevX: "Processing EDI Documents into XML with Python" In-Reply-To: <41F13CA5.3050901@bellsouth.net> References: <35c0hcF4jnr7pU1@individual.net> <41F13CA5.3050901@bellsouth.net> Message-ID: <41F64F6B.2030106@zeomega.com> There has already been some work in this area - although for X12 transactions for the healthcare industry. Its on sourceforge already and best of all the development language is Python: http://sourceforge.net/projects/pyx12/ thanks, Satchit ---- Satchidanand Haridas (sharidas at zeomega dot com) ZeOmega (www.zeomega.com) Open Minds' Open Solutions #20,Rajalakshmi Plaza, South End Road, Basavanagudi, Bangalore-560 004, India Jeremy Jones wrote: > Claudio Grondi wrote: > >> "You don't have to rely on expensive and proprietary EDI conversion >> software >> to parse, validate, and translate EDI X12 data to and from XML; you can >> build your own translator with any modern programming language, such as >> Python." >> >> by Jeremy Jones >> http://www.devx.com/enterprise/Article/26854 >> >> Excerpt: >> "Python is an object-oriented, byte-compiled language with a clean >> syntax, clear and consistent philosophy, and a strong user community. >> These >> attributes (both of the language and the community) make it possible to >> quickly write working, maintainable code, which in turn makes Python an >> excellent choice for nearly any programming task. Processing any >> "flavor" of >> EDI is no exception." >> >> >> Hi, >> just wanted to share with you, that the last issue >> of the DevX newsletter comes with a Python related >> article as first item in the list of subjects. >> >> Claudio >> >> >> >> > Anyone interested in processing EDI with Python will probably be > interested in giving it a read. Please feel free to scrutinize the > code mercilessly. I plan on creating a project on Sourceforge with > the code that is attached to that article (and hopefully with > modifications coming from user input in the ensuing months). Comments > are greatly appreciated. > > Thanks for posting this, Claudio. > > Jeremy Jones From tassilo.von.parseval at rwth-aachen.de Tue Jan 18 12:14:18 2005 From: tassilo.von.parseval at rwth-aachen.de (Tassilo v. Parseval) Date: Tue, 18 Jan 2005 18:14:18 +0100 Subject: [perl-python] 20050118 keyed list References: <1106027360.920787.321590@z14g2000cwz.googlegroups.com> Message-ID: Also sprach J?rgen Exner: > Xah Lee wrote: >> ? %a = ('john',3, 'mary', 4, 'jane', 5, 'vicky',7); >> ? use Data::Dumper qw(Dumper); >> ? print Dumper \%a; > > Wow, my compliments. The very first time that using Data::Dumper actually > may do something useful (formats the data more nicely). Still, why you are > passing a reference is beyond me. How else would you use 'Dumper' on a hash? Tassilo -- $_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({ pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus})!JAPH!qq(rehtona{tsuJbus#; $_=reverse,s+(?<=sub).+q#q!'"qq.\t$&."'!#+sexisexiixesixeseg;y~\n~~dddd;eval From kartic.krishnamurthy at gmail.com Wed Jan 26 11:16:49 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 26 Jan 2005 08:16:49 -0800 Subject: import hook, overwrite import? In-Reply-To: References: Message-ID: <1106756209.188804.270160@c13g2000cwb.googlegroups.com> Hi Torsten, If you want to use other methods to import (other than good ole file system), yes, you can create an importer class and register it as an importer module, that import will use to search and import. For example, it is possible to use zip imports (this functionality is already builtin) to import from a zip archive. py>>> import zlib # required py>>> import sys py>>> sys.path.append('/location/to/zippedmodules.zip') py>>> import testzip py>>> testzip.__file__ '/location/to/zippedmodules.zip/testzip,py' To generally do it, you have to: 1. Create a class that provides a load_module method that returns a module type. 2. Install your class as a hook using sys.path_hooks.append(your_importer_class) Please take a look at the imp module : http://docs.python.org/lib/module-imp.html for a complete description on accessing the import internals. There is also a simple example in this section. Is this is what you are looking for? Thanks, --Kartic PS: This about how much I know...the more I find out, I will share :-) From eurleif at ecritters.biz Thu Jan 13 16:50:56 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 13 Jan 2005 16:50:56 -0500 Subject: Octal notation: severe deprecation In-Reply-To: References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105575689.335040.174490@c13g2000cwb.googlegroups.com> Message-ID: <34o8n7F4e6uduU1@individual.net> Tim Roberts wrote: > Stephen Thorne wrote: > >>I would actually like to see pychecker pick up conceptual errors like this: >> >>import datetime >>datetime.datetime(2005, 04,04) > > > Why is that a conceptual error? Syntactically, this could be a valid call > to a function. Even if you have parsed and executed datetime, so that you > know datetime.datetime is a class, it's quite possible that the creation > and destruction of an object might have useful side effects. I'm guessing that Stephen is saying that PyChecker should have special knowledge of the datetime module and of the fact that dates are often specified with a leading zero, and therefor complain that they shouldn't be used that way in Python source code. From rmemmons at member.fsf.org Sun Jan 16 14:33:05 2005 From: rmemmons at member.fsf.org (Rob Emmons) Date: Sun, 16 Jan 2005 13:33:05 -0600 Subject: Newbie: module structure and import question References: <8fb821f9.0501120706.499dd04c@posting.google.com> <41e80972$1_1@rain.i-cable.com> Message-ID: > yes i know it's related to search path, but i don't know how to set it in a > practical way (beside hard coding). > my concern is, if i want to create a custom module/library, i don't know > what py file will import it and where the working directory should be. Regarding where the current working directory is -- on Linux your right, you probably don't know where it is going to be. On Windows -- you can pretty much demand that users set up the launcher so that your python program is opened in a specific location -- typically the root directory of the installed package. So in the windows situation -- if all your components are in that package directory you can access everything via relative roots. Linux is not so easy -- I'll get to that. On the other hand, if your installing a general directory library module that your going to use from a variety of other programs, then you need to have the installer setup things so other applications can find it. The standard way to do this is to use the distutils package that is part of the python distribution to install these modules in a standard location which should already be in the search path. If you don't want to do that you have to do something special: on windows create a registry entry that can be accessed and looked up probably, or setup the default python path for your system (or user) to include the extra directories, or like GNOME does on Linux -- create a script in the executable search path that your program or installer can run -- and have it return the path you need. So on the application side, you'd find out the location of the library as described above and set sys.path. You can either do this at launch time in your main program -- or you can have the installer hard code it at the top of the main program. This is not really any different then for example using shared libraries. You either need to install all of your modules in the search path to start with or you need to modify the search path by some method. There is one more thought -- if you want to find out where the python module is in the file system -- there are sometimes ways to do this -- I've never done this but I have some notes somewhere about this. This might also be helpful in finding directories for example. If your interested in this -- maybe someone else here can remember? > But if i put a set of classes in a py file as a module, will it increase > the dependency of each class? > back to my example, of course, i can put BaseA and ClassA together in one py > file. what should i do when i need to add one more class later, "ClassB", > which also extend BaseA. Put it into the same file or in a new file? if put > in in the same file, i think it should difficult to maintain versioning. Versioning -- hmm. Well I think it depends. If ClassB is intended to be a general capability that you want to add to to moduleA (the module with BaseA and ClassA), then add it to moduleA but make the module upwardly compatible. If you want to track versions, then just keep old version snapshots if you need to or use something like CVS to do it for you. I'm pretty basic so I keep old copies but try to make my general libraries upwardly compatible if possible. Of course on the other hand, if the new class classB has a special function then I'd either create a new module, or I'd just include it into my main program module, or some other application module. To merge the functions just import what you need into that module. I for example often use "from mymodule import *" which imports everything rather than the limited imports you used -- nothing wrong with either, just a matter of taste. I also often use "import" and write the full module name when I reference things too. The point is -- I personally think one should look at modules as being collections of functions, classes, and other constructs that form librararies rather than putting each class and function in a separate module. Thanks, Rob From http Sun Jan 9 05:05:30 2005 From: http (Paul Rubin) Date: 09 Jan 2005 02:05:30 -0800 Subject: The best way to do web apps with Python? References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41E02FD5.5080703@holdenweb.com> Message-ID: <7xd5wezzmd.fsf@ruckus.brouhaha.com> Steve Holden writes: > You can read about it in Philip Eby's excellent PEP at > > http://www.python.org/peps/pep-0333.html I looked at this and I have the impression that it tries to do something worthwhile, but I can't tell precisely what. The "rationale and goals" section explains good reasons why it doesn't do various certain things. What's not explained is what DOES it do. The only thing I can tell is that it connects to an abstracted web server, and builds up what looks like traditional CGI variables from the incoming requests. From bokr at oz.net Thu Jan 20 19:20:06 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 21 Jan 2005 00:20:06 GMT Subject: Freezing a mutable (was Re: lambda) References: <41EBA021.5060903@holdenweb.com> <41ed8c13.1209309354@news.oz.net> Message-ID: <41f04937.1388801641@news.oz.net> On 20 Jan 2005 14:07:57 GMT, Antoon Pardon wrote: >Op 2005-01-20, Nick Coghlan schreef : >> Antoon Pardon wrote: >>> I missed that you would use it with the idiom: dct[x.frozen()] >> >> The list itself isn't hashable with this approach, so you don't have much >> choice. I wasn't particularly clear about that point, though. >> >>> I have two problems with this approach. >>> >>> 1) It doesn't work when you get your keys via the keys/items >>> methods. >> >> True - the frozen object has no link back to the original object. That could be >> added though (by returning a tuple subtype with the extra attribute) >> >>> 2) This is rather minor, but a user could still unfreeze >>> untimely >> >> True - doing that is less likely than mutating a hashable list though :) >> >> I'm just noting this as a way to avoid copying data more than once when storing >> immutable copies of mutable data in a dictionary. You're quite right that there >> isn't a really clean idiom for doing that in Python (aside from moving to a >> different data structure that works natively as a dict key, naturally). > >The problem here is IMO is the, we are all consenting adults (which we >are not but I wont start on this now), approach. > >I have been thinking a bit in your freeze direction, but more thorough. >The idea i had was that freeze would replace all mutating methods >with methods that would throw an exception. a thaw method would inverse >the proces. It would then be the responsibilty of the dictionary to >freeze an object on entry and thaw it when removed. However this >wouldn't work with ordinary python objects, since there is no easy way >to have readonly or private variables. > Would you like a dictionary that acts as you want and takes care of all problems internally, and accepts keys and values of any type without wrapping or other modification -- or do you want a wrapper that can make any object suitable for use as key or value in python's curent definition of dict? Just DYFR please. You still haven't you know ;-) Regards, Bengt Richter From elephantum at dezcom.mephi.ru Mon Jan 10 12:09:05 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Mon, 10 Jan 2005 20:09:05 +0300 Subject: python3: 'where' keyword In-Reply-To: References: <3480qqF46jprlU1@individual.net> <34cri1F47gda5U1@individual.net> Message-ID: <34fr5iF4aiud8U1@individual.net> Nick Coghlan wrote: >> And about examples for usage "where" keyword >> >> reading http://manatee.mojam.com/~skip/python/fastpython.html I >> understand that almost every example should use that keyword =) > I suspect polluting the outer namespace would still be faster, since > Python wouldn't have to create the extra level of scoping all the time. sure, but just a little bit slower =) From cdavisNOSP at NOSPstaffmail.ed.ac.uk Fri Jan 14 04:40:24 2005 From: cdavisNOSP at NOSPstaffmail.ed.ac.uk (Cory Davis) Date: Fri, 14 Jan 2005 09:40:24 +0000 Subject: distutils linux script installation broken? Sorted In-Reply-To: References: Message-ID: Problem solved. I was actually using scipy_distutils and not distutils, without good reason. Changing setup.py to use distutils made the problem go away. Cory. Cory Davis wrote: > Hi all, > I have been successfully deploying my own python package with distutils > for some time now, but lately, with Python 2.4, the build_scripts > command has been behaving badly. In the part where it is supposed to > adjust the first line of the script it now produces > > #!None > > instead of > > #!/whereverpythonis/python > > Has anyone else encountered this? > > Cheers, > Cory. > From fperez.net at gmail.com Fri Jan 28 04:29:59 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Fri, 28 Jan 2005 02:29:59 -0700 Subject: bdist_wininst post-install bug? Message-ID: Hi all, I just noticed a problem (which forced me to a last-minute update of the windows ipython installer). As far as I can tell, this should be considered a bug. >From the Python docs, sys.executable is: executable A string giving the name of the executable binary for the Python interpreter, on systems where this makes sense. However, during the execution of a post-install script, this string actually resolves to the name of the binary installer! This name should resolve, I think to the name of the Python executable for which the installer is running (a value selectable at the start of the installation, if more than one Python is detected). Having this value available allows you to properly generate shortcuts with the proper full path to the python executable. I resorted to using sys.prefix+r'\python.exe', which will most likely work, but I'd rather see sys.executable give me a more sensible answer. Should this be filed as a distutils bug? I'd rather not clog the database if it was the result of a deliberate decision, as strange as it may seem to me. Cheers, f From tundra at tundraware.com Wed Jan 26 05:48:19 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 26 Jan 2005 05:48:19 EST Subject: re Insanity In-Reply-To: References: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> Message-ID: Aahz wrote: > In article <4ln9c2-0mh1.ln1 at eskimo.tundraware.com>, > Tim Daneliuk wrote: > >>Given an arbitrary string, I want to find each individual instance of >>text in the form: "[PROMPT:optional text]" >> >>I tried this: >> >> y=re.compile(r'\[PROMPT:.*\]') >> >>Which works fine when the text is exactly "[PROMPT:whatever]" but >>does not match on: >> >> "something [PROMPT:foo] something [PROMPT:bar] something ..." >> >>The overall goal is to identify the beginning and end of each [PROMPT...] >>string in the line. >> >>Ideas anyone? > > > Yeah, read the Friedl book. (Okay, so that's not gonna help right now, > but trust me, if you're going to write lots of regexes, READ THAT BOOK.) I've read significant parts of it. The problem is that I don't write re often enough to recall all the subtle details ... plus I am getting old and feeble... ;) -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From bulba at bulba.com Mon Jan 10 11:52:42 2005 From: bulba at bulba.com (Bulba!) Date: Mon, 10 Jan 2005 17:52:42 +0100 Subject: Speed revisited References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> <1105237556.402188.126980@c13g2000cwb.googlegroups.com> <1105303172.147395.63580@c13g2000cwb.googlegroups.com> <36c3u0tpbg6f98ta6cm4fkj2kn0dkv624m@4ax.com> Message-ID: On Sun, 09 Jan 2005 22:51:47 GMT, Andrea Griffini wrote: >>Tip 1: Once you have data in memory, don't move it, move a pointer or >>index over the parts you are inspecting. >> >>Tip 2: Develop an abhorrence of deleting data. > >I've to admit that I also found strange that deleting the >first element from a list is not O(1) in python. My wild >guess was that the extra addition and normalization required >to have insertion in amortized O(1) and deletion in O(1) at >both ends of a random access sequence was going to have >basically a negligible cost for normal access (given the >overhead that is already present in python). Smth similar happened here - I _assumed_ that since lists in Python can hold arbitrary objects, the low level C implementation was smth like "array" of pointers to those objects (or offsets of those objects stored elsewhere). If so, deleting an element from a list would merely be deleting a pointer (or zeroing particular offset to get this object "released"), which would have negligible cost. I've read that Python's memory management technique is 'reference counting' - it would seem only logical that the list is an array (or linked list or linked list of arrays maybe, as it can grow in size arbitrarily) of such references. >But I'm sure this idea is too obvious for not having been >proposed, and so there must reasons for refusing it >(may be the cost to pay for random access once measured was >found being far from negligible, or that the extra memory >overhead per list - one int for remembering where the live >data starts - was also going to be a problem). But either the book-keeping of offsets or pointers or references to list elements has to be done by Python interpreter, oops, VIRTUAL MACHINE, somehow anyway. I don't see why should deleting element from a list be O(n), while saying L[0]='spam' when L[0] previously were, say, 's', not have the O(n) cost, if a list in Python is just an array containing the objects itself? Why should JUST deletion have an O(n) cost? -- I have come to kick ass, chew bubble gum and do the following: from __future__ import py3k And it doesn't work. From claird at lairds.us Sat Jan 15 10:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Sat, 15 Jan 2005 15:08:04 GMT Subject: Integration with java (Jpype vs. JPE) References: <34s5krF4c85d5U1@individual.net> Message-ID: In article <34s5krF4c85d5U1 at individual.net>, Jon Perez wrote: >Can someone summarize in a nutshell what is the >difference between JPype and JPE? JPE's the original. It provided more functionality than JPype has achieved so far, I believe (though that could change any day). I think no one now maintains JPE. Someone really ought to include a couple of sentences to that effect on the front page of . From petite.abeille at gmail.com Fri Jan 28 21:00:12 2005 From: petite.abeille at gmail.com (PA) Date: Sat, 29 Jan 2005 03:00:12 +0100 Subject: what's OOP's jargons and complexities? In-Reply-To: References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com><3602hiF4tvskbU1@individual.net> Message-ID: <03aaae973b277edcdbd97e1d34530125@gmail.com> Hi Dan, On Jan 29, 2005, at 02:31, Dan Perl wrote: > At first I thought you were being sarcastic. For once, no. Something which is pretty much out of character I have to confess 8^) > I doubt that now. Iindulge my > curiosity please and tell us what you enjoy about it. Well... perhaps it's a question of timing... I'm trying to keep up with some New Year resolutions: http://www.pragmaticprogrammer.com/loty/ And therefore learning a little language named Lua: http://www.lua.org/about.html The catch is that I have been doing OOP for well over a decade now, so me first Lua perversion is to build an OO system of sort: http://article.gmane.org/gmane.comp.lang.lua.general/13515 Ironically enough, Xah Lee's post spelled out quite incisively all the things I was attempting to do in Lua, but from the opposite point of view. Therefore my sincere enjoyment of his post :) Even though Mr Lee seems to have quite a reputation in some circles, I have to admit I enjoyed reading some of his, er, more convoluted essays as well. Plus, a man which such cinematographic tastes [1] cannot be entirely bad :P http://xahlee.org/PageTwo_dir/Personal_dir/favorite_movies.html Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From francis.girard at free.fr Thu Jan 20 14:31:24 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 20 Jan 2005 20:31:24 +0100 Subject: Overloading ctor doesn't work? In-Reply-To: <41effd30$1_1@newspeer2.tds.net> References: <35ab8oF4idc25U1@individual.net> <41effd30$1_1@newspeer2.tds.net> Message-ID: <200501202031.24832.francis.girard@free.fr> Wow ! Now, this is serious. I tried all sort of things but can't solve the problem. I'm mystified too and forget my last reply. I'm curious to see the answers. Francis Girard Le jeudi 20 Janvier 2005 19:59, Kent Johnson a ?crit?: > > Martin H?cker wrote: > >> Hi there, > >> > >> I just tried to run this code and failed miserably - though I dunno > >> why. Could any of you please enlighten me why this doesn't work? > > Here is a simpler test case. I'm mystified too: > > from datetime import datetime > > class time (datetime): > def __init__(self, hours=0, minutes=0, seconds=0, microseconds=0): > datetime.__init__(self, 2001, 10, 31, hours, minutes, seconds, > microseconds) > > print time(1,2,3,4) # => 0001-02-03 04:00:00 > print time() # => TypeError: function takes at least 3 arguments (0 > given) > > > What happens to the default arguments to time.__init__? What happens to the > 2001, 10, 31 arguments to datetime.__init__? > > I would expect the output to be > 2001-10-31 01:02:03.000004 > 2001-10-31 00:00:00.000000 > > Kent From philippecmartin at sbcglobal.net Fri Jan 7 09:34:40 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Fri, 07 Jan 2005 15:34:40 +0100 Subject: Tkinter: passing parameters to menu commands (looping through a list) Message-ID: <1105108480.9221.23.camel@localhost> I face a strange behavior when adding menu labels / command parameters from a list: *** This is the code that works but I wish to avoid - ATR and IN appear in the menu, and __Dec is called with ATR or IN depending on the choice *** l_dec.add_command(label = 'ATR', command= lambda: self.__Dec('ATR')) l_dec.add_command(label = 'IN', command= lambda: self.__Dec('IN')) *** This is the code that does not works but I wish I had - ATR and IN appear in the menu, but __Dec is always called with the last list item (IN in this case) *** l_dec_list = ['ATR','IN'] for i in l_dec_list: l_dec.add_command(label = i, command= lambda: self.__Dec(i)) Any clue ? Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From tundra at tundraware.com Fri Jan 7 06:28:31 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 07 Jan 2005 06:28:31 EST Subject: Tkinter Puzzler In-Reply-To: References: Message-ID: <5582b2-6ph.ln1@eskimo.tundraware.com> Tim Daneliuk wrote: > I am trying to initialize a menu in the following manner: > > for entry in [("Up", KeyUpDir), ("Back", KeyBackDir), ("Home", > KeyHomeDir), ("Startdir", KeyStartDir), ("Root", KeyRootDir)]: > > func = entry[1] > UI.ShortBtn.menu.add_command(label=entry[0], command=lambda: > func(None)) > > However, at runtime, each of the menu options binds to the *last* function > named in the list (KeyStartDir). > > Explicitly loading each entry on its own line works fine: > > UI........command=lambda:KeyWHATEVERDir(None) > > Any ideas why the first form does not fly? > > > TIA, > ---------------------------------------------------------------------------- > > Tim Daneliuk tundra at tundraware.com > PGP Key: http://www.tundraware.com/PGP/ Thanks All - great responses! -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From golux at comcast.net Sat Jan 15 00:03:05 2005 From: golux at comcast.net (Stephen Waterbury) Date: Sat, 15 Jan 2005 00:03:05 -0500 Subject: Python.org, Website of Satan In-Reply-To: References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: <41E8A409.5070508@comcast.net> Michael Hoffman wrote: > Denis S. Otkidach wrote: >> Certainly, it can be done more efficient: > > Yes, of course. I should have thought about the logic of my code before > posting. But I didn't want to spend any more time on it than I had to. ;-) Bah, you satanic types are so lazy. From g.brandl-2005-01 at gmx.net Sun Jan 23 16:03:04 2005 From: g.brandl-2005-01 at gmx.net (Georg Brandl) Date: Sun, 23 Jan 2005 22:03:04 +0100 Subject: finding name of instances created In-Reply-To: <1106513417.897059.92250@c13g2000cwb.googlegroups.com> References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106513417.897059.92250@c13g2000cwb.googlegroups.com> Message-ID: <35iho4F4nhdncU1@individual.net> Michael Tobis wrote: > I have a similar problem. Here's what I do: > > .def new_robot_named(name,indict=globals()): > . execstr = name + " = robot('" + name + "')" > . exec(execstr,indict) > > .class robot(object): > . def __init__(self,name): > . self.name = name > > . def sayhi(self): > . print "Hi! I'm %s!" % self.name > > .if __name__=="__main__": > . new_robot_named('Bert') > . new_robot_named('Ernie') > . Ernie.sayhi() > . Bert.sayhi() Uh. Try explaining this to newbies... ;) On a second thought, the idea is quite usable considering some differences: class Robot(object): # as above class Robots(dict): def new(self, name): new_robot = Robot(name) self[name] = new_robot return new_robot def __getattr__(self, name): if name in self: return self[name] raise AttributeError robots = Robots() robots.new('Bert') robots.new('Ernie') robots.Bert.sayhi() robots["Bert"].sayhi() for robot in robots: robot.sayhi() ... etc ... This doesn't include ugly globals() and exec "tricks". Georg From peter at engcorp.com Mon Jan 24 19:50:16 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jan 2005 19:50:16 -0500 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> Message-ID: James Stroud wrote: > Martin v. L?wi said >>Hmm. Most applications don't have any crypto needs. > > Any program where one stores data would have crypto needs. James, you must have mistyped the above, or your logic is quite flawed. I have written dozens of programs which store data, and only a couple have had any crypto needs. This alone invalidates your statement as it stands. What did you really mean to say? Maybe "could" instead of "would"? That would make the statement true, yet somewhat pointless, and it doesn't contradict what Martin wrote in either case. -Peter From martin at v.loewis.de Wed Jan 19 17:07:59 2005 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 19 Jan 2005 23:07:59 +0100 Subject: xml parsing escape characters In-Reply-To: <357s61F4iossjU1@individual.net> References: <357s61F4iossjU1@individual.net> Message-ID: <41eeda3a$0$27828$9b622d9e@news.freenet.de> Luis P. Mendes wrote: > I get the following result: > > > <DataSet> > ~ <Order> Most likely, this result is correct, and your document really does contain <Order> > I don't get any elements. But, if I access the same url via a browser, > the result in the browser window is something like: > > > ~ Most likely, your browser is incorrect (or atleast confusing), and renders < as "<", even though this is not markup. > I already browsed the web, I know it's about the escape characters, but > I didn't find a simple solution for this. Not sure what "this" is. AFAICT, everything works correctly. Regards, Martin From g.tagliarettiNO at SPAMparafernalia.org Mon Jan 24 13:45:32 2005 From: g.tagliarettiNO at SPAMparafernalia.org (Gian Mario Tagliaretti) Date: Mon, 24 Jan 2005 19:45:32 +0100 Subject: [perl-python] 20050124 classes & objects References: <1106578456.705117.74220@c13g2000cwb.googlegroups.com> Message-ID: <35kmq1F4natj7U1@individual.net> Chris Mattern wrote: > > It doesn't have OO, but it emulates in software! > Better go with python, which has hardware OO. :-) Chris don't feed the troll From steven.bethard at gmail.com Tue Jan 25 17:02:05 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Jan 2005 15:02:05 -0700 Subject: python without OO In-Reply-To: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: Davor wrote: > Is it possible to write purely procedural code in Python, or the OO > constructs in both language and supporting libraries have got so > embedded that it's impossible to avoid them? Hmmm... sorta depends on how you define write procedural code... If you mean, can you write Python code without accessing object attributes (e.g. lst.sort()), then the answer's probably almost certainly no. If you mean can you write Python code without ever writing a class, the answer's probably yes. It'll make some things harder, and it'll probably make some modules off-limits, but it's doable. Could you clarify what you mean by "write purely procedural code"? Steve From roy at panix.com Sun Jan 2 13:17:50 2005 From: roy at panix.com (Roy Smith) Date: Sun, 02 Jan 2005 13:17:50 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xacrs230c.fsf@ruckus.brouhaha.com> Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > In article , > Steve Holden wrote: > >Aahz wrote: > >> In article <7xacrs230c.fsf at ruckus.brouhaha.com>, > >> Paul Rubin wrote: > >>> > >>>I was pretty skeptical of Java's checked exceptions when I first used > >>>them but have been coming around about them. There's just been too > >>>many times when I wrote something in Python that crashed because some > >>>lower-level function raised an exception that the upper level hadn't > >>>been expecting, after the program had been in use for a while. I'd > >>>sure rather find out about that at compile time. > >> > >> That's funny -- Bruce Eckel talks about how he used to love checked > >> exceptions but has come to regard them as the horror that they are. > >> I've learned to just write "throws Exception" at the declaration of > >> every method. > > > >Pretty sloppy, though, no? And surely the important thing is to have a > >broad handler, not a broad specification of raisable exceptions? > > Yes, it's sloppy, but I Don't Care. I'm trying to write usable code > while learning a damnably under-documented Java library -- and I'm *not* > a Java programmer in the first place, so I'm also fighting with the Java > environment. Eventually I'll add in some better code. The whole point of exceptions is that they get propagated automatically. If I'm not going to catch it, why do I have to even know it exists? I don't consider "throws Exception" to be sloppy, I consider it to be programmers voting with their feet. From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 20:38:51 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?UTF-8?B?TWFydGluIE1PS1JFSsWg?=) Date: Tue, 11 Jan 2005 02:38:51 +0100 Subject: Writing huve ge Sets() to disk In-Reply-To: <1f7befae05011015362e17f610@mail.gmail.com> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> <41E2E69C.7080104@ribosome.natur.cuni.cz> <1f7befae0501101245679b26f2@mail.gmail.com> <41E2F38C.30200@ribosome.natur.cuni.cz> <1f7befae05011015362e17f610@mail.gmail.com> Message-ID: <41E32E2B.3090508@ribosome.natur.cuni.cz> Tim Peters wrote: > [Tim Peters] > >>>As I mentioned before, if you store keys in sorted text files, >>>you can do intersection and difference very efficiently just by using >>>the Unix `comm` utiltity. > > > [Martin MOKREJ?] > >>Now I got your point. I understand the comm(1) is written in C, but it still >>has to scan file1 once and file2 n-times, where n is a number of lines >>in file1, right? Without any index ... I'll consider it, actually will test, >>thanks! > > > `comm` is much more efficient than that. Note that the input files > have to be sorted. Then, in a single pass over both files (not 2 > passes, not 3, not n, just 1), it can compute any subset of these > three (do `man comm`): > > 1. The words common to both files. > 2. The words unique to "the first" file. > 3. The words unique to "the second" file. I read the manpage actually before answering to the list. > It's essentially just doing a merge on two sorted lists, and how it > works should be obvious if you give it some thought. It takes time > proportional to the sum of the lengths of the input files, and nothing > *can* be faster than that. Well, I think I understand now because "Scott David Daniels" wrote probably the very same logic in python code in this thread. >>I was really hoping I'll get an answer how to alter the indexes for dictionaries >>in python. > > > Sorry, I don't have a guess for what that might mean. I'm not an expert, mysql for example givs you ability to index say first 10 characters of a text column, which are typically varchar. Just for curiosity I'd like to know how do it in python. When importing data from a flatfile into mysql table, there's an option to delay indexing to the very last moment, when all keys are loaded (it doesn't make sense to re-create index after each new row into table is added). I believe it's exactly same waste of cpu/io in this case - when I create a dictionary and fill it with data, I want to create index afterward, not after every key/value pair is recorded. >>You convinced me not to even try to construct to theoretical dictionary, >>as it will take ages just to create. Even if I'd manage, I couldn't >>save it (the theoretical and possibly not even the dict(theoret) - dict(real) >>result). > > > Worse, it didn't sound like a good approach even if you could save it. > > >>Still, before I give the whole project, once more: >> >>I'll parse some text files, isolates separate words and add them to >>either Set(), list, dict, flatfile line by line. >> >>Depending on the above, I'll compare them and look for those unique >>to some "language". I need to keep track of frequencies used >>in every such language, > > > Frequencies of what? "A language" here can contain some words > multiple times each? Yes, to compute the frequency of each word used in say "language A", I'll count number of occurencies and them compute frequency of it. Frequency number should be recorded as a value in the dictionary, where the keys are unique and represent the word itself (or it's hash as recommended already). Once more, the dictionary will contain every word only once, it will be really a unique key. >>so the dict approach would be the best. The number stored as a value vould >>be a float ^H^H^H^H^H^H Decimal() type - very small number. > > > Integers are the natural type for counting, and require less memory > than floats or decimals. I hoped I was clear ... when I said I'll compute frequency of those words. The algorithm to compute it will be subject to change during developemnt. ;) >>Once more, I expect to have between E4 or E5 to E8??? words >>stored in 20 dictionaries (remember words of sizes in range 1-20? >>Every of those 20 dictionaries should be, I believe, indexed just once. >>The indexing method should know all entries in a given file are of same >>size, i.e. 5 chars, 15 chars, 20 chars etc. > > > I think you're making this more complicated than it needs to be. I hope the algoritm can save some logic. For example, can turn off locking support, index only part of the key etc. > > >>I already did implement the logic to walk through those 20 different >>dictionaries from language a and from language b and find uout those >>unique to a or common to both of them. Why I went to ask on this list >>was to make sure I took right approach. Sets seemed to be better solution >>for the simple comparison (common, unique). To keep track of those >>very small frequencies, I anyway have to have dictionaries. I say >>that again, how can I improve speed of dictionary indexing? >>It doesn't matter here if I have 10E4 keys in dictionary or >>10E8 keys in a dictionary. > > > What reason do you have for believing that the speed of dictionary > indexing is worth any bother at all to speed up? Dict lookup is > generally considered to be extremely fast already. If you're just > *guessing* that indexing is the bottleneck, you're probably guessing > wrong -- run a profiler to find out where the real bottleneck is. For example, looking up a key with it's value only once in the whole for loop tells me I don't need an index. Yes, I'll do this 4 times for those 4 languages, but still I think it's faster to live without an index, when I can sort records. I think I like the sorted text file approach, and the dictionary approach without an index would be almost the same, especially if I manage to tell the db layout not to move the cursor randomly but just to walk down the pre-sorted data. As an extra, I could record those frequences within a dictionary. Actually, I need them, that's why I do all this work. The idea of using Sets() I had just to find more quickly unique/common words because of the possible speed gain. But I don't see a way to solve this without dictionaries. From invalidemail at aerojockey.com Tue Jan 4 21:38:57 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 4 Jan 2005 18:38:57 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) In-Reply-To: References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> Message-ID: <1104892737.215470.34590@c13g2000cwb.googlegroups.com> Skip Montanaro wrote: > I started to answer, then got confused when I read the docstrings for > unicode.encode and unicode.decode: [snip] It certainly is confusing. When I first started Unicoding, I pretty much stuck to Aahz's rule of thumb, without understanding this details, and still do that. But now I do undertstand it. Although encodings are bijective (i.e., equivalent one-to-one mappings), they are not apolar. One side of the encoding is arbitrarily labeled the encoded form; the other is arbitrarily labeled the decoded form. (This is not a relativistic system, here.) The encode method maps from the decoded to the encoded set. The decode method does the inverse. That's it. The only real technical difference between encode and decode is the direction they map in. By convention, the decoded form is a Python unicode string, and the encoded form is the byte string. I believe it's technically possible (but very rude) to write an "inverse encoding", where the "encoded" form is a unicode string, and the decoded form is UTF-8 byte string. Also, note that there are some encodings unrelated to Unicode. For example, try this: . >>> "abcd".encode("base64") This is an encoding between two byte strings. -- CARL BANKS From rogerb at rogerbinns.com Sun Jan 9 12:21:17 2005 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 9 Jan 2005 09:21:17 -0800 Subject: Recent infoworld column References: <41DEEF0F.5000300@nospamyahoo.com> Message-ID: "Peter Hansen" wrote in message news:G8Odndd9s7Zkv33cRVn-og at powergate.ca... > Dwarf Electrician wrote: >> from a long time listener... >> >> http://www.infoworld.com/article/04/12/30/01OPstrategic_1.html > > Kudos for Roger Binns! It is a very nice article :-) BitPim like many other projects is an effort by several people, but what John did was entirely my code. And of course that code wouldn't be possible without the various components I had available to me which including Python and wxPython as well as several others. http://bitpim.org/testhelp/credits.htm http://bitpim.org/testhelp/3rdparty.htm You may also find a talk I gave at baypiggies in July 2004 of interest. http://bitpim.org/papers/baypiggies/ It covers the various issues in doing a "real world" Python application, including packaging them up so they are indistinguishable from native applications, accessing serial ports, USB and SWIG, threading, the GUIs available and why I picked wxPython, Outlook and Evolution integration, dealing with an undocumented binary protocol, user and programmer documentation, secure remote access etc. Roger From rupole at hotmail.com Mon Jan 31 06:13:00 2005 From: rupole at hotmail.com (Roger Upole) Date: Mon, 31 Jan 2005 06:13:00 -0500 Subject: COM on a network drive can't find pywintypes23.dll References: Message-ID: <41fe134f$1_2@127.0.0.1> This means the machine is finding an older verion of pywintypes23.dll first, rather than not finding it at all. You may have an old version hanging around in the \system32 directory on that machine. (or anywhere else that it would be found first). You might also want to verify that the dll's you're copying around both come from the same distribution. Roger "Marco Aschwanden" wrote in message news:mailman.1627.1107161880.22381.python-list at python.org... > Hi > > I have installed Python (2.3.4) on a shared network drive. I use it to run > a bunch of application on the workstations (Win2K). > > Now I am running into the first problem ever. I try to use COM to generate > a word-file. It runs fine on my machine (Python installed locally). When I > deploy it and start the app on another workstation from the fileserver - > it runs but as soon as it comes to the COM part it exits saying: > > The procedure entry point > ?PyWinObject_AsDEVMODE@@YAHPAU_object@@PAPAU_devicemodeA@@H at Z could not be > located in the dynamic link library pywintypes23.dll > > > Heck... I copied the files: > > pythoncom23.dll > pywintypes23.dll > > to about "1000" locations to make it run (Application's dir, Workstation's > System Dirs, Fileserver's Python main and bin dir, ...). I tried setting > the path on the workstations. But nothing seems to solve the problem. > > Do you have any proposals how to solve this problem? > > Thanks in advance, > > Marco > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From apardon at forel.vub.ac.be Tue Jan 18 09:57:30 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Jan 2005 14:57:30 GMT Subject: generator expressions: performance anomaly? References: <354esdF4fouh0U1@individual.net> Message-ID: Op 2005-01-18, Steve Holden schreef : > Python is *designed* as a dynamic language. I wish you would embrace > this aspect rather than continually trying to shoehorn it into a static > straitjacket. Efficiency is good. Flexibility is better. Flexibility is better? IMO flexibilty implies more than one way to do things. But that is a big no no here in c.l.py. I also see a lot of remarks that go: "Don't do this!" when some of the more dynamic aspects are talked about, because there are security risks involved. One of the results was that I ended up writing a parser for some kind of game instead of just dumping the structure in textual form and doing an eval of the file when reading it in. But if I need a parser I could just as well used a static language. I'm beginning to guess the dynamic aspect of python is overrated. -- Antoon Pardon From emami at knmi.nl Tue Jan 11 05:34:27 2005 From: emami at knmi.nl (Nader Emami) Date: Tue, 11 Jan 2005 11:34:27 +0100 Subject: here document Message-ID: L.S., Would somebody help me how i can write the 'here document' in Python script please? I have a csh script in which a program is invoked with some argument in the form of here document: /bin/exe.x << End_Here CategorY = GRIB etc. End_Here I translate this script to Python and i don't know how can I do this! with regards, Nader From mike at pcblokes.com Wed Jan 12 06:26:55 2005 From: mike at pcblokes.com (Michael Foord) Date: Wed, 12 Jan 2005 11:26:55 +0000 Subject: [Ann] Voidspace Pythonutils Website Change and Updates Message-ID: <41E5097F.2070109@pcblokes.com> The Voidspace Pythonutil Pages have had a long overdue overhaul. The url of the Voidspace Pythonutils homepage has changed. It is now : http://www.voidspace.org.uk/python/index.html There are now separate pages for programs, modules, recipes, and CGIs. Several of the bigger modules and programs have their own pages. The following modules have also been updated : StandOut Version 2.1.0 6th Jan 2005 http://www.voidspace.org.uk/python/modules.shtml#standout This simple 'Flexible Output Object' has now been updated to work with sys.stderr as well as sys.stdout. It can log them separately or to the same file. StandOut is a simple way of adding 'variable verbosity levels' to your program *and* logging, just using normal print commands. guestbook.py http://www.voidspace.org.uk/python/cgi.shtml#guestbook Version 1.2.0 3rd December 2004 The Voidspace Python Guestbook has been updated. You can now use sendmail instead of smtplib as an option (my current host will only allow sendmail). License change (again!) - now the BSD license. Changed to use the UTF-8 encoding throughout. We ought to be able to accept 'foreign' (non-ascii) entries now. ConfigObj Version 3.2.3 2nd December 2004 Fixes a critical bug and a couple of minor improvements. ConfigObj is for simple but powerful config file parsing/creation. Fixed bug in creating non-flatfiles from scratch. (__comments__ KeyError). (critical bugfix) Tuple entries are written out as lists rather than being converted to strings. When an exception is raised, it's no longer printed first. Added the istrue method. Changed the license to BSD-License. As far as I know these are the only substantial changes to modules. A few others have had *minor* bugfix updates as well. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From devries at idolstarastronomer.com Mon Jan 31 11:26:45 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: Mon, 31 Jan 2005 11:26:45 -0500 Subject: Microsoft Visual C++ and pyton In-Reply-To: <1107126726.533325.104300@z14g2000cwz.googlegroups.com> References: <1107126726.533325.104300@z14g2000cwz.googlegroups.com> Message-ID: <20050131162645.GB10363@miyu.cjas.org> On Sun, Jan 30, 2005 at 03:12:06PM -0800, mike wrote: > I am new with python. Is it possible to have an MFC application and > develop some module using python? what are the steps in doing this? can > anybody give me a url or some documentation for this.. thanks.. It is possible to embed python in a C or C++ application, enabling you to call python functions from C. I would recommend reading "Extending and Embedding the Python Interpreter" at http://docs.python.org/ext/ext.html for more information. If you are currently using Visual C++ 6.0, either stick with Python 2.3 or read this: http://www.vrplumber.com/programming/mstoolkit/ to learn how to build extensions for python 2.4 with the free VC++ toolkit compiler. If you are already using version 7 of the Microsoft C++ compiler then you should have no problems with Python 2.4. I usually do not embed the interpreter, but I have written some extension modules... well, I should say I have used SWIG (http://www.swig.org/) to create wrappers around some C libraries. For information (read: rants) on extending versus embedding see http://twistedmatrix.com/users/glyph/rant/extendit.html and http://c2.com/cgi/wiki?EmbedVsExtend . You can also use win32 python extensions to make your module available through COM, but I don't know anything about that. Chris From daniel at bowettsolutions.com Thu Jan 20 14:52:42 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Thu, 20 Jan 2005 19:52:42 +0000 Subject: What's the best python web-developer's editor In-Reply-To: <41EFFCD9.7060302@wild-flower.co.uk> References: <41EFFCD9.7060302@wild-flower.co.uk> Message-ID: I only use Windows and I only ever use Textpad. It gives nice syntax highlighting, indentation and you can run your script with it too. andy wrote: > Anybody like to comment on which editor they use for python web app > development - for both discrete and mixed python and html code, and why? > > I'm comfortable with IDLE (used it for years) but of course it lacks ftp > or webDAV abilities, obviously because it's not intended for that type > of use. > > I've had a look at Screem - and that seems to do python syntax > highlighting, but it dosn't seem to be python syntax aware (unless > there's a hidden option somewhere). Although I can live without auto > indent, I'd rather not... > > I'm sure emacs, xemacs, vi, elvis and so on can do the same, but I have > no experience with them for heavy python or html coding, nor the time > to trip off down a blind-alley to find out! I know Enough Vi To Get > By(tm) but it's by no means my favourite editor. Emacs is a complete > mystery to me. > > I guess I *could* use IDLE and Screem together, but that's a clunky > solution! > > all opinions greatfully received, > -andyj From "yardholler\" at Nospam,charter.net> Sat Jan 15 07:08:19 2005 From: "yardholler\" at Nospam,charter.net> (Misty) Date: Sat, 15 Jan 2005 06:08:19 -0600 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: Jane wrote: > "Lucas Raab" wrote in message > news:UsuFd.5434$KJ2.1253 at newsread3.news.atl.earthlink.net... > >>Jane wrote: >> >>> wrote in message >>>news:1105495569.479185.166340 at z14g2000cwz.googlegroups.com... >>> >>> >>>>python.org = 194.109.137.226 >>>> >>>>194 + 109 + 137 + 226 = 666 >>>> >>>>What is this website with such a demonic name and IP address? What >>>>evils are the programmers who use this language up to? >>>> >>> >>>Some people have too much time on their hands... >>> >>>Jane >>> >>> >> >>Better get some ointment for that burn!! > > > Huh??? > > Jane > > From apardon at forel.vub.ac.be Fri Jan 14 05:51:49 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Jan 2005 10:51:49 GMT Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-01-14, Fredrik Lundh schreef : > Antoon Pardon wrote: > >>> no, expressions CAN BE USED as statements. that doesn't mean >>> that they ARE statements, unless you're applying belgian logic. >> >> No I am applying set logic. Any string that is in the set of >> valid expressions is also in the set of valid statements. > > since you're arguing that one concept is identical to another concept, that > operation has to work in both directions. No I'm not. "is" doesn't mean the concepts are the same. >> Like any animal that is in the set of dogs is also in the >> set of mamals. > > and all mammals are dogs? No but every dog is a mammal, and saying that doesn't imply dog and mammal are identical concepts > it this a language problem? do you have problems parsing the statements > you reply to? even when someone explictly says "Given that we are having > this discussion in the context of", you chose to ignore that context. what's > wrong with you? Well IMO I have explained clearly that I understood this in a set logical sense in my first response. It seems you chose to ignore that context. So what's wrong with you? -- Antoon Pardon From wittempj at hotmail.com Mon Jan 17 11:26:44 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 17 Jan 2005 08:26:44 -0800 Subject: List problems in C code ported to Python In-Reply-To: References: Message-ID: <1105979204.943270.289830@z14g2000cwz.googlegroups.com> l = [] for i in range(2): for j in range(2): l[i],[j] = 0 print l gives Traceback (most recent call last): File "C:\TEMP\test.py", line 75, in -toplevel- l[i],[j] = 0 TypeError: unpack non-sequence That's why your current code needs a matrix class. From amand.nospam at alrj.org Fri Jan 14 04:43:15 2005 From: amand.nospam at alrj.org (Amand Tihon) Date: Fri, 14 Jan 2005 10:43:15 +0100 Subject: Debian says "Warning! you are running an untested version of Python." on 2.3 References: Message-ID: <41e79433$0$2022$6c56d894@feed0.news.be.easynet.net> rbt wrote: > Nick Craig-Wood wrote: > >> Alex Stapleton wrote: >>> Whenever I run python I get >>> >>> "Warning! you are running an untested version of Python." >>> >>> prepended to the start of any output on stdout. >>> >>> This is with Debian and python 2.3 (running the debian 2.1 and 2.2 >>> binaries doesn't have this effect) >> >> What version of a) Debian and b) python are you running? >> >> I don't have that problem here (I'm running testing/sarge) > > Same here... Debian testing with Python2.3 no problem. Perhaps he's > running Debian unstable? Same result here on unstable, no problem. And experimental has no python2.3 package. However, I remember vaguely about something like this. Perhaps the OP is running an old unstable version, never upgraded ? -- Amand Tihon From aahz at pythoncraft.com Fri Jan 14 14:49:12 2005 From: aahz at pythoncraft.com (Aahz) Date: 14 Jan 2005 14:49:12 -0500 Subject: Free NNTP (was Re: how to stop google from messing Python code) References: <1105620098.878376.110250@z14g2000cwz.googlegroups.com> <1105666406.272397.170730@c13g2000cwb.googlegroups.com> <1105704548.146263.229220@f14g2000cwb.googlegroups.com> Message-ID: In article , Fredrik Lundh wrote: >Fuzzyman wrote: >> >> I guess that most people use google to post to newsgroups is that they >> don't have nntp access. Telling htem to use a newsreader is facetious >> and unhelpful. Most people use Gooja to post because they're lazy. >if you have internet access, you have NNTP access. gmane.org provides >access to more than 6,500 mailing lists via NNTP, including all >relevant Python forums. You also have access to the free netnews server http://news.cis.dfn.de/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From tjreedy at udel.edu Thu Jan 27 22:27:07 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Jan 2005 22:27:07 -0500 Subject: Talking to the wind References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> <1106875259.426213.252030@z14g2000cwz.googlegroups.com> Message-ID: "The Flow" wrote in message news:1106875259.426213.252030 at z14g2000cwz.googlegroups.com... > Xah Lee, > > Do you want to be taken seriously? > First, stop posting. > Second, learn perl. > Third, learn python. Hey all, I have seen no evidence that XL even reads the responses that have been directed thereto. The above is like /dev/null, Why don't you ever answer the messages I keep sending to you? Terry J. Reedy From fredrik at pythonware.com Wed Jan 26 11:15:22 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Jan 2005 17:15:22 +0100 Subject: re.search - just skip it References: <1106754436.876675.144290@c13g2000cwb.googlegroups.com> Message-ID: wrote: > but output is: > > SET2_S_W CHAR(1) NOT NULL, > SET4_S_W CHAR(1) NOT NULL, > > It should delete every, not every other! for i in range(len(lines)): try: if s_ora.search(lines[i]): del lines[i] except IndexError: ... when you loop over a range, the loop counter is incremented also if you delete items. but when you delete items, the item numbering changes, so you end up skipping over an item every time the RE matches. to get rid of all lines for which s_ora.search matches, try this lines = [line for line in lines if not s_ora.search(line)] for better performance, get rid of the leading and trailing ".*" parts of your pattern, btw. not that it matters much in this case (unless the SQL state- ment is really huge). From vincent at visualtrans.de Mon Jan 17 12:38:59 2005 From: vincent at visualtrans.de (vincent wehren) Date: Mon, 17 Jan 2005 18:38:59 +0100 Subject: how to find site-packages path In-Reply-To: References: Message-ID: Philippe C. Martin wrote: > Hi, > > I am using my own install script for my software and am looking for a > flawless way to figure out where python, and more specifically > site-packages is installed. You can take a look at how this is done in Lib/site.py. Look for the bit of code that starts with prefixes = [sys.prefix] sitedir = None # make sure sitedir is initialized because of later 'del' ... etc. -- Vincent Wehren > > Any clue ? > > Regards, > > Philippe > > > From peter at engcorp.com Sun Jan 23 21:00:25 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jan 2005 21:00:25 -0500 Subject: Set parity of a string In-Reply-To: References: Message-ID: Peter Hansen wrote: > snacktime wrote: >> Is there a module that sets the parity of a string? > > As to the specific question: a module is not really required. But here's one for you anyway. It raises an exception if any input character is non-ASCII, otherwise when you call set_parity() with a string and a parity parameter of 'even', 'mark', 'none', 'odd', or 'space', it returns a string of the same length with the high (parity) bits set appropriately. '''parity module for python''' # Copyright 2005 Engenuity Corporation # Released under the "MIT license" # at http://www.opensource.org/licenses/mit-license.php import string import operator def _makeTable(parity): bitMap = {'even': [0,128], 'odd': [128,0], 'mark': [128,128]} table = [] for c in range(128): even_odd = (sum(bool(c & 1< Hi, I am using my own install script for my software and am looking for a flawless way to figure out where python, and more specifically site-packages is installed. Any clue ? Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From ncoghlan at iinet.net.au Fri Jan 14 02:57:31 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 14 Jan 2005 17:57:31 +1000 Subject: Class initialization from a dictionary, how best? In-Reply-To: <1105677379.632236.17020@z14g2000cwz.googlegroups.com> References: <1105677379.632236.17020@z14g2000cwz.googlegroups.com> Message-ID: <41E77B6B.2010305@iinet.net.au> brianobush at gmail.com wrote: > t2 = Test(dictionary.get('a'), dictionary.get('b'), > dictionary.get('c')) > print t2 Try this: t2 = Test(**dictionary) This performs keyword argument expansion on the dictionary, matching the dictionary entries with the named arguments to the Test.__init__ function. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From g.brandl-2005-01 at gmx.net Sun Jan 23 16:08:31 2005 From: g.brandl-2005-01 at gmx.net (Georg Brandl) Date: Sun, 23 Jan 2005 22:08:31 +0100 Subject: What is print? A function? In-Reply-To: References: Message-ID: <35ii2aF4nhdncU2@individual.net> Roy Smith wrote: >> So I wonder, what _is_ exactly the print statement? The untraditional way of >> invoking it(without paranteses) makes me wonder. > > It's a statement, just like "write" in Fortran. When C came around, the > idea of a language having no built-in print statement and having to call > a function to generate output was "untraditional". The function was > named "printf" (with an "f" at the end) to emphasize that it was a > function call, not a built-in language keyword. I beg to differ. Doesn't 'printf' stand for 'PRINT Formatted string'? > Java, and many other > quasi-C-based languages also use print functions, and this has become so > common that people have come to expect it. It's even a function in > Perl, although that language's devil-may-care attitude about punctuation > makes it difficult to tell for sure :-) And it should have been and perhaps will be a function in Python, see "Python Regrets" by GvR. Georg From sjmachin at lexicon.net Tue Jan 18 20:11:34 2005 From: sjmachin at lexicon.net (John Machin) Date: 18 Jan 2005 17:11:34 -0800 Subject: file copy portability In-Reply-To: References: Message-ID: <1106097094.789862.275060@z14g2000cwz.googlegroups.com> Bob Smith wrote: > Is shutil.copyfile(src,dst) the *most* portable way to copy files with > Python? I'm dealing with plain text files on Windows, Linux and Mac OSX. > > Thanks! Portable what? Way of copying?? Do you want your files transferred (a) so that they look like native text files on the destination system, or (b) so that they are exact byte-wise copies? A 5-second squint at the source (Lib/shutil.py) indicates that it provides, reliably and portably, option b: fsrc = open(src, 'rb') fdst = open(dst, 'wb') One way of doing option (a): you would need to be running Python on the destination system, open the src file with 'rU', open the dst file with 'w'. From jfine at pytex.org Thu Jan 6 02:02:35 2005 From: jfine at pytex.org (Jonathan Fine) Date: Thu, 06 Jan 2005 07:02:35 +0000 Subject: What could 'f(this:that=other):' mean? References: <41DC52CA.5070104@pytex.org> <10toomjdjcs5v21@corp.supernews.com> Message-ID: <41DCE28B.70806@pytex.org> Jeff Shannon wrote: > Jonathan Fine wrote: > >> Giudo has suggested adding optional static typing to Python. >> (I hope suggested is the correct word.) >> http://www.artima.com/weblogs/viewpost.jsp?thread=85551 >> >> An example of the syntax he proposes is: >> > def f(this:that=other): >> > print this >> I'm going to suggest a different use for a similar syntax. >> >> In XML the syntax >> > >> is used for name spaces. >> >> Name spaces allow independent attributes to be applied to an >> element. For example, 'fo' attributes for fonts and layout. >> XSLT is of course a big user of namespaces in XML. >> >> Namespaces seems to be a key idea in allow independent >> applications to apply attributes to the same element. >> [...] >> Here's an example of how it might work. With f as above: >> > f(this:that='value') >> {'that': 'value'} > > > I fail to see how this is a significant advantage over simply using > **kwargs. It allows you to have multiple dictionaries instead of just > one, that's all. And as you point out, it's trivial to construct your > own nested dicts. This argument could be applied to **kwargs (and to *args). In other words, **kwargs can be avoided using a trivial construction. >>> def f_1(**kwargs): print kwargs ... >>> f_1(a=3, b=4) {'a': 3, 'b': 4} >>> >>> def f_2(kwargs): print kwargs ... >>> f_2({'a':3, 'b':4}) {'a': 3, 'b': 4} (and in Python 2.3) >>> f_2(dict(a=3, b=4)) {'a': 3, 'b': 4} f_1() is internally the same as f_2(), but the argument passing is different. Jeff, are you in favour of kwargs as a language feature? If so, you may wish to refine your argument. (One can be in favour of kwargs and against my proposal. That kwargs is widely used, and my proposal would not be, is a good argument, IMO.) I'll post some usage examples later today, I hope. > Besides, Python already uses the concept of namespaces by mapping them > to object attributes. Module references are a namespace, exposed via > the attribute-lookup mechanism. This (IMO) fails the "there should be > one (and preferably only one) obvious way to do things" test. The > functionality already exists, so having yet-another way to spell it will > only result in more confusion. (The fact that we're borrowing the > spelling from XML does little to mollify that confusion.) Here, I don't understand. Could you give an example of two obvious ways of doing the same thing, should my suggestion be adopted? -- Jonathan http://www.pytex.org From invalidemail at aerojockey.com Wed Jan 19 20:01:42 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 19 Jan 2005 17:01:42 -0800 Subject: Zen of Python In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> Message-ID: <1106182902.759111.79140@z14g2000cwz.googlegroups.com> Timothy Fitz wrote: > On 19 Jan 2005 15:24:10 -0800, Carl Banks wrote: > > The gist of "Flat is better than nested" is "be as nested as you have > > to be, no more," because being too nested is just a mess. > > Which I agree with, and which makes sense. However your "gist" is a > different meaning. It's not that "Flat is better than nested" it's > that "Too flat is bad and too flat is nested so be as nested (or as > flat) as you have to be and no more." Perhaps Tim Peters is far too > concise for my feeble mind Couldn't you say the same about Simple and Complex? or Explicit and Implicit? -- CARL BANKS From D.Sean.Morris at gmail.com Sun Jan 2 17:56:47 2005 From: D.Sean.Morris at gmail.com (Sean) Date: 2 Jan 2005 14:56:47 -0800 Subject: ? about file() and open() Message-ID: <1104706607.022890.314500@c13g2000cwb.googlegroups.com> Was wondering if there was any difference between these two functions. I have read some text that said file() wasn't introduced until 2.2 and that it was synonymous with open(). Does this mean that I should be using file() where I used open() before? Sean Morris From tim.peters at gmail.com Fri Jan 14 13:16:40 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 14 Jan 2005 13:16:40 -0500 Subject: Why 'r' mode anyway? (was: Re: Pickled text file causing ValueError (dos/unix issue)) In-Reply-To: <41e80785$0$6203$e4fe514c@news.xs4all.nl> References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> <41e80785$0$6203$e4fe514c@news.xs4all.nl> Message-ID: <1f7befae05011410167e49a5bb@mail.gmail.com> [Irmen de Jong] > I've been wondering why there even is the choice between binary mode > and text mode. Why can't we just do away with the 'text mode' ? > What does it do, anyways? At least, if it does something, I'm sure > that it isn't something that can be done in Python itself if > really required to do so... It's not Python's decision, it's the operating system's. Whether there's an actual difference between text mode and binary mode is up to the operating system, and, if there is an actual difference, every detail about what the difference(s) consists of is also up to the operating system. That differences may exist is reflected in the C standard, and the rules for text-mode files are more restrictive than most people would believe. On Unixish systems, there's no difference. On Windows boxes, there are conceptually small differences with huge consequences, and the distinction appears to be kept just for backward-compatibility reasons. On some other systems, text and binary files are entirely different kinds of beasts. If Python didn't offer text mode then it would be clumsy at best to use Python to write ordinary human-readable text files in the format that native software on Windows, and Mac Classic, and VAX (and ...) expects (and the native format for text mode differs across all of them). If Python didn't offer binary mode then it wouldn't be possible to use Python to process data in binary files on Windows and Mac Classic and VAX (and ...). If Python used its own platform-independent file format, then it would end up creating files that other programs wouldn't be able to deal with. Live with it . From FBatista at uniFON.com.ar Tue Jan 4 08:39:10 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 4 Jan 2005 10:39:10 -0300 Subject: Python evolution: Unease Message-ID: [Iwan van der Kleyn] #- need: a better standard ide, an integrated db interface with #- a proper #- set of db drivers (!!), a better debugger, a standard widget/windows #- toolkit, something akin to a standard for web programming, better #- documentation, a standard lib which is better organized, a #- formalized #- set of protocols and patterns for program construction. And an #- interpreter which is fast enough to avoid using C or Pyrex in most #- obvious cases. Let's take one by one: - IDE: Better than what? Than IDLE? Than Eclipse? Than SPE? Than Pythonwin? - Integrated DB interface with a proper set of db drivers (what means the "!!"?): What do you mean with an integrated db interface? An standard API to access different DB engines? Something like the Database API specification (http://www.python.org/topics/database/DatabaseAPI-2.0.html)? There's a SIG on DB at http://www.python.org/sigs/db-sig/ you may want to look at. Regarding drivers, to what DB do you miss one? - Debugger: Again, better than what? I use the debugger in IDLE and it's pretty ok. - Standard widget/windows toolkit: More standard than Tk? - Something akin to a standard for web programming: specifically? - Better documentation: Did you find *any* issue in the docs? And why you didn't post a bug on that? - Better organization of the std lib: What do you propose (specifically)? Please, in your proposal, take in consideration migration plans and how the migration affect actual systems. And of course, why the new organization is better than the old one. BTW, I also think that it should be better organized, but don't know how. - a formalized set of protocols and patterns for program construction: a what? - an interpreter which is fast enough to avoid using C or Pyrex in most obvious cases: CPython is More Than Fast Enough. In which obvious cases it's not enough for you? Don't misinterpret this response. I know it was a rambling. But *maybe* you have something to contribute to Python development, even good ideas only and no work. . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From invalidemail at aerojockey.com Sat Jan 8 19:13:39 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 8 Jan 2005 16:13:39 -0800 Subject: python3: 'where' keyword In-Reply-To: <41dfc018.305122743@news.oz.net> References: <3480qqF46jprlU1@individual.net><41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> Message-ID: <1105229619.776339.218900@c13g2000cwb.googlegroups.com> Bengt Richter wrote: > And, is the whole thing after the '=' an expression? E.g., > > x = ( foo(x) where: > x = math.pi/4.0 > ) where: > def foo(x): print 'just for illustration', x How would that be any improvement over this? . x = foo(x) where: . x = math.pi/4.0 . def foo(x): print 'just for illustration', x Can anyone think of a use case for embedding "where" inside an expression as opposed to making it part of a simple statement? And, if so, is the benefit of it worth the massive hit in readability. > or is this legal? > > for y in ([foo(x) for x in bar] where: > bar = xrange(5) > ): baz(y) where: > def baz(arg): return arg*2 Here, I can only hope not. One reason I proposed a where...do syntax is so that, if you wanted to localize a variable to a for loop or some other compound statement, you could do it with a minimum of fuss. . where: . bar = xrange(5) . def baz(arg): return arg*2 . do: . for y in [foo(x) for x in bar]: . baz(y) > Not trying to sabotage the idea, really, just looking for clarification ;-) That's ok. For it fly, it's got to be able to withstand the flak. -- CARL BANKS From shoot at the.moon Fri Jan 7 18:26:25 2005 From: shoot at the.moon (Steve Horsley) Date: Fri, 07 Jan 2005 23:26:25 +0000 Subject: "A Fundamental Turn Toward Concurrency in Software" In-Reply-To: References: Message-ID: Jack Diederich wrote: > On Fri, Jan 07, 2005 at 01:35:46PM -0800, aurora wrote: > >>Hello! >> >>Just gone though an article via Slashdot titled "The Free Lunch Is Over: A >>Fundamental Turn Toward Concurrency in Software" >>[http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that the >>continous CPU performance gain we've seen is finally over. And that future >>gain would primary be in the area of software concurrency taking advantage >>hyperthreading and multicore architectures. > > > It got most things right, AMD & Intel are moving towards multiple cores on > a chip so programmers will adapt. I don't see this as a big deal, the current > trend is rack farms of cheap boxes for heavy computing needs. Multi-core CPUs > will help those kinds of applications more than single threaded ones. Existing > threaded apps don't have to worry at all. > But my understanding is that the current Python VM is single-threaded internally, so even if the program creates multiple threads, just one core will be dividing its time between those "threads". > His picking on Intel to graph CPU speeds was a mistake (I'll be generous and > not say deliberate). Intel screwed up and pursued a megahertz-at-all-costs > strategy for marketing reasons. AMD didn't worry about MHz, just about CPUs > that did more work and so AMD is eating Intel's lunch. Intel has abandoned > their "faster" line of processors and is using their CPUs that are slower in > MHz but get more work done. So the author's "MHz plateau" graph isn't all > Moore's law breaking down, it is the result of Intel's marketing dept breaking > down. > You may be right, but I agree with the thrust of the article that multicore looks to be the new in thing at the moment. Steve From aahz at pythoncraft.com Sat Jan 1 00:33:33 2005 From: aahz at pythoncraft.com (Aahz) Date: 1 Jan 2005 00:33:33 -0500 Subject: what is lambda used for in real code? References: Message-ID: In article , Adam DePrince wrote: > >Unless internationalization was a concern, few people would write: > >THE_ANSWER_IS = "The answer is" >print THE_ANSWER_IS, x However, there's a moderately large (and growing!) set of people who would argue that I18N is *always* a concern -- it's just that a lot of people either don't know it yet or ignore it. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From petite.abeille at gmail.com Sat Jan 29 09:16:28 2005 From: petite.abeille at gmail.com (PA) Date: Sat, 29 Jan 2005 15:16:28 +0100 Subject: The next Xah-lee post contest In-Reply-To: <5a309bd305012905357e14df62@mail.gmail.com> References: <5a309bd305012905357e14df62@mail.gmail.com> Message-ID: On Jan 29, 2005, at 14:35, Steve wrote: > Here's my contribution (tho' I'm not really in my most creative frame > of mind): Not being very creative myself, here is a contribution "by proxy": "Unlike Java programmers, who are hip on the outside, dreary conformists on the inside, Smalltalk programmers are a bunch of faded flower children who listen to Mantovani and the Star Wars soundtrack. They are 68% more likely to be Clinton supporters and 94% of them laughed when Bob Dole fell down in the last election campaign. Most Smalltalk programmers smoke weak pot and hide their stash from their kids (who are Java programmers)." -- Steve Wart, why Smalltalk never caught on http://hoho.dyndns.org/~holger/smalltalk.html Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From sylvain.thenault at nospam.logilab.fr Tue Jan 18 09:11:44 2005 From: sylvain.thenault at nospam.logilab.fr (Sylvain Thenault) Date: Tue, 18 Jan 2005 15:11:44 +0100 Subject: MemoryError with parser.suite and wrong encoding declaration Message-ID: Hi there ! I've noticed the following problem with python >= 2.3 (actually 2.3.4 and 2.4): syt at musca:test$ python Python 2.3.4 (#2, Sep 24 2004, 08:39:09) [GCC 3.3.4 (Debian 1:3.3.4-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import parser >>> parser.suite('# -*- coding: IBO-8859-1 -*-') Traceback (most recent call last): File "", line 1, in ? MemoryError >>> parser.suite('# -*- coding: ISO-8859-1 -*-') Shouldn't parser.suite just ignore the wrong encoding declaration, or at least raise a more appropriate exception. IMHO the first solution would be better, since that's the behaviour of the (C) python interpreter. -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From steve at holdenweb.com Tue Jan 25 16:08:33 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 25 Jan 2005 16:08:33 -0500 Subject: Import from database In-Reply-To: <1106681053.863328.261670@f14g2000cwb.googlegroups.com> References: <1106587145.067483.14710@z14g2000cwz.googlegroups.com> <1106681053.863328.261670@f14g2000cwb.googlegroups.com> Message-ID: Kartic wrote: > Steve, > > Hmmm... Yes, I see what you are saying. Could you post your create > table statement so that I can create a db and play around with > dbimport? > > Thanks, > --Kartic > Here it is, plus also the loader program I used to suck in the standard library (in case it's that that's faulty): CREATE TABLE `module` ( `modName` varchar(25) NOT NULL default '', `modPackage` tinyint(1) NOT NULL default '0', `modCompileTime` timestamp(14) NOT NULL, `modCode` longtext, PRIMARY KEY (`modName`) ) TYPE=MyISAM; #### WARNING: email client may wrap some lines ... # # Establish standard library in database # import db import os import glob import sys import marshal conn = db.conn() curs = conn.cursor() if sys.argv[1] == "-d": curs.execute("delete from module") print "All existing modules cleared" del sys.argv[1] def importpy(path, modname, package): print "Importing", path, modname c = compile(file(path).read(), "db:%s" % modname, "exec") curs.execute("""delete from module where modName = %s""", (modname,)) curs.execute("""insert into module (modName, modCode, modPackage, modCompileTime) values (%s, %s, %s, now())""", (modname, marshal.dumps(c), package)) print "Added", modname conn.commit() def importall(path, modlist): os.chdir(path) for f in glob.glob("*"): if os.path.isdir(f): fn = os.path.join(path, f, "__init__.py") if os.path.exists(fn): ml = modlist + [f] importpy(fn, ".".join(ml), 1) importall(os.path.join(path, f), ml) elif f.endswith('.py') and '.' not in f[:-3] and f != "__init__.py": importpy(os.path.join(path, f), ".".join(modlist+[f[:-3]]), 0) if __name__ == "__main__": for path in sys.argv[1:]: importall(path, []) regards Steve From jerf at jerf.org Thu Jan 6 15:05:31 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 06 Jan 2005 15:05:31 -0500 Subject: wxPython clipboard References: <1105010876.075011.261070@z14g2000cwz.googlegroups.com> Message-ID: On Thu, 06 Jan 2005 03:27:56 -0800, lbolognini wrote: > Could you please give me some advice on the best approach to solve this > problem? To the best of my knowledge, and I'd be surprised if this wasn't true, wxPython does not have the necessary tools to do this. That program doesn't even use the clipboard; it uses low-level security flaws* in Windows to directly access text in other programs as it is being typed, watch for trigger text to go by, and then dynamically replace it; all of which is a major security flaw in the absence of user permission. This *particular* application is harmless, but it's still exploiting holes. Since those holes don't exist cross-platform, wxWindows won't reflect them. You'd need to go to the WinAPI, and after that I have no idea what comes next... but I do know it's going to be tricky, painful work and if you didn't already know you needed to do this, you probably don't want to go here. Here There Be Dragons. *: The security flaw lies in the Windows messaging model; once you have a window handle you can send it any message and get back any data you want, including stuffing that window with any new data you want, which is a gaping flaw indeed in a world of buffer exploits. IIRC, there is no way to do any sort of user-based security, so even if you do everything as a low-priv user except use this one program as administrator, if that program has a window on the screen and a buffer overflow, that's a root exploit waiting to be coded. From grante at visi.com Thu Jan 6 11:15:49 2005 From: grante at visi.com (Grant Edwards) Date: 06 Jan 2005 16:15:49 GMT Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> <41DD5C6B.2070708@holdenweb.com> Message-ID: <41dd6435$0$45194$a1866201@visi.com> On 2005-01-06, Peter Hansen wrote: > Steve Holden wrote: >> Peter Hansen wrote: >>> But the whole argument is fairly moot... I've needed a rectangle >>> operation only once in the last ten years, and if I hadn't known at >>> the time that my editor could do it (and spent about half an hour >>> figuring out how it worked), I could have written a utility to >>> do the job faster if I'd been using Python at the time... >> >> Or even used cut(1) from the command line. > > Or myybe not :-) > > Microsoft Windows XP [Version 5.1.2600] > (C) Copyright 1985-2001 Microsoft Corp. > > c:\> That's not a command line. ;) > 'cut' is not recognized as an internal or external command, > operable program or batch file. -- Grant Edwards grante Yow! I am having FUN... I at wonder if it's NET FUN or visi.com GROSS FUN? From dbickett at gmail.com Sun Jan 23 11:26:25 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 23 Jan 2005 11:26:25 -0500 Subject: compile python to binary In-Reply-To: References: <1d6cdae3050123080242bf8994@mail.gmail.com> Message-ID: <1d6cdae30501230826a7b468@mail.gmail.com> Fredrik Lundh wrote: > oh, you mean that "python compiler" didn't mean "the python compiler". > [snip] I simply inferred that he was using the wrong terminology, being that he said "binary" twice ;-) sam wrote: > I have seen some software written in python and delivered as binary form. > > How does these binary code get generated by python compiler? Daniel Bickett From roy at panix.com Tue Jan 25 08:14:31 2005 From: roy at panix.com (Roy Smith) Date: Tue, 25 Jan 2005 08:14:31 -0500 Subject: Another scripting language implemented into Python itself? References: <1106624803.825442.73870@f14g2000cwb.googlegroups.com> Message-ID: "Carl Banks" wrote: > > Imbed > EMBED. My apologies for being sloppy. And with an initial capital, so it just jumps off the page at you :-) > > Python, or Perl, or TCL, or Ruby, or PHP, > > Not PHP. PHP is one of the better (meaning less terrible) examples of > what happens when you do this sort of thing, which is not saying a lot. But, that's exactly my point. To be honest, I've never used PHP. But however bad it may be, at least it's got a few years of people fixing bugs, writing books, writing add-on tools, etc, behind it. Better to use somebody else's well-known and well-supported mess of a scripting language than to invest several person-years inventing your own mess that's no better. There are a lot of existing scripting languages to pick from. It's nice to pick the best one, but even if you pick the worst, that's probably better than you can do on your own. > TCL isn't that great in this regard, either, as it makes a lot of > common operations that ought to be very simple terribly unweildy. In my last job, I did a lot of TCL. I've posted on this before (when I was at a previous employer), so I'll just provide a pointer (http://tinyurl.com/44w6n). That article says most of what that needs saying, *AND* proves that I really do know how to spell embed :-) It might be worth adding, however, that the TCL implementation discussed above was a 3rd generation for that product. Generation #1 was a bunch of shell scripts. Generation #2 was a home-grown scripting language. Fortunately, they learned their lesson soon enough to rescue the project with a conversion to TCL. I'm not sure how many person-years were wasted both in the initial implementation and in the conversion effort, but I imagine it was a $500,000 mistake. From peter at engcorp.com Fri Jan 21 20:36:33 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Jan 2005 20:36:33 -0500 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> Message-ID: A.M. Kuchling wrote: > On Fri, 21 Jan 2005 18:54:50 +0100, > Fredrik Lundh wrote: >>judging from http://yaml.org/spec/current.html (750k), the YAML designers are >>clearly insane. that's the most absurd software specification I've ever seen. they >>need help, not users. > > IMHO that's a bit extreme. Specifications are written to be detailed, so > consequently they're torture to read. Seen the ReStructured Text spec > lately? [...] > But YAML ... the format is now ... not really simpler than > XML and in some ways weaker (e.g. only two encodings supported, more > complicated escaping rules). As I recall, one of the key original goals for XML was that the parsers be relatively easy to write (relative to SGML). Judging by that YAML spec, I can imagine that a YAML parser could well be much more difficult to write than an XML parser would be. Anyone have personal experience with this? (Yes, I know people don't write parsers as often as they use them, and that's probably some of the justification behind YAML, but looking at that YAML spec, I find it hard to imagine I could ever remember enough of it to write a YAML file by hand, and yet I can and do write XML files by hand often.) -Peter From steven.bethard at gmail.com Tue Jan 11 02:45:01 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 11 Jan 2005 00:45:01 -0700 Subject: stretching a string over several lines (Re: PyChecker messages) In-Reply-To: References: Message-ID: Frans Englich wrote: > Also, another newbie question: How does one make a string stretch over several > lines in the source code? Is this the proper way? (1) > print "asda asda asda asda asda asda " \ > "asda asda asda asda asda asda " \ > "asda asda asda asda asda asda" A couple of other options here: (2) print """asda asda asda asda asda asda asda asda asda asda asda asda asda asda asda asda asda asda""" (3) print """\ asda asda asda asda asda asda asda asda asda asda asda asda asda asda asda asda asda asda""" (4) print ("asda asda asda asda asda asda " "asda asda asda asda asda asda " "asda asda asda asda asda asda") Note that backslash continuations (1) are on Guido's list of "Python Regrets", so it's likely they'll disappear with Python 3.0 (Of course this is 3-5 years off.) I typically use either (3) or (4), but of course the final choice is up to you. Steve From steve at holdenweb.com Fri Jan 14 17:48:43 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 17:48:43 -0500 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <10ue4s49jl8s6d7@corp.supernews.com> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <41e5ebee.709560864@news.oz.net> <1105632841.461042.68310@c13g2000cwb.googlegroups.com> <10udfj4c4rgkvcc@corp.supernews.com> <1105651353.769879.229690@f14g2000cwb.googlegroups.com> <10ue4s49jl8s6d7@corp.supernews.com> Message-ID: Jeff Shannon wrote: > Chris Lasher wrote: > >>> And besides, for long-term archiving purposes, I'd expect that zip et >>> al on a character-stream would provide significantly better >>> compression than a 4:1 packed format, and that zipping the packed >>> format wouldn't be all that much more efficient than zipping the >>> character stream. >> >> >> This 105MB FASTA file is 8.3 MB gzip-ed. > > > And a 4:1 packed-format file would be ~26MB. It'd be interesting to see > how that packed-format file would compress, but I don't care enough to > write a script to convert the FASTA file into a packed-format file to > experiment with... ;) > If your compression algorithm's any good then both, when compressed, should be approximately equal in size, since the size should be determined by the information content rather than the representation. > Short version, then, is that yes, size concerns (such as they may be) > are outweighed by speed and conceptual simplicity (i.e. avoiding a huge > mess of bit-masking every time a single base needs to be examined, or a > human-(semi-)readable display is needed). > > (Plus, if this format might be used for RNA sequences as well as DNA > sequences, you've got at least a fifth base to represent, which means > you need at least three bits per base, which means only two bases per > byte (or else base-encodings split across byte-boundaries).... That gets > ugly real fast.) > Right! regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From jeff at ccvcorp.com Thu Jan 13 13:22:28 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 13 Jan 2005 10:22:28 -0800 Subject: Refactoring; arbitrary expression in lists In-Reply-To: References: <41e5cb07.701137402@news.oz.net> <41e5fdce.714136143@news.oz.net> Message-ID: <10udep396j2492f@corp.supernews.com> Stephen Thorne wrote: > As for the overall efficiency concerns, I feel that talking about any > of this is premature optimisation. I disagree -- using REs is adding unnecessary complication and dependency. Premature optimization is a matter of using a conceptually more-complicated method when a simpler one would do; REs are, in fairly simple cases such as this, clearly *not* simpler than dict lookups. > The optimisation that is really > required in this situation is the same as with any > large-switch-statement idiom, be it C or Python. First one must do a > frequency analysis of the inputs to the switch statement in order to > discover the optimal order of tests! But if you're using a dictionary lookup, then the frequency of inputs is irrelevant. Regardless of the value of the input, you're doing a single hash-compute and (barring hash collisions) a single bucket-lookup. Since dicts are unordered, the ordering of the literal (or of a set of statements adding to the dict) doesn't matter. Jeff Shannon Technician/Programmer Credit International From nino at nordman.org Tue Jan 11 06:39:41 2005 From: nino at nordman.org (Nils Nordman) Date: Tue, 11 Jan 2005 12:39:41 +0100 Subject: Checking for X availability In-Reply-To: References: Message-ID: <20050111113941.GA28570@resourcing.se> On Tue, Jan 11, 2005 at 03:32:01AM -0800, Flavio codeco coelho wrote: > So my question is: how can I check for the availability of X? i.e., > How will my program know if its running in a text only console or in > console window over X? Well, one way to do it is to check whether the environment variable DISPLAY is set (which it is when running under X, and should not be otherwise). Cheers, -- Nils Nordman From robby at planetargon.com Fri Jan 28 15:57:37 2005 From: robby at planetargon.com (Robby Russell) Date: Fri, 28 Jan 2005 12:57:37 -0800 Subject: Accessing Postgress from Windows In-Reply-To: <41FAA5E3.10008@novasyshealth.com> References: <41FAA5E3.10008@novasyshealth.com> Message-ID: <1106945857.17940.379.camel@linus> On Fri, 2005-01-28 at 14:51 -0600, Greg Lindstrom wrote: > Hello, All- > > I am running Python 2.3 on a Windows XP box and would like to access a > postgres database running on a Linux fileserver. I've googled for > Python and Postgres but most of the stuff I saw looked stale. I would > like to use a secure connection (ssl) and a direct connection, if > possible. What can you recommend for the task? > > Thanks...and see you all at PyCon! > --greg > You could try this mxODBC from Windows. http://www.egenix.com/files/python/mxODBC.html Cheers, Robby -- /*************************************** * Robby Russell | Owner.Developer.Geek * PLANET ARGON | www.planetargon.com * Portland, OR | robby at planetargon.com * 503.351.4730 | blog.planetargon.com * PHP/PostgreSQL Hosting & Development * --- Now hosting PostgreSQL 8.0! --- ****************************************/ From skip at pobox.com Fri Jan 7 14:32:03 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 7 Jan 2005 13:32:03 -0600 Subject: why not datetime.strptime() ? In-Reply-To: References: Message-ID: <16862.58291.925714.488870@montanaro.dyndns.org> josh> Shouldn't datetime have strptime? Sure, but it's not quite as trivial to implement as was strftime() support. While strftime() is a C library function and thus easily called from within the datetime C code, strptime() is implemented in Python as part of the time module for portability (strptime(3) is not universally available). You'd need to import the time module, call its strptime() function with the input string and format, then use the tuple it returns to initialize a new datetime object. If someone wants to get their feet wet with extension module programming this might be a good place to start. Mostly, I think nobody who has needed/wanted it so far has the round tuits available to spend on the task. Skip From roy at panix.com Thu Jan 13 20:12:37 2005 From: roy at panix.com (Roy Smith) Date: Thu, 13 Jan 2005 20:12:37 -0500 Subject: porting C code References: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> Message-ID: Lucas Raab wrote: > I am currently in the process of porting some C code into Python and am > stuck. I don't claim to be the greatest C/C++ programmer; in fact, my > skills at C are rudimentary at best. My question is I have the > statement: "typedef unsigned long int word32" and later on: "word32 > b[3]" referencing the third bit of the integer. Are you sure that's accessing the third bit? It looks to me like it's accessing index 3 (counting from 0) of an array of ints. > How do I do the same in Python?? In any case, if you're doing bit-fiddling in Python, you've got two basic sets of tools. First, the basic arithmetic operators. Boolean and (&), or (|), left-shift (<<) and right-shift (>>) operators work in Python just like they do in C. Integer constants starting with 0x are in hex, and the "%x" format specifier prints integers in hex. You can play all the normal C bit-operation tricks. To test bit 7, you can do "word & (0x1 << 7)". To set bit 4, use "word |= (0x1 << 4)". Second, the struct module (http://docs.python.org/lib/module-struct.html) is useful for packing and unpacking C structures written out into binary files. From bj_666 at gmx.net Tue Jan 4 15:57:46 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 04 Jan 2005 21:57:46 +0100 Subject: Pythonic search of list of dictionaries References: Message-ID: In , Bulba! wrote: > I put those dictionaries into the list: > > oldl=[x for x in orig] # where orig=csv.DictReader(ofile ... If you don't "do" anything with each `x` you can write this as: oldl = list(orig) Ciao, Marc 'BlackJack' Rintsch From http Sun Jan 2 19:02:13 2005 From: http (Paul Rubin) Date: 02 Jan 2005 16:02:13 -0800 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <7xd5wn8jne.fsf@ruckus.brouhaha.com> Roy Smith writes: > Around here, AOL/Moviephone has been trolling for years for Tcl people; > I guess that counts as a big company. The AOL web server also uses tcl as a built-in dynamic content generation language (i.e. sort of like mod_python), or at least it used to. From root at [127.0.0.1] Wed Jan 12 22:33:48 2005 From: root at [127.0.0.1] (scott) Date: Thu, 13 Jan 2005 13:33:48 +1000 Subject: Apache/mod_python & MySQLdb Message-ID: <1105587223.861674@chloe.intranet> AIUI, global variables are supposed to be preserved within each Apache thread/prcoess. However, I'm importing and using MySQLdb within a class in a separate module, which is in turn imported and used within a _function (ie. not "published"). So, AFAICT, it's not supposed to be preseved. But unless I specifically close() the database connection, it gets stranded and I eventually run out of connections, even if I del the connection and cursor objects. What gives? What happened to GC? Also, is there an easy way to run pychecker on mod_python scripts? It fails since _apache doesn't exist outside of Apache.... regards, Confused & tired of PHP. From newsgroups at jhrothjr.com Thu Jan 6 23:10:03 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 6 Jan 2005 22:10:03 -0600 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> Message-ID: <10ts2thq3mc3f3f@news.supernews.com> "David Brown" wrote in message news:10trb0mgiflcj4f at corp.supernews.com... > Hello. I recently came across a free operating system called Unununium (or > something like that) and it was developed in Python and Assembly. > > Now, I have been looking for a way to make an operating system for a long > long time and the only possibilities I could find were C++ and assembly. I > don't mind assembly so much if I don't have to use it very often. But C++ > is > so complicated and errors are pretty much impossible to find in the code > for > me. > > So, I was wondering if it would be possible to find a bootloader that > loads > a python file at startup or something... > > Is there an example somewhere of a Python OS? As far as I know, there's no working example. Unununium is still very early development, and it's going off in a quite interesting direction that is hardly standard. Writing an operating system is a lot of work. The approach I'd take would be to start out with an existing micro-kernel and enhance it with a kernel level Python system so that you wouldn't need any C or Asm level code in a typical process. Then I'd pursue a restricted subset of Python that could be compiled directly to machine code, and start recoding the various C and Asm parts in that. See the PyPy project for the direction they're taking for writing the Python system in Python. Have fun with the project! John Roth > > Thanks! > > From bvande at po-box.mcgill.ca Sat Jan 29 19:49:17 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat, 29 Jan 2005 19:49:17 -0500 Subject: naive doc question In-Reply-To: <5175a81c050129163826fcd734@mail.gmail.com> References: <5175a81c050129163826fcd734@mail.gmail.com> Message-ID: <41FC2F0C.8040300@po-box.mcgill.ca> Gabriel B. said unto the world upon 2005-01-29 19:38: > Is it just me that can't find a full reference in the docs? > > I wanted a list of all the methods of dict for example... where can > i find it? > > Thanks, and sorry if this question is just dumb, i really can't > find it It's just you ;-) Try the Library Reference, section 2.3.8 Mapping Types. (Perhaps confusing to a newcomer, but Pythons dicts are, as yet, its only standard mapping types, mapping being the general comp sci concept.) Best, Brian vdB From carribeiro at gmail.com Sat Jan 8 17:36:42 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 8 Jan 2005 20:36:42 -0200 Subject: "A Fundamental Turn Toward Concurrency in Software" In-Reply-To: References: <7x4qhs52rq.fsf@ruckus.brouhaha.com> Message-ID: <864d37090501081436d6dd9e6@mail.gmail.com> On Sat, 08 Jan 2005 11:52:03 -0800, aurora wrote: > One of the author's idea is many of today's main stream technology (like > OO) did not come about suddenly but has cumulated years of research before > becoming widely used. A lot of these ideas may not work or does not seems > to matter much today. But in 10 years we might be really glad that we have > tried. One thing that I would love to see included in Python is a native library for fast inter-process communication, including support for message passing primitives and remote object calls. I know that there are a number of offerings in this arena: third party libraries such as Pyro, message passing libraries such as the ones from ScyPy, and standard libraries such as the XMLRPC ones. The key requirements are: "fast", and "native". By fast, I mean, highly optimized, and at least as fast (in the same order of magnitude, let's say) as any other competitive environment available. By native, it means that it has to be included in the standard distribution, and has to be as transparent and convenient as possible. In other words, it has to feel like a native part of the language. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From daniel at bowettsolutions.com Thu Jan 13 17:43:06 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Thu, 13 Jan 2005 22:43:06 +0000 Subject: News Reader In-Reply-To: References: Message-ID: <41E6F97A.9010100@bowettsolutions.com> OK, ask a stupid question.... I wasn't aware I needed a Usenet account. It's simple when you know how. Peter Hansen wrote: > Robert Kern wrote: > >> Robert Kern wrote: >> >>> Daniel Bowett wrote: >>> >>>> Is anyone reading this list through thunderbird as news? If so - how >>>> did you set it up? >>> >>> >>> I subscribed to comp.lang.python under my USENET news server account. >> >> >> I guess I should add that that's all I did. There's nothing special to >> set up. > > > Having to add the news server by first selecting "File->New->Account" > might qualify as important enough to mention too. ;-) > > -Peter From michele.simionato at gmail.com Wed Jan 26 09:06:22 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 26 Jan 2005 06:06:22 -0800 Subject: FTP Server In-Reply-To: References: <1106743852.600769.72820@c13g2000cwb.googlegroups.com> <1106746068.798541.219240@c13g2000cwb.googlegroups.com> Message-ID: <1106748382.746575.52550@c13g2000cwb.googlegroups.com> Do you have a code snippet/pointer so I have an idea of how to use it? M.S. From lbates at syscononline.com Mon Jan 31 15:13:06 2005 From: lbates at syscononline.com (Larry Bates) Date: Mon, 31 Jan 2005 14:13:06 -0600 Subject: Description Field in WinXP Services In-Reply-To: References: <41fc0646$1_1@127.0.0.1> Message-ID: Roger, I wrote an extension to Mark Hammond's win32serviceutil.ServiceFramework class (that I submitted to him also) that extends the class to provide you with this functionality (along with the ability to support py2exe frozen services better). Here it is: import _winreg import os import win32evtlogutil class NTserviceBase: ''' Written by: Larry A. Bates - Syscon, Inc. March 2004 This is a base class for creating new NTservices with Python. It should be included when you are defining your class as follows: class newNTservice(win32serviceutil.ServiceFramework, NTserviceBase): # # Required attributes for a service # _svc_name_="newNTservice" _svc_display_name_="newNTservice" _svc_description_='newNTservice is a service that can be installed ' \ 'and 'run on any Windows NT, 2000, XP, 2003 ' \ 'computer. It can be controlled by services applet' \ 'in the Control Panel and will run unattended ' \ 'after being started.' def __init__(self, args): NTserviceBase.__init__(self) win32serviceutil.ServiceFramework.__init__(self, args) # # Create an event which we will use to wait on. # The "service stop" request will set this event. # self.hWaitStop=win32event.CreateEvent(None, 0, 0, None) return Note: the __init__ method of the created class should call the __init__ method of NTserviceBase AND win32serviceutil.ServiceFramework to get everything initialized properly ''' def __init__(self): #------------------------------------------------------------------- # Call function to set self.PythonService (0=binary, 1=Python) #------------------------------------------------------------------- self.getSERVICEtype() self.installpath=self.getSERVICEpath() #------------------------------------------------------------------- # Call function to set Service's long description string. Can't # seem to find a way to do this that works for both PythonServices # and binary (py2exe) services. So I will set the description # every time the service is started. #------------------------------------------------------------------- self.setSERVICEdescription() #------------------------------------------------------------------- # Call function to register eventlog message handler which is # different if I'm a binary vs. PythonService. #------------------------------------------------------------------- self.getPythonServicePath() #------------------------------------------------------------------- # If this is a PythonService, point to installed PythonService.exe # if not, point to a copy of PythonService.exe that gets installed # along with the binary. Note: on binary distributions you must # include a copy of PythonService.exe along with your other files # to provide EventLog message decoding. #------------------------------------------------------------------- if self.PythonService: sourcepath=self.PythonServicePath else: sourcepath=os.path.join(self.installpath, "PythonService.exe ") self.setSERVICEeventlogSource(sourcepath) return def getSERVICEtype(self): ''' Function to determine if this is a Python service or a binary service created by py2exe. Sets self.PythonService=1 if it is a Python service or PythonService=0 if it is a binary service. ''' #--------------------------------------------------------------------- # This service can run as a PythonService or it can run as a binary # .EXE service (created by py2exe). We can sense this by looking # to see if # HKLM\SYSTEM\CurrentControlSet\Services\_svc_name_\PythonClass # key exists in the registry. If it doesn't, then I'm a binary # install. #--------------------------------------------------------------------- # Open registry and search for PythonService install #--------------------------------------------------------------------- regkey='SYSTEM\CurrentControlSet\Services\%s' % self._svc_name_ key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, regkey) nsubkeys, nvalues, lastmodified=_winreg.QueryInfoKey(key) #--------------------------------------------------------------------- # Begin by assuming I'm a binary (non-Python) service created by py2exe #--------------------------------------------------------------------- self.PythonService=0 #--------------------------------------------------------------------- # Loop over the keys in this branch looking for "PythonService" key #--------------------------------------------------------------------- for i in range(nsubkeys): subkeyname=_winreg.EnumKey(key, i) if subkeyname == 'PythonClass': self.PythonService=1 break return def getSERVICEpath(self): ''' Function to retrieve the full pathname to where the service has been installed on the machine. This can be used to locate .INI or other data files (if this service uses any). ''' if self.PythonService: regkey='SYSTEM\CurrentControlSet\Services\%s\PythonClass' \ % self._svc_name_ value_name='' # Default else: regkey='SYSTEM\CurrentControlSet\Services\%s' % self._svc_name_ value_name="ImagePath" #--------------------------------------------------------------------- # Get the contents of the value_name value under this key. This # contains the full pathname where the service was installed and # points me to the .INI file. #--------------------------------------------------------------------- key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, regkey) SERVICEpath=_winreg.QueryValueEx(key, value_name)[0] #--------------------------------------------------------------------- # Extract the full pathname where this service has been installed from # this registry entry so I can locate the .INI file. #--------------------------------------------------------------------- SERVICEpath=str(os.path.split(SERVICEpath)[0]) return SERVICEpath def getPythonServicePath(self): ''' Function to retrieve the full pathname to where PythonService.exe has been installed on the machine (only used for Python Services, not binary ones). This can be used to locate PythonService.exe for EventLog message decoding. ''' self.PythonService=None regkey='SOFTWARE\Python\PythonService' try: key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, regkey) except: return #--------------------------------------------------------------------- # Get first subkeyname (Python Version) #--------------------------------------------------------------------- subkeyname=_winreg.EnumKey(key, 0) #--------------------------------------------------------------------- # Get the contents of the value_name value under this key. This # contains the full pathname where the PythonService.exe is installed. #--------------------------------------------------------------------- self.PythonServicePath=_winreg.QueryValue(key, subkeyname) return def setSERVICEdescription(self): ''' This function sets the long description string that is displayed in the Control Panel applet when this service is selected to the contents of self._svc_description_ defined at the top of the service. ''' #--------------------------------------------------------------------- # Open registry at the proper key #--------------------------------------------------------------------- regkey='SYSTEM\CurrentControlSet\Services\%s' % self._svc_name_ key=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, regkey, 0, \ _winreg.KEY_SET_VALUE) _winreg.SetValueEx(key, 'Description', 0, _winreg.REG_SZ, \ self._svc_description_) return def setSERVICEeventlogSource(self, sourcepath): ''' This function sets the path to PythonService.exe so that EventLog messages can be properly decoded. ''' win32evtlogutil.AddSourceToRegistry(self._svc_name_, sourcepath, 'Application') return Hope it helps, Larry Bates rbt wrote: > rbt wrote: > >> Roger Upole wrote: >> >>> ChangeServiceConfig2 is the api functions that sets the description, >>> but it's not in the win32service module (yet). >>> >>> Roger >> >> >> >> OK, I can use _winreg to add the 'Description' field under the >> appropriate registry key. > > > Here's an example of it... kludgey but it works ;) > > from _winreg import * > import time > > def Svc_Description(): > try: > key_location = r"SYSTEM\CurrentControlSet\Services\test_py_service" > svc_key = OpenKey(HKEY_LOCAL_MACHINE, key_location, 0, > KEY_ALL_ACCESS) > SetValueEx(svc_key,'Description',0,REG_SZ,u"Brad's Test Python > Service") > CloseKey(svc_key) > except Exception, e: > print e > > Svc_Description() > time.sleep(10) From whereU at now.com Wed Jan 19 01:53:10 2005 From: whereU at now.com (Eric Pederson) Date: Tue, 18 Jan 2005 22:53:10 -0800 Subject: File objects? - under the hood question In-Reply-To: <20050119034955.75129.qmail@web50306.mail.yahoo.com> References: <20050119034955.75129.qmail@web50306.mail.yahoo.com> Message-ID: <20050118225310.1939807216.whereU@now.com> I didn't come across any illuminating discussion via Google, thus my question here (though it may be a neophyte question.) I am interested in the workings under the hood of Python's access of "files". What is actually happening at the various stages when I create a file object and "read" it? (1) >>> f = file("C:/GuidosParrot.txt","r") (2) >>> hesjustsleeping = f.read() At (1) have I loaded the file from hard drive into RAM when I create the file object? What does this object know and how did it find it out? At (2) am I loading the file contents into RAM, or just assigning what is already in RAM to a variable? Where is the work split between the OS and Python? I assume the OS is responsible for "presenting" the file to Python, so perhaps the OS assembles this file from the blocks on disk and loads it into RAM at the time the file object is created? Or would the OS simply have pointers that can assemble the file, and pass those pointers to Python? Perhaps I've answered my question and the under-the-hood mechanics are handled on the OS side, and Python is just making requests of the OS... My brain-teaser: What I'd like to do is read the last ~2K of a large number of large files on arbitrary servers across the net, without having to read each file from the beginning (which would be slow and resource inefficient)... Eric Pederson http://www.songzilla.blogspot.com ::::::::::::::::::::::::::::::::::: domainNot="@something.com" domainIs=domainNot.replace("s","z") ePrefix="".join([chr(ord(x)+1) for x in "do"]) mailMeAt=ePrefix+domainIs ::::::::::::::::::::::::::::::::: From stephen.thorne at gmail.com Wed Jan 12 19:01:33 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 10:01:33 +1000 Subject: dict.updated In-Reply-To: <5GiFd.8571$Vj3.3354@newssvr17.news.prodigy.com> References: <5GiFd.8571$Vj3.3354@newssvr17.news.prodigy.com> Message-ID: <3e8ca5c805011216011c75e2c@mail.gmail.com> On Wed, 12 Jan 2005 23:47:13 GMT, Rick Morrison wrote: > I could live with creating a new dict, sure (although it seems wasteful). I > realize that something like this probably doesn't stand a chance of ever > making it into the std library for what might be called "philosophical" > reasons. I just want it for me (my personal philosophy runs more to the > pragmatic -- well at least for coding). > > I suppose the in-place version would be more along the lines of: > > >>> def updated(d, updates): > ... d.update(updates) > ... return d > ... > >>> [updated(d, {'c':3}) for d in [{'a':1, 'b':2}, {'x':10, 'y':'11'}]] > [{'a': 1, 'c': 3, 'b': 2}, {'y': '11', 'x': 10, 'c': 3}] > > But I'd like to put the "updated" method on the "dict" object, which is what > I can't seem to figure out. > Yeah I know that's "bad", but to my mind so is polluting the global > namespace with the "updated" function. [dict(d.items() + {'c':3}.items()) for d in [{'a':1, 'b':2}, {'x':10, 'y':'11'}]] seems logical enough to me.... > -- Or maybe I'm just lazy and picked up too many bad habits from > Javascript. probably. Stephen. From rnd at onego.ru Tue Jan 4 17:42:40 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 5 Jan 2005 01:42:40 +0300 (MSK) Subject: args (was Re: Lambda as declarative idiom (was RE: what is lambda used for in real code?)) In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> Message-ID: On Tue, 4 Jan 2005, Michael Spencer wrote: >Roman Suzi wrote: > >> Maybe this is too outlandish, but I see lambdas as a "quote" mechanism, >> which presents a possibility to postpone (precisely control, delegate) >> evaluation. That is, an ovehead for lambda must be much lower but at the >> same time visible to the programmer: >> >> d = a + (lambda x, y: x+ y)(3, 4) >[...] > >I believe that this "possibility to postpone" divides into two related but >separate concepts: controlling the moment of evaluation, and assembling the >arguments required at that moment. Yes. I have the same understanding. >They are both species of 'eval', but >managing arguments is more specialized, because it includes possibly renaming >parameters, assigning default values, processing positional and keyword >arguments, and, perhaps in the future dealing with argument types. Very precise! >Meanwhile, GvR wrote (about defining Interfaces in the context of Optional >Static Type Checking) As for GvR's writing, I think he is exploring the ground. What he wrote is too complex for Python and he guesses it is. There i another thread in c.l.p where I propose generic programming approach for Python's "type checking": IMHO, a much simpler and more natural for Python than programming by contract, just interfaces and such. And the syntactic way to express concepts is going thru declarations. That is why lambdas are to be on steroids for this task. More than that, compile vs. evaluation/parameter dispetching must not muddy the waters for programmer. It must always be clear (syntactically too) for him what is going on in the expression at hand. (But I do not know how this could be elegantly done sytactically) Is declaration-chewing engine built into Python an overkill? There are at least 2 specialized ones in it: parser and re.compile + many for different formats, like xml.dom. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From frans.englich at telia.com Wed Jan 26 17:14:40 2005 From: frans.englich at telia.com (Frans Englich) Date: Wed, 26 Jan 2005 22:14:40 +0000 Subject: Inherting from object. Or not. In-Reply-To: <1106774681.501533.156220@f14g2000cwb.googlegroups.com> References: <1106774681.501533.156220@f14g2000cwb.googlegroups.com> Message-ID: <200501262214.40597.frans.englich@telia.com> On Wednesday 26 January 2005 21:24, M.E.Farmer wrote: > Hello Frans, > What you are seeing is a step on the path to unification of types and > classes. I changed all base classes in my project to inherit object. There appears to be no reason to not do it, AFAICT. Thanks, Frans From grante at visi.com Wed Jan 26 17:15:23 2005 From: grante at visi.com (Grant Edwards) Date: 26 Jan 2005 22:15:23 GMT Subject: exclude binary files from os.walk References: Message-ID: <41f8167b$0$8648$a1866201@visi.com> On 2005-01-26, rbt wrote: > Is there an easy way to exclude binary files (I'm working on > Windows XP) from the file list returned by os.walk()? Sure, assuming you can provide a rigorous definition of 'binary files'. :) > Also, when reading files and you're unsure as to whether or > not they are ascii or binary, I've always thought it safer to > 'rb' on the read, is this correct... That depends on what you want. Adding a 'b' will disable the cr/lf handling. Not sure what else it does. > and if so, what's the reasoning behind this? Behind what? > Again all of this pertains to files on Windows XP and Python 2.4 -- Grant Edwards grante Yow! Now that I have my at "APPLE", I comprehend COST visi.com ACCOUNTING!! From premshree.pillai at gmail.com Tue Jan 18 08:44:18 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Tue, 18 Jan 2005 19:14:18 +0530 Subject: Employablity of python programmers In-Reply-To: <1105974549.835152.280590@z14g2000cwz.googlegroups.com> References: <1105974549.835152.280590@z14g2000cwz.googlegroups.com> Message-ID: Hi, I program in Python -- but not at work. There are very few opportunities for Python work in India. As of now, at least. (If somebody else has better information, please correct me.) A lot of people _do_ use Python, but not many organizations use it. Okay, as an aside, as a computer _science_ graduate, a programming language alone should not decide what career you choose. Nor should you choose a career based on the liking of a particular language alone. And I kinda don't understand this idea of "choosing what's best". How do you define "what is best"? I guess you should do what you like -- and not something that is "in demand". My 2 paisas. :) On 17 Jan 2005 07:09:09 -0800, Mir Nazim wrote: > Hi, > > Here I am once again to give a bit trouble. > > I am at the verge of completing my graduation in computer sciences. I > will be graduating within 6-8 months. Now I am faced with the problems > of my career. I am in a fix what skill set I must choose to be safe as > far as job openings are concerned. I understand that skill set should > be that one like most but job is also important. I will try to achieve > a balance in both with the help of you advice. > > I am currently developing in PHP as a freelance web developer. But I > want to move to python(for all it all cool reasons discussed a zillion > times on c.l.py) and wanted to know the job oportunites available to a > python programmer(I know these have been also discussed a zillion time > here but still..). I am living in India and would like to know about > employability of python programmers in India (I know that a few Indians > frequent c.l.py. Hello Sridhar, where are you). > > I would also like to know that if the knowledge of any other language > will boost employability of a python programmer. As far as I see it, > the following combination are desirable. > > 1) C/C++ and Python. > 2) Java and Python. > 3) Pure Python. > > Out of the three Java along with python seems to be straight forward > choice as far as employability is concerned. But I would like to know > the benifits which one is a better career choice to take out of these > three choices(other suggestions are welcome). For me choice three would > be better, not because I have only one language to learn. If I choose > choice three I could spend more time in learning different approaches > to develop the application and better master the library and frameworks > avaialble for python. > > So what are the recomendations from your side. Please help. > Thanks > --- > Mir Nazim. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From timr at probo.com Sat Jan 15 03:02:41 2005 From: timr at probo.com (Tim Roberts) Date: Sat, 15 Jan 2005 00:02:41 -0800 Subject: Threading Or Other Suggestions?!? References: Message-ID: <5fjhu0ls0dhue317jif73r824p7dem0ak8@4ax.com> andrea.gavana at agip.it wrote: > > I have a wxPython application that does a lot of things. One of them, >in particular, I have doubts on how to implement it. Essentially, this part >of my application calls an external executable (an oil reservoir >simulator). What I would like to do, is to give the user the possibility to >run more than 1 simulation at the same time. This means: > >1) Writing the executable "data file" needed by the simulator >2) Run the executable file (and wait until completion) >3) Examine the simulation results > >For this, I was thinking about threads... does anyone have other/better >suggestion(s)? Does anyone see any difficulty/memory problems in using >threads? Yes. Threads are used to run multiple parts of your own program. To run another program, you need to launch a new process. You can still monitor it. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mhoffman at lightlink.com Sat Jan 22 17:58:05 2005 From: mhoffman at lightlink.com (Mark M. Hoffman) Date: Sat, 22 Jan 2005 17:58:05 -0500 Subject: RFC: Python bindings to Linux i2c-dev Message-ID: <20050122225805.GA20351@jupiter.solarsys.private> Hi everyone: I've created a Python extension in C for the Linux i2c-dev interface. As this is my first attempt at extending Python, I would appreciate any comments or suggestions. I'm especially interested to know if (and where) I got any of the ref-counting wrong. But I'm also interested in comments about the style, the interface, or whatever else. You can find my source code here [1]. If you actually want to build/install/use this thing, you better read the caveats here [2]. And in case you're interested, here is a page full of links to info on I2C/SMBus [3]. [1] http://members.dca.net/mhoffman/sensors/python/20050122/ [2] http://archives.andrew.net.au/lm-sensors/msg28792.html [3] http://www2.lm-sensors.nu/~lm78/cvs/lm_sensors2/doc/useful_addresses.html Thanks and regards, -- Mark M. Hoffman mhoffman at lightlink.com From steve at holdenweb.com Mon Jan 24 11:34:45 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 24 Jan 2005 11:34:45 -0500 Subject: Import from database Message-ID: I'm trying to load module code from a database, which stores for each module its full name, code, load date and a Boolean indicating whether it's a package or not. The following simple program: import dbimp, sys if __name__ == "__main__": dbimp.install() #import bsddb.db import a.b.c.d import bsddb gives a traceback from its last line. The whole output is $ python -i test.py Accepted *db* found a in db load_module: a a loaded: pkg: 1 found a.b in db load_module: a.b a.b loaded: pkg: 1 found a.b.c in db load_module: a.b.c a.b.c loaded: pkg: 1 found a.b.c.d in db load_module: a.b.c.d a.b.c.d loaded: pkg: 0 found bsddb in db load_module: bsddb found weakref in db load_module: weakref weakref loaded: pkg: 0 Traceback (most recent call last): File "test.py", line 7, in ? import bsddb File "/c/steve/Projects/Python/dbimp/dbimp.py", line 49, in load_module exec code in module.__dict__ File "db:bsddb", line 62, in ? File "/usr/lib/python2.4/os.py", line 133, in ? from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep, ImportError: No module named path >>> It appears that for some reason execution of the code in bsddb/__init__.pyc (loaded from the database using my importer) is causing the os module to execute again although it has already run and been cached in sys.modules. Any explanations would be welcome. The importer module is shown below (a posting with an attachment to avoid code folding didn't appear to make it out) Also if someone can suggest how associate the source file with module/package code from the database that would make tracebacks look more conventional, though I'd like to retain the indication the module was loaded by dbimp somehow. # # Import modules from a database # import sys, db, marshal, imp, new conn = db.conn() curs = conn.cursor() curs.execute("select modName from module") impdict = {} for n in [x[0] for x in curs.fetchall()]: impdict[n] = 1 class dbimporter(object): def __init__(self, item, *args, **kw): if item != "*db*": raise ImportError print "Accepted", item def find_module(self, fullname, path=None): #print "find_module:", fullname, "from", path if fullname not in impdict: #print "Bailed on", fullname return None else: print "found", fullname, "in db" return self def load_module(self, modname): print "load_module:", modname if modname in sys.modules: return sys.modules[modname] curs.execute("select modCode, modPackage from module where modName=%s", (modname, )) row = curs.fetchone() # should only BE one ...S if not row: #print modname, "not found in db" raise ImportError, "DB module %s not found in modules" code, package = row code = marshal.loads(code) module = new.module(modname) sys.modules[modname] = module module.__name__ = modname exec code in module.__dict__ module.__file__ = "db:%s" % modname module.__loader__ = dbimporter if package: module.__path__ = sys.path exec code in module.__dict__ print modname, "loaded:", repr(module), "pkg:", package return module def install(): sys.path_hooks.append(dbimporter) sys.path_importer_cache.clear() # probably not necessary sys.path.insert(0, "*db*") # probably not needed with a metea-path hook? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From ianb at colorstudy.com Tue Jan 4 16:59:55 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Tue, 04 Jan 2005 15:59:55 -0600 Subject: Python evolution: Unease In-Reply-To: References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> Message-ID: <41DB11DB.4090805@colorstudy.com> Roman Suzi wrote: >>The term "generic programming" is too... er... generic. :) > > > Nope. It is not generic. It has it's definition made by the co-author > of STL - A.Stepanov. And the Boost C++ library (many of us know it as > Boost Python) standardise on the approach, AFAIK. > > >>As you know, Python >>already includes a _lot_ of support for generic programming (a function that >>iterates over a sequence can easily process a list, or a string, or a tuple as >>input; a function that takes a file-like object can often work just as will with >>a true file object or a cStringIO object; etc.). So when you bring up "generic >>programming", it's too easy to dismiss the comment because (1) it's too vague >>and (2) Python already does a lot of it. >> >>So, what is your term for the type of generic programming that Python doesn't >>yet support? Interfaces? Protocols? Adapters? Metatype hierarchies? > > > Python could have honest support of concepts. Everything else will be > available with them. Umm... this isn't helpful. "Generic" and "concept" are not terms that belong to Boost or STL or whatever. They are just words. Coining the term doesn't mean anyone else knows what it means, nor that anyone *should* know what they mean -- personally I get very suspicious of ideas that are based on redefined words, that tends to be a way of hiding complexity or fuzziness. But anyway, if you use these terms, you really must provide references, otherwise no one will know what you mean. "Python could have honest support of concepts" is simply an incomplete sentence. "Python could have honest support of Concepts (url)" would be more reasonable. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From ajsiegel at optonline.com Tue Jan 25 07:45:47 2005 From: ajsiegel at optonline.com (Arthur) Date: Tue, 25 Jan 2005 07:45:47 -0500 Subject: Another scripting language implemented into Python itself? References: Message-ID: On Mon, 24 Jan 2005 19:40:31 -0500, Roy Smith wrote: >In article , > Quest Master wrote: > > >Python *is* a scripting language. Why not just let your users write >Python modules which you them import and execute via some defined API? This is the tact I take with PyGeo. The burden is on myself, as the API designer and documenter to make it as accessible as I might want it to be. And I think I can accomplish that without building in crippling limitations as to what depth a "scripter" might want to explore - even to the extent of extending the API itself. I guess its a matter of the audience one hopes to reach. There are a number of other dynamic geometry applications out there. Despite my own interest in the subject, it was precisely the limitations their API, whether GUI based or otherwise, that led me to the explorations that is becoming PyGeo. It was the limitaions in exploring *geometry* to which I refer. Having no per se interest in programming, I would not impose the assumption of such an interest on my users. I guess I hope to reach others like myself. With no particular interest in programming, per se. Just with what you can get do with it. Art From skip at pobox.com Fri Jan 14 22:49:50 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 14 Jan 2005 21:49:50 -0600 Subject: Why 'r' mode anyway? In-Reply-To: <1f7befae0501141613545a30cd@mail.gmail.com> References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> <41e80785$0$6203$e4fe514c@news.xs4all.nl> <41e827df$0$6219$e4fe514c@news.xs4all.nl> <1f7befae0501141613545a30cd@mail.gmail.com> Message-ID: <16872.37598.662485.896493@montanaro.dyndns.org> Tim> "Plays well with others" was a strong motivator for Python's Tim> design, and that often means playing by others' rules. -- My vote for QOTW... Is it too late to slip it into the Zen of Python? Skip From jacek.generowicz at cern.ch Fri Jan 7 11:38:56 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 07 Jan 2005 17:38:56 +0100 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> Message-ID: Nick Coghlan writes: > Jacek Generowicz wrote: > > [*] Funnily enough, getting them to understand that "lambda x: fn(x)" > > is just a very silly way of writing "fn", can be quite a struggle > > at times ... but that's probably a consequence of the context in > > which lambda is introduced. > > If you genuinely taught them that, you may have done them a disservice: Yes, I was wondering whether I should add lots of caveats to the above. > Py> def f(x): > ... print x > ... > Py> f1 = f > Py> f2 = lambda x: f(x) > Py> f1("hi") > hi > Py> f2("hi") > hi > Py> def f(x): > ... print x * 2 > ... > Py> f1("hi") > hi > Py> f2("hi") > hihi There are far less contrived situations in which my original statement (taken at face value) is wrong. Functions with optional arguments, for example. What actually happens is that some of them end up writing: lambda x: int(x) in a situation where they want to specify something which will perform conversions of the type: "123" -> 123 ie, string to integer conversions. Usually one or two have trouble grasping that "int" would be perfectly adequate in this situation. From danperl at rogers.com Thu Jan 27 23:08:15 2005 From: danperl at rogers.com (Dan Perl) Date: Thu, 27 Jan 2005 23:08:15 -0500 Subject: Talking to the wind References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com><1106875259.426213.252030@z14g2000cwz.googlegroups.com> Message-ID: <3eSdnZWnTLApJ2TcRVn-rQ@rogers.com> "Terry Reedy" wrote in message news:mailman.1481.1106882832.22381.python-list at python.org... > > Hey all, I have seen no evidence that XL even reads the responses that > have been directed thereto. The above is like > > /dev/null, > Why don't you ever answer the messages I keep sending to you? > > Terry J. Reedy According to his own website, he suspects himself of having a schizoid personality. This is how Britannica Online describes "schizoid": "In this disorder there is a disinclination to mix with others, the individual appearing aloof, withdrawn, indifferent, unresponsive, and disinterested. Such a person prefers solitary to gregarious pursuits, involvement with things rather than with people, and often appears humourless or dull." Does that explain things for you? I really think that nothing we say gets through to him. Dan From asda at sdarta.com Wed Jan 5 21:41:57 2005 From: asda at sdarta.com (worzel) Date: Thu, 6 Jan 2005 10:41:57 +0800 Subject: is python more popular than coldfusion? References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41dca575$0$14347$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Thanks for all the feedback guys. It seems CF is not really a big money earner or even recognised as a serious language to many folk. by the way, does anybody want to buy any coldfusion books :) (I just bought O'Reileys 'Learning Python' - its extremely readable and very thorough) "worzel" wrote in message news:41dbd699$0$23092$5a62ac22 at per-qv1-newsreader-01.iinet.net.au... is python more popular than coldfusion? I realsie that is a very general question as one thing does not directly relate to the other. My issue is that I am ditching coldfusion due to there being next to no work for it, and I am thinking of taking on python as a second language to java in the hope of improving my resume. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Wed Jan 26 18:54:09 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 16:54:09 -0700 Subject: Classical FP problem in python : Hamming problem In-Reply-To: References: <63b5e209.0501210558.686f5c10@posting.google.com> <6PKdnVpD-4f3CGvcRVn-gQ@comcast.com> Message-ID: Francis Girard wrote: > For the imerge function, what we really need to make the formulation clear is > a way to look at the next element of an iteratable without consuming it. Or > else, a way to put back "consumed" elements in the front an iteration flow, > much like the list constructors in FP languages like Haskell. > > It is simple to encapsulate an iterator inside another iterator class that > would do just that. Here's one. The additional "fst" method returns the next > element to consume without consuming it and the "isBottom" checks if there is > something left to consume from the iteration flow, without actually consuming > anything. I named the class "IteratorDeiterator" for lack of imagination : > [snip] Another implementation is my peekable class: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304373 It allows you to peek several elements ahead if that's necessary. Steve From jicman at cinops.xerox.com Mon Jan 31 19:23:35 2005 From: jicman at cinops.xerox.com (jose isaias cabrera) Date: Mon, 31 Jan 2005 19:23:35 -0500 Subject: Java Integer.ParseInt translation to python Message-ID: <008d01c507f4$451d9b30$2820790d@stso.xcdg.xerox.com> Greetings! I've looked through the internet (not long, though) but I have not been able to find a python translation to buffer[0] = (byte)Integer.parseInt(string,16); Has anyone ported any java programs to python and has translated this? any help would be greatly appreciated. thanks. jos? From adsr at poczta.onet.pl Fri Jan 7 13:58:08 2005 From: adsr at poczta.onet.pl (AdSR) Date: Fri, 07 Jan 2005 19:58:08 +0100 Subject: Working with recordsets In-Reply-To: <1105119853.927871.293390@z14g2000cwz.googlegroups.com> References: <1105119853.927871.293390@z14g2000cwz.googlegroups.com> Message-ID: chema.rey at gmail.com wrote: > Hi. > > I have one recorset that I would like to pass to 2 functions, one is > for create an CSV file and the other one is to create a HTML file. The > problem is that the recordset is totally read in the first function, > and then when I pass it to the second funtion the recordset is in the > last record. > > I've read docs, but I think that one cursor doesn't have something > like movefirst() method. Anybody have an idea to solve this? > > Thank's. > Try loading the whole recordset with the fetchall() method and use the resulting sequence in your functions. It won't be memory-efficient but it will be easy to do. AdSR From newsgroups at jhrothjr.com Thu Jan 20 13:03:43 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 20 Jan 2005 12:03:43 -0600 Subject: QOTW from Ryan Tomayko References: Message-ID: <10uvskttdbqrba0@news.supernews.com> "Robert Brewer" wrote in message news:mailman.957.1106239771.22381.python-list at python.org... http://naeblis.cx/rtomayko/2005/01/20/getters-setters-fuxors "...Many people coming to Python can't believe no one uses IDEs. The automatic assumption is that Python is for old grey beards who are comfortable with vi and Emacs and refuse to accept breakthroughs in programming productivity like IDEs. Then they write a little Python code and realize that an IDE would just get in their way." FuManChu [response] It's also not true. Lots of people use IDEs - look at the number of Python IDEs out there, and the number of attempts (some of them reasonable) to add Python support to Eclipse. The thing is, there are relatively fewer programming tools needed to work with Python than there are for Java, for example, so the available IDEs are much simpler. Line oriented editors are an acquired taste, and they are one I've never acquired regardless of the environment. I've used both edit under TSO and vi on a timesharing arrangement with an AIX system, and both of them suck compared to the screen editors available. John Roth From kst-u at mib.org Fri Jan 28 19:06:39 2005 From: kst-u at mib.org (Keith Thompson) Date: Sat, 29 Jan 2005 00:06:39 GMT Subject: what's OOP's jargons and complexities? References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> Message-ID: "Xah Lee" writes: [snip] If you must post a followup to this, please drop comp.lang.c from the newsgroups header. I can't speak for the other newsgroups, but it's definitely off-topic here in comp.lang.c. Thank you. -- Keith Thompson (The_Other_Keith) kst-u at mib.org San Diego Supercomputer Center <*> We must do something. This is something. Therefore, we must do this. From fccoelho at gmail.com Fri Jan 21 11:31:02 2005 From: fccoelho at gmail.com (Flavio codeco coelho) Date: 21 Jan 2005 08:31:02 -0800 Subject: circular iteration Message-ID: hi, is there a faster way to build a circular iterator in python that by doing this: c=['r','g','b','c','m','y','k'] for i in range(30): print c[i%len(c)] thanks, Fl?vio From flamesrock at gmail.com Mon Jan 3 20:36:46 2005 From: flamesrock at gmail.com (flamesrock) Date: 3 Jan 2005 17:36:46 -0800 Subject: Howto Extract PNG from binary file @ 0x80? In-Reply-To: References: <1102753727.706459.105920@f14g2000cwb.googlegroups.com> <1104797038.407042.32580@z14g2000cwz.googlegroups.com> Message-ID: <1104802606.806575.178870@c13g2000cwb.googlegroups.com> Hmm...I'm not sure exactly. One of the things I've read is that sometimes stuff is compressed in a savegame file, but I don't know why they'd do that with a png.. I have some code that does the exact same thing in php only I don't understand php syntax and how they did it. Does it give any clues as to whether its truncated or not? (assuming you understand php) http://simcitysphere.com/sc4Extractor.php.txt (original, only extracts png) http://simcitysphere.com/regionFileDecode_inc.php.txt (extracts png and some fancy stuff like image map position) -thanks From ggg at zzz.it Thu Jan 20 08:43:01 2005 From: ggg at zzz.it (deelan) Date: Thu, 20 Jan 2005 14:43:01 +0100 Subject: Problem in importing MySQLdb In-Reply-To: References: Message-ID: <6ogosc.9uv.ln@news1.interplanet.it> Gurpreet Sachdeva wrote: > I am using Mysql version 5.0.2-alpha on RedHat 9.0 (python2.2) > > When I try to import MySQldb i' not completely sure mysqldb works with mysql 5.0 and its bundled client libraries. to be more precise: '' MySQL-5.0 and newer are not currently supported, but might work.'' from: > Is there any problem in library files?? Do I need to install anything > I have installed MySQL-shared-3.23.54a-1.i386.rpm, > MySQL-devel-5.0.2-0.i386.rpm, MySQL-client-5.0.2-0.i386.rpm, > MySQL-server-5.0.2-0.i386.rpm are u sure you have compiled mysqldb against 5.0 client libs? you may want to post on the mysqldb forum of ask for help there: HTH, deelan -- @prefix foaf: . <#me> a foaf:Person ; foaf:nick "deelan" ; foaf:weblog . From saint_infidel at hotmail.com Wed Jan 19 14:54:18 2005 From: saint_infidel at hotmail.com (infidel) Date: 19 Jan 2005 11:54:18 -0800 Subject: delay and force in Python References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> Message-ID: <1106164457.982053.214970@f14g2000cwb.googlegroups.com> It took me a while to figure out what the "translated" code was trying to do. Here's a quick example that I think accomplishes the same thing: >>> for i, n in enumerate(x for x in xrange(998) if x % 2 == 0): ... if i == 1: ... print n ... 2 From http Fri Jan 7 16:25:45 2005 From: http (Paul Rubin) Date: 07 Jan 2005 13:25:45 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> Message-ID: <7xr7kx0w4m.fsf@ruckus.brouhaha.com> mike at hobbshouse.org (Michael Hobbs) writes: > The problem when using Python instead of C for OS development is that > C was *specifically designed* to create an OS, while Python was designed > for completely different purposes. If you want to write an OS, it would > be wise to use a language that is suited for that purpose. If you > dislike C so much and prefer Python so much more, your first step should > be to design a Python dialect that is more appropriate for writing OS's. But I thought Python was an all-purpose language. After all, OS's have been written in Lisp before too. From tjreedy at udel.edu Wed Jan 26 14:08:43 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Jan 2005 14:08:43 -0500 Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com><1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106723545.429728.308620@f14g2000cwb.googlegroups.com> Message-ID: Xah the arrogant wrote, among other things, # one can change data inside the class x.i = 400 # one can also add new data to the class x.j=4 print x.j # or even override a method x.square = 333 # (the following line will no longer work) # print "3 squared is:", x.square(3) # in Python, one must be careful not to # overwrite data or methods defined in a # class. -------------- However, there are several errors in the above that would mislead a Python learner. I advise any such to ignore Xah's writings. Terry J. Reedy From tim.peters at gmail.com Fri Jan 14 11:17:54 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 14 Jan 2005 11:17:54 -0500 Subject: Writing huge Sets() to disk In-Reply-To: <41E7EF70.1020505@ribosome.natur.cuni.cz> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> <41E2E69C.7080104@ribosome.natur.cuni.cz> <1f7befae0501101245679b26f2@mail.gmail.com> <41E7EF70.1020505@ribosome.natur.cuni.cz> Message-ID: <1f7befae05011408173df5ec96@mail.gmail.com> [Martin MOKREJ?] > This comm(1) approach doesn't work for me. It somehow fails to > detect common entries when the offset is too big. > > file 1: > > A > F > G > I > K > M > N > R > V > AA > AI > FG > FR > GF > GI > GR > IG > IK > IN > IV > KI > MA > NG > RA > RI > VF > AIK > FGR > FRA > GFG > GIN > GRI > IGI > IGR > IKI > ING > IVF > KIG > MAI > NGF > RAA > RIG > > file 2: > > W > W > W > W > W > W > W > W > W > W > AA > AI > FG > FR > GF > GI > GR > IG > IK > IN > IV > KI > MA > NG > RA > RI > VF > AAAAA > AAAAA > AAAAA > AAAAA > AAAAA > AAAAA > AAAAA > AAAAA > AAAAA > AAAAA > AAAAA > AAAAA I'll repeat: >> As I mentioned before, if you store keys in sorted text files ... Those files aren't in sorted order, so of course `comm` can't do anything useful with them. Do `man sort`; sorting is not optional here. From newsgroups at jhrothjr.com Thu Jan 13 11:26:37 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Thu, 13 Jan 2005 10:26:37 -0600 Subject: dynamically inserting function into an object References: Message-ID: <10ud8anie9e3sbd@news.supernews.com> If what you want is to insert a method into an instance, look at new.instancemethod. John Roth "michael" wrote in message news:f11c8440.0501130808.6c50a62b at posting.google.com... > Hi, > > below is a snipplet that could be seen as a part of a spreadsheet with > getter and setter properties and a way how to dynamically insert > function to be used when setting the value of a "cell" instance > > > import new > import inspect > > class Cell (object): > > def __init__ (self, initialvalue = 0): > self._func = None > self.__value = initialvalue > > def setvalue (self, newvalue): > if self._func: > self.__value = self._recalculate (newvalue) > else: > self.__value = newvalue > > def getvalue (self): > return self.__value > > def _recalculate (self, value): > > ret_value = self._func (value) > > return ret_value > > def delvalue (self): > del self.__value > > > value = property(getvalue, setvalue, delvalue, "I'm the 'value' > property.") > > def curry(self, func, *args): > self._func = new.function(func.func_code, func.func_globals, > argdefs=args) > > func = property(curry, "I'm the 'func' property.") > > def func (value, firstcell, secondcell): > return value + firstcell.value + secondcell.value > > cell0 = Cell (10) > cell1 = Cell (20) > > curriedcell = Cell (100) > > print "uncurried initial %d " % (curriedcell.value) > > curriedcell.value = 60 > > print "uncurried set %d " % (curriedcell.value) > > curriedcell.curry (func, cell0, cell1) > curriedcell.value = 62 > > print "curried set %d " % (curriedcell.value) > > > > Is there a better way to do this or am I totally on the wrong way ? > > Regards > > Michael From holbertr at dma.org Mon Jan 10 11:34:40 2005 From: holbertr at dma.org (Rick Holbert) Date: Mon, 10 Jan 2005 11:34:40 -0500 Subject: pulling info from website References: <41e2a556$0$14576$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: Bob, Have a look at feedparser: http://www.feedparser.org/ http://diveintomark.org/projects/feed_parser/ For bbc news feeds, I use the following url: http://www.bbc.co.uk/syndication/feeds/news/ukfs_news/front_page/rss091.xml bob wrote: > i am trying to write a script for Xbox media center that will pull > information from the bbc news website and display the headlines , how do i > pull this info into a list??? From nelson at monkey.org Sun Jan 2 10:57:22 2005 From: nelson at monkey.org (Nelson Minar) Date: Sun, 02 Jan 2005 15:57:22 GMT Subject: Python! Is! Truly! Amazing! References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: "Erik Bethke" writes: > I have NEVER experienced this kind of programming joy. Yep, I feel the same way since learning Python. It's really a productive and pleasant language. Congratulations on all your game successes! From tjreedy at udel.edu Wed Jan 26 02:05:58 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Jan 2005 02:05:58 -0500 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com><1106694083.199064.240680@f14g2000cwb.googlegroups.com><41f6f4ee$1@nntp.zianet.com> <1106718853.867328.55760@z14g2000cwz.googlegroups.com> Message-ID: Davor, Before I learned Python, I too was put off by OO hype. And I suppose I still would be if I still listened to it. But Python's class statement is somewhere inbetween a C typedef and C++/Jave classes. Stripped down pretty much to the essentials and only used when really useful, it made more sense to me. If you start a project in Python and enlist other competant Pythoneers, they most likely will not be OO fanatics. Simply tell prospective partners that you prefer structured procedural programming to user-written object classes everywhere. An OO afionado will realise that yours is not the project to join. I think you should perhaps read and write more Python code before making a decision. Do note that methods within a class are functions first and benefit from good procedural-code-writing ability. Terry J. Reedy From steven.bethard at gmail.com Sat Jan 1 17:34:14 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 01 Jan 2005 22:34:14 GMT Subject: UserDict deprecated In-Reply-To: References: Message-ID: Uwe Mayer wrote: > Saturday 01 January 2005 22:48 pm Hans Nowak wrote: >>I am curious, what would you do with a class that derives from both file >>and dict? > > I was writing a class that read /writes some binary file format. I > implemented the functions from the file interface such that they are > refering to records. However, the file format has some header fields and > I'd wanted to grant access to those via the dict-interface. If you implemented the file interface functions yourself, why do you want to inherit from file? > Another example: working with PyQt I have an instance of a QListView and > wanted to use the list-interface to get and set individual records. But just inheriting from list won't make this work, will it? Don't you want to do something like: class C(QListView): def __getitem__(self, i): return self.getIndividualRecord(i) # or whatever method gives # you the record Steve From fredrik at pythonware.com Thu Jan 27 15:47:18 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 27 Jan 2005 21:47:18 +0100 Subject: Question about 'None' References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> <200501272106.22291.francis.girard@free.fr> Message-ID: Francis Girard wrote: > Wow ! What is it that are compared ? I think it's the references (i.e. the > adresses) that are compared. The "None" reference may map to the physical 0x0 > adress whereas 100 is internally interpreted as an object for which the > reference (i.e. address) exists and therefore greater than 0x0. > > Am I interpreting correctly ? your hypothesis might match the observations, but it doesn't match the implementation. nor the documentation: " ... objects of different types always compare unequal, and are ordered consistently but arbitrarily." (see my others posts in this thread for more details) From g.horvath at gmx.at Tue Jan 4 10:46:31 2005 From: g.horvath at gmx.at (Gregor Horvath) Date: Tue, 04 Jan 2005 15:46:31 GMT Subject: Reaching the real world In-Reply-To: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> References: <1104850540.610295.152240@f14g2000cwb.googlegroups.com> Message-ID: Hi, I have just written a python module to program the M232 measurement unit from elv. It has 8 digital I/O and 6 analog ports (0-5V). Works fine, although it is a little bit slow (0,2 s to measure) Furthermore the digital ports do not have enough power to switch a relay directly, I had to do it with additional transistors. It controls my heating together with a python program an a eletric motor / gearbox and some sensors. german store: http://www.elv.de/ Type M232 into the search field. english: http://www.elv.de/shopping/elvcom/ If you are intersted in the python code, just drop a note. -- Greg Fuzzyman wrote: > I have a friend who would like to move and program lights and other > electric/electro-mechanical devices by computer. I would like to help - > and needless to say Python would be an ideal language for the > 'programmers interface'. > > What I'd like is an electronic interface that connects to several > relays and a python extension module to switch on and off the relays. > I've had a quick google and can't see anything too similar to what I > want. pyro (python robotics) seems to require expensive (relatively) > robotic equipment. > > Does anyone know anything *similar* to what I have in mind, or have > alternative suggestions ? > Regards, > > Fuzzy > http://www.voidspace.org.uk/python/index.shtml > From rkern at ucsd.edu Tue Jan 25 04:22:04 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 25 Jan 2005 01:22:04 -0800 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <7x1xchlpqv.fsf@ruckus.brouhaha.com><41efeb82$0$27807$9b622d9e@news.freenet.de><41f1a70b$0$25959$9b622d9e@news.freenet.de><7xekgdmpll.fsf@ruckus.brouhaha.com><7xpszxcnfa.fsf@ruckus.brouhaha.com><7xllalcmqc.fsf@ruckus.brouhaha.com><7xbrbhosh7.fsf@ruckus.brouhaha.com><7xzmz0lw6h.fsf@ruckus.brouhaha.com><41f4324a$0$1547$9b622d9e@news.freenet.de><41f589f9$0$3357$9b622d9e@news.freenet.de><1106615822.2400.122.camel@l Message-ID: Fredrik Lundh wrote: > wrote: > > >>The likely-best-known Python application in the world (probably more >>people have heard of it than have heard of Python) originally had >>crypto > > > and what Python application is that? I can think of quite a few applications > written in Python that are widely known, but none of these are distributed as > Python code to end users. BitTorrent, probably. I believe that a very high percentage of users get the BitTorrent apps as standalone executables, not as a Python package where one has to go download Python first. The ones that do get it as Python source probably get it from their Linux/FreeBSD/other distribution where such dependencies are also taken care of for them. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From club4_2 at mail.ru Sat Jan 29 21:20:16 2005 From: club4_2 at mail.ru (Club-B42) Date: Sun, 30 Jan 2005 12:20:16 +1000 Subject: [Tkinter] problem Message-ID: when i start opt_newlogin.py directly it works fine(outputs '1 1 1 1'), but if i start it from options.py there is an error(outputs ''). ======== opt_newlogin.py ======== from config import * from Tkinter import * from opt_newlogin import newlogin def OptionsWindow(): """ """ root = Tk() root.title(msg_OptionsWindowTitle) b1 = Button(root, text = msgForgotPassword, width = 40).grid(padx = 5, pady = 5, column = 0, row = 0) b2 = Button(root, text = msgNewLogin, command = newlogin, width = 40).grid(padx = 5, pady = 5, column = 0, row = 1) root.mainloop() if __name__ == '__main__': OptionsWindow() ======== ======== options.py ======== from config import * from Tkinter import * import tkMessageBox, os.path def create_new_account(login, password, secretq, secreta): print login, password, secretq, secreta if os.path.exists(os.path.join(data_path, login)): tkMessageBox.showerror(title = msgError, message = msgPasswordLoginExists) elif login == '': pass else: os.mkdir(os.path.join(data_path, login)) fd = file(os.path.join(data_path, login, data_info_file_name), 'wb') fd.write(password + os.linesep) fd.write(secretq + os.linesep) fd.write(secreta + os.linesep) fd.close() tkMessageBox.showinfo(title = msgInfoAccountCreated, message = msgInfoAccountCreated2) def newlogin(): """ """ root = Tk() root.title(msg_NewLoginWindowTitle) l1 = Label(root, text = msgLogin).grid(padx = 5, pady = 5, column = 0, row = 0, sticky = E) l2 = Label(root, text = msgPassword).grid(padx = 5, pady = 5, column = 0, row = 1, sticky = E) l3 = Label(root, text = msgConfirmPassword).grid(padx = 5, pady = 5, column = 0, row = 2, sticky = E) l4 = Message(root, text = msgKeyQuestion, width = 250).grid(padx = 5, pady = 5, column = 0, row = 3, sticky = E) l5 = Label(root, text = msgKeyQuestionAnswer).grid(padx = 5, pady = 5, column = 0, row = 4, sticky = E) v1 = StringVar() v2 = StringVar() v3 = StringVar() v4 = StringVar() v5 = StringVar() e1 = Entry(root, width = 50, textvariable = v1) e1.grid(padx = 5, pady = 5, column = 1, row = 0) e1.focus_force() e2 = Entry(root, width = 50, textvariable = v2, show = '*') e2.grid(padx = 5, pady = 5, column = 1, row = 1) e3 = Entry(root, width = 50, textvariable = v3, show = '*') e3.grid(padx = 5, pady = 5, column = 1, row = 2) e4 = Entry(root, width = 50, textvariable = v4) e4.grid(padx = 5, pady = 5, column = 1, row = 3) e5 = Entry(root, width = 50, textvariable = v5, show = '*') e5.grid(padx = 5, pady = 5, column = 1, row = 4) def b1_cmd(): if v2.get() <> v3.get(): tkMessageBox.showerror(title = msgError, message = msgPasswordConfirmError) print v1.get(), v2.get(), v4.get(), v5.get() create_new_account(v1.get(), v2.get(), v4.get(), v5.get()) b1 = Button(root, text = msgCreateNewLoginButton, command = b1_cmd).grid(padx = 5, pady = 5, column = 0, row = 5) b2 = Button(root, text = msgCancelButton, command = root.destroy).grid(padx = 5, pady = 5, column = 1, row = 5) root.mainloop() if __name__ == '__main__': newlogin() ======== ======== config.py ======== # codepage = cp1251 # # # def u(s): return unicode(s, 'cp1251') msgMainWindowTitle = u('???????? ?????????? ????? B 4\\2') msgLogin = u('?????') msgPassword = u('??????') msgGameNumber = u('????? ????') msgSaveButton = u(' ????????? ') msgLoadButton = u(' ????????? ') msgOptionsButton = u(' ????????????? ') msg_OptionsWindowTitle = u('?????????????') msgForgotPassword = u(' ????? ?????? ') msgNewLogin = u(' ????? ????? ') msg_NewLoginWindowTitle = u('???????? ?????? ??????') msgConfirmPassword = u('??? ??? ??????') msgKeyQuestion = u('????????? ?????? - ????? ?? ??????? ?????? ?????? ?? - ?? ??????, ???? ?? ???????? ??????') msgKeyQuestionAnswer = u('????? ?? ????????? ??????') msgCreateNewLoginButton = u(' ??????? ') msgCancelButton = u(' ?????? ') msgError = u('??????') msgPasswordConfirmError = u('?????? ?? ?????????.') msgPasswordLoginExists = u('????? ????? ??? ??????????.') msgInfoAccountCreated = u('????? ??????? ???????????????') msgInfoAccountCreated2 = u('?? ?????? ???????????? ???? ????? ? ?????? ??? ?????????? ? ????????????? ????? ??????????.') msgInvalidGameNumber = u('???????????? ????? ????.') msgInvalidPassword = u('???????????? ??????.') msgInvalidLogin = u('????? ?? ??????????.') msgSaveError = u('?? ??????? ???????????.') msgSuccess = u('?????????') msgSuccessCopy = u('?????????? ??????? ????????? ?? ??????, ?????? ?? ?????? ???????????? ?? ?? ????? ??????????.') data_path = '\\\\192.168.1.1\\??????????\\' data_info_file_name = 'info' info_path = 'info' ======== From jan.dries at dcube-resource.be Sat Jan 8 08:18:15 2005 From: jan.dries at dcube-resource.be (Jan Dries) Date: Sat, 08 Jan 2005 14:18:15 +0100 Subject: Another look at language comparisons In-Reply-To: <1105188426.955508.263030@c13g2000cwb.googlegroups.com> References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> <1105188426.955508.263030@c13g2000cwb.googlegroups.com> Message-ID: <41DFDD97.2030209@dcube-resource.be> beliavsky at aol.com wrote: >>From the web site: > "Why Microsoft can Blow-Off with C#? These people have thought up > programming languages Fortran, Prologue, Ada." > > The author is ignorant. Fortran was invented by IBM in the late 1950s, > long before Microsoft existed. Ada was commissioned by the U.S. > Department of Defense in the 1970s. The Prolog programming language is > not spelled "Prologue". I don't think that "these people" is refering to Microsoft. Instead, it is refering to the three pictures below the text. I assume they are the pictures of the respective authors of these languages. The bottom line of the article is that languages authored by men with beards are more successful than those authored by people without beards. At least the anecdotical evidence to that is overwhelming :-) And there is hope for Python, as Guido has recently been seen with a beard :-) http://www.tbray.org/ongoing/When/200x/2004/12/08/-big/IMG_3061.jpg Regards, Jan From marklists at mceahern.com Sun Jan 16 09:26:39 2005 From: marklists at mceahern.com (Mark McEahern) Date: Sun, 16 Jan 2005 08:26:39 -0600 Subject: Newbie inheritance question. In-Reply-To: <41EA754D.8020307@gmail.com> References: <41EA754D.8020307@gmail.com> Message-ID: <41EA799F.7070102@mceahern.com> bwobbones wrote: > Hi all, > > I'm a java programmer struggling to come to terms with python - bear > with me! Welcome! > I'm trying to subclass a class, and I want to be able to see it's > attributes also. Here are my classes: [snip] > class two(one): > def __init__(self): > print "two" The problem is that you're not calling the parent class' __init__:: class two(one): def __init__(self): one.__init__(self) ... You can also use super() to do that, but I do that so rarely I forget the syntax. Of course, that's no big deal, since:: python >>> help(super) is always to the rescue, but I'm lazy. // m From as006d4848 at blueyonder.co.uk Fri Jan 28 05:24:33 2005 From: as006d4848 at blueyonder.co.uk (Philip Smith) Date: Fri, 28 Jan 2005 10:24:33 GMT Subject: Elliptic Code Message-ID: Hi Does anyone have/know of a python implementation of the elliptic curve factoring algorithm (lenstra) which is both: simply and cleanly coded functional I'm aware of William Stein's code (from elementary number theory book) but I don't understand his coding style and the algorithm doesn't seem to work efficiently. For that matter has anyone come across any useable math/number theory packages apart from nzmath or aladim? Thanks Phil From wuwei23 at gmail.com Tue Jan 4 22:30:42 2005 From: wuwei23 at gmail.com (alex23) Date: 4 Jan 2005 19:30:42 -0800 Subject: Python evolution: Unease In-Reply-To: <7xoeg4txrp.fsf@ruckus.brouhaha.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> Message-ID: <1104895842.200010.42720@z14g2000cwz.googlegroups.com> Paul Rubin wrote: > The Python advocates who claim that Python is well-documented and take > exception to when someone say it isn't. Their idea of "it's > well-documented" seems to be "if there's parts that you think are > poorly documented, feel free to document it". What kind of nonsense > is that? It's called "having an opinion". "Good" documentation does its job, if noone else thought it was poorly documented then to them it wasn't. The only person who knows how the current documentation is unsatisfactory to you is *you*. The mistake being made here by the OS community is the assumption, based on their own personal experiences, that others will take the absence of something as a challenge to fill it themselves, serving the dual role of obtaining what they need for their own purposes AND providing it for the purposes of others. It's a mistaken assumption because for most people it's easier to gripe that someone else, oh let's say "advocates", should be doing it for you. > "Python code runs just as fast as C code. If you think it's > slower, feel free to speed it up". The objective, qualifiable speed of Python has *what* exactly to do with the subjective, interprative assessment of the Python documentation? > "Python's standard library includes a database module. If it isn't there, > feel free to add one". Which part of the open source movement do you just not get? > "Programming in Python cures cancer. If your cancer doesn't clear up > when you code in Python, feel free to submit a patch". Wow, you quickly ran out of points of blind Pythonic advocation, didn't you? > Software advocacy, which Python has an awful lot of, [...] Unjustifiable claims, which your postings have an awful lot of...see how easy it is to characterise someones position in the negative? See how pointless it is for useful dialogue? You've done nothing but kvetch about how others aren't providing you with what you need. Let's face it, people like you are never going to take the initiative and actually contribute something when you're already quite comfortable sponging off the efforts of others and hiding behind claims of advocacy whenever anyone questions your own motivations. In short: grow up and just write the damn documentation. - alex23 - From alan.ezust at gmail.com Sat Jan 22 20:03:53 2005 From: alan.ezust at gmail.com (alan dot ezust at gmail dot com) Date: 22 Jan 2005 17:03:53 -0800 Subject: debugging xmlrpc servers Message-ID: <1106442233.305138.24790@f14g2000cwb.googlegroups.com> Problems with XMLRPC I have an xmlrpc server with a method called results() which returns an XML message. I've been able to use this function without problems when I had only one client talking to one server. I have recently introduced a P2P aspect to this process and now I have servers calling each other's methods all the time. I am running into some bugs which I am unable to debug. I am using http://rpdb.digitalpeers.com/Download.htm As per the instructions, I called rpdb.set_trace() right before calling server.serve_forever(). Then I ran the server, and ran the client. At a certain point, the client asks the server for the results(), and instead of getting a proper result, I get this exception: /usr/lib/python2.3/xmlrpclib.py in close(self=) 743 raise ResponseError() 744 if self._type == "fault": 745 raise Fault(**self._stack[0]) 746 return tuple(self._stack) 747 global Fault = , self = , self._stack = [{'faultCode': 1, 'faultString': 'exceptions.ValueError:too many values to unpack'}] Fault: args = () faultCode = 1 faultString = 'exceptions.ValueError:too many values to unpack' I thought that my rpdb problems were related to the fact that I was multiply-inheriting from SocketServer.ThreadingMixIn (which I believe starts a new thread for each incoming request), so I changed this: class QueryServer(SocketServer.ThreadingMixIn, SimpleXMLRPCServer.SimpleXMLRPCServer): to this: class QueryServer(SimpleXMLRPCServer.SimpleXMLRPCServer): I am still unable to set a breakpoint in the results() method. I'd really like to trace through it so I can figure out why I am getting this weird exception. Any ideas? From tom.willis at gmail.com Thu Jan 27 21:24:09 2005 From: tom.willis at gmail.com (Tom Willis) Date: Thu, 27 Jan 2005 21:24:09 -0500 Subject: win32com/makepy question Message-ID: Just a general question. It seems in COM late binding is something that should be avoided if possible. Because python seems to be really good at doing thing dynamically I'm wondering why no one has figured out how to make the functionality in makepy fire automagically when you need it. For example, it would be nice if you are creating an object repeatedly(ADODB.Recordset) that some logic would trigger whatever makepy does to generate and cache the modules generated from the typelib that's accessed. It would be cool, that's all I'm saying. I'm sure the standard response is "Why don't you write it" and maybe I will, I'm just wondering if anyone has thought of it before and is working on it or whatever. -- Thomas G. Willis http://paperbackmusic.net From skip at pobox.com Fri Jan 28 15:25:23 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 28 Jan 2005 14:25:23 -0600 Subject: Mac OS and MySQLdb In-Reply-To: <41f95b17$0$3331$9b622d9e@news.freenet.de> References: <41f95b17$0$3331$9b622d9e@news.freenet.de> Message-ID: <16890.40883.660734.642623@montanaro.dyndns.org> Thomas> is there a MySQLdb-Version for the latest Mac OS (or can I use Thomas> the Linux-tarball)? I just built the latest version from source (1.1.7 or something). Skip From phr at localhost.localdomain Thu Jan 27 00:41:56 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Thu, 27 Jan 2005 05:41:56 GMT Subject: What's so funny? WAS Re: rotor replacement References: <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: Jeremy Bowers writes: > The policy has been laid out, multiple times, by multiple people now. The > answer is, you are not going to get any such indication that will satisfy > you. Actually I already got an indication that satisfied me, from Guido and Andrew, although it was later withdrawn for nontechnical reasons (i.e. legal restrictions) that I don't feel entitled to argue against very much. I do, however, believe that what Frederik and Martin are saying is bogus on technical grounds, and furthermore, they're just being busybodies, since they've had no involvement at all in what's happened already with that module, and their picture of the Python development process doesn't have much resemblance to how the current Python distro got to be the way it is. > Note that I am not a Python contributor of any kind. Also note that I > figured this out about two days ago. You can wheedle these guys all you > want, I have not asked them for anything, since they are not in a position to give it. >but they are too experienced for you to extract a promise from them. Actually, one of them already gave a promise that he couldn't keep even if he wanted to. He said that if I wrote a crypto module and got it tested enough, it would be considered for inclusion (i.e. based on its technical merits). But, he doesn't get to decide that. Current policy per per Guido seems to be that because of the legal stuff, there will be no crypto module in the stdlib regardless of its merits. From jurgenex at hotmail.com Wed Jan 26 18:51:06 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Wed, 26 Jan 2005 23:51:06 GMT Subject: [perl-python] 20050126 find replace strings in file References: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: [...] > In perl, similar code can be achieved. > the following code illustrates. > > if (scalar @ARGV != 4) Why scalar()? The comparison already creates a scalar context, no need to enforce it twice. > {die "Wrong arg! Unix BNF: $0 > \n"} > $stext=$ARGV[0]; > $rtext=$ARGV[1]; > $infile = $ARGV[2]; > $outfile = $ARGV[3]; Ouch, how ugly. What's wrong with a simple my ($one, $two, $three, $four) = @ARGV; or the standard way using shift for ($one, $two, $three, $four) { $_ = shift; } > open(F1, "<$infile") or die "Perl fucked up. Reason: $!"; > open(F2, ">$outfile") or die "Perl fucked up. Reason: $!"; Really? Usually it's either the OS or the user (disk full, no write permissions, wrong file name, ...) > while ($line = ) { Why $line? It doesn't serve any useful purpose here. > chomp($line); Why chomp()? It doesn't serve any useful purpose here. > $line =~ s/$stext/$rtext/g; If you would not have used $line above then you would not need the binding here. > print F2 "$line\n"; If you would not have chomped the line above then you would not need to add the newline back here. A simpler print F2 $_; would have sufficed > } > close(F1) or die "Perl fucked up. Reason: $!"; > close(F2) or die "Perl fucked up. Reason: $!"; I find this highly unlikely. If at all then the OS failed to complete the close. jue From rpm1deleteme at direcway.com Sun Jan 30 07:26:47 2005 From: rpm1deleteme at direcway.com (RPM1) Date: Sun, 30 Jan 2005 07:26:47 -0500 Subject: Python 2.1 - 2.4 differences References: Message-ID: <364225F4s613eU1@individual.net> "BOOGIEMAN" wrote ... > I found some e-book about Python 2.1, I want to print it but just to check > first if sintax of Python 2.1 is same as 2.4 ? Also does anybody know where > can I download any newer Python related e-book, because there isn't any > published yet in my country. Take a look at: http://diveintopython.org From deetsNOSPAM at web.de Fri Jan 21 06:31:00 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 21 Jan 2005 12:31:00 +0100 Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> Message-ID: <35c7d8F4lckakU1@individual.net> Xah Lee wrote: > i've started to read python tutorial recently. > http://python.org/doc/2.3.4/tut/tut.html Finally! It was about time... > Here are some quick critique: Given that you seem to be totally inert to critique yourself - e.g. your continued posting of useless language comparison, and the plethorea of posts requesting to stop that and limit yourself to your mailing list - I doubt you'll get much attention for that. -- Regards, Diez B. Roggisch From Scott.Daniels at Acm.Org Tue Jan 4 14:41:22 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 04 Jan 2005 11:41:22 -0800 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> Message-ID: <41daeeac$1@nntp0.pdx.net> Bulba! wrote: > .... The Americans show the French engineers a working prototype. > The French engineers scratch their heads and ask warily: > "OK, it works in practice; but will it work in theory?" I once worked with a computer built by two graduate students who formed a company. The scuttlebutt was that they were very different people. Of one it was said, "his designs are beautiful and provably correct, but they have the nasty habit of not working when you wire them up." The other's story was more like, "its amazing, you can prove his designs cannot possibly work, but every time he builds them, they seem to work in defiance of every engineering principle." Both of them had some version of the social skills of your average technical genius, that is to say, less than the world normally requires. When it became known these two were working together, the generally accepted view was that this company would either produce a spectacularly fast machine, or at least one of them would be dead. --Scott David Daniels Scott.Daniels at Acm.Org From missiplicity at yahoo.com Tue Jan 25 17:17:58 2005 From: missiplicity at yahoo.com (missiplicity at yahoo.com) Date: 25 Jan 2005 14:17:58 -0800 Subject: Question Regarding SocketServer In-Reply-To: <1106688660.694617.290330@c13g2000cwb.googlegroups.com> References: <1106684900.771730.218060@f14g2000cwb.googlegroups.com> <1106688660.694617.290330@c13g2000cwb.googlegroups.com> Message-ID: <1106691478.621949.44020@z14g2000cwz.googlegroups.com> sp1d3rx at gmail.com wrote: > I tried to reply earlier... basically your "SocketServer.py" file is > messed up. That line "AF_INET{,6}: IP (Internet Protocol) sockets > (default)" should be commented out. It should be part of a block of > lines that are all commented out. Thanks for your quick response. I am suprised that "SocketServer.py" is messed up because I just installed Python and didnt touch any files in Python's installation folder. Anyway I removed the comments at the top and I still get the error File "C:\Python24\lib\SocketServer.py", line 8, in ? AttributeError: 'module' object has no attribute 'StreamRequestHandler' If it is of any help here are the first few lines in SocketServer.py __version__ = "0.4" import socket import sys import os __all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer", "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler", "StreamRequestHandler","DatagramRequestHandler", "ThreadingMixIn", "ForkingMixIn"] if hasattr(socket, "AF_UNIX"): __all__.extend(["UnixStreamServer","UnixDatagramServer", "ThreadingUnixStreamServer", "ThreadingUnixDatagramServer"]) I opened the SocketServer.py in the IDE and it seems normal. Is there a way I can check if the module is corrupted in the IDE? Thanks, Kris From cookedm+news at physics.mcmaster.ca Wed Jan 26 17:50:17 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 26 Jan 2005 17:50:17 -0500 Subject: MMTK Install Problem References: Message-ID: Justin Lemkul writes: > Hello All, > > I am hoping that someone out there will be able to help me. During the > "build" phase of MMTK installation, I receive the following series of errors: > > $ python setup.py build > running build > running build_py > running build_ext > building 'lapack_mmtk' extension > gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd > -fno-common > -dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DLIBM_HAS_ERFC > -DEXTENDED_TYPES -IInclude > -I/System/Library/Frameworks/Python.framework/Versions/ > 2.3/include/python2.3 -c Src/lapack_mmtk.c -o > build/temp.darwin-7.7.0-Power_Macintosh > -2.3/Src/lapack_mmtk.o > Src/lapack_mmtk.c:2:33: Numeric/arrayobject.h: No such file or directory Always look at the first error :-) GCC is awful for, when it can't find an include file, saying it can't, then spewing millions of error messages afterwards that are a direct result of not having stuff declared. In this case, it's obvious that you don't have Numeric installed correctly; the header files should be picked from one of the directories specified by the -I flags in the gcc invocation above. > I am attempting the install on a Mac OS X v10.3 with Python v2.3, NumPy v23.1, > and SciPy v2.4.3 (You mean ScientificPython, not SciPy, right? Scipy is at 0.3.2) How did you install Numeric? The newest version is 23.7. It should be real easy to upgrade to that, as that version picks up Apple's vecLib framework for the linear algebra routines. Just do the usual 'python setup.py build', 'sudo python setup.py install'. That should put the header files where the MMTK installation expects them. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From skip at pobox.com Sat Jan 29 08:16:43 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 29 Jan 2005 07:16:43 -0600 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xacqt56ga.fsf@ruckus.brouhaha.com> References: <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> Message-ID: <16891.36027.277548.194352@montanaro.dyndns.org> >> http://www.python.org/pypi >> THIS IS ALL PYTHON. Paul> No. Those are programs people have written in Python or as Python Paul> extensions. What's your point? That I have to download and perhaps install them to use them? In that case, how are these two scenarios different: * I have to download and build the MySQLdb package to talk to MySQL servers from Python code * I have to ensure that the readline library and include files are installed on my system before the readline module (which is included in the core distribution) can be built I and many other people happily use external packages other people have written as well as make stuff available. My guess is that you do as well. If everyone adopted your position that it wasn't Python unless it had been added to the core, we'd all be reinventing lots of wheels or tackling much less challenging tasks, if we programmed in Python at all. Here's an incomplete list of stuff not in the core I have used happily over the past several years to do my jobs using Python: * MySQLdb, Sqlite, pycopg, sybase-python - all database modules * CSV, Object Craft's csv, DSV - csv modules predating csv in the core * SpamBayes * Quixote * Docutils * MoinMoin * Pyrex * Psyco * PyInline * PyGTK * xmlrpclib before it was in the core * MAL's mx.DateTime before the core datetime module was available * timeout_socket before sockets supported timeouts Many of those things I could never have written myself, either for lack of time, lack of skill or both. I'm grateful they were available when I needed them and feel no qualms about using them even though they are not distributed with Python proper. Notice another interesting feature of several of those items: csv, xmlrpclib, mx.DateTime, timeout_socket. They were all modules I used that eventually wound up in the core in some fashion. They didn't go in the core first, then demonstrate their usefulness. It was the other way around. Not everything that is useful belongs in the core distribution. I think you are confusing "batteries included" with "everything, including the kitchen sink". Skip From alanmk at hotmail.com Fri Jan 28 17:07:59 2005 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 28 Jan 2005 22:07:59 +0000 Subject: Textual markup languages (was Re: What YAML engine do you use?) In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> Message-ID: [Alan Kennedy] >>However, I'm torn on whether to use ReST for textual content. On the one >>hand, it's looks pretty comprehensive and solidly implemented. But OTOH, >>I'm concerned about complexity: I don't want to commit to ReST if it's >>going to become a lot of hard work or highly-inefficient when I really >>need to use it "in anger". >> >>From what I've seen, pretty much every textual markup targetted for web >>content, e.g. wiki markup, seems to have grown/evolved organically, >>meaning that it is either underpowered or overpowered, full of special >>cases, doesn't have a meaningful object model, etc. [Aahz] > My perception is that reST is a lot like Python itself: it's easy to hit > the ground running, particularly if you restrict yourself to a specific > subset of featuers. It does give you a fair amount of power, and some > things are difficult or impossible. > > Note that reST was/is *not* specifically aimed at web content. Several > people have used it for writing books; some people are using it instead > of PowerPoint. Thanks, Aahz, that's a key point that I'll continue on below. [Alan Kennedy] >>So, I'm hoping that the learned folks here might be able to give me some >>pointers to a markup language that has the following characteristics >> >>1. Is straightforward for non-technical users to use, i.e. can be >>(mostly) explained in a two to three page document which is >>comprehensible to anyone who has ever used a simple word-processor or >>text-editor. >> >>2. Allows a wide variety of content semantics to be represented, e.g. >>headings, footnotes, sub/superscript, links, etc, etc. [Aahz] > These two criteria seem to be in opposition. I certainly wouldn't > expect a three-page document to explain all these features, not for > non-technical users. reST fits both these criteria, but only for a > selected subset of featuers. The point is well made. When I wrote my requirements, I did have a specific limited feature set in mind: basically a print-oriented set of features with which anyone who reads books would be familiar. I'm trying to capture scientific abstracts, of the sort that you can see linked off this page. http://www.paratuberculosis.org/proc7/ But I'm basically only interested in representation of the original input text. I'll be capturing a lot of metadata as well, but most of that will be captured outside the markup language, through a series of form inputs which ask specific metadata questions. So, for example, the relationships between authors and institutions, seen on the next page, will not be recorded in the markup. http://www.paratuberculosis.org/proc7/abst5_p2.htm I think that is where a lot of markup languages fall down, in that they end trying to develop a sophisticated metadata model that can capture that kind of information, and re-engineering the markup to support it. This co-evolution of the markup and model can go horribly awry, if the designers are inexperienced or don't know where they're headed. Since ReST seems to do this stuff fairly well, I think I'll take a closer look at it. From what I've seen of it, e.g. PEPs, python module documentation (SQLObject, etc), it seems to be reasonably unobtrusive to the author. regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From ncoghlan at iinet.net.au Fri Jan 7 11:11:18 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 02:11:18 +1000 Subject: Securing a future for anonymous functions in Python In-Reply-To: <7xis6930ah.fsf@ruckus.brouhaha.com> References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <7xis6930ah.fsf@ruckus.brouhaha.com> Message-ID: <41DEB4A6.4060805@iinet.net.au> Paul Rubin wrote: > "Anna" writes: > >>Having taken some calculus (derivatives, limits, some integrals) but >>never even heard of lambda calculus, to me, lambda means absolutely >>NOTHING. Less than nothing. > > > Lambda calculus is from mathematical logic, but more to the point > "lambda" has been the term used in Lisp for this operation since time > immemorial. I think that's part of the problem though - people familiar with lambda calculus and Lisp's lambdas want Python's lambdas to be equally capable, and they just plain *aren't*. If you have a complex function, the Pythonic way is to give it a meaningful name. Having a way to defer evaluation of a simple expression *is* quite handy, but 'lambda' is the wrong name for it - the parallels to lambda calculus and Lisp's lambda functions are likely to be misleading, rather than helpful. Add in the fact that there are many, many Python programmers with non-CS backgrounds, and the term 'lambda' sticks out like a sore thumb from amongst Python's other English-based keywords. 'def' is probably the second-most cryptic when you first encounter it, but it is a good mnemonic for "define a function", so it's still easy to parse. "Lambda is the term mathematicians use to refer to an anonymous function" is nowhere near as grokkable ;) For me, the alternative syntax discussion is based on 3 of the 4 mentioned reasons: 1. The syntax I don't like re-using colons as something other than suite delimiters - it breaks up the affected expression too much (particularly function calls). Code with dict literals inside function calls bugs me for the same reason (it's OK when the literal is separated out into an assignment statement for the dict). It's also too easy to write lambdas which look ambiguous, even though they technically aren't. Finally, Python has a reputation as "executable pseudocode". Lambda expressions don't read like any sort of psuedocode you're likely to see outside a maths department. 2. The limitation to a single expression I consider this no more of a problem than the restriction to a single expression in the main loop of a generator expression or a list comprehension. When those get too complicated, you switch to using a real for loop somewhere. Deferred expressions are no different - when the guts get too complicated, switch to a named function. 3. The word 'lambda' itself This _is_ one of my objections for the reasons stated above: for people unfamiliar with the term, they don't know what it is; for people familiar with the term, it isn't what they think it should be. Python already has a perfectly good keyword for functions, which has the additional virtue of being half the length of lambda (this matters, since this is a keyword that gets embedded in expressions - all the other keywords currently in that category are three letters or less: and, or, is, in, for) 4. People complaining about 2 Oh hell yes, this bugs me. And I think changing the syntax and calling them "deferred expressions" instead of "lambdas" would go a long way towards eliminating the griping. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From rays at blue-cove.com Fri Jan 21 14:29:00 2005 From: rays at blue-cove.com (Ray Schumacher) Date: Fri, 21 Jan 2005 11:29:00 -0800 Subject: is there better 32 clock() timing? Message-ID: <5.2.0.4.0.20050121102015.00b5ae48@216.122.242.54> I have a need for a time.clock() with >0.000016 second (16us) accuracy. The sleep() (on Python 2.3, Win32, at least) has a .001s limit. Are they lower/better on other's platforms? Test code, 2.4GHz P4 Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32 import time t0 = time.clock() t1 = time.clock() t2 = time.clock() t3 = time.clock() t4 = time.clock() t5 = time.clock() print (-t0+t5)/5. print t1-t0 print t2-t1 print t3-t2 print t4-t3 print t5-t4 >>> ave 0.000342754564927 0.000321028401686 0.00030348379596 0.000297101358228 0.000295895991258 I had also considered forking a thread that would spin a loop checking time.clock() and firing the TTL pulse after the appropriate interval, but the real, ultimate resolution of time.clock() appears to be ~.00035s. If I increase process priority to real-time, it is ~.00028s The alternative appears to be more C code... Ray BCI/Congitive Vision From ncoghlan at iinet.net.au Thu Jan 6 07:38:49 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 06 Jan 2005 22:38:49 +1000 Subject: navigating/changing directories In-Reply-To: References: Message-ID: <41DD3159.4020303@iinet.net.au> The script is executed in a process separate from your command shell, and hence has no effect on your shell's current directory. There are some things that batch files and shell scripts are still good for - manipulating the shell :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ed at leafe.com Thu Jan 13 16:29:35 2005 From: ed at leafe.com (Ed Leafe) Date: Thu, 13 Jan 2005 16:29:35 -0500 Subject: Dabo Windows Runtime 0.3 Available Message-ID: <38F0EDD0-65AA-11D9-A18A-003065B11E84@leafe.com> For all of you who have been curious about Dabo, but who don't want to go through the work of installing Python, wxPython, MySQLdb, etc., on your machines, I'm pleased to announce the release of the Dabo Runtime for Windows v. 0.3. The Dabo Runtime comes in the form of a standard Windows Installer. It will install the runtime in the directory you choose, along with the Dabo framework. It will also install the Dabo Demo and IDE directories, so that you can try out some of the stuff we've come up with to show what Dabo can do. The framework and other files are installed as source code, so not only can you look at the code to see what's going on, you can also update it as new releases are made without having to re-install anything. The Dabo Runtime installer is available from our Download page: http://dabodev.com/download. Enjoy! ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From bob_smith_17280 at hotmail.com Tue Jan 18 20:18:39 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Tue, 18 Jan 2005 20:18:39 -0500 Subject: file copy portability In-Reply-To: <1106097094.789862.275060@z14g2000cwz.googlegroups.com> References: <1106097094.789862.275060@z14g2000cwz.googlegroups.com> Message-ID: John Machin wrote: > Bob Smith wrote: > >>Is shutil.copyfile(src,dst) the *most* portable way to copy files > > with > >>Python? I'm dealing with plain text files on Windows, Linux and Mac > > OSX. > >>Thanks! > > > Portable what? Way of copying?? > > Do you want your files transferred (a) so that they look like native > text files on the destination system, or (b) so that they are exact > byte-wise copies? > > A 5-second squint at the source (Lib/shutil.py) indicates that it > provides, reliably and portably, option b: > fsrc = open(src, 'rb') > fdst = open(dst, 'wb') > > One way of doing option (a): you would need to be running Python on the > destination system, open the src file with 'rU', open the dst file with > 'w'. > The files are not copied from one platform to the other. The app must run on all platforms. I want to make the app as portable as possible to reduce platform specific code. From tundra at tundraware.com Fri Jan 7 18:08:30 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 07 Jan 2005 18:08:30 EST Subject: Tkinter, Alt, and Windows In-Reply-To: <1qf3b2-pdp.ln1@eskimo.tundraware.com> References: <1qf3b2-pdp.ln1@eskimo.tundraware.com> Message-ID: Tim Daneliuk wrote: > Arrrrrggg. I have a program that runs comfortably across both Unix > variants > and Windows ... except .... I wish to bind an Alt-ButtonRelease-3 > combination > to popup a menu. This works flawlessly under Unix, but with windows, > the menu appears briefly and then disappears. I'm guessing that Alt > under windows generates another event that I am not catching and the > default internal Tk message handler is processing it and causing my > menu to get destroyed. > > It seems that any combination involving the Alt key has this issue - > for example Control-Alt-ButtonRelease-3 does the same thing. > > Has anyone else run into this behavior and have a fix??? > I have a partial workaround but the mechanics still mystify me. I actually was trying to bind two different popup menus to as follows: Alt-ButtonRelease-3 Menu1 Alt-Control-ButtonRelease-3 Menu2 This did not work ... so I began to wonder if this was problem with Tk using greedy matching with event descriptors. So, I changed it as follows: Control-ButtonRelease-3 Menu1 Alt-Control-ButtonRelease-3 Menu2 This now works fine, BUT ONLY if Alt is pressed *before* Control when popping up Menu2. IOW Windows is sensitive to the *order* of Alt being applied where Unix is not. Very, very strange ... -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From fredrik at pythonware.com Fri Jan 14 12:07:11 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 14 Jan 2005 18:07:11 +0100 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com><7xmzvfn096.fsf@ruckus.brouhaha.com><7xsm559heo.fsf@ruckus.brouhaha.com><7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: Antoon Pardon wrote: > Well IMO I have explained clearly that I understood this in a set > logical sense in my first response. what does "first" mean on your planet? From hcslmf at texlife.com Wed Jan 26 16:39:23 2005 From: hcslmf at texlife.com (brolewis) Date: 26 Jan 2005 13:39:23 -0800 Subject: MSI Difficulties Message-ID: <1106775563.795954.50420@z14g2000cwz.googlegroups.com> I am trying to deploy Python onto a number of laptops and have been trying to take advantage of Python 2.4's MSI installer. I have tried using the following commands to install, but to no avail: msiexec /i python-2.4.msi /qb ALLUSERS=1 -- and -- msiexec /i python-2.4.msi /qb ALLUSERS=1 ADDLOCAL=ALL However both of these commands fail to update the Windows path to include C:\Python24 and as such creates problems for me when trying to actually use Python. How can I rectify this situation? Is there a command I am missing? Do I need to manually update the Path, and if so, is there a programatic way I can do this? Thanks in advance From roy at panix.com Fri Jan 28 09:27:17 2005 From: roy at panix.com (Roy Smith) Date: Fri, 28 Jan 2005 09:27:17 -0500 Subject: a sequence question References: Message-ID: In article , Chris Wright wrote: > Hi, > > 1) I want to iterate over a list "N at a time" You could do it with slicing and zip: >>> l = [1, 2, 3, 4, 5, 6, 7, 8] >>> zip (l[::2], l[1::2]) [(1, 2), (3, 4), (5, 6), (7, 8)] To my eyes, that's a bit cryptic, but it works and it's certainly compact. I don't use either zip() or extended slicing a lot; perhaps if I used them more often, the above would be more obvious to me if I read it in somebody else's code. The interesting thing would be generalizing this to the "N at a time" case. I think this works: def nzip (list0, n): args = [] for i in range(n): slice = list0[i::n] args.append (slice) return zip (*args) l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] print nzip (l, 3) Roy-Smiths-Computer:play$ ./nzip.py [(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12)] but I haven't given any thought to what happens if the length of the list isn't a multiple of n (exercise for the reader). It's also annoying that the above generates a bunch of temporary lists. It would be cool if there was a way to have the intermediates be generator expressions, but I'm not that good with that stuff, so I'll leave that as an exercise for other readers :-) From mcfletch at rogers.com Sun Jan 23 19:13:54 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Sun, 23 Jan 2005 19:13:54 -0500 Subject: Weakref.ref callbacks and eliminating __del__ methods In-Reply-To: <1gqv9il.7udkdu1oqaaqmN%aleaxit@yahoo.com> References: <1gqv9il.7udkdu1oqaaqmN%aleaxit@yahoo.com> Message-ID: <41F43DC2.6010808@rogers.com> Alex Martelli wrote: >Mike C. Fletcher wrote: > > > >> weakref.ref( self, self.close ) >> >>but the self.close reference in the instance is going away *before* the >>object is called. >> >> > >Uh -- what's holding on to this weakref.ref instance? I guess the >weakreference _itself_ is going away right after being created... > > You know, you're right. I'd been thinking (not-very-clearly) that registering the callback would keep the reference alive until it was called, guess I'm too used to PyDispatcher's operation. Urgh, that's seriously annoying, requires storing the callback somewhere external. Back to __del__ I suppose. Thanks Alex, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From t-meyer at ihug.co.nz Sun Jan 30 17:42:14 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Mon, 31 Jan 2005 11:42:14 +1300 Subject: gmail access with python! In-Reply-To: Message-ID: > i want to write a python program which will grab all my gmail > msgs and store them on my hard drive. [...] > my question is: does anyone have a working script which can > grab msgs from a gmail inbox ? Possibly not of use, but if you're not using POP3 access to your gmail account for anything else, then you could simply enable POP3 access and use poplib. =Tony.Meyer From newsgroups at jhrothjr.com Mon Jan 17 15:03:25 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 17 Jan 2005 14:03:25 -0600 Subject: Assigning to self References: Message-ID: <10uo6hbn040qt24@news.supernews.com> "Frans Englich" wrote in message news:mailman.805.1105987092.22381.python-list at python.org... > > Hello, > [...] > > What the code attempts to do is implementing a, to the API user, > transparent > memory-saver by ensuring that no more than one instance of the class foo > exists for a particular id. E.g, the user can simply "create" an instance > and > if one not already exists, it is created. In other words, you're trying to create a singleton. In general, singletons are frowned on these days for a number of reasons, not least because of the difficulty of testing them. > First of all; am I approaching the goal with the right solution? No. In all Python releases since 2.2, the correct way of doing this is to use the __new__() method. Unfortunately, the only place it is documented is here: http://www.python.org/2.2.3/descrintro.html and here: http://users.rcn.com/python/download/Descriptor.htm The first reference contains an example of how to do a singleton: simply search on the word Singleton. John Roth > Cheers, > > Frans > > > > From grante at visi.com Tue Jan 18 14:43:17 2005 From: grante at visi.com (Grant Edwards) Date: 18 Jan 2005 19:43:17 GMT Subject: hex notation funtion References: <41ed60f9$0$29427$a1866201@visi.com> Message-ID: <41ed66d5$0$92053$a1866201@visi.com> On 2005-01-18, Grant Edwards wrote: > On 2005-01-18, tertius wrote: > >> Is there a builtin function that will enable me to display the hex >> notation of a given binary string? (example below) > > ' '.join('%02x' % ord(b) for b in s) Oops. Should be: ' '.join(['%02x' % ord(b) for b in s]) -- Grant Edwards grante Yow! .. Am I in a SOAP at OPERA?? visi.com From steve at holdenweb.com Mon Jan 3 14:37:42 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Jan 2005 14:37:42 -0500 Subject: Continuations Based Web Framework - Seaside. In-Reply-To: References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <7aTBd.11928$H%6.521997@twister1.libero.it> Message-ID: <41D99F06.8060809@holdenweb.com> Ian Bicking wrote: > Steve Holden wrote: > >> I did actually do some sort-of-related work in this area, which I >> presented at PyCon DC 2004 - you can access the paper at >> >> http://www.python.org/pycon/dc2004/papers/18/Setting_A_Context.pdf >> >> An audience member mentioned the Smalltalk and Scheme-based work on >> web continuation frameworks, and I was sorry my answer at the time >> seemed unduly dismissive. There are some interesting similarities, and >> though my own implementation is decidedly clunky I like to think the >> paper explains some of the advantages of maintaining state and why the >> "back" button is an obnoxious anachronism :-) > > > I think the technique you talked about is an easier way to achieve a > similar goal as the continuation-based frameworks. While using > continuations for web applications is an interesting idea, I don't think > it's been shown to be successful. It's certainly not something I'd want > to implement on Python (even given the actual features to make it > possible), and from what I've read of the Ruby projects that use it > (Borges and Wee?), they aren't ready to implement production > applications either. The technique you present could be implemented on > any framework, right now, with the expectation that it would work in a > production situation. > That's true, but there's no denying it's clunky, and there are a few problems with it. Despite that, I am still persisting with developemnt, albeit slowly due to lack of time, and hope to have something further to report. It's the *ideas* that are important, though, rather than the implementation, and my initial hope was to publicise the weakness of statelessness on the web as applications become more complex. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From gurpreet.sachdeva at gmail.com Thu Jan 6 01:53:41 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Thu, 6 Jan 2005 12:23:41 +0530 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: <003801c4f3b9$af17fa20$0800a8c0@vishnu> References: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> <003801c4f3b9$af17fa20$0800a8c0@vishnu> Message-ID: I tried logfile=file(r'test.txt','w+') logfile.write('datetime') test=logfile.readlines() print test I got : Open an encoded file using the given mode and return a wrapped version providing transparent encoding/decoding. Note: The wrapped version will only accept the object format defined by the codecs, i.e. Unicode objects for most builtin codecs. Output is also codec dependent and will usually by Unicode as well. Files are always opened in binary mode, even if no binary mode was specified. This is done to avoid data loss due to encodings using 8-bit values. The default file mode is 'rb' meaning to open the file in binary read mode. encoding specifies the encoding which is to be used for the file. errors may be given to define the error handling. It defaults to 'strict' which causes ValueErrors to be raised in case an encoding  and a hell lot of junk. Can anyone explain that??? AFAIK w+ was ment for opening a file for both writting and reading... Regards, Garry On Thu, 6 Jan 2005 12:03:27 +0530, Vishnu wrote: > logfile = file(r'test.txt','w') > logfile.write('datetime') > logfile.close() # <- close the file > > logfile = file(r'test.txt','r') # <- Open the file in read mode > test=logfile.readlines() > > > ~Vishnu. > > -----Original Message----- > From: python-list-bounces+vishnube=acmet.com at python.org > [mailto:python-list-bounces+vishnube=acmet.com at python.org] On Behalf Of > wordsender at gmail.com > Sent: Thursday, January 06, 2005 11:53 AM > To: python-list at python.org > Subject: file.readlines() - gives me error (bad file descriptor) > > Hey guys, > > I can't figure this one out, why is this simple script giving me > problems? > > logfile=file(r'test.txt','w') > logfile.write('datetime') > test=logfile.readlines() > > When I run it I get the error message: > Traceback (most recent call last): > File "C:\Documents and Settings\Gregory\My Documents\Get New Great > Job\testfile.py", line 3, in ? > test=logfile.readlines() > IOError: [Errno 9] Bad file descriptor > > I'm running Windows XP, Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC > v.1200 32 bit (Intel)] on win32 > Any help would be greatly appricated. > > Thanks, > > Greg > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Thanks and Regards, GSS From kartic.krishnamurthy at gmail.com Sun Jan 9 09:04:39 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 9 Jan 2005 06:04:39 -0800 Subject: Python application extending, plugins References: Message-ID: <1105277699.092737.3370@c13g2000cwb.googlegroups.com> John, To achieve this, your application must define an API that third party coders can use to extend your application. How you define your API is upto you; there are no general "guidelines", AFAIK. But if you want seamless extensibility, it entirely depends on how elegantly you design the API for you application. My approach has been to study other applications (python or otherwise) that allow plug-ins to be written and get ideas. You can may be look at SPE, Stani's Python Editor, as it allows extending the app using plug-ins and there are some sample plug-ins. I have also read some plugin-related articles at codeproject.com (VB and C++). The good thing about Python is its introspection that you can use to detect the presence of certain functions in order to qualify as a plug-in for your application. And you can use pycheck (pycheck.sf.net) to check the plugin's python code before you load it into your application's namespace. Cheers! --Kartic From thisissantanu at yahoo.com Thu Jan 27 09:36:51 2005 From: thisissantanu at yahoo.com (santanu) Date: 27 Jan 2005 06:36:51 -0800 Subject: Please suggest on the book to follow In-Reply-To: References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> <1106829519.540737.164210@z14g2000cwz.googlegroups.com> Message-ID: <1106836611.862211.283470@c13g2000cwb.googlegroups.com> Thanks for the reply. >From your suggestions, I guess I would have no problems learning from Programming Python. I didn't like Core Python Programming and such books. I like to read cover to cover and the chapters on data structures and such elementary things put me to sleep. I already have an idea of those things. I have a fair knowledge of C and some Perl. >From what you and Fyzzyman said, I guess when I am done with Programming Python, graduating to the latest features would be quite easy. Isn't it? Regards, Santanu From wolfgang.keller.nospam at gmx.de Tue Jan 11 05:58:13 2005 From: wolfgang.keller.nospam at gmx.de (Wolfgang Keller) Date: Tue, 11 Jan 2005 11:58:13 +0100 Subject: Frameworks for database/forms applications? Message-ID: Hello, apart from GNUe (forms) and Dabo, what other "Delphi-lookalike" Python frameworks are there for typical forms-oriented database applications? It's not that the above mentioned are not enough for me, I just want to get a candidate list that is as exhaustive as possible for my evaluation... TIA, Best regards Wolfgang Keller From yaipa at yahoo.com Thu Jan 13 01:36:54 2005 From: yaipa at yahoo.com (yaipa) Date: 12 Jan 2005 22:36:54 -0800 Subject: finding/replacing a long binary pattern in a .bin file Message-ID: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> What would be the common sense way of finding a binary pattern in a .bin file, say some 200 bytes, and replacing it with an updated pattern of the same length at the same offset? Also, the pattern can occur on any byte boundary in the file, so chunking through the code at 16 bytes a frame maybe a problem. The file itself isn't so large, maybe 32 kbytes is all and the need for speed is not so great, but the need for accuracy in the search/replacement is very important. Thanks, --Alan From http Tue Jan 11 16:07:01 2005 From: http (Paul Rubin) Date: 11 Jan 2005 13:07:01 -0800 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> Message-ID: <7xmzvfn096.fsf@ruckus.brouhaha.com> michele.simionato at gmail.com writes: > 2. One could proposed hygienic pattern-matching macros in Python, > similar to > Scheme syntax-rules macros. Again, it is not obvious how to > implement pattern-matching in Python in a non-butt-ugly way. Plus, > I feel hygienic macros quite limited and not worth the effort. It wasn't obvious how to do it in Scheme either. There was quite a bit of head scratching and experimental implementation before there was consensus. > 3. We would add to Python the learning curve of macros and their > subtilities and we do not want it. I can't imagine how it could be worse than the learning curve of __metaclass__, which we already have. If it was done in a way that most of us would just rely on a few standard ones, that would be fine. > 4. Macros would complicate a lot Python module system. I don't see how, but maybe I'm missing something. > 5. We have Guido providing a good syntax for us all, why we should be > fiddling with it? More seriously, if some verbosity is recognized > in the language (think to the "raison d'etre" of decorators, for > instance) I very much prefer to wait for Guido to take care of > that, once and for all, than having 100 different custom made > solutions based on macros. Every time some newbie asks an innocent "how do I ..." question, we see unbelievably horrid answers from gurus. Just check the FAQ about conditional expressions, etc. I just don't see Python syntax changes as forthcoming. > What I would be interested in is a Lisp/Scheme implementation > compiling to Python bytecode, but I am not aware of any project > in that direction. But that sounds like a bizarre idea. Python bytecode is just a CPython artifact, not part of the language. And it's not even that good an artifact. Good Lisp/Scheme implementations compile to native code that beats the pants off of CPython bytecode. It would make much more sense to have a Python implementation that compiles Python to S-expressions and then lets a high performance Lisp or Scheme system take care of the rest. From invalidemail at aerojockey.com Mon Jan 10 10:02:38 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 10 Jan 2005 07:02:38 -0800 Subject: python3: 'where' keyword In-Reply-To: <7xllb1jsdz.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> <7xllb2f3z4.fsf@ruckus.brouhaha.com> <1105355380.040837.189270@c13g2000cwb.googlegroups.com> <7xis65a5w6.fsf@ruckus.brouhaha.com> <1105357839.696387.309900@c13g2000cwb.googlegroups.com> <7xr7kt314a.fsf@ruckus.brouhaha.com> <1105364925.848973.73080@c13g2000cwb.googlegroups.com> <7xllb1jsdz.fsf@ruckus.brouhaha.com> Message-ID: <1105369358.663904.60310@c13g2000cwb.googlegroups.com> Paul Rubin wrote: > "Carl Banks" writes: > > When I asked you to do this, it was just a rhetorical way to tell you > > that I didn't intend to play this game. It's plain as day you're > > trying to get me to admit something. I'm not falling for it. > > > > If you have a point to make, why don't you just make it? > > You asked me to compare the notion of macros with the Zen list. I did > so. I didn't see any serious conflict, and reported that finding. > Now you've changed your mind and you say you didn't really want me to > make that comparison after all. I asked you to make an educated guess about what I would think of them, which you didn't do. I wanted you to apply the Zen to macros so that you could justify the guess. I wasn't interested in your thoughts. > An amazing amount of the headaches that both newbies and experienced > users have with Python, could be solved by macros. That's why there's > been an active interest in macros for quite a while. It's not clear > what the best way to do design them is, but their existence can have a > profound effect on how best to do these ad-hoc syntax extensions like > "where". Arbitrary limitations that are fairly harmless without > macros become a more serious pain in the neck if we have macros. What good are macros going to do when they entail (according to you) saddling the language with all this unreadable crap? You may say macros are not against the Zen of Python, but for their sake, you will add a million things that are. Net effect is, you've taken away everything that makes Python great. But here's the best part: all of this is to avoid a "serious pain in the neck." Get real, Paul. Here's a thought: if macros are so great, it should be pretty easy for you to create a halfway syntax with none of these pesky so-called "arbitrary limitations" and have macros automatically turn it into legal Python. Don't you think that's maybe better than turning the language into an unreadable blob? No, of course you don't, because an unreadable blob is the LISP way. > So, we shouldn't consider these topics separately from each other. > They are likely to end up being deeply related. No, Paul, they're likely never to be related because Python is never going to have macros. Or, at least not the general sort that you want. -- CARL BANKS From aleaxit at yahoo.com Sat Jan 29 11:04:29 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 29 Jan 2005 17:04:29 +0100 Subject: limited python virtual machine References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr5osy.7eipfq7xyz72N%aleaxit@yahoo.com> <16891.41849.882856.527798@montanaro.dyndns.org> Message-ID: <1gr5th5.13asce21fjmj8tN%aleaxit@yahoo.com> Stephen Thorne wrote: > On Sat, 29 Jan 2005 08:53:45 -0600, Skip Montanaro wrote: > > > > >> One thing my company has done is written a ``safe_eval()`` that uses > > >> a regex to disable double-underscore access. > > > > Alex> will the regex catch getattr(object, > > Alex> 'subclasses'.join(['_'*2]*2)...?-) > > > > Now he has two problems. ;-) > > I nearly asked that question, then I realised that 'getattr' is quite > easy to remove from the global namespace for the code in question, and > assumed that they had already thought of that. OK then -- vars(type(object)) is a dict which has [[the unbound-method equivalent of]] object.__subclasses__ at its entry for key '__subclasses__'. Scratch 'vars' in addition to 'getattr'. And 'eval' of course, or else building up the string 'object.__subclasses__' (in a way the regex won't catch) then eval'ing it is easy. I dunno, maybe I'm just being pessimistic, I guess... Alex From jeff at ccvcorp.com Wed Jan 12 18:24:18 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 12 Jan 2005 15:24:18 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <10u5fu3o7v4h9e3@corp.supernews.com> <10u8e65lju3atbd@corp.supernews.com> Message-ID: <10ubc2vkskmuh49@corp.supernews.com> Jacek Generowicz wrote: > One more question. Imagine that Python had something akin to Smalltalk > code blocks. Would something like > > map([x | x+1], seq) > > be any better for you than > > map(lambda x:x+1, seq) > > ? I'd say that this is very slightly better, but it's much closer (in my mind) to map/lambda than it is to a list comprehension. In this case, at least the code block is visually self-contained in a way that lambdas are not, but I still have to do more mental work to visualize the overall results than I need with list comps. Jeff Shannon Technician/Programmer Credit International From mnations at gmail.com Mon Jan 31 20:06:21 2005 From: mnations at gmail.com (Mudcat) Date: 31 Jan 2005 17:06:21 -0800 Subject: How do I delete the bound character which triggered callback? Message-ID: <1107219981.965449.84370@f14g2000cwb.googlegroups.com> Howdy, I have a simple combox that I have commands entered into which looks like this: """This is a list with the commands to be run in rotisserie fasion.""" self.comList = Pmw.ComboBox(self.boxFrame, labelpos=W, label_text='Command List: ', entry_width=20, selectioncommand=self.temp ) self.comList.pack(side=LEFT) self.comList.component('entry').bind(';', self.enterCommand) I have bound the ';' key because that is the terminating character in the protocol we are using, and once that is entered the entry is complete. Basically it skips the normal methond this box uses to capture commands. However, I can't get rid of it once the call is made. This is what I'm doing on the callback: def enterCommand(self, widget): # Get current list of commands, must convert to list comTuple = self.comList.get(0, END) commandsList = list( comTuple) # Get current command entered into the entry field currentCommand = self.comList.component('entry').get() currentCommand += ";" print currentCommand # Append new entry into current list and set the new list commandsList.append(currentCommand) self.comList.setlist( commandsList ) self.comList.component('entryfield').delete(0,END) At the end of this function I want to completely erase everything in the entryfield. However it erases everything but the bound key, ';'. Does anyone know how to erase that one as well? Thanks, Marc From kdahlhaus at yahoo.com Mon Jan 3 09:40:49 2005 From: kdahlhaus at yahoo.com (kdahlhaus at yahoo.com) Date: 3 Jan 2005 06:40:49 -0800 Subject: Py2exe and extension issues Message-ID: <1104763249.008031.100100@f14g2000cwb.googlegroups.com> Is anyone aware of issues with Py2exe and extensions compiled with cygwin/mingw for Python 2.3? I have an extension that wraps access to some C DLLs. The generated executable always segfaults at startup, although things work fine when running through the normal python interpreter. I had a guess that perhaps the issue stems from my extension being compiled with cygwin and py2exe compiled with Visual C++? From jeff at ccvcorp.com Thu Jan 13 12:50:39 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 13 Jan 2005 09:50:39 -0800 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> Message-ID: <10udctfs1dtq44@corp.supernews.com> Nick Coghlan wrote: > def f(): > a = 1 > b = 2 > print 1, locals() > print 3, locals() using: > a = 2 > c = 3 > print 2, locals() > print 4, locals() > > I think the least suprising result would be: > > 1 {'a': 1, 'b': 2} # Outer scope > 2 {'a': 2, 'c': 3} # Inner scope > 3 {'a': 2, 'b': 2, 'c': 3} # Bridging scope > 4 {'a': 1, 'b': 2} # Outer scope Personally, I think that the fact that the bridging statement is executed *after* the inner code block guarantees that results will be surprising. The fact that it effectively introduces *two* new scopes just makes matters worse. It also seems to me that one could do this using a nested function def with about the same results. You wouldn't have a bridging scope with both sets of names as locals, but your nested function would have access to the outer namespace via normal nested scopes, so I'm really not seeing what the gain is... (Then again, I haven't been following the whole using/where thread, because I don't have that much free time and the initial postings failed to convince me that there was any real point...) Jeff Shannon Technician/Programmer Credit International > > In that arrangement, the statement with a using clause is executed > normally in the outer scope, but with the ability to see additional > names in its local namespace. If this can be arranged, then name binding > in the statement with the using clause will work as we want it to. > > Anyway, I think further investigation of the idea is dependent on a > closer look at the feasibility of actually implementing it. Given that > it isn't as compatible with the existing nested scope structure as I > first thought, I suspect it will be both tricky to implement, and hard > to sell to the BDFL afterwards :( > > Cheers, > Nick. > From aleaxit at yahoo.com Mon Jan 31 12:49:15 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 31 Jan 2005 18:49:15 +0100 Subject: variable declaration References: <1gr98se.102e9b1qnsknwN%aleaxit@yahoo.com> <1107188359.375703.110590@f14g2000cwb.googlegroups.com> Message-ID: <1gr9lyc.1rrm543162uefN%aleaxit@yahoo.com> Michael Tobis wrote: > With all due respect, I think "so go away if you don't like it" is > excessive, and "so go away if you don't like it and you obviously don't > like it so definitely go away" is more so. The writer is obviously I disagree: I believe that, if the poster really meant what he wrote, he may well be happier using other languages and all the declarations he cherishes, so recommending that course of action to him is quite proper on my part. Nobody forces him to follow my advice, in particular if, as you suggest, he's mis-expressed himself. > neither a native speaker of English nor an accomplished user of Python, > so there are two language issues here. Try expressing your reply in > Russian before deciding that "very ugly" means exactly what you think > it does. I don't know any Russian, and I don't see how that's relevant. If the poster said "it's very ugly" meaning "I'm not fully comfortable with it" or "it's the best thing I've ever seen in my life", he can perfectly well correct his misexpression if he cares to -- not my job to try to read his mind and perform exegesis on his words. > I think just saying that "experienced Python users have not > found the lack of declarations to be a major hindrance" would have been > more appropriate. I think it would have been true, but weak and insufficient. Not only experienced Python users have that opinion: lack of declarations didn't faze me even I was a total newbie (other things did, and I learned that most of them were good only gradually; but if I'd blocked on something as obviously *fundamental* to Python, I'd never have gone deeper, of course). Plus, I did offer a URL for a classic post by Robert Martin, who's not even talking about Python yet came to exactly the same conclusion *while using statically typed languages*, just on the basis of unit-testing experience. > Also, the assertion that "Python has no declarations whatsoever" is no > longer obviously true. In the 2.4 decorator syntax, a decorator line is > not executable, but rather a modifier to a subsequent symbol binding. I > call it a declaration. You may call it a strawberry, if you wish, but that doesn't mean it will taste good with fresh cream. It's nothing more and nothing less than an arguably weird syntax for a perfectly executable statement: @ def functionname means EXACTLY the same thing as def functionname functionname = (functionname) Nothing more, nothing less. The splat-syntax isn't a "declaration" in any sense of the word, just a not-so-short shortcut for an assignment statement. Proof by disassembly: >>> def f(): ... @foo ... def g(): pass ... >>> dis.dis(f) 2 0 LOAD_GLOBAL 0 (foo) 3 LOAD_CONST 1 (", line 2>) 6 MAKE_FUNCTION 0 9 CALL_FUNCTION 1 12 STORE_FAST 0 (g) 15 LOAD_CONST 0 (None) 18 RETURN_VALUE >>> def f(): ... def g(): pass ... g = foo(g) ... >>> dis.dis(f) 2 0 LOAD_CONST 1 (", line 2>) 3 MAKE_FUNCTION 0 6 STORE_FAST 0 (g) 3 9 LOAD_GLOBAL 1 (foo) 12 LOAD_FAST 0 (g) 15 CALL_FUNCTION 1 18 STORE_FAST 0 (g) 21 LOAD_CONST 0 (None) 24 RETURN_VALUE the splat-syntax optimizes away one STORE_FAST of g and the corresponding LOAD_FAST, by having the LOAD_GLOBAL of foo earlier; nice, but not earth-shaking, and definitely no "declaration" whatsoever. > Let me add that I remain unconvinced that a language cannot combine the > best features of Python with very high performance, which is ultimately I'm also unconvinced. Fortunately, so is the EU, so they have approved very substantial financing for the pypy project, which aims in good part exactly at probing this issue. If any single individual can be called the ideator of pypy, I think it's Armin Rigo, well-known for his excellent psyco specializing-compiler for Python: the key research thesis behind both projects is that a higher-level, dynamic language need not have performance inferior to a lower-level one and indeed may well beat it. > what I want. It seems to me that such a language (possibly Python, > possibly a Python fork, possibly something else) will need substantial > programmer control over references as well as referents. pypy is dedicated to proving you're wrong. With at least half a dozen great people now finally having started working full-time on the project, and due to continue so doing for the next couple of years, I like our chances. > It seems to me that Python has a weaker case for purity in this regard > now that the dam has been breached with decorator syntax, which is, I > think, a declaration. I entirely disagree that a minor syntax wheeze to introduce a shortcut for a particular executable statement ``is a a declaration''. > Let me conclude with the confession that I'm still on the steep part of > the learning curve (if it ever flattens out at all...). Python has > definitely significantly modified how I think about things, and I > deeply appreciate all the efforts of you veterans. So I say this all > with some trepidation, because I don't want to join Alexander in > inadvertently offending you. And since I presumably missed some intense > flame wars about decorators by only a couple of months, this may be a > real hornet's nest I am poking. Almost nobody really liked the splat-syntax for decorators, except of course Guido, who's the only one who really counts (the BDFL). But that was strictly a syntax-sugar issue -- which was exactly the reason making the flamewars SO ferocious. It's one of Parkinson's Laws: the amount and energy of discussion on an issue is inversely proportional to the issue's importance. Fortunately, I was otherwise busy, so didn't enter the fray at all (I intensely dislike the splat, but I don't care all that much about such minor syntax sugar one way or another, anyway). fici > In summary, again with all due respect and gratitude for the > spectacularly excellent product that Python is today, I wonder *why* > this strong aversion to declarative statements, and *whether* decorator > syntax constitutes a violation of it. I'd appreciate any responses or > links. If "declarative statement" means anything, I guess it means "having to tell stuff to the compiler to be taken into account during compilation but irrelevant at runtime". Python does have one such wart, the 'global' statement, and it's just as ugly as one might imagine, but fortunately quite marginal, so one can almost forget it. I have nothing against a declarative style _per se_ -- it just doesn't fit Python's "everything happens at runtime" overall worldview, and that simple and powerful worldview is a good part of what makes Python tick SO well. I think there's a space for declarative languages, and it is mostly ``orthogonal'' to Python. See, for example, , specifically the part of the presentation that's about BLAM -- that's a declarative language (with embedded Python for ``actions'', e.g., triggers, and computations), and I think a neat and useful design, too. Alex From beliavsky at aol.com Sun Jan 30 16:11:44 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 30 Jan 2005 13:11:44 -0800 Subject: Regarding exception handling References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> Message-ID: <1107119504.793109.184450@c13g2000cwb.googlegroups.com> Aggelos I. Orfanakos wrote: > (I don't know why, but indentation was not preserved once I posted.) This problem and its possible solutions was discussed here in the thread "OT: spacing of code in Google Groups". From http Tue Jan 18 22:12:13 2005 From: http (Paul Rubin) Date: 18 Jan 2005 19:12:13 -0800 Subject: generator expressions: performance anomaly? References: <377Hd.77904$Jk5.30235@lakeread01> <41ED1C0F.4030800@holdenweb.com> Message-ID: <7xhdlejenm.fsf@ruckus.brouhaha.com> Steve Holden writes: > You probably already know that sensible compiled language systems have > used constant folding since time immemorial, but Python has always > eschewed it. That's what comes of being a pragmatist's language: if > such optimizations really are required the programmer is expected to > perform them. You mean the lack is deliberate? I just figured it was an artifact of the implementation and that PyPy had some reasonable chance of fixing it. From jjl at pobox.com Mon Jan 3 13:27:52 2005 From: jjl at pobox.com (John J. Lee) Date: 03 Jan 2005 18:27:52 +0000 Subject: HTTP GET request with basic authorization? References: <7c60b60505010215123462c90e@mail.gmail.com> Message-ID: <652efjvb.fsf@pobox.com> Jonas Galvez writes: > Christopher J. wrote: > > I tried this, but it didn't work: > > conn.request("GET", "/somepage.html", None, > > {"AUTHORIZATION": "Basic username:password"}) [...] > import re, base64, urllib2 > > userpass = ('user', 'pass') > url = 'http://somewhere' > > request = urllib2.Request(url) > authstring = base64.encodestring('%s:%s' % userpass) > authstring = authstring.replace('\n', '') > request.add_header("Authorization", "Basic %s" % authstring) > > content = urllib2.urlopen(request).read() There are handlers in urllib2 to do this for you, you shouldn't need to do it by hand. I rarely do, so I won't risk an example... John From littlejohn.75 at news.free.fr Fri Jan 28 10:03:00 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 28 Jan 2005 15:03:00 GMT Subject: a sequence question References: Message-ID: <41fa5424$0$24554$626a14ce@news.free.fr> Le Fri, 28 Jan 2005 13:59:45 GMT, Chris Wright a ?crit : > Hi, > > 1) I want to iterate over a list "N at a time" > > > Is there a nifty way to do with with list comprehensions, > or do I just have to loop over the list ? > > cheers and thanks seq = xrange(1, 9) # an iterable [1, 2, ... 8] N = 2 it = (iter(seq,)*N # a tuple containing N times the *same* iterator on seq print zip(*it) # the list you are after from itertools import izip help(izip) it = (iter(seq),)*2 for tup in izip(*it): print tup > > chris wright From fouff at visitmail.com Wed Jan 12 01:36:38 2005 From: fouff at visitmail.com (Fouff) Date: Wed, 12 Jan 2005 07:36:38 +0100 Subject: [OT] SciTe In-Reply-To: <58%Ed.4827$C52.2609@newsread2.news.atl.earthlink.net> References: <58%Ed.4827$C52.2609@newsread2.news.atl.earthlink.net> Message-ID: <41e4c577$0$6628$626a14ce@news.free.fr> I use Scintilla which is Scite with a lot of configurations files. In directory exists a file "cpp.properties" and near the end of the file is describe the command line use to compile, to link, ... I think you would be able to change here the compiler. regards Fouff From eurleif at ecritters.biz Tue Jan 18 13:35:33 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Tue, 18 Jan 2005 13:35:33 -0500 Subject: One-Shot Property? In-Reply-To: <20050118115456510-0500@braeburn.themorgue.org> References: <20050118115456510-0500@braeburn.themorgue.org> Message-ID: <35534hF4ehdtaU1@individual.net> Kevin Smith wrote: > I have many cases in my code where I use a property for calculating a > value on-demand. Quite a few of these only need to be called once. > After that the value is always the same. In these properties, I set a > variable in the instance as a cached value and return that value on > subsequent calls. It would be nice if there was a descriptor that would > do this automatically. Actually, what would be really nice is if I > could replace the property altogether and put the calculated value in > its place after the first call, but the property itself prevents me from > doing that. This should do it: class CachingProperty(object): def __init__(self, attr_name, calculate_function): self._name = attr_name self._calculate = calculate_function def __get__(self, obj, type=None): if obj is None: return self else: value = self._calculate(obj) setattr(obj, self._name, value) return value And example code: >>> class Foo(object): ... def calculate_value(self): ... print 'Calculating...' ... return 42 ... foo = CachingProperty('foo', calculate_value) ... >>> bar = Foo() >>> bar.__dict__ {} >>> bar.foo Calculating... 42 >>> bar.foo # Notice that the print statement doesn't run this time 42 >>> bar.__dict__ {'foo': 42} From aahz at pythoncraft.com Sun Jan 9 11:44:32 2005 From: aahz at pythoncraft.com (Aahz) Date: 9 Jan 2005 11:44:32 -0500 Subject: Old Paranoia Game in Python References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> Message-ID: In article <5JcEd.1988$KJ2.907 at newsread3.news.atl.earthlink.net>, Lucas Raab wrote: >Sean P. Kane wrote: >> >> I ported the old (and long since removed) game from the bsd-game pacakge >> called, Paranoia, based on the old Paranoia role playing game from C to >> Python as a simple exercise in learning the language and pure late night >> boredom. Anyways, here it is for anyone looking for a few minutes of >> nostalgia. I may get around to posting this at >> http://homepage.mac.com/spkane/ or http://www.spkane.org/, but for now >> here it is. Improvements or corrections, welcome. > > > >> Equipment: Red Reflec Armour, Laser Pistol, Laser Barrel (red), >> Notebook & Stylus, Knife, Com Unit 1, Jump suit, >> Secret Illuminati Eye-In-The-Pyramid(tm) Decoder ring, >> Utility Belt & Pouches >> =============================================================================== > > > >The Illuminati really have infiltrated our society. Stay alert! Trust no one! Keep your laser handy! -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From http Sat Jan 22 14:00:59 2005 From: http (Paul Rubin) Date: 22 Jan 2005 11:00:59 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> Message-ID: <7xllalcmqc.fsf@ruckus.brouhaha.com> "Fredrik Lundh" writes: > > Excellent. I hope you will re-read it several times a day. Doing > > that might improve your attitude. > > you really don't have a fucking clue about anything, do you? You're not making any bloody sense. I explained to you why I wasn't interested in writing that particular piece of code unless it was going in the core. That was in response to your suggestion that I write the code without regard to whether it was going in the core or not. If you didn't understand the explanation, I suggest you read it again, perhaps by putting it on your wall like you said. If you have any questions after that, feel free to post them. From tmohr at s.netic.de Sun Jan 9 10:11:41 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Sun, 09 Jan 2005 16:11:41 +0100 Subject: use a file as a database, access rights Message-ID: Hi, i'd like to write a script that makes use of a database. It would be great if the database would store all its data in a file, that would be great for data exchange. It would also be great if i could use SQL, as i have some experience in that. Also, i NEED access rights to certain parts of the database. Several people should work on it and NEED to have different access rights. Can anybody give me some recommendations on what to use? Thanks for any hints, Torsten. From franco.fiorese at tin.it Sat Jan 29 16:18:11 2005 From: franco.fiorese at tin.it (Franco Fiorese) Date: Sat, 29 Jan 2005 21:18:11 GMT Subject: Pystone benchmark: Win vs. Linux (again) In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Franco Fiorese wrote: > > >>I am relatively new about Python benchmarks. >>After some experiments I found that Python on my PC Windows XP has a relevant higher performance >>than on Linux. The simple test using pystone.py shows this: >> >> * Windows XP Pro: 16566.7 pystones/second >> * Linux (kernel 2.6.9 NPTL): 12346.2 pystones/second > > > what Python version are you using for these tests? what Windows build? > > > > > I have performed the test under Linux Fedora Core 3 and Windows XP Professional SP2. This is the info about my system and Python (from /proc/cpuinfo): processor : 0 vendor_id : GenuineIntel cpu family : 6 model : 8 model name : Pentium III (Coppermine) stepping : 10 cpu MHz : 896.418 cache size : 256 KB fdiv_bug : no hlt_bug : no f00f_bug : no coma_bug : no fpu : yes fpu_exception : yes cpuid level : 2 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 mtrr pge mca cmov pat pse36 mmx fxsr sse bogomips : 1769.47 System RAM: 256MB ------------------------------------- Under Linux The python version is 2.3.4 (release 11) stock Fedora 3 RPM (compiled from python-2.3.4-11.src.rpm) Under Windows the Python version is 2.3.4 ------------------------------------- Anyway I will try to build the latest version (2.4) from source using the best possible optmizations with the gcc compiler. Being the pystone a benchmark that exercises mostly the compiler optimizations I wonder if there is a benchmark that could bring up the whole capabilities of the operating system (I/O, multithreading, memory allocation, etc.). From jbellis at gmail.com Thu Jan 27 17:44:31 2005 From: jbellis at gmail.com (Jonathan Ellis) Date: 27 Jan 2005 14:44:31 -0800 Subject: gnuplot on Canvas widget In-Reply-To: <1106852695.371569.234820@f14g2000cwb.googlegroups.com> References: <1106852695.371569.234820@f14g2000cwb.googlegroups.com> Message-ID: <1106865871.537454.128830@c13g2000cwb.googlegroups.com> Blues wrote: > I have used two great models - Tkinter and Gnuplot.py - for a while. I > can display an image on a Canvas widget using Tkinter and I can also > generate a gnuplot from Python on the fly in a separate window. Does > anyone know how to display such a gnuplot on the Canvas widget with an > image in it? Thanks. >From my experience, the Gnuplot module isn't designed to be used in "headless" mode -- it can save to the usual formats, but you have to render everything in an x11 window interactively first. It might not be hard to modify this, though. -Jonathan From koko9991 at compuserve.de Sun Jan 9 04:22:29 2005 From: koko9991 at compuserve.de (Konrad Koller) Date: Sun, 09 Jan 2005 09:22:29 GMT Subject: curses is not imported under Linux (and Python 2.4) References: <41dd65bd.785984171@news.compuserve.de> Message-ID: <41e0f2dd.126821062@news.compuserve.de> Thanks for your hint. >What Linux distro? SuSE 9.1 >Is the Python version you're running one you compiled, one that shipped >with the distro, or a 3rd party RPM? compiled with Python-2.4.tar.bz2 > >At a guess, I'd say you compiled it yourself and you don't have the >ncurses development packages (providing the ncurses header files and >static libs) installed. see above, but I did not exclude anything, it was a totally normal run. I did the same installation of Python2.4 on a different computer with Fedora2 and found there the _curses.so and _curses_panel.so in lib-dynload, which I missed in SuSE Linux, although under SuSE the curses package was present in Lib. I don't understand this strange behavior between the two installations. After having the 2 mentioned static libs transfered from the "Fedora computer" to the the "SuSE computer" the curses worked fine under SuSE linux Konrad Koller From siona at chiark.greenend.org.uk Mon Jan 24 10:03:16 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 24 Jan 2005 15:03:16 +0000 (GMT) Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> <7xoefhtavd.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >YAML looks to me to be completely insane, even compared to Python >lists. I think it would be great if the Python library exposed an >interface for parsing constant list and dict expressions, e.g.: > [1, 2, 'Joe Smith', 8237972883334L, # comment > {'Favorite fruits': ['apple', 'banana', 'pear']}, # another comment > 'xyzzy', [3, 5, [3.14159, 2.71828, []]]] > [ ... ] >Note that all the values in the above have to be constant literals. >Don't suggest using eval. That would be a huge security hole. I'm probably not thinking deviously enough here, but how are you going to exploit an eval() which has very tightly controlled globals and locals (eg. eval(x, {"__builtins__": None}, {}) ? -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From baas at ira.uka.de Mon Jan 31 15:03:03 2005 From: baas at ira.uka.de (Matthias Baas) Date: Mon, 31 Jan 2005 21:03:03 +0100 Subject: msvcp71.dll and Python 2.4 C++ extensions Message-ID: Hi, are there any guidelines about what to do if a Windows extension for Python 2.4 requires the C++ runtime (msvcp71.dll)? If I want to distribute a binary installer of an extension that contains C++ code, should I really include the msvcp71.dll in the package? It doesn't sound like a good idea to me if every package places another copy of this dll somewhere in the Python directory. Python 2.4 does install the C runtime (msvcr71.dll) in the Windows system32 directory, doesn't it? (btw, shouldn't this be installed in the Python directory instead?) So would it be possible that future Python releases would also install the C++ runtime? I think it's better if the dll would only be installed once by Python instead of several times by every extension that uses C++. Currently, I do not package the C++ runtime and leave it up to the user to install the dll if it isn't already somewhere on his system. But this really is not a satisfying solution... - Matthias - From hwlgw at hotmail.com Fri Jan 21 08:58:27 2005 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 21 Jan 2005 05:58:27 -0800 Subject: Funny Python error messages Message-ID: <1106315907.551660.276380@c13g2000cwb.googlegroups.com> Add your funny or surprising Python error messages to this thread. A requirement is that you should also show (minimal) code that produces the message. Put the code below, so people can think about how to generate the message first, a little puzzle if you like. Perhaps this will even be a useful thread, to brighten the life of the brave people doing the hard work of providing us with error messages. My first one (i'm learning, i'm learning) is TypeError: 'callable-iterator' object is not callable # # # # # >>> it = iter(lambda:0, 0) # >>> it() # TypeError: 'callable-iterator' object is not callable From ajsiegel at optonline.com Mon Jan 31 08:01:58 2005 From: ajsiegel at optonline.com (Arthur) Date: Mon, 31 Jan 2005 08:01:58 -0500 Subject: The next Xah-lee post contest References: <20050130114008.797088857.whereU@now.com> <1107137465.973491.42050@f14g2000cwb.googlegroups.com> Message-ID: On Mon, 31 Jan 2005 07:40:40 -0500, Steve Holden wrote: >gene.tani at gmail.com wrote: > >> Tragi-comic. really. BTW you forgot cross-post to c.l.scheme, C, >> smalltalk and C++ >> >Would there, I wonder, be any enthusiasm for a "Best Xah Lee impression" >prize at PyCon? And the rules of the game, if he shows? I guess "no ringers", would have to be the rule. Art From steve at holdenweb.com Wed Jan 5 16:50:53 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 05 Jan 2005 16:50:53 -0500 Subject: Cookbook 2nd ed Credits (was Re: The Industry choice) In-Reply-To: <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> Message-ID: <41DC613D.1020806@holdenweb.com> Alex Martelli wrote: [...] > If you wished to count only _authored_ recipes (but that's a bit > misleading, since in several recipes-as-published there is a merge of > two or three separately submitted and accepted recipes, and here I'm > counting only the first-listed-author per published-recipe...): > > 1: 25 u'Luther Blissett' > 2: 21 u'Alex Martelli' > 3: 9 u'John Nielsen' > 4: 8 u'Raymond Hettinger' > 5: 8 u'J\x9frgen Hermann' > 6: 6 u'S\x8ebastien Keim' > 7: 6 u'Peter Cogolo' > 8: 6 u'Anna Martelli Ravenscroft' > 9: 5 u'Scott David Daniels' > 10: 5 u'Paul Prescod' > 11: 5 u'Michele Simionato' > 12: 5 u'Mark Nenadov' > 13: 5 u'Jeff Bauer' > 14: 5 u'Brent Burley' > > ....but each still gets ONE free copy...!-) > And I *still* think we deserve to be told the Luther Blissett story ... conspiratorial-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From aleaxit at yahoo.com Fri Jan 28 06:40:17 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 28 Jan 2005 12:40:17 +0100 Subject: limited python virtual machine References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> Message-ID: <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> Steven Bethard wrote: ... > If I could see how to go from 'object' (or 'int', 'str', 'file', etc.) > to 'eval' or '__import__', that would help out a lot... >>> object.__subclasses__() [, , , , , , , , , , , , , , , , ] Traipse through these, find one class that has an unbound method, get that unbound method's func_globals, bingo. Alex From bokr at oz.net Fri Jan 7 17:53:28 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 07 Jan 2005 22:53:28 GMT Subject: Notification of PEP Updates References: Message-ID: <41df128d.260695390@news.oz.net> On Sat, 08 Jan 2005 03:28:34 +1000, Nick Coghlan wrote: >I can't recall which thread this came up in, so I'm starting a new one. . . > >Barry Warsaw has kindly added a "peps" topic to the python-checkins mailing >list. If you want to be notified only when PEP's get updated, then subscribe to >python-checkins and edit your settings to select just the 'peps' topic. How does one get to editing one's settings? > >Let us know if it does anything odd (e.g. sending updates about other checkins) > >The URL for the mailing list is: >http://mail.python.org/mailman/listinfo/python-checkins > >I believe the mail you receive should contain the checkin messages, along with a >summary of the differences between the old version and the new version (handy if >you can read a context diff, not so handy otherwise). > Sounds good. Regards, Bengt Richter From klachemin at comcast.net Sun Jan 2 20:26:24 2005 From: klachemin at comcast.net (Kamilche) Date: 2 Jan 2005 17:26:24 -0800 Subject: Calling Function Without Parentheses! Message-ID: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> What a debug nightmare! I just spent HOURS running my script through the debugger, sprinkling in log statements, and the like, tracking down my problem. I called a function without the ending parentheses. I sure do WISH Python would trap it when I try to do the following: MyFunc instead of: MyFunc() aaaaaaaaaaaah. From daniel.dittmar at sap.corp Wed Jan 26 13:03:45 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Wed, 26 Jan 2005 19:03:45 +0100 Subject: inherit without calling parent class constructor? In-Reply-To: References: Message-ID: Christian Dieterich wrote: > I need to create many instances of a class D that inherits from a class > B. Since the constructor of B is expensive I'd like to execute it only > if it's really unavoidable. Below is an example and two workarounds, but > I feel they are not really good solutions. Does somebody have any ideas > how to inherit the data attributes and the methods of a class without > calling it's constructor over and over again? - rename B to A - class B (A) - move the costly constructor from A to B - class D (A) You can now move some parts from B.__init__ to A.__init__ if they are really needed by D as well. In OO speak: D is not really a subclass of B. Refactor the common code into a new class A. Daniel From steve at holdenweb.com Sat Jan 1 15:01:01 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Jan 2005 15:01:01 -0500 Subject: what is lambda used for in real code? In-Reply-To: <1gpq3nl.8f2klu80m2z0N%aleaxit@yahoo.com> References: <1gpq3nl.8f2klu80m2z0N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Steve Holden wrote: > > >>Adam DePrince wrote: >>[...] >> >>>In sort, we must preserve the ability to create an anonymous function >>>simply because we can do so for every other object type, and functions >>>are not special enough to permit this special case. >>> >> >>And you'd create an anonymous type how, exactly? > > >>>>type('',(),{}) > > > > maybe...? > > Indeed. And then you'd insert all the methods as lambdas by .... We both know that the Python language framework has enough introspection capabilities to do this, but I'm pretty sure you wouldn't try to pretend that this would represent a realistic programming style. Or am I wrong? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From aahz at pythoncraft.com Sat Jan 29 06:52:51 2005 From: aahz at pythoncraft.com (Aahz) Date: 29 Jan 2005 06:52:51 -0500 Subject: Marketing reST (was Re: What YAML engine do you use?) References: <35a6tpF4gmat2U1@individual.net> Message-ID: In article , Fredrik Lundh wrote: > >I've read many specs; YAML (both the spec and the format) is easily >among the worst ten-or-so specs I've ever seen. > >ReST and YAML share the same deep flaw: both formats are marketed as >simple, readable formats, and at a first glance, they look simple and >readable -- but in reality, they're messy as hell, and chances are >that the thing you're looking at doesn't really mean what you think it >means (unless you're the official ReST/YAML parser implementation). >experienced designers know how to avoid that; the ReST/YAML designers >don't even understand why they should. While I can see how you'd get that impression of reST, it's not true: like Python, reST is intended to be simpl*er* and readable, but not simple. The joy of reST is that I can concentrate on writing instead of formatting, just as I do when writing Usenet posts. ;-) Even after using reST for a long time, I'm still constantly looking up features that I use rarely (such as correct formatting of URLs). But reST is great because it's relatively unobtrusive. Those of us who've used reST to document code for a long time have gotten into the habit of using some reST-isms even when not writing reST: have you noticed the number of Pythonistas who use constructs like ``foo()``? Even if you didn't know it was from reST, the meaning is obvious. As you say, reST can/does get messy when you're doing complicated things, but it stays more readable than XML/DocBook. For the most part, I think I'd also have to disagree with your assertion that reST formatting doesn't do what you think it does. In cases where your statement is correct, it's either labeled as an explicit design decision (to prevent other ugliness) or it's a bug. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From baas at ira.uka.de Thu Jan 20 15:29:54 2005 From: baas at ira.uka.de (Matthias Baas) Date: Thu, 20 Jan 2005 21:29:54 +0100 Subject: video analysis with python References: <20050116114407.GE3276@zoran.com> Message-ID: <3q40v09jfkhv9m99djj9eatp0sdkl9fpca@4ax.com> On Mon, 17 Jan 2005 08:08:46 +0100, "Alexander 'boesi' B?secke" wrote: >> 1. There is PyMedia (http://pymedia.org/) > >Is this library able to extract single images from a video? AFAICS it >can only convert videos from one format to another. But I didn't try it, >I've looked only in the docu. Yes, you can extract single images from a video. The package uses the avformat and avcodec libraries from ffmpeg and it provides rather low level access to video/audio files. You can access the individual streams in a file, obtain the stream data and decode the data therein. What you do with the data is up to your application. Converting the file into another format is just one such application. - Matthias - From jerf at jerf.org Sun Jan 30 22:52:33 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 30 Jan 2005 22:52:33 -0500 Subject: gmail access with python! References: Message-ID: On Sun, 30 Jan 2005 21:54:46 -0500, Daniel Bickett wrote: > Indeed, here is a detailed help document on GMail POP3 access: > > http://gmail.google.com/support/bin/answer.py?answer=12103 > > huh...look at that, they're using python :) Never noticed that before. Can you expand on that for us non-GMail users? A login is required to view that page. (I don't care to use GMail; having your own domain still ought to out-geek it :-).) From steven.bethard at gmail.com Mon Jan 31 11:36:38 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 31 Jan 2005 09:36:38 -0700 Subject: re module - cannot make expression In-Reply-To: References: Message-ID: Laszlo Zsolt Nagy wrote: > I would like to match strings not beginning with '/webalizer'. How can I > do this? Are you sure you need a regular expression? The str.startswith method is what I would normally use to solve this kind of problem: py> lst = ['aax', 'abx', 'acx', 'aay', 'aby', 'acy'] py> [s for s in lst if not s.startswith('ab')] ['aax', 'acx', 'aay', 'acy'] If you do need a regular expression, Steve Holden's suggestion about negative lookahead assertions is the right way to go: py> s = 'aaxabxacxaayabyacy' py> re.compile(r'(?!ab).{2}[xy]+').findall(s) ['aax', 'acx', 'aay', 'acy'] Steve From cam.ac.uk at mh391.invalid Sun Jan 16 20:04:16 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 17 Jan 2005 01:04:16 +0000 Subject: List problems in C code ported to Python In-Reply-To: References: <41ead925$0$87061$a1866201@visi.com> Message-ID: Lucas Raab wrote: > Grant Edwards wrote: >> http://www.catb.org/~esr/faqs/smart-questions.html > > I didn't expect to get bitched out just because I didn't follow "protocol." I didn't see anyone bitch you out. And you were lucky that one person was kind enough to go through your web site and make some suggestions. If you had written a better question I guarantee you would have had more people answering your question sooner. Oh yeah, and: http://www.catb.org/~esr/faqs/smart-questions.html#not_losing -- Michael Hoffman From steven.bethard at gmail.com Fri Jan 7 10:44:57 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Jan 2005 08:44:57 -0700 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: Message-ID: Alan Gauld wrote: > On Thu, 06 Jan 2005 21:02:46 -0600, Doug Holton wrote: > >>used, but there are people who do not like "lambda": >>http://lambda-the-ultimate.org/node/view/419#comment-3069 >>The word "lambda" is meaningless to most people. Of course so is "def", >>which might be why Guido van Robot changed it to "define": >>http://gvr.sourceforge.net/screen_shots/ > > > The unfamiliar argument doesn't work for me. After all most > people are unfamiliar with complex numbers (or imaginary) numbers > but python still provides a complex number type. Just because the > name is unfamiliar to some doesn't mean we shouldn't use the > term if its the correct one for the concept. I'm not sure this is really a fair comparison. What's the odds that if you're unfamiliar with complex numbers that you're going to have to read or write code that uses complex numbers? Probably pretty low. I don't think I've ever had to read or write such code, and I *do* understand complex numbers. Lambdas, on the other hand, show up in all kinds of code, and even though I hardly ever use them myself, I have to understand them because other people do (over-)use them. Steve From apardon at forel.vub.ac.be Tue Jan 18 02:51:00 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Jan 2005 07:51:00 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-17, Just schreef : > In article , > Antoon Pardon wrote: > >> >> I don't see a big difference between these principles >> >> and the hash key principle, >> > >> > Than you haven't looked hard enough. >> >> All of these can get unexpected behaviour because of the >> assignment-doesn't-copy semantics. The same semantics >> that can cause problems if you work with mutable dictionary >> keys. > > Again, the difference is: > > 1. assigning mutable objects *can* cause unexpected behavior > (however, it's a useful feature, everyone using Python > for longer than a day or two knows this, and then it's > *expected* behavior. > > 2. mutating dict keys *does* *always* cause problems. > (unless you use an identity hash/cmp) 3 mutating an item in a sorted list *does* *always* cause problems 4 mutating an item in a heap queue *does* *always* cause problems > It's nonsense to forbid 1) since it's a useful feature. It's useful to > forbid ("discourage") 2) since mutating dict keys is seldom useful (and > when it is, Python lets you support it in your own objects). Yes mutating dict keys is seldom usefull. But again you are conflating mutable dict keys with mutating dict keys. No mutables as dict keys means you can't mutate the object even if it is not a key. But whether assigning mutable objects is usefull or not doesn't depend on whether the object will also be usefull as a key or not. You treat this as if an obejct is always a key or never and then decide mutable objects as dict keys is not usefull because mutating keys is not usefull. More specific the Decimal class is mutable and usable as dict key. -- Antoon Pardon From tmj at SPAMLESSjarmania.com Fri Jan 14 10:20:25 2005 From: tmj at SPAMLESSjarmania.com (Tim Jarman) Date: Fri, 14 Jan 2005 15:20:25 +0000 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: <34q69pF4dvkhqU1@individual.net> Skip Montanaro wrote: > > Fredrik> no, expressions CAN BE USED as statements. that doesn't mean > Fredrik> that they ARE statements, unless you're applying belgian > logic. > > Hmmm... I'd never heard the term "belgian logic" before. Googling > provided a few uses, but no formal definition (maybe it's a European > phrase so > searching for it in English is futile). The closest thing I found was > > Or is it another case of Belgian logic, where you believe it because > theres no evidence or motive whatsoever? > > Fredrik> no, it's Python, and it's designed this way on purpose. go > Fredrik> read the language reference. > IANA French person, but I believe that Belgians are traditionally regarded as stupid in French culture, so "Belgian logic" would be similar to "Irish logic" for an English person. (Feel free to insert your own cultural stereotypes as required. :) -- Website: www DOT jarmania FULLSTOP com From benn at cenix-bioscience.com Fri Jan 14 04:26:05 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Fri, 14 Jan 2005 10:26:05 +0100 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <10ue4s49jl8s6d7@corp.supernews.com> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <41e5ebee.709560864@news.oz.net> <1105632841.461042.68310@c13g2000cwb.googlegroups.com> <10udfj4c4rgkvcc@corp.supernews.com> <1105651353.769879.229690@f14g2000cwb.googlegroups.com> <10ue4s49jl8s6d7@corp.supernews.com> Message-ID: <41E7902D.6080507@cenix-bioscience.com> Jeff Shannon wrote: > Chris Lasher wrote: > >>> And besides, for long-term archiving purposes, I'd expect that zip et >>> al on a character-stream would provide significantly better >>> compression than a 4:1 packed format, and that zipping the packed >>> format wouldn't be all that much more efficient than zipping the >>> character stream. >> >> >> This 105MB FASTA file is 8.3 MB gzip-ed. > > > And a 4:1 packed-format file would be ~26MB. It'd be interesting to > see how that packed-format file would compress, but I don't care > enough to write a script to convert the FASTA file into a > packed-format file to experiment with... ;) > > Short version, then, is that yes, size concerns (such as they may be) > are outweighed by speed and conceptual simplicity (i.e. avoiding a > huge mess of bit-masking every time a single base needs to be > examined, or a human-(semi-)readable display is needed). > > (Plus, if this format might be used for RNA sequences as well as DNA > sequences, you've got at least a fifth base to represent, which means > you need at least three bits per base, which means only two bases per > byte (or else base-encodings split across byte-boundaries).... That > gets ugly real fast.) > > Jeff Shannon > Technician/Programmer > Credit International > Hello, Just to clear up a few things on the topic : If the file denotes DNA sequences there are five basic identifiers AGCT and X (where X means 'dunno!'). If the files denoites RNA sequences, you will still only need five basic indentifiers the issue is that the T is replaced by a U. One very good way I have found to parse large files of this nature (I've done it with many a use case) is to write a sax parser for the file. Therefore you can register a content handler, receive events from the sax parser and do whatever you like with it. Basically, using the sax framework to read the files - if your write the sax parser carefully then you stream the files and remove old lines from memory, therefore you have a scalable solution (rather than keeping everything in memory). As an aside, I would seriously consider parsing your files and putting this information in a small local db - it's really not much work to do and the 'pure' python thing is a misnomer, whichever persistence mechanism you use (file,DB,etching it on the floor with a small robot accepting logo commands,etc) is unlikely to be pure python. The advantage of putting it in a DB will show up later when you have fast and powerful retrieval capability. Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From beliavsky at aol.com Sun Jan 30 16:06:52 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 30 Jan 2005 13:06:52 -0800 Subject: Need programming tip References: <1107071340.486489.146580@f14g2000cwb.googlegroups.com> Message-ID: <1107119212.051910.233130@z14g2000cwz.googlegroups.com> A Usenet tip is that one should never use such a generic subject as "need programming tip" or the ever-popular "newbie question". In this case, "create a database of posts made to binary groups" could have been a better title, so that people unable to answer to the question and not interested in the topic can skip it. From jdhunter at ace.bsd.uchicago.edu Thu Jan 20 22:34:23 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 20 Jan 2005 21:34:23 -0600 Subject: Unbinding multiple variables In-Reply-To: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> ("Johnny Lin"'s message of "20 Jan 2005 19:24:43 -0800") References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> Message-ID: >>>>> "Johnny" == Johnny Lin writes: Johnny> Hi! Is there a way to automate the unbinding of multiple Johnny> variables? Say I have a list of the names of all Johnny> variables in the current scope via dir(). Is there a Johnny> command using del or something like that that will iterate Johnny> the list and unbind each of the variables? Hi Johnny I assume you are the one and only Johnny Lin at the U of C, no? John-Hunters-Computer:~> python Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x = 1 >>> y = 2 >>> locals() {'__builtins__': , '__name__': '__main__', 'y': 2, '__doc__': None, 'x': 1} >>> print x,y 1 2 >>> del locals()['x'] >>> print x,y Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined >>> locals() {'__builtins__': , '__name__': '__main__', 'y': 2, '__doc__': None} >>> From aahz at pythoncraft.com Mon Jan 24 08:48:05 2005 From: aahz at pythoncraft.com (Aahz) Date: 24 Jan 2005 08:48:05 -0500 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> Message-ID: In article , Tim Peters wrote: >[Paul Rubin] >> >> And you can break out of a containing loop from a nested loop >> with try/raise. > >Heh heh. Yes, you can. I've never seen a real Python program that >did, but there's nothing to stop you. What did you think the "direct" >in "direct way" might have been intended to mean? Actually, I like breaking out of nested "search" loops with try/except. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From theller at python.net Thu Jan 13 05:54:08 2005 From: theller at python.net (Thomas Heller) Date: Thu, 13 Jan 2005 11:54:08 +0100 Subject: from __future__ import decorators References: Message-ID: Jacek Generowicz writes: > I have some code, which makes copious use of the @decorator syntax > which was introduced in Python2.4. Now I find myself in a situation > where I have to run the code under Python 2.3. However, I would like > to keep developing the code with the new syntax. > > How could I best automate the process of making the syntax digestible > by Python2.3 ? The only way that I know of is this, although you have to rewrite your code somewhat: http://dirtsimple.org/2004/11/using-24-decorators-with-22-and-23.html Thomas From kartic.krishnamurthy at gmail.com Tue Jan 11 19:54:47 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 11 Jan 2005 16:54:47 -0800 Subject: python guy ide References: <41e46d24@usenet01.boi.hp.com> Message-ID: <1105491287.384930.167400@z14g2000cwz.googlegroups.com> Ionel, There are IDE's based on wxPython like SPE and DrPython. SPE is great, but it stops responding when I try to run my wxPython apps (probably something I am doing!). DrPython is another free IDE and it is nice too. >From what I have read, WingIDE is an excellent product (it is a commercial product). Actually , the "best" IDE depends on how you will be using it. If you are looking at nifty debugging features I believe WingIDE is one of the top environments. SPE has it own GUI designer (basically invokes wxGlade), also has a 3D modelling tool (Blender), does syntax checking using pycheck and has good debug capabilities. From what I have seen, I like SPE quite a bit (except for my wx programs hanging). SPE - http://spe.pycs.net/ DrPython - http://drpython.sourceforge.net/ WingIDE - http://www.wingide.com/ You can google for Python IDE and see what comes up. Thanks, --Kartic From bulba at bulba.com Fri Jan 7 08:07:00 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 14:07:00 +0100 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com><7x652che6z.fsf@ruckus.brouhaha.com><7x4qhw859p.fsf@ruckus.brouhaha.com><7xk6qrnbum.fsf@ruckus.brouhaha.com><41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <5fGdnfXE0u2qd0DcRVn-iQ@powergate.ca> Message-ID: <5r0tt0l1h465t9n7tc0dbgf00crvt3irme@4ax.com> On Thu, 6 Jan 2005 23:42:40 -0500, "Terry Reedy" wrote: >>> Would it be possible, at least for Windows, to write a Python script >>> implementing a 'virtual distribution'? IE, download Python, install it, >>> download next package, install it, etc. -- prefereably table driven? >> >> How would you run the script in the first place? > >Duh... with my existing version of Python (which I have had some version of >for so long that I had forgotten what it is to not have one handy) ;-). >Ok, 2 step process for first timers. That is not a problem. The problem is "complex dependencies of stuff you use on plethora of stuff you never even heard of, some of which is missing or WRONG VERSION or broken". Sometimes it gets on the nerves of the developers, too - I remember Vietse Venema, author of Postfix, pulling his hair out, because RedHat was systematically shipping the broken package with DB library that Postfix relied on. The significant problem was, even if you tried to rip out broken DB package (it was Berkeley DB IIRC), and replace with fixed version, packages X, Y and Z from RH whined that they needed previous version. Arrrgh.. (finally, not wanting to break dependencies with using things like --nodeps, I compiled Postfix entirely myself, with everything in custom directories - doesn't that defeat the very purpose of having the package system in the first place?). This problem doesn't appear around that often, but when it does, it stinks, has warts, and bites you in the bottom. Now suppose you have a single tree that Vietse blesses or not. The problem would never arise in the first place. You can't do it in Linux, but you (probably) can do it with Python. When you have it ALL in the single distro, released from time to time, you can easily test it _together_. You don't get _temporal dependencies between various versions_. The released, stable distro has the same things on the same days, and either it all works together or it doesn't. When you depend on a tree of packages, some of which are present and some are not, you _have_ to resolve dependencies like above on the user's side. Which means development has to be done for this, like with a dozen or so of online update programs for Linux (went through it all, from small and primitive programs to using rpmfind.net almost daily to up2date to yum, to finally arrive in the near-paradise of apt). Which means some of the precious and scarce time of developers has to be devoted to solving unnecessary problem. -- It's a man's life in a Python Programming Association. From jelleferinga at planet.nl Sat Jan 29 07:57:45 2005 From: jelleferinga at planet.nl (jelle) Date: 29 Jan 2005 04:57:45 -0800 Subject: future of computing languages Message-ID: <1107003465.707681.161950@f14g2000cwb.googlegroups.com> Quite suprised while reading the Amazin c2.com Wiki: http://c2.com/cgi/wiki?FutureOfProgrammingLanguages Take a look, and feel incredible good about yourself & your decision to opt for python. Did work for me. Cheers, Jelle. From irmen at -nospam-remove-this-xs4all.nl Fri Jan 14 15:13:22 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Fri, 14 Jan 2005 21:13:22 +0100 Subject: Why 'r' mode anyway? In-Reply-To: References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> <41e80785$0$6203$e4fe514c@news.xs4all.nl> Message-ID: <41e827df$0$6219$e4fe514c@news.xs4all.nl> Tim Peters wrote: > That differences may exist is reflected in the C > standard, and the rules for text-mode files are more restrictive than > most people would believe. Apparently. Because I know only about the Unix <-> Windows difference (windows converts \r\n <--> \n when using 'r' mode, right). So it's in the line endings. Is there more obscure stuff going on on the other systems you mentioned (Mac OS, VAX) ? (That means that the bug in Simplehttpserver that my patch 839496 addressed, also occured on those systems? Or that the patch may be incorrect after all??) While your argument about why Python doesn't use its own platform- independent file format is sound ofcourse, I find it often a nuisance that platform specific things tricle trough into Python itself and ultimately in the programs you write. I sometimes feel that some parts of Python expose the underlying C/os implementation a bit too much. Python never claimed write once run anywhere (as that other language does) but it would have been nice nevertheless ;-) In practice it's just not possible I guess. Thanks, --Irmen From beliavsky at aol.com Sat Jan 1 18:01:31 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 1 Jan 2005 15:01:31 -0800 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> Message-ID: <1104620491.542938.92100@z14g2000cwz.googlegroups.com> Paul Rubin wrote: >I don't find static type declarations to have much cost. It's just a >few more keystrokes. I'm open to persuasion about whether they have >benefit. Overall I agree with you and would like to have OPTIONAL static type declarations in Python, as has often been discussed. But without facilities for generic programming, such as templates in C++, static type declarations can force one to duplicate a LOT of code, with one sorting routine each for integer, floats, strings, etc. Some algorithms are type invariant, and Python is a concise language for expressing those algorithms. From dbickett at gmail.com Fri Jan 21 16:20:54 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Fri, 21 Jan 2005 16:20:54 -0500 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> Message-ID: <1d6cdae3050121132062013661@mail.gmail.com> Istvan Albert wrote: > XML with elementtree is what makes me never have think about XML again. I second that. I heard about yaml and I read into it, but when I tried to use it I didn't seem to get in touch with all of the glory surrounding it. The yaml module -- when I tried to use it -- was very error prone, and simply didn't work. I didn't have the time to go through and try to tweak it because I was pressed for time and need a quick solution. As for syck, I don't know if it was just me, but when I downloaded it I got a whole lot of directories with obscure names and files with .c extensions. So, discouraged, I gave up on yaml. Elementtree, on the other hand, is wonderful :) Irmen de Jong wrote: > +1 QOTW I second that, as well. here's-to-appreciating-the-end-without-having-to-be-interested-in-the-means-ly y'rs Daniel Bickett From duncan.booth at invalid.invalid Thu Jan 20 05:06:01 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Jan 2005 10:06:01 GMT Subject: why are these not the same? References: Message-ID: Lowell Kirsh wrote: > On a webpage (see link below) I read that the following 2 forms are not > the same and that the second should be avoided. They look the same to > me. What's the difference? > > Lowell > > ---- > > def functionF(argString="abc", argList = None): > if argList is None: argList = [] > ... > > def functionF(argString="abc", argList=None): > argList = argList or [] > ... > > http://www.ferg.org/projects/python_gotchas.html (number 5) If functionF mutates its argument then these two will give different and possibly unexpected results. I suspect this is what they are hinting at: >>> def f1(s="abc", l=None): if l is None: l = [] l.append(s) return '*'.join(l) >>> def f2(s="abc", l=None): l = l or [] l.append(s) return '*'.join(l) >>> f1('foo', ['bar']) 'bar*foo' >>> f2('foo', ['bar']) 'bar*foo' >>> f1('foo', []) 'foo' >>> f2('foo', []) 'foo' So far the functions appear to operate identically. But: >>> myList = [] >>> f1('foo', myList) 'foo' >>> myList ['foo'] >>> myList = [] >>> f2('foo', myList) 'foo' >>> myList [] It looks as though f1 mutates its argument but f2 doesn't, until you try: >>> f2('foo', myList) 'bar*foo' >>> myList ['bar', 'foo'] >>> >>> So f2 mutates a non-empty list but leaves an empty list unchanged which is probably not what you intend and certainly confusing. From has.temp2 at virgin.net Tue Jan 25 22:38:30 2005 From: has.temp2 at virgin.net (has) Date: 25 Jan 2005 19:38:30 -0800 Subject: HAVE YOU HEARD THE GOOD NEWS! In-Reply-To: <1106701661.128249.250310@c13g2000cwb.googlegroups.com> References: <1106701661.128249.250310@c13g2000cwb.googlegroups.com> Message-ID: <1106710710.367825.94960@f14g2000cwb.googlegroups.com> google_groups_web at yahoo.com wrote: > Good News! What! Guido's just announced Python 3000? Woo-Ho....Oh. F**t. -- TROLLS 13.12: 'And lo, did the Lord Gawd Almighty command: "Go ye forth and Spam all the Seven Thousand and Seventy-seven Groups of Usenet. For truly I am a Beneficent Gawd, and shall surely be picking up the Bill for all thy blessed recipients' Freaking Bandwidth Charges - NOT!"' From bob_smith_17280 at hotmail.com Sat Jan 22 18:01:16 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Sat, 22 Jan 2005 18:01:16 -0500 Subject: [perl-python] 20050121 file reading & writing In-Reply-To: <1106395060.211314.54530@f14g2000cwb.googlegroups.com> References: <1106395060.211314.54530@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > # reading entire file as a list, of lines > # mylist = f.readlines() To do this efficiently on a large file (dozens or hundreds of megs), you should use the 'sizehint' parameter so as not to use too much memory: sizehint = 0 mylist = f.readlines(sizehint) From fredrik at pythonware.com Wed Jan 26 11:50:44 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Jan 2005 17:50:44 +0100 Subject: .WAV processing library ? References: Message-ID: Chris Stiles wrote: > Is there a library available for python that will enable me to process .wav > files ? > > Preferably extensible so I can write handlers for dealing with the non audio > sections. K?re Sj?lander's Snack library might be useful: http://www.speech.kth.se/snack/ From aaronwmail-usenet at yahoo.com Wed Jan 26 14:47:18 2005 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 26 Jan 2005 11:47:18 -0800 Subject: On benchmarks, heaps, priority queues Message-ID: <1106768838.722154.219320@c13g2000cwb.googlegroups.com> I've been wondering about benchmarks recently. What is a fair benchmark? How should benchmarks be vetted or judged? I decided to see what you folks thought, so for discussion I compared two priority queue implementations I published for Python in 1995 against the "heap" priority queue implementation added to the python distribution recently (python 2.3+). My implementations and the benchmark code are in http://xsdb.sourceforge.net/bench/pq3.py (benchmark code near the bottom of the file). The python standard implementation should be in your Lib/ directory. Below please find the numerical results of the benchmarks. They compare the implementations PQPython23 - the Lib implementation PQ0 - my insertion sort based variant PQueue - my "heap" based variant (like PQPython23, but different). There are 2 benchmarks used. insertBench -- which does insertions followed by deletes. mixBench -- which does insertions and deletes mixed together. Here is my summary of the results: 1) For sizes less than 10000 the insertion sort PQ0 is always better. 2) For insertBench sized >10000 PQ0 is very bad and the other two are comparable with PQPython23 always a little faster. 3) For mixBench both of my implementations are better than the Python23 implementation for all sizes tested, but PQ0 is far superior. Here is my analysis of the results: 1) The python23 implementation is best when you expect to be doing mainly inserts with few deletions and the expected size is >10000 (otherwise use pq0). 2) PQ0 is best if you expect to be doing many deletions interspersed with many inserts. 3) PQueue is generally worse than the other two unless you want to use a non-standard comparison function (which the others don't support). My questions to you: Are my conclusions valid? What is a better way to perform and publish benchmarks? -- thanks, Aaron Watters === JUVENILE COURT TO TRY SHOOTING SUSPECT -- a "real life headline" (that should work) ENCLOSURE: run of http://xsdb.sourceforge.net/bench/pq3.py on my machine. ======================= BENCHMARKS FOR 1000 insertBench __main__.PQPython23 on 1000 elapsed 0.039999961853 got 1000 __main__.PQ0 on 1000 elapsed 0.00999999046326 got 1000 __main__.PQueue on 1000 elapsed 0.0299999713898 got 1000 mixBench __main__.PQPython23 on 1000 elapsed 0.00999999046326 got 502 __main__.PQ0 on 1000 elapsed 0.0 got 502 __main__.PQueue on 1000 elapsed 0.00999999046326 got 502 BENCHMARKS FOR 10000 insertBench __main__.PQPython23 on 10000 elapsed 0.261000156403 got 10000 __main__.PQ0 on 10000 elapsed 0.209999799728 got 10000 __main__.PQueue on 10000 elapsed 0.361000061035 got 10000 mixBench __main__.PQPython23 on 10000 elapsed 0.0599999427795 got 5003 __main__.PQ0 on 10000 elapsed 0.0500001907349 got 5003 __main__.PQueue on 10000 elapsed 0.0699999332428 got 5003 BENCHMARKS FOR 100000 insertBench __main__.PQPython23 on 100000 elapsed 3.24500012398 got 100000 __main__.PQ0 on 100000 elapsed 7.93099999428 got 100000 __main__.PQueue on 100000 elapsed 4.82699990273 got 100000 mixBench __main__.PQPython23 on 100000 elapsed 0.641000032425 got 50000 __main__.PQ0 on 100000 elapsed 0.470999956131 got 50000 __main__.PQueue on 100000 elapsed 0.651000022888 got 50000 BENCHMARKS FOR 200000 insertBench __main__.PQPython23 on 200000 elapsed 6.98000001907 got 200000 __main__.PQ0 on 200000 elapsed 28.3209998608 got 200000 __main__.PQueue on 200000 elapsed 10.4350001812 got 200000 mixBench __main__.PQPython23 on 200000 elapsed 1.29099988937 got 100001 __main__.PQ0 on 200000 elapsed 0.911999940872 got 100001 __main__.PQueue on 200000 elapsed 1.33200001717 got 100001 BENCHMARKS FOR 300000 insertBench __main__.PQPython23 on 300000 elapsed 10.9159998894 got 300000 __main__.PQ0 on 300000 elapsed 69.6300001144 got 300000 __main__.PQueue on 300000 elapsed 19.3279998302 got 300000 mixBench __main__.PQPython23 on 300000 elapsed 2.4430000782 got 150000 __main__.PQ0 on 300000 elapsed 1.58299994469 got 150000 __main__.PQueue on 300000 elapsed 2.14300012589 got 150000 BENCHMARKS FOR 400000 insertBench __main__.PQPython23 on 400000 elapsed 16.2630000114 got 400000 __main__.PQ0 on 400000 elapsed 153.661000013 got 400000 __main__.PQueue on 400000 elapsed 24.7860000134 got 400000 mixBench __main__.PQPython23 on 400000 elapsed 2.91400003433 got 200000 __main__.PQ0 on 400000 elapsed 1.8630001545 got 200000 __main__.PQueue on 400000 elapsed 2.73399996758 got 200000 BENCHMARKS FOR 500000 insertBench __main__.PQPython23 on 500000 elapsed 20.1890001297 got 500000 __main__.PQ0 on 500000 elapsed 246.383999825 got 500000 __main__.PQueue on 500000 elapsed 30.1040000916 got 500000 mixBench __main__.PQPython23 on 500000 elapsed 3.2650001049 got 250000 __main__.PQ0 on 500000 elapsed 2.35299992561 got 250000 __main__.PQueue on 500000 elapsed 3.32500004768 got 250000 BENCHMARKS FOR 1000000 insertBench __main__.PQPython23 on 1000000 elapsed 43.0320000648 got 1000000 __main__.PQ0 on 1000000 elapsed 1376.39899993 got 1000000 __main__.PQueue on 1000000 elapsed 67.2970001698 got 1000000 mixBench __main__.PQPython23 on 1000000 elapsed 6.93000006676 got 500001 __main__.PQ0 on 1000000 elapsed 4.8069999218 got 500001 __main__.PQueue on 1000000 elapsed 6.82999992371 got 500001 From http Tue Jan 4 23:14:35 2005 From: http (Paul Rubin) Date: 04 Jan 2005 20:14:35 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> Message-ID: <7xhdlwh5qs.fsf@ruckus.brouhaha.com> "alex23" writes: > It's called "having an opinion". "Good" documentation does its job, if > noone else thought it was poorly documented then to them it wasn't. Obviously other people thought Tkinter is poorly documented in the Python distro, since the Python library manual says so itself and invites people to look at external references instead. > > Software advocacy, which Python has an awful lot of, [...] > > Unjustifiable claims, which your postings have an awful lot of... I've justified every claim I've made. > You've done nothing but kvetch about how others aren't providing you > with what you need. Let's face it, people like you are never going > to take the initiative and actually contribute something when you're > already quite comfortable sponging off the efforts of others and > hiding behind claims of advocacy whenever anyone questions your own > motivations. I'm not one of the Python developers, I'm just a user, I have my own projects that I spend my time on. I like the idea of using Python in some of those projects. Python advocacy revolves around encouraging people to use Python in their projects, without having to be Python developers themselves. Python advocates say "Python does what you need, so use it". That's supposed make Python sound attractive. If the real truth is "Python does something sort of related to what you need, so if besides your own project that you need to finish, you are willing to stop in the middle and take on some additional projects of improving Python, it can end up being useful for your task", that's a lot less attractive. I'm happy to use Python, as it is, for various kinds of noncritical and throwaway tasks. For critical projects I'm looking for tools that work (e.g. Linux, Apache, GCC), not "it's open source, go fix it". But just one or two days ago, various people on this group were urging me to do a critical project in Python instead of Java. I like Python enough to get into these romantic quarrels with it (which is what you're seeing now) and feel pretty cold toward Java. But while Java's libraries are poorly designed, their implementations tend to be quite complete, while Python's are well-designed but often incompletely implemented. And so with Java, I feel much less likely to look in the manual and note the existence of some feature and plan to use it, only to find out after it's too late, that the feature's implementation is missing some crucial functionality that would be a lot of work to add. (Then there's issues with the languages themselves, that are separate). > In short: grow up and just write the damn documentation. In short, I should grow up and quietly ignore a lot of Python advocacy as being groundless and just use Python for limited purposes. But what I want instead is for Python itself to grow up, and do things properly instead of half-assedly. From luismgz at gmail.com Wed Jan 5 12:10:01 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 5 Jan 2005 09:10:01 -0800 Subject: is python more popular than coldfusion? References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dbec00$0$23064$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1104945001.133408.205250@f14g2000cwb.googlegroups.com> worzel wrote: > Wth respect to coldfusion, is there much doubt about the fact that Python is > a more prominent and important technology? > > How is colfusion percieved by the Python community? Many people belive > coldfusion is becomeing irrelavant and is on its death bed - do Python folk > generally feel this way about it? I think this is a little bit like comparing oranges to apples... I wouldn't say Coldfusion is a programming language. It is a tag based scripting language designed for web development and, as such, it is very easy to learn and use, but its application domain is limited to the web. It comes in handy if you're a designer with no programming skills and you want to hook your site to a database or do some easy web development, but I think that professional developers (non-designers) use other alternatives ranging from php (open source, free) to asp.net (propietary -MS). On the other hand, python is a general purpose programming language and it can be used for almost anything you can think of. It is not just a web scripting language. My advice: if you want to learn something for getting a job and making a living, forget about Coldfusion. It is ok for a web designer or for a hobbyist who doesn't know and doesn't want to know about programming, but who needs to get the job done with the least delay. Now if you're serious about making a living as a programmer, and you are willing to study and learn, (and provided you're new to programming) I would highly recommend python as your first language. It is very easy to learn and with it, you'll learn advanced programming concepts quickier and easier than by studying java, for example, because its syntax is cleaner and much more concise, easy to read and to the point. Then, and once you have a good grasp about the basics of programming and object oriented concepts, you will be able to learn any other language such as java or c# (for making big bucks). And if you are not interested in learning another language, python alone will make a very good general purpose programming language. Why the way, it's also very fun! From phr at localhost.localdomain Thu Jan 20 18:06:31 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Thu, 20 Jan 2005 23:06:31 GMT Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" writes: > > Some countries have laws about cryptography software (against some > > combination of export, import, or use). The Python maintainers didn't > > want to deal with imagined legal hassles that might develop from > > including good crypto functions in the distribution. Then it became > > obvious that the same imagined hassles could also befall the rotor > > module, so that was removed. > > Do you know this for a fact? I'm going by newsgroup messages from around the time that I was proposing to put together a standard block cipher module for Python. > The PSF does comply with the U.S. American export procedures for > crypto code, and reports the crypto code in Python appropriately to BXA. Since rotor was removed, there is no crypto code in Python that needs reporting. From theller at python.net Tue Jan 4 10:41:05 2005 From: theller at python.net (Thomas Heller) Date: Tue, 04 Jan 2005 16:41:05 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> Message-ID: Skip Montanaro writes: > michele> BTW what's the difference between .encode and .decode ? > > I started to answer, then got confused when I read the docstrings for > unicode.encode and unicode.decode: > > >>> help(u"\xe4".decode) > Help on built-in function decode: > > decode(...) > S.decode([encoding[,errors]]) -> string or unicode > > Decodes S using the codec registered for encoding. encoding defaults > to the default encoding. errors may be given to set a different error > handling scheme. Default is 'strict' meaning that encoding errors raise > a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' > as well as any other name registerd with codecs.register_error that is > able to handle UnicodeDecodeErrors. > > >>> help(u"\xe4".encode) > Help on built-in function encode: > > encode(...) > S.encode([encoding[,errors]]) -> string or unicode > > Encodes S using the codec registered for encoding. encoding defaults > to the default encoding. errors may be given to set a different error > handling scheme. Default is 'strict' meaning that encoding errors raise > a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and > 'xmlcharrefreplace' as well as any other name registered with > codecs.register_error that can handle UnicodeEncodeErrors. > > It probably makes sense to one who knows, but for the feeble-minded like > myself, they seem about the same. It seems also the error messages aren't too helpful: >>> "?".encode("latin-1") Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0x84 in position 0: ordinal not in range(128) >>> Hm, why does the 'encode' call complain about decoding? Why do string objects have an encode method, and why do unicode objects have a decode method, and what does this error message want to tell me: >>> u"?".decode("latin-1") Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 0: ordinal not in range(128) >>> Thomas From tim.peters at gmail.com Fri Jan 28 14:52:14 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 28 Jan 2005 14:52:14 -0500 Subject: Who should security issues be reported to? In-Reply-To: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> Message-ID: <1f7befae05012811521cd5ca48@mail.gmail.com> [grahamd at dscpl.com.au] > Who are the appropriate people to report security problems to > in respect of a module included with the Python distribution? > I don't feel it appropriate to be reporting it on general mailing > lists. The Python project has no non-public resources for this. Filing a bug report on SourceForge is the usual approach. If you must, you could send email directly to Guido . He may or may not have time to follow up on it; public disclosure is the norm in this project. Be forewarned that despite that he currently works for a security startup, his threshold for "security panic" is very high. From gandalf at geochemsource.com Fri Jan 21 10:07:45 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Fri, 21 Jan 2005 16:07:45 +0100 Subject: wx.BoxSizer problem Message-ID: <41F11AC1.6040108@geochemsource.com> Hi All, Here is the code of a frame: import wx class PanelDatabaseDefinition(wx.Panel): def __init__(self,parent): wx.Panel.__init__(self,parent) self.sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self.sizer) self.sizer.Add(wx.Button(self,label="test1"),flag=wx.EXPAND,proportion=1) self.sizer.Add(wx.Button(self,label="test2"),flag=wx.EXPAND,proportion=1) class FrameDatabaseDefinition(wx.Frame): def __init__(self,parent,title): wx.Frame.__init__(self,parent,title=title) self.panel = PanelDatabaseDefinition(self) self.sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(self.sizer) self.sizer.Add(self.panel,flag=wx.EXPAND,proportion=1) self.Layout() I would like to use the panel PanelDatabaseDefinition on the frame FrameDatabaseDefinition, but I should also be able to use the panel on other frames. (A la "Delphi frames".) My problem is that only one of the buttons is visible and that one is not expanded. (System: Windows, Python 2.3.4, wxPython 2.5.3) Best, Laci From elctrcelctrcgtr1 at aol.com Sat Jan 29 20:04:12 2005 From: elctrcelctrcgtr1 at aol.com (ElctrcElctrcgtr1) Date: 30 Jan 2005 01:04:12 GMT Subject: tutorial idea Message-ID: <20050129200412.21858.00000323@mb-m05.aol.com> have a java applet that runs python code, with a tutorial that goes along with it. that way you just have to go to a website to learn it, instead of downloading and installing a few programs. (i would make it so it assumes that you don't know how to program anything.) From just at xs4all.nl Wed Jan 19 06:21:07 2005 From: just at xs4all.nl (Just) Date: Wed, 19 Jan 2005 12:21:07 +0100 Subject: Dictionary keys (again) (was Re: lambda) References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: In article , Nick Coghlan wrote: > Antoon Pardon wrote: > > A rule of thumb is context sensitive. If circumstances change, > > so do the rules of thumb. Principles have a broader field > > of application. > > > > IMO there is nothing principally wrong with using a mutable object > > as a dictionary key. But avoiding doing so is a good rule of > > thumb if you have a python-like implementation of a dictionary. > > For a 'mutable key' to make sense, the following: > > lst = [] > dct = {l: "Hi!"} > print dct[[]] > print dct[lst] > lst.append(1) > print dct[[1]] > print dct[lst] > > Should print: > Hi > Hi > Hi > Hi > > That's completely impractical though - for any sane implementation, at least > one > of the above print statements will throw a KeyError. > > Your example of a 'safe_dict' that copies mutable keys means that the final > print statement is the one that fails. > > My suggestion of an "identity_dict" means that both of the same-value based > lookups would fail. > > Notice that both of these approaches take a mutable key and make it immutable > (either by holding the sole reference to a copy, or retrieving an immutable > property of the mutable object). > > There's also your solution of "I promise not to mutate the key while it is in > the dictionary". Workable, but opens the door to some entertaining bug hunts > when the promise is broken. > > Which solution is the best default behaviour? > > Well, the Zen of Python states "In the face of ambiguity, refuse the > temptation > to guess". > > So that's the policy the builtin dict follows - it doesn't try to guess when > to > make a copy, or whether or not to use identity based semantics in the face of > mutability. Instead, it raises an exception at key entry time, asking the > programmer to clarify their intent. > > The principle is *certainly* that hash tables should contain immutable keys. > Your own 'safe_dict' example implicitly concedes this point by making copies > 'when required'. 'When required' for what? When required to preserve > immutability, perhaps? > > In short, sane hash tables require immutable keys, and how mutable keys > acquire > the requisite immutability is going to be application dependent. > > Provision of a safe_dict or identity_dict would merely allow a programmer to > state their intent at the time the container is created, rather than having > to > state it whenever keys are generated or referenced. FWIW, the Cocoa framework on OSX supports mutable objects as keys. However, it makes an immutable copy. This is cheap for immutable objects -- Cocoa has both a mutable array as well as an immutable array, likewise for dicts -- since the "copy" will then simply be the same object. Thanks to PyObjC we can explore this from Python: Python 2.3 (#1, Sep 13 2003, 00:49:11) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from Foundation import * >>> lst = [] >>> dct = NSMutableDictionary.alloc().init() >>> dct {} >>> dct[lst] = "Hi!" >>> dct {(1) = "Hi!"; } (Note that Python lists get wrapped as native Cocoa arrays. '(1)' is Cocoa's repr for the wrapped array.) >>> dct[lst] u'Hi!' >>> lst.append(1) >>> dct[lst] Traceback (most recent call last): File "", line 1, in ? File "build/lib.darwin-7.6.0-Power_Macintosh-2.3/objc/_convenience.py", line 77, in __getitem__objectForKey KeyError: [1, 1] >>> dct.keys() ((1)) >>> dct[[1]] u'Hi!' >>> k = dct.keys()[0] >>> k (1) >>> k.append(2) Traceback (most recent call last): File "", line 1, in ? File "build/lib.darwin-7.6.0-Power_Macintosh-2.3/objc/_convenience.py", line 205, in objc.error: NSInternalInconsistencyException - *** -[NSCFArray addObject:]: mutating method sent to immutable object >>> This is not all that different from Python actually, in that Cocoa tries very hard to make it impossible to mutate dict keys. Just From jeff at ccvcorp.com Thu Jan 27 13:53:06 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 27 Jan 2005 10:53:06 -0800 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <10vidp7lujmrt03@corp.supernews.com> Davor wrote: > so you get a nice program with separate data structures and functions > that operate on these data structures, with modules as containers for > both (again ideally separated). Very simple to do and maintain [...] Replace "modules" with "classes" in the above quote, and you have the very essence of object-oriented programming. (What you describe here *is* object-oriented programming, you're just trying to avoid the 'class' statement and use module-objects where 'traditional' OO would use class instances.) Jeff Shannon Technician/Programmer Credit International From philippecmartin at sbcglobal.net Wed Jan 12 06:45:14 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Wed, 12 Jan 2005 12:45:14 +0100 Subject: encryption/decryption help Message-ID: <1105530314.7190.9.camel@localhost> Did you look at pycrypto ? http://www.amk.ca/python/code/crypto.html Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From roy at panix.com Sun Jan 2 12:57:04 2005 From: roy at panix.com (Roy Smith) Date: Sun, 02 Jan 2005 12:57:04 -0500 Subject: Python! Is! Truly! Amazing! References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: In article , Ron Garret wrote: > In article <1104657461.868175.252380 at c13g2000cwb.googlegroups.com>, > "Erik Bethke" wrote: > > > > > I have NEVER experienced this kind of programming joy. > > Just wait until you discover Lisp! > > ;-) > > rg Shouldn't that be ;-)))))))))))))) ? From aleaxit at yahoo.com Sat Jan 29 03:44:27 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 29 Jan 2005 09:44:27 +0100 Subject: limited python virtual machine References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> Message-ID: <1gr58wn.m3n0xac2j9qbN%aleaxit@yahoo.com> Nick Coghlan wrote: > Alex Martelli wrote: > > Steven Bethard wrote: > > ... > > > >>If I could see how to go from 'object' (or 'int', 'str', 'file', etc.) > >>to 'eval' or '__import__', that would help out a lot... > > > >>>>object.__subclasses__() ... > > Traipse through these, find one class that has an unbound method, get > > that unbound method's func_globals, bingo. > > So long as any Python modules are imported using the same restricted > environment their func_globals won't contain eval() or __import__ either. Sure, as long as you don't need any standard library module using eval from Python (or can suitably restrict them or the eval they use), etc, you can patch up this specific vulnerability. > And C methods don't have func_globals at all. Right, I used "unbound method" in the specific sense of "instance of types.UnboundMethodType" (bound ones or any Python-coded function you can get your paws on work just as well). > However, we're talking about building a custom interpreter here, so there's no It didn't seem to me that Steven's question was so restricted; and since he thanked me for my answer (which of course is probably inapplicable to some custom interpreter that's not written yet) it appears to me that my interpretation of his question was correct, and my answer useful to him. > reason not to simply find the dangerous functions at the C-level and replace > their bodies with "PyErr_SetString(PyExc_Exception, "Access to this operation > not allowed in restricted build"); return NULL;". > > Then it doesn't matter *how* you get hold of file(), it still won't work. > (I can hear the capabilities folks screaming already. . .) Completely removing Python-level access to anything dangerous might be a safer approach than trying to patch one access route after another, yes. > Combine that with a pre-populated read-only sys.modules and a restricted > custom interpreter would be quite doable. Execute it in a separate process > and things should be fairly solid. If you _can_ execute (whatever) in a separate process, then an approach based on BSD's "jail" or equivalent features of other OS's may be able to give you all you need, without needing other restrictions to be coded in the interpreter (or whatever else you run in that process). Alex From newsgroups at jhrothjr.com Sat Jan 8 16:02:30 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Sat, 8 Jan 2005 15:02:30 -0600 Subject: "A Fundamental Turn Toward Concurrency in Software" References: <10tu7s9tjnbur81@news.supernews.com> Message-ID: <10u0ik37cs56dca@news.supernews.com> "Peter Hansen" wrote in message news:b9GdnaH9LN5mvX3cRVn-iQ at powergate.ca... > John Roth wrote: >> I have yet to write a multi-thread program for performance reasons. > > If we include in the set of things covered by the term > "performance" not only throughput, but also latency, then > I suspect you actually have written some multithreaded programs > for "performance" reasons. > > *I* certainly have: that's easily the reason for threading > in 95% of the cases I've dealt with, and I suspect those of > many others. Actually, I've never written a multi-threaded program for any reason. There were only two times I had to deal with concurrency: one was a very nice co-routine implementation (HASP, the predecessor to the JES2 subsystem on MVS), and the other was event driven (on an IBM SP). The former system didn't have a threading library, let alone a lightweight one, and the event driven design was a lot simpler for the second application - and I did consider all three options. John Roth > > -Peter From bj_666 at gmx.net Wed Jan 26 17:24:56 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 26 Jan 2005 23:24:56 +0100 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <41f6f4ee$1@nntp.zianet.com> Message-ID: In , Frank Bechmann (w) wrote: > know what's funny: in the Lua mailing list there is currently a > discussion about adding OO to Lua. >From my quick glance at the language last year I recall that one can access elements of tables (in Python: dict()) with this syntax: ``tbl.attr`` and it's also possible to put functions into those tables. So it's already a prototype based OO language. Remember: you need objects for an OO language -- classes are optional! Ciao, Marc 'BlackJack' Rintsch From ncoghlan at iinet.net.au Sun Jan 2 00:56:15 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 02 Jan 2005 15:56:15 +1000 Subject: The Industry choice In-Reply-To: <7xsm5kfyse.fsf@ruckus.brouhaha.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> <7xsm5kfyse.fsf@ruckus.brouhaha.com> Message-ID: <41D78CFF.4050706@iinet.net.au> Paul Rubin wrote: > I don't see that big a problem. The current Python sorting routine > operates on instances of class "object" and calls the __cmp__ method > to do comparisons. Every class of sortable objects either defines a > __cmp__ method or inherits one from some superclass, and sort calls > those methods. Static type declarations would not require writing any > additional sorting routines. Python's list.sort doesn't check the *type* of the arguments at all. It only looks for the relevant comparison methods (__cmp__ or __lt__, as I recall). Sure, classes written in *Python* will ultimately inherit from either object or types.ClassType, but extension classes need not do any such thing. Yet list.sort works with them all, anyway. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From fredrik at pythonware.com Sun Jan 23 07:41:47 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 13:41:47 +0100 Subject: Textual markup languages (was Re: What YAML engine do you use?) References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> Message-ID: Alan Kennedy wrote: > From what I've seen, pretty much every textual markup targetted for web content, e.g. wiki markup, > seems to have grown/evolved organically, meaning that it is either underpowered or overpowered, > full of special cases, doesn't have a meaningful object model, etc. I spent the eighties designing one textual markup language after another, for a wide variety of projects (mainly for technical writing). I've since come to the conclusion that they all suck (for exactly the reasons you mention above, plus the usual "the implementation is the only complete spec we have" issue). these days, I usually use HTML+custom classes for authoring (and run them through a HTML->XHTML converter for processing). the only markup language I've seen lately that isn't a complete mess is John Gruber's markdown: http://daringfireball.net/projects/markdown/ which has an underlying object model (HTML/XHTML) and doesn't have too many warts. not sure if anyone has done a Python implementation yet, though (for html->markdown, see http://www.aaronsw.com/2002/html2text/ ), and I don't think it supports footnotes (HTML doesn't). > If I can't find such a markup language, then I might instead end up using a WYSIWYG editing > component that gives the user a GUI and generates (x)html. > > htmlArea: http://www.htmlarea.com/ > Editlet: http://www.editlet.com/ > > But I'd prefer a markup solution. some of these are amazingly usable. have you asked your users what they prefer? (or maybe you are your user? ;-) From michele.simionato at gmail.com Tue Jan 11 04:08:52 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 11 Jan 2005 01:08:52 -0800 Subject: Python & unicode In-Reply-To: <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> Message-ID: <1105434532.132061.24030@f14g2000cwb.googlegroups.com> Uhm ... >>> class C(object): ... pass ... >>> setattr(C, "?", "The letter ?") >>> getattr(C, "?") 'The letter \xe8' ;-) Michele Simionato From python-url at phaseit.net Sat Jan 15 11:08:03 2005 From: python-url at phaseit.net (Cameron Laird) Date: Sat, 15 Jan 2005 16:08:03 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 15) Message-ID: QOTW: "Python: it tastes so good it makes you hungrier." -- EP "I don't consider 'throws Exception' to be sloppy, I consider it to be programmers voting with their feet." -- Roy Smith The Centre for Epidemiology and Research has released a high-quality suite of Python-based "Network-enabled epidemiology" tools. Among other packages, NetEpi leverages MxDateTime, Albatross, Numeric Python, pyPGSQL, and RPy: http://mail.python.org/pipermail/python-list/2004-December/257928.html Bengt Richter and John Lenton expertly handle binary data, the latter through reliance on mmap: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d9d74e3df5b7495d/ When tackling tedious capabilities like SSL, experts know to leverage the work--Twisted, Medusa, Apache, ...--of others: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/e0ae7d7e43dc606 When tackling tedious capabilities like FASTA, experts know to leverage the work--biopython, mmap, gdbm, ...--of others: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/cf9949fce8d51e7e/ So, you're on a desert island, no credit card, no modern OS, nothing but a thin telnet to the universal IP cloud--you can still practice Python: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/c6e33ffbc0726732 twander 3.160 boasts ... well, read for yourself the details of this quite-cool filesystem browser: http://www.tundraware.com/Software/twander No, you do NOT really want XQuery: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/86afefc7cdad4f6d/ Paul McGuire soberly illustrates pyparse's place in programming: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/387915357b5eb524 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. deli.cio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From cwittern at yahoo.com Tue Jan 11 18:18:57 2005 From: cwittern at yahoo.com (cwittern at yahoo.com) Date: 11 Jan 2005 15:18:57 -0800 Subject: Wide Unicode build for Windows available somewhere? Message-ID: <1105485536.966610.76570@z14g2000cwz.googlegroups.com> Hi there, I am trying to locate a windows binary of a recent python (2.4 preferred, but not essential) with support for Unicode characters with values greater than 0x10000. I have tested the python.org binaries and those from Activestate, both give me a traceback on unichr(0x10000) and tell me its a "narrow" build. Any pointers appreciated. Chris From ialbert at mailblocks.com Tue Jan 4 12:14:46 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 04 Jan 2005 12:14:46 -0500 Subject: Python evolution: Unease In-Reply-To: References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> Message-ID: <98WdnVGqi-yaUkfcRVn-tw@giganews.com> Doug Holton wrote: > application is so important that I expect Python 3000 will have > optional type declarations integrated into the argument list." I think that *optional* part of the "optional type declaration" is a myth. It may be optional in the sense that the language will accept missing declarations but as soon as the feature is available it will become "mandatory" to use it (peer pressure, workplace practices). Istvan. From vanduuren at gmail.com Tue Jan 4 04:26:35 2005 From: vanduuren at gmail.com (Robert) Date: 4 Jan 2005 01:26:35 -0800 Subject: search backward Message-ID: <4c57226b.0501040126.7f0eafc2@posting.google.com> I need to find the location of a short string in a long string. The problem however is that i need to search backward. Does anybody know how to search in reverse direction? Thanks, Robert From asda at sdarta.com Sat Jan 8 08:11:49 2005 From: asda at sdarta.com (worzel) Date: Sat, 8 Jan 2005 21:11:49 +0800 Subject: The best way to do web apps with Python? Message-ID: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> What is the best way to web developemnt with Python? Is there anything close to PHP style in-page script placement that can create and use other Python objects? I am not really interested in Zope (I believe that is more a CMS than anything else?) I am also looking for something a little more structured than a series of CGI Scripts. While on the topic - what is the expectataion of Python for this kind of stuff? Would one use Python for certain other things but turn to PHP for web apps - or would one use their Python skills in place of PHP? TIA -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael at i2partners.com Tue Jan 25 14:46:42 2005 From: michael at i2partners.com (Michael Spencer) Date: Tue, 25 Jan 2005 13:46:42 -0600 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) Message-ID: Steven Bethard wrote: > > I wish there was a way to, say, exec something with no builtins and with > import disabled, so you would have to specify all the available > bindings, e.g.: > > exec user_code in dict(ClassA=ClassA, ClassB=ClassB) > > but I suspect that even this wouldn't really solve the problem, because > you can do things like: > > py> class ClassA(object): > ... pass > ... > py> object, = ClassA.__bases__ > py> object > > py> int = object.__subclasses__()[2] > py> int > > > so you can retrieve a lot of the builtins. I don't know how to retrieve > __import__ this way, but as soon as you figure that out, you can then > do pretty much anything you want to. > > Steve Steve Safe eval recipe posted to cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 Couldn't safe exec be programmed similarly? 'import' and 'from' are syntax, so trivially avoided Likewise, function calls are easily intercepted As you say, attribute access to core functions appears to present the challenge. It is easy to intercept attribute access, harder to know what's safe. If there were a known set of 'dangerous' objects e.g., sys, file, os etc... then these could be checked by identity against any attribute returned Of course, execution would be painfully slow, due to double - interpretation. Michael From golux at comcast.net Sun Jan 9 13:58:43 2005 From: golux at comcast.net (Stephen Waterbury) Date: Sun, 09 Jan 2005 13:58:43 -0500 Subject: Recent infoworld column In-Reply-To: References: <41DEEF0F.5000300@nospamyahoo.com> Message-ID: <41E17EE3.8040207@comcast.net> Roger Binns wrote: > You may also find a talk I gave at baypiggies in July 2004 of interest. > > http://bitpim.org/papers/baypiggies/ > > It covers the various issues in doing a "real world" Python application, > including packaging [etc -- lots of great stuff ...] *Very* nice presentation -- THANKS! Especially interesting to me because my project uses wxPython and I'm always looking at the rationales of other GUI projects for their choices ... I agree with all your points! Wrt event-driven vs. threading decision, I chose the event-driven path (Twisted). For non-GUI aspects (e.g. services), it's awesome ... not as awesome when the Twisted and wxPython event loops have to co-exist. :^/ I'm still hoping some guru will come up with a better solution than the current compromises (timer, etc.), but they are adequately functional for now, for my purposes. Although I probably won't use BitPim myself (I'm very old-fashioned in my cell phone usage ;) I admire your concept and execution. Cheers, Steve From loredo at somewhere.cornell.edu Mon Jan 24 17:46:41 2005 From: loredo at somewhere.cornell.edu (Tom Loredo) Date: Mon, 24 Jan 2005 17:46:41 -0500 Subject: simultaneous multiple requests to very simple database References: Message-ID: <41F57AD1.76AEA58D@somewhere.cornell.edu> Just learned of this today, so I don't know enough details to judge its suitability for you: Durus http://www.mems-exchange.org/software/durus/ It does not do locking, but alleges to be compact and easy to understand, so perhaps you could modify it to meet your needs, or find some other way to handle that requirement. -Tom -- To respond by email, replace "somewhere" with "astro" in the return address. From petite.abeille at gmail.com Sat Jan 29 08:12:07 2005 From: petite.abeille at gmail.com (PA) Date: Sat, 29 Jan 2005 14:12:07 +0100 Subject: what's OOP's jargons and complexities? In-Reply-To: <41fb3c85$0$10470$8fcfb975@news.wanadoo.fr> References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> <41fb3c85$0$10470$8fcfb975@news.wanadoo.fr> Message-ID: <3d5781782629752567b9d46129522caa@gmail.com> On Jan 29, 2005, at 08:34, jacob navia wrote: > First article that demistifies this OO centered approach > in quite a long time. http://www.google.com/search?q=OOP+criticism&ie=UTF-8&oe=UTF-8 http://www.google.com/search?hl=en&lr=&q=OOP+debunked&btnG=Search Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From rkern at ucsd.edu Thu Jan 6 08:43:39 2005 From: rkern at ucsd.edu (Robert Kern) Date: Thu, 06 Jan 2005 05:43:39 -0800 Subject: Python evolution: Unease In-Reply-To: <1gpyxxv.wxsci81e0054aN%aleaxit@yahoo.com> References: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> <41dcc35a$0$3872$afc38c87@news.optusnet.com.au> <1gpyxxv.wxsci81e0054aN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Robert Kern wrote: > ... > >>>>I love eric3, but if you're an eclipse fan, look at enthought's >>>>"envisage" IDE -- it seems to me that it has superb promise. > > ... > >>>Is it available for download somewhere? >> >>Alex is, I think, jumping the gun a bit. Envisage isn't quite ready for >>prime time as your day to day IDE. It might be useful to you right now > > > I apologize if I gave a misleading impression: I did not mean it was > ready to use, or _already_ here; I suggested "looking at" in the sense > of "paying attention to", and specifically mentioned "promise". > > Since the subthread was about future IDE developments, I thought it was > appropriate to mention envisage, in the context of comparisons with > eclipse's plugin-centered architecture. The subthread was? Okay. Never mind me, then. The threading got broken up in my newsreader and I couldn't tell the context. >>as a platform to build a dynamic GUI application (Envisage's intended >>use) if you are willing to get your hands dirty and help us build >>Envisage. Hence, it is not being advertised widely. > > > I saw a Pycon proposed talk about it, so I didn't stop to consider the > "not advertised widely" issue. Thinking about it, I realize Pycon is > almost 3 months from now, so wanting to enthuse about envisage then > doesn't imply already wanting to widely advertise it now; sorry. No worries. The SVN repository address isn't being kept secret, just not advertised much. If anyone is interested in anonymous read-access, they can ask me for the address. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tzot at sil-tec.gr Tue Jan 18 11:46:23 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Tue, 18 Jan 2005 18:46:23 +0200 Subject: Advice to a Junior in High School? [OT] References: <1106034944.793262.19950@z14g2000cwz.googlegroups.com> Message-ID: On Tue, 18 Jan 2005 11:04:01 -0500, rumours say that Peter Hansen might have written: >collegebabe2004 wrote: >> I would suggest taking Japanese because you will have to work with them >> eventually if you do decide to choose compsci as your proffesion. [Peter] >Over what time frame should I expect this requirement to become >critical? I'd like to know so I can reserve a spot in the next >Japanese course in the area, if you think it's really urgent. >Also, should I plan on adopting various aspects of the Japanese >culture as well, or will a mastery of the language be sufficient? I think having a katana next to your keyboard will suffice to give the *impression* you have mastered enough of the japanese culture, Peter :) -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Wed Jan 12 03:59:30 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Wed, 12 Jan 2005 09:59:30 +0100 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <41e41633$1@nntp0.pdx.net> <41e458a9$0$7090$8fcfb975@news.wanadoo.fr> <1105487872.494278.128510@f14g2000cwb.googlegroups.com> Message-ID: <41e52dca$0$7102$8fcfb975@news.wanadoo.fr> Hi ! Sorry, but I think that, for russians, english is an *add-on*, and not a common-denominator. English is the most known language, but it is not common. It is the same difference as between co-operation and colonization. Have a good day -- Michel Claveau From fredrik at pythonware.com Tue Jan 25 02:54:34 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 Jan 2005 08:54:34 +0100 Subject: What's so funny? WAS Re: rotor replacement References: <7x1xchlpqv.fsf@ruckus.brouhaha.com><41efeb82$0$27807$9b622d9e@news.freenet.de><41f1a70b$0$25959$9b622d9e@news.freenet.de><7xekgdmpll.fsf@ruckus.brouhaha.com><7xpszxcnfa.fsf@ruckus.brouhaha.com><7xllalcmqc.fsf@ruckus.brouhaha.com><7xbrbhosh7.fsf@ruckus.brouhaha.com><7xzmz0lw6h.fsf@ruckus.brouhaha.com><41f4324a$0$1547$9b622d9e@news.freenet.de><41f589f9$0$3357$9b622d9e@news.freenet.de><1106615822.2400.122.camel@l Message-ID: wrote: > The likely-best-known Python application in the world (probably more > people have heard of it than have heard of Python) originally had > crypto and what Python application is that? I can think of quite a few applications written in Python that are widely known, but none of these are distributed as Python code to end users. > I do know that its author wanted an AES module in the core > to use for that application, in order to not have to distribute a C > extension From timr at probo.com Fri Jan 21 02:48:34 2005 From: timr at probo.com (Tim Roberts) Date: Thu, 20 Jan 2005 23:48:34 -0800 Subject: Is there a library to parse Mozilla "mork" documents? References: Message-ID: <1rb1v0566bmkesg9mclsk28idkjopgofuc@4ax.com> John Reese wrote: > >Mozilla, Firefox, Thunderbird, and so forth use this awful format >called MORK to store all kinds of things: which messages you've read >in a newsgroup, headers and indexes into the mbox file of messages in >a mail folder, and address books. Yes. What a crock that is. The MORK format is a great way to compress tabular information, IF the information consists of the same pieces of data over and over. E-mail boxes do not fit into that class, so I have no doubt that the typical Thunderbird MORK file is singificantly LARGER than the same file would be in, say, INI format. I wrote a Python script to parse it, but it isn't terribly robust. I was able to produce a dictionary, but I didn't do anything with the results. You're welcome to take a look: http://www.probo.com/timr/parsemsf.py -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mcfletch at rogers.com Tue Jan 11 17:41:55 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 11 Jan 2005 17:41:55 -0500 Subject: Game programming in Python In-Reply-To: References: Message-ID: <41E45633.8020208@rogers.com> Lucas Raab wrote: > Baza wrote: > >> I'm looking for any books or on-line resources on game programming using >> Python. Does anyone have any advice? >> -- Computer says, 'no' >> >> > > www.panda3d.com, www.pygame.org, www.blender3d.com ... http://www.vrplumber.com/py3d.py?category=game HTH, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From mail at tuxipuxi.org Fri Jan 14 10:06:28 2005 From: mail at tuxipuxi.org (Michael Goettsche) Date: Fri, 14 Jan 2005 16:06:28 +0100 Subject: Using Sqlite with Python under Windows In-Reply-To: <1105710976.907378.193400@c13g2000cwb.googlegroups.com> References: <1105710976.907378.193400@c13g2000cwb.googlegroups.com> Message-ID: <200501141606.28584.mail@tuxipuxi.org> On Friday 14 January 2005 14:56, Kartic wrote: > > I posted this morning but I don't know what happened to my post! > > In any case, PySqlite is the distribution I have used and is available > at pysqlite.org. > > I believe there is another module called APSW (Another Python Sqlite > Wrapper) available, that I stumbled upon just today, after reading your > post. Home page : http://www.rogerbinns.com/apsw.html > > Please read the section "pysqlite differences" to see which one you > want to install. > > As for installation, it should be as simple as downloading the win32 > binaries for your Python distro and executing it. I do not have admin > rights on my Win2K PC at work, but it installed and worked just fine. > So, you should not have any problem. You will not have to install > anything additional other the python-sqlite module itself. > > Good choice on selecting Sqlite..I love it and hope you will enjoy it > too! > > Thanks, > --Kartic Hi Kartic, thanks for your answer. I've installed PySqlite on my system at home and will look into the docs now. I think it's good for our purposes. Thanks, Michael From achan90 at gmail.com Thu Jan 6 12:06:28 2005 From: achan90 at gmail.com (Angie) Date: 6 Jan 2005 09:06:28 -0800 Subject: wsse:Security header Message-ID: <1105031188.673468.30370@z14g2000cwz.googlegroups.com> Hi, all, I would like to use Python to generate SOAP message with wsse:Security, UsernameToken header, does anyone has some example how to using ZSI? Thanks Angie From "yardholler\" at Nospam,charter.net> Sat Jan 15 07:10:40 2005 From: "yardholler\" at Nospam,charter.net> (Misty) Date: Sat, 15 Jan 2005 06:10:40 -0600 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> <1105739748.306557.72120@z14g2000cwz.googlegroups.com> <6e1xcnjxre.fsf@dingo.beable.com> Message-ID: Brian Eable wrote: > "mr_little" writes: > > >>Brian Eable wrote: >> >>>perl -e '$a="194.109.137.226"; @a = reverse split /\./, $a; for $i >> >>(0..3) { $sum += $a[$i]*(256**$i) } print "sum = $sum\n"' >> >>>226 + 35072 + 7143424 + 3254779904 = 3261958626 >>> >>>http://3261958626/ >>> >>>Which is NOT 666. >> >>Comrade, why perl here? :) > > > Huh? Alt.prophecies.nostradamus is ALL ABOUT PERL! > > And at the end of the age > There shall be a mysterious language > Filled with punctuation > It will connect many things. > > >>Are you afraid python? :) > > > I asked you to stop calling me python. > > Feel free to write a python version if you want to. > > From christiancoder at gmail.com Mon Jan 17 17:43:30 2005 From: christiancoder at gmail.com (Grover) Date: 17 Jan 2005 14:43:30 -0800 Subject: Cygwin Popen object In-Reply-To: References: <1105994485.770313.141910@f14g2000cwb.googlegroups.com> Message-ID: <1106001810.012793.32920@z14g2000cwz.googlegroups.com> Yup that fixed it, thanks a million :) From martin at v.loewis.de Fri Jan 21 20:06:27 2005 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sat, 22 Jan 2005 02:06:27 +0100 Subject: rotor replacement In-Reply-To: References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> Message-ID: <41f1a70b$0$25959$9b622d9e@news.freenet.de> phr at localhost.localdomain wrote: >>Do you know this for a fact? > > > I'm going by newsgroup messages from around the time that I was > proposing to put together a standard block cipher module for Python. Ah, newsgroup messages. Anybody could respond, whether they have insight or not. >>The PSF does comply with the U.S. American export procedures for >>crypto code, and reports the crypto code in Python appropriately to BXA. > > > Since rotor was removed, there is no crypto code in Python that needs > reporting. We have released different versions of Python in the past. For Python 2.2, a report about the rotor module was sent to BXA. Regards, Martin From steve at holdenweb.com Mon Jan 31 18:25:59 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 18:25:59 -0500 Subject: Want to meet any of these people? They are registered for PyCon In-Reply-To: References: Message-ID: Stephen Thorne wrote: > On Mon, 31 Jan 2005 17:49:53 -0500, Steve Holden wrote: > >>Aahz wrote: >> >>>In article , >>>Steve Holden wrote: >>> >>> >>>>Note that the sort order isn't perfect - I just sorted on the second >>>>"word" in each name. PyCon is a *great* place to meet people and discuss >>>>ideas. Hope to see you there. >>> >>> >>>Good thing I'm not coming this year, eh? ;-) >> >>If you mean specifically for sorting purposes, it would have put the >>null second name at the beginning just like you'd expect. > > > Odd, the naive way I would have written such a script would have been: > > all_names = (line.split() for line in sys.stdin) > sys.stdout.writelines(' '.join(x[1])+'\n' for x in sorted((name[1], > name) for name in all_names)) > > which would not have worked correctly, it would have thrown an > exception because "Aahz\n".split()[1] does not exist. > > I guess the second iteration would use name[1:] instead... > > unfortunately-not-going-to-pycon-ly y'rs. > Stephen Thorne Sorry you can't make it to Python. My even-naiver way of approaching the problem was to use the sort utility built into Cygwin, thereby avoiding writing any code at all. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From jeff at ccvcorp.com Wed Jan 26 14:17:42 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 26 Jan 2005 11:17:42 -0800 Subject: Browsing text ; Python the right tool? In-Reply-To: <1106707324.874852.208520@z14g2000cwz.googlegroups.com> References: <10vdpohm549g44a@corp.supernews.com> <1106707324.874852.208520@z14g2000cwz.googlegroups.com> Message-ID: <10vfqra5knegoa3@corp.supernews.com> John Machin wrote: > Jeff Shannon wrote: > >> [...] If each record is CRLF terminated, then >>you can get one record at a time simply by iterating over the file >>("for line in open('myfile.dat'): ..."). You can have a dictionary >>classes or factory functions, one for each record type, keyed off >>of the 2-character identifier. Each class/factory would know the >>layout of that record type, > > This is plausible only under the condition that Santa Claus is paying > you $X per class/factory or per line of code, or you are so speed-crazy > that you are machine-generating C code for the factories. I think that's overly pessimistic. I *was* presuming a case where the number of record types was fairly small, and the definitions of those records reasonably constant. For ~10 or fewer types whose spec doesn't change, hand-coding the conversion would probably be quicker and/or more straightforward than writing a spec-parser as you suggest. If, on the other hand, there are many record types, and/or those record types are subject to changes in specification, then yes, it'd be better to parse the specs from some sort of data file. The O.P. didn't mention anything either way about how dynamic the record specs are, nor the number of record types expected. I suspect that we're both assuming a case similar to our own personal experiences, which are different enough to lead to different preferred solutions. ;) Jeff Shannon Technician/Programmer Credit International From peter at engcorp.com Sun Jan 2 10:25:43 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 02 Jan 2005 10:25:43 -0500 Subject: What can I do with Python ?? In-Reply-To: References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> Message-ID: Casey Hawthorne wrote: > Aren't games using full screen mode to address only 320 by 240 > resolution for faster screen painting? > > If one used only 320 by 240 in a window, then that would be 1/4 of the > screen or less! And, on many of our screens, only a few inches across and too small to see without a magnifying glass... Providing the user with the *option* of running in a window, preferably resizable, or full-screen, would be best. -Peter From me at privacy.net Thu Jan 13 15:26:36 2005 From: me at privacy.net (Dan Sommers) Date: 13 Jan 2005 15:26:36 -0500 Subject: Octal notation: severe deprecation References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> Message-ID: On Thu, 13 Jan 2005 09:56:15 -0500, Steve Holden wrote: > I remember using a langauge (Icon?) in which arbitrary bases up to 36 > could be used with numeric literals. IIRC, the literals had to begin > with the base in decimnal, folowed by a "b" followed by the digits of > the value using a through z for digits from ten to thirty-five. So > gunk = 36b8H6Z9A0X > would have been valid. Lisp also allows for literals in bases from 2 through 36. Lisp also allows programs to change the default (away from decimal), so that an "identifier" like aa is read by the parser as a numeric constant with the decimal value of 170. Obviously, this has to be used with care, but makes reading external data files written in strange bases very easy. > nothing-new-under-the-sun-ly y'rs - steve every-language-wants-to-be-lisp-ly y'rs, Dan -- Dan Sommers Never play leapfrog with a unicorn. From itsme at yahoo.com Fri Jan 7 00:11:20 2005 From: itsme at yahoo.com (It's me) Date: Fri, 07 Jan 2005 05:11:20 GMT Subject: Another PythonWin Excel question References: <41ddb59e$0$8338$afc38c87@news.optusnet.com.au> <41de0285$0$5108$afc38c87@news.optusnet.com.au> Message-ID: Okay, thanks. That helps a lot. "Mike Thompson" wrote in message news:41de0285$0$5108$afc38c87 at news.optusnet.com.au... > It's me wrote: > > Yes, Mike, > > > > Others pointed that out as well. > > For good reason. > > > > > The difficulty is that they are all in VBAs. Most of them can be > > translated to Python fairly easily, and some I can get from looking at the > > recorded macro - but some requires quite a bit of head scratching. > > > > For instance, I wanted to figure out how create a new window. So, I went > > through the record macro process and looked at the VBA code, it says: > > > > ActiveWindow.NewWindow > > app.ActiveWindow.NewWindow() > > > > > Okay. Now what??? > > > > And for switching window, it says: > > > > Windows("Book1:1").Activate > > app.Windows.Item("Book1:1").Activate() > > --------------------------------------------------------------------- > > from win32com.client import Dispatch, constants > > app = Dispatch("Excel.Application") > app.Visible = True > > workbook = app.Workbooks.Add() > > defaultWorksheet = workbook.Worksheets(1) > > app.ActiveWindow.NewWindow() > app.ActiveWindow.NewWindow() > > # grab the capation (like 'Book1:1') from one of the windows > thridWindowsCaption = app.Windows[2].Caption > > print thridWindowsCaption > app.Windows.Item(thridWindowsCaption).Activate() > > ------------------------------------------------------------------------ > > Sometimes its useful to look in the file generated by makepy. It details > all the classes and their methods AND there are annotations in the form > of comments. Having said that, if you've never looked in a makepy > generated module before, you're in for a shock - it takes a while > before you figure out what you are looking at. > > When you get stuck, trial & error and a good debuger are your friend. > > -- > Mike From ncoghlan at iinet.net.au Fri Jan 28 06:32:42 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 28 Jan 2005 21:32:42 +1000 Subject: Who should security issues be reported to? In-Reply-To: <1106911061.429966.303510@f14g2000cwb.googlegroups.com> References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> Message-ID: <41FA22DA.2090402@iinet.net.au> grahamd at dscpl.com.au wrote: > I'm sorry, but this isn't really good enough. If Open Source wants to > say that > they are better than these proprietary companies, they need to deal > with these > sorts of things more professionally and establish decent channels of > communications for dealing with it. Is that the sound of a volunteer I hear? All you have to do is put your hand up, and the problem will be solved. If not you, who? Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From klachemin at comcast.net Wed Jan 26 01:57:54 2005 From: klachemin at comcast.net (Kamilche) Date: 25 Jan 2005 22:57:54 -0800 Subject: script to search ebay? References: Message-ID: <1106722674.838311.308520@z14g2000cwz.googlegroups.com> This script works. But why not make a 'Favorite Search' in ebay, and have it send you daily email for a year? --Kamilche |import urllib |import smtplib | |def main(): | # Perform the search | results = SearchEbay(['So long and thanks for all the fish', | 'NOMATCHFOUND', | 'Python Programming']) | | # Email the results | Email('me at somewhere.com', | 'you at somewhere.com', | 'eBay Search Results', | results) | |def SearchEbay(searchstrings): | ' Search eBay for the desired items' | searchURL = "http://search.ebay.com/%s" | results = "" | s = "eBay Search Results:\n" | print s, | results += s | for i in range(len(searchstrings)): | | # Build the search URL | search = searchstrings[i].replace(' ', '-') | s = searchURL % search + " : " | print s, | results += s | | # Download the URL | url = urllib.urlopen(searchURL % search) | data = url.read() | url.close() | | # Write the URL to a file for debugging | fd = open('ebay %d.html' % i, 'w') | fd.write(data) | fd.close() | | # Search for the number of items found | c = data.find('items found for') | if c >= 0: | start = data.rfind('', 0, c) + 3 | stop = data.find('', start + 1) | cnt = data[start:stop] | else: | cnt = '0' | s = "%s items found.\n" % cnt | print s, | results += s | | return results | |def Email(fromaddr, toaddr, subject, msg): | ' Send email' | msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % \ | (fromaddr, toaddr, subject, msg)) | server = smtplib.SMTP('your.smtp.server.here') | server.set_debuglevel(1) | server.sendmail(fromaddr, toaddr, msg) | server.quit() | |main() From crap1234 at hotmail.com Fri Jan 7 17:02:26 2005 From: crap1234 at hotmail.com (Stefan Axelsson) Date: Fri, 07 Jan 2005 23:02:26 +0100 Subject: The Industry choice In-Reply-To: References: <10trej2fl8dip65@corp.supernews.com> Message-ID: <348f7jF45k2kdU1@individual.net> Bulba! wrote: > Oh, and by the way - since Python bytecode can be relatively > easily decompiled to source, could it interpreted to "really" > count as source code and not binary? What are the consequences > of releasing code _written in Python_ as GPLed? Well, to your first question, in a word 'no', it wouldn't count as source code. To quote the GPL section 3: "The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable." As the preferred form for making changes to Python programs would be Python source, that's what counts. This is also what forbids obfuscated code. If you were to *write* Python bytecode, as a form of assembly, then of course that's another matter. I've released Python source as GPL and as far as I'm concerned it ought to work, even though that's not explicitly covered. As the only way you're going to receive my program is by receiving the source then you'll end up having it and everything's basically OK. If someone tries to make a binary from that and distribute that without also making the source available then the GPL obviously comes into effect, and the game is up. I haven't sought legal (or FSF) input on this matter though, it's just my understanding. You can be fairly confident that the GPL is iron clad though, it would have been dragged through every court in the land by now if it wasn't. I've also followed the LGPL/GPL library debate, and while I have opinions on that as well, this is getting long in the tooth already. Stefan, -- Stefan Axelsson (email at http://www.cs.chalmers.se/~sax) From paschott at no.yahoo.spamm.com Thu Jan 20 14:27:18 2005 From: paschott at no.yahoo.spamm.com (Peter A. Schott) Date: Thu, 20 Jan 2005 19:27:18 GMT Subject: FTPLIB & FTPS or SFTP? References: <9b9tu0te197u3bmheldg2hsvkbtuivlov6@4ax.com> <64p3c2-tl1.ln1@home.rogerbinns.com> Message-ID: Can't seem to hit the site right now. I'll have to try back later. From what I can tell, there aren't any mirrors set up, either. Two quick recommendations is promising, though. Thanks for the recommendations. -Pete "Roger Binns" wrote: > > "Peter A. Schott" wrote in message news:9b9tu0te197u3bmheldg2hsvkbtuivlov6 at 4ax.com... > > have a handful of partners who use FTPS or SFTP and I need to pull/push files > > to/from them. > > For SFTP, run don't walk, over to http://www.lag.net/paramiko/ > > Paramiko is a pure Python(*) implementation of SSH and all the > sub-protocols such as SFTP. Works on all platforms, very responsive > author, works reliably and LGPL license. > > (*) It does require PyCrypto which is a native code package available > for all platforms. > > Roger > From tmohr at s.netic.de Mon Jan 17 15:52:07 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Mon, 17 Jan 2005 21:52:07 +0100 Subject: extension module, thread safety? Message-ID: Hi, i write an extension module in C at the moment. This module does some work on some own data types that consist of some values. The functions that can change the data are written in C. The question came up if this is by itself thread safe, if some two or more threads try to change these data types, are the C functions by themselves are "atomic" or can they be interrupted be the perl interpreter and then (data types are in some inconsistent half-changed state) another function that works on these data is called? Thanks for hints, Torsten. From gene.tani at gmail.com Sun Jan 30 21:11:06 2005 From: gene.tani at gmail.com (gene.tani at gmail.com) Date: 30 Jan 2005 18:11:06 -0800 Subject: The next Xah-lee post contest In-Reply-To: References: <20050130114008.797088857.whereU@now.com> Message-ID: <1107137465.973491.42050@f14g2000cwb.googlegroups.com> Tragi-comic. really. BTW you forgot cross-post to c.l.scheme, C, smalltalk and C++ From bh at intevation.de Wed Jan 12 14:10:38 2005 From: bh at intevation.de (Bernhard Herzog) Date: Wed, 12 Jan 2005 20:10:38 +0100 Subject: counting items References: Message-ID: "It's me" writes: > May be flatten should be build into the language somehow.... That shouldn't be necessary as it can easily be written in a single list comprehension: a = [[1,2,4],4,5,[2,3]] flat_a = [x for cur, rest in [[a[:1], a[1:]]] for x in cur if (not isinstance(x, (list, tuple)) and (not rest or not cur.append(rest.pop(0))) or (x and (cur.append(x[0]) or rest.__setslice__(0, 0, x[1:]))) or (not x and rest and cur.append(rest.pop(0))))] ;-) Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ From bulba at bulba.com Thu Jan 6 18:40:55 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 00:40:55 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> <1gpwrh7.b7z8qtablx7gN%aleaxit@yahoo.com> <41DD4E62.1020404@holdenweb.com> Message-ID: On Thu, 06 Jan 2005 09:42:42 -0500, Steve Holden wrote: >> You see, I'm not disagreeing with you that your model applies >> _where it applies_. I only disagree that it applies in face of >> stronger forces. Now what kind of forces is dominant in >> most frequent scenarios would have to be worked out in tedious >> empirical research I think. Which I haven't done, because >> learning some economics is just a hobby to me. >Yes, by all means let's just spout our opinions without any of that >inconvenient tedious empirical research which might invalidate them. Err, but what did I do that got you visibly pissed off? I certainly did not mean offending anyone. If I did smth that did, I apologize, but honestly I didn't mean that. I just expressed my opinion and cited some small bits of evidence, which I think I'm entitled to. >> Capital investments per worker in auto industries are reportedly >> very high. Simple physical tasks are done largely by machines, >> like this 100 million Deutschmark costing laser-cutting installation >> that I've seen there, where a pile of iron bars is pulled in at one >> end and the pile of ready components is spitted out of the other end >> (unlike typical thermal cutting, laser has the advantage of not >> destroying the metal structure adjacent to the cut, so the parts >> of the machines subject to high-stress are oft produced this way). >The same is true of plasma-arc cutting for thicker steels, and I believe >it's still not possible to cut 3-inch stainless with a laser. But what's >your point? I was just explaining the issue for someone who could wonder "why bother with cutting that with laser". The components of those machines, even bigger ones, typically were not as thick as 3 inches. >> Oh, and by the way that installation doesn't get used much. >> Somebody at the office didn't check carefully enough the >> energy prices before ordering it and later someone discovered >> that off-site specialized cutting firms that take advantage of >> energy available at low prices at special times in other countries >> can get it produced cheaper. Moving it elsewhere or selling >> is not an option, since it is a specially constructed, low, 50-meters >> long hall that stands inside the huge manufacturing hall of the >> company. >And you are using this example to try and argue that engineers are >better-educated than sales people? Nope. The context was that behavior of companies tends to be highly rational, optimized and not wasting resources. My naturally individual experience was that it was oft not the case, and that was the example. Which was my point when explaining the clustering that demonstrably happened: if the behavior of decisionmakers is highly informed, rational and not really induced much by risk avoidance as Alex claims, then the clusters are created by "natural economic forces". However, if the process is not that rational, then maybe clusters are the correlation of "cover your ass" aspect in managers' behavior all wanting to get their branch office in yesterday in Tokyo, today in Beijing, and during speculative craze in Russia in Moscow "because everybody is doing that". Which observations of Paul Krugman on "defective investors" seem to support. Now, I'm very strongly opposed to saying that all that somehow invalidates economics, including economics of software, as _science_. All I'm saying is that maybe this particular model is not what some people think it is. This is the problem with economics, people tend to get hot under the collar about it for some reason and it's oft hard to debate that calmly. Which personally I find a pity, because e.g. economics of software is such an interesting subject.. >Who sold this installation? Who >bought it? I have no idea, as I were not a manager there and it didn't really pertain my work. >> I was utterly shocked. Having grown up in Soviet times I have >> been used to seeing precious resources wasted by organizations >> as if resources were growing on trees, but smth like this?! In a >> shining ideal country of Germany?! Unthinkable. >Indeed not. Quite often the brown paper bag is a factor in purchases >like this. I wouldn't be at all surprised if somebody with a major input >to the decision-making process retired to a nice place in the country >shortly afterwards. You appear to be making the mistake of believing >that people will act in the larger interest, when sadly most individuals >tend to put their own interests first (some would go as far as to define >self-interest as the determinant of behavior). But there is a subtler point here: most likely it was NOT in the short-term personal interest to make this mistake (as I believe corruption was not the case in this decision)! After all, whoever responsible was still running the considerable risk of getting fired. It is an example that precisely negates either collective or individual, long-term or short-term, interest was primary factor in this decision. >>>The firm I was working for had a consensus decision-making process (even >>>I was involved) and managers (and other employees) and stockholders were >>>mostly the same people -- it wasn't all that large a firm at the time. >>>Nobody needed to practice risk avoidance. >> Again, you may have had good luck. Where I worked (including >> some places in Germany and UK) it was almost the only factor >> that seemed to matter to people - they'd do ANYTHING not to >> take a risky decision, to "pass the buck", not to stick their necks >> out, not to declare doing some work that involved challenges. >Some people are like that. I chose a long time ago to try not to work >with them whenever I could avoid it and, while that may have had >negative economic consequences I an convinced it has improved my quality >of life immensely. Of course, I have no proof for such an assertion. Which in economic terms could mean that your "utility function" is "modeled" in this particular way (well, strictly speaking utility functions regard simple consumption), while most people tend to misunderstand it as the idea that supposedly is "vulgar consumption of as much stuff as possible is what makes people happy" and they feel rightly repulsed from such an idiotic idea. The trouble is, well-informed people do not to argue that, while people tend to think economists actually do... -- It's a man's life in a Python Programming Association. From steve at holdenweb.com Mon Jan 3 15:35:32 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Jan 2005 15:35:32 -0500 Subject: What can I do with Python ?? In-Reply-To: References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> <1gpqhbl.125l3evz09uefN%aleaxit@yahoo.com> Message-ID: <84iCd.67879$Jk5.21234@lakeread01> John J. Lee wrote: > Lee Harr writes: > [...] > >>I think it looks pretty good. The only problem I see is section 5 >>where it says: >> >>5. Did we miss your concern? >> >> Please add a comment to this page. >> >> >>but the page is immutable. > > > > Hopefully one of the site maintainers will read this and demonstrate > that it's actually readonly rather than immutable, then make it > appendable ;-) > > To be even more pedantic, I believe it's possible to gain editing privileges on the Wiki by authenticating yourself to the engine at http://www.python.org/moin/UserPreferences The point is to be able to track changes and thereby discourage defacement, which was starting to happen of a depressingly regular basis. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From nick at craig-wood.com Fri Jan 28 13:30:01 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 28 Jan 2005 18:30:01 GMT Subject: Elliptic Code References: Message-ID: Philip Smith wrote: > I understand the algorithm quite well but how to code the multiplication > stage most efficiently in python eludes me. You might want to look at http://gmpy.sourceforge.net/ It has very fast multiplication up to any size you like! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From siggy2 at supereva.it Tue Jan 18 05:08:27 2005 From: siggy2 at supereva.it (siggy2 at supereva.it) Date: 18 Jan 2005 02:08:27 -0800 Subject: ftplib strange behaviour References: <1104495025.682424.72160@c13g2000cwb.googlegroups.com> <1104559663.334186.285970@z14g2000cwz.googlegroups.com> Message-ID: <1106042907.555673.321610@c13g2000cwb.googlegroups.com> Kartic wrote: > I have used ftplib but never for such a huge file (assuming your > problem is related to the size of the file). we're doing that since python 2.2 from different site to different hosts where our script was installed... needless to say all the (few) problems we had came from the servers... > Have you tried downloading the file using another ftp client? Does that > download succeed? The reason I ask is because I have attempted > downloads from servers that terminate the connection after a certain > connection time, in the middle of a download! After two weeks the sysadms of the ftp server discovered a misconficuration in some router... Anyway we had already change the script: we managed to trap any exception and we added a "retry" loop. > > That is the best I can help you out with the information. Thank you for your help anyway. bye, PiErre From davidf at sjsoft.com Mon Jan 10 03:13:38 2005 From: davidf at sjsoft.com (David Fraser) Date: Mon, 10 Jan 2005 10:13:38 +0200 Subject: SuSE 9.1: updating to python-2.4 In-Reply-To: References: Message-ID: Torsten Mohr wrote: > Hi, > > along with my distribution SuSE 9.1 came python 2.3.3. > > I'd like to update to 2.4 now, is this an easy thing to do > or will lots of installed modules refuse to work then? > > Is there an easy way to find out what i need to update? > > > Thanks for any hints, > Torsten. > What you probably want to do is install python2.4 alongside python2.3.3 as an alternate installation, since a lot of other programs in SuSE probably depend on having python2.3.3 and won't work with the upgrade. Have a look at the RPMs on the python 2.4 downloads page and see if you can install them OK (I just did this fine for python 2.3 on whitebox linux). David From spkane at mac.com Mon Jan 10 22:00:58 2005 From: spkane at mac.com (SPK) Date: Mon, 10 Jan 2005 19:00:58 -0800 Subject: Old Paranoia Game in Python References: <1105400673.731851.87080@f14g2000cwb.googlegroups.com> Message-ID: <2005011019005849659%spkane@maccom> You can download the code from the web directly now at: http://homepage.mac.com/spkane/python/ Thanks for all the code suggestions. This is what I was hoping for, but was honestly suprised to actually get it all, although I did get at least one emotional blast, so I don't feel like Usenet has completely changed from it's old self...grin.... I already made a change to the this_page() method based on a suggestion, and will happily pursue many of the other sugestions here. I'm only about 100 pages into Mark Lutz's "Learning Python" book, so I'm sure there is a lot more learning to do. Thanks for all your input! Sean On 2005-01-10 15:44:33 -0800, "McBooCzech" said: > Newbie in Python. > I did copy the whole script form the web and save it as para1.py. I did > download pyparsing module and save it to > C:\\Python23\\Lib\\pyparsing122. > I did run following script: > > import sys > sys.path.append('C:\\Python23\\Lib\\pyparsing122') > > from pyparsing import * > extraLineBreak = White(" ",exact=1) + LineEnd().suppress() > text = file("Para1.py").read() > newtext = extraLineBreak.transformString(text) > file("para2.py","w").write(newtext) > > I did try to run para2.py script, but following message > > File "para2.py", line 169 > choose(4,"You give your correct clearance",5,"You lie and claim > ^ > SyntaxError: EOL while scanning single-quoted string > > So my questions are: > Why pyparser didn't correct the script? > What I am doing wrong? > Is it necessary to correct the script by hand anyway? > > Petr From philippecmartin at sbcglobal.net Fri Jan 7 09:18:24 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Fri, 07 Jan 2005 15:18:24 +0100 Subject: Tkinter: passing parameters to menu commands Message-ID: <1105107504.9221.15.camel@localhost> >>menu.add_cascade(label="File", menu=filemenu) >>filemenu.add_command(label="New", command=lambda: callback('New')) >>filemenu.add_command(label="Open...", command=lambda: callback('Open')) >>filemenu.add_separator() >>filemenu.add_command(label="Exit", command=lambda: callback('Exit')) mainloop() >>Of course you could do this with named forwarding functions if you prefer I'm not sure what 'named forwarding functions' are but I'm actually in a class and when applying your suggestion in the following manner, everything works (THANKS!) **************************** def __Dec(self,p_string): for i in p_string: self.__Insert(i) . . . #menu creation l_dec.add_command(label = 'ATR', command=lambda: self.__Dec('ATR')) l_dec.add_command(label = 'IN', command=lambda:self.__Dec('IN')) . . . **************************** Yet I have a question: If I replace the menu creation code as below, and since __Insert appends the string p_string into a text widget that is created _after_ the menu creation; the method __Dec seems to be called at the menu creation and I get an error in __Insert because the test widget is equal to None. My reflexes of C programmer tell me that command=self.__Dec.... just passes a method pointer (sorry I said it) to add_command - yet it does not seem to be so. What is actually going on ? #menu creation l_dec.add_command(label = 'ATR', command=self.__Dec('ATR')) l_dec.add_command(label = 'IN', command=self.__Dec('IN')) Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From rupole at hotmail.com Wed Jan 19 01:01:10 2005 From: rupole at hotmail.com (Roger Upole) Date: Wed, 19 Jan 2005 01:01:10 -0500 Subject: makepy crashing References: <1106068266.402828.301030@f14g2000cwb.googlegroups.com> Message-ID: <41edf831$1_1@127.0.0.1> Looks like the makepy step creates the generated file successfully, but python is choking with an assertion failure on lines longer than 512 when it tries to import it. This is the line it was processing when it died: def GetSpellingSuggestions(self, Word=defaultNamedNotOptArg, CustomDictionary=defaultNamedOptArg, IgnoreUppercase=defaultNamedOptArg, MainDictionary=defaultNamedOptArg, SuggestionMode=defaultNamedOptArg, CustomDictionary2=defaultNamedOptArg, CustomDictionary3=defaultNamedOptArg, CustomDictionary4=defaultNamedOptArg, CustomDictionary5=defaultNamedOptArg, CustomDictionary6=defaultNamedOptArg, CustomDictionary7=defaultNamedOptArg, CustomDictionary8=defaultNamedOptArg, CustomDictionary9=defaultNamedOptArg, CustomDictionary10=defaultNamedOptArg): You might be able to do a workaround by hacking genpy.py and replacing the default....Arg names with something shorter. ...Nope, there are a few other lines that exceed 512. I think it's a problem with the encoding. If you remove the mbcs tag (# -*- coding: mbcs -*-) from the top of the generated file, the import succeeds. Roger wrote in message news:1106068266.402828.301030 at f14g2000cwb.googlegroups.com... > Has anyone sucessfully run makepy and Microsoft Word Object Library > (9.0)? Mine crashes under XP Pro and Python 2.4. > > It only seems to be word that has the problem, though. > > I get a dialog that says that pythonwin.exe has crashed: > AppName: pythonwin.exe AppVer: 0.0.0.0 ModName: ntdll.dll > ModVer: 5.1.2600.1217 Offset: 000096f9 > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From wittempj at hotmail.com Sun Jan 23 10:03:04 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 23 Jan 2005 07:03:04 -0800 Subject: is there better 32 clock() timing? In-Reply-To: References: Message-ID: <1106492584.328364.125300@z14g2000cwz.googlegroups.com> alternatively you could use the now() method of the datetime module, it has a resolution of 1 microsecond From michael.bierenfeld at web.de Wed Jan 12 12:04:49 2005 From: michael.bierenfeld at web.de (michael) Date: 12 Jan 2005 09:04:49 -0800 Subject: property () for Java Programmers ? Message-ID: Hi there, I am somewhat confused by the following : class C(object): def getx(self): return self.__x def setx(self, value): self.__x = "extended" + value def delx(self): del self.__x x = property(getx, setx, delx, "I'm the 'x' property.") So far so good :-) But what to do with this now >>> c = C >>> c >>> dir (c) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'delx', 'getx', 'setx', 'x'] >>> c.x >>> ?????? What can I do with this "property object" now. Confused greetings Michael From steven.bethard at gmail.com Fri Jan 7 20:27:42 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Jan 2005 18:27:42 -0700 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: Message-ID: Alan Gauld wrote: > On Fri, 07 Jan 2005 08:44:57 -0700, Steven Bethard > wrote: > >>>The unfamiliar argument doesn't work for me. After all most >>>people are unfamiliar with complex numbers (or imaginary) numbers >> >>complex numbers. Lambdas, on the other hand, show up in all kinds of >>code, and even though I hardly ever use them myself, I have to >>understand them because other people do (over-)use them. > > > That's a fair point I suppose but I still don't see much point in > introducing new names and syntaxes when the existing name is a > sensible one, even if unfamiliar to many. After all it works in > Lisp and Haskell - Haskell even uses Lambda as its emblem... Yeah, I personally expect that if GvR doesn't like lambda now, he won't like any of the new syntaxes either. But I'm in the camp that won't miss lambda if it's gone, so I'm not too worried. ;) Steve From yaipa at yahoo.com Wed Jan 19 16:20:11 2005 From: yaipa at yahoo.com (yaipa) Date: 19 Jan 2005 13:20:11 -0800 Subject: finding/replacing a long binary pattern in a .bin file In-Reply-To: <41e88c55.881695170@news.oz.net> References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> <41e6293f.725257715@news.oz.net> <10udjc3fmnhro9d@corp.supernews.com> <41e7a190.821594009@news.oz.net> <1105746027.819673.236650@c13g2000cwb.googlegroups.com> <41e88c55.881695170@news.oz.net> Message-ID: <1106169611.150326.67280@z14g2000cwz.googlegroups.com> Bengt, Thanks for the input, sorry, your diff threw me the first time I looked at it, but then I went back and tried it later. Yes it works fine and I've tucked it away for later use. For this particular Use Case String.replace seems to get the job done in short order and the tool needs to be maintained by folks not familiar /w Python so I went a head and used that. But, I image I will use this bit of code when I need a finer grained tool. Thanks again. Cheers, --Alan From esj at harvee.org Tue Jan 18 18:30:21 2005 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 18 Jan 2005 18:30:21 -0500 Subject: simultaneous multiple requests to very simple database In-Reply-To: References: Message-ID: <41ED9C0D.8090907@harvee.org> Ricardo Bugalho wrote: > On Tue, 18 Jan 2005 17:33:26 -0500, Eric S. Johansson wrote: > > >>When I look at databases, I see a bunch of very good solutions that are >>either overly complex or heavyweight on one hand and very nice and simple >>but unable to deal with concurrency on the other. two sets of point >>solutions that try to stretch themselves and the developers to fit other >>application contexts. >> > > > Have you considerded SQLite/pySQLite ? yep and apparently it won't work http://www.sqlite.org/faq.html#q7 if I had record level locking, the code would do a very common pattern like: if record present: Lock record modify record release lock else: create record atomically (actual method TBB) if I read their opinion correctly, the SQL lite folks are wrong in that only the applications need massive concurrency. Small applications need significant to massive concurrency for very tiny windows on very little data. but I do appreciate the pointer. From frans.englich at telia.com Wed Jan 26 15:49:17 2005 From: frans.englich at telia.com (Frans Englich) Date: Wed, 26 Jan 2005 20:49:17 +0000 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <200501262049.17156.frans.englich@telia.com> On Wednesday 26 January 2005 18:55, Terry Reedy wrote: > Your Four Steps to Python Object Oriented Programming - vars, lists, dicts, > and finally classes is great. It makes this thread worthwhile. I saved it > and perhaps will use it sometime (with credit to you) to explain same to > others. I think so too. M.E. Farmer's reflections on management was also a shining piece of gold in this thread. Cheers, Frans From jerf at jerf.org Tue Jan 18 18:20:19 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 18 Jan 2005 18:20:19 -0500 Subject: macros References: <10ur3gueivenob6@corp.supernews.com> Message-ID: On Tue, 18 Jan 2005 14:36:08 -0800, Jeff Shannon wrote: > I think that this sort of thing is better to have as an explicitly > risky hack, than as an endorsed part of the language. The mere fact > that this *is* something that one can clearly tell is working around > certain deliberate limitations is a big warning sign, and it makes it > much less likely to be used extensively. Relatively few people are > going to want to use something called "bytecodehacks" in a > mission-critical piece of software, compared to the number who'd be > perfectly happy to use a language's built-in macro facilities, so at > least it keeps the actual usage down to a somewhat more manageable level. > > To rephrase this a bit more succinctly ;) there's a big difference > between having no practical way to prevent something, and actually > encouraging it. Hey, argument, there you are. I figured you'd work your way out somehow without me having to type you. :-) The counterargument that leaps to mind is that if enough people do it, there's a need, and that need should be met explicitly rather than with "hacks", for the benefit of all. Again, I emphasize my ambivalence. Are there "enough"? (It's hard to tell, maybe if it weren't so hard more would do it.) Is the benefit big enough? Is "the need" the need to tell people "stop juggling chainsaws!"? (In which case I guess "the need" has been met.) Basically, I'm willing to trust Guido overall on the grounds that he has earned it. But I still can't help but wonder if outright dismissal isn't missing something that could be useful and positive if Guido et al turned their minds to it. But then, I have no idea what it may be and it may be impossible. Like I said, I'm torn on this one :-) From steven.bethard at gmail.com Tue Jan 25 16:26:13 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Jan 2005 14:26:13 -0700 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: References: Message-ID: Michael Spencer wrote: > Steven Bethard wrote: > >> Michael Spencer wrote: >> >>> Safe eval recipe posted to cookbook: >>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 >> >> This recipe only evaluates constant expressions > [snip > > Indeed. But it's easy to extend this to arbitrary constructs. You just > need to decide what code to emit for the other 50 or so ast node types. > Many of those are boiler-plate binops. Ahh, gotcha. Thanks for the clarification. I haven't ever spent much time dealing with Python's ASTs, but my guess is doing anything here is probably worth putting off until the AST branch is merged into main CVS for Python 2.5. (I understand there are supposed to be some substantial changes, but I don't know exactly what they are or what they affect.) > Right - the crux of the problem is how to identify dangerous objects. > My point is that if such as test is possible, then safe exec is very > easily implemented within current Python. If it is not, then it is > essentially impossible. > [snip] > > It might still be possible to have a reliable test within a > problem-specific domain i.e., white-listing. Yeah, that was basically my intent -- provide a white-list of the usable objects. I wonder how complicated this would be... You also probably have to white-list the types of all the attributes of the objects you provide... Steve From fumanchu at amor.org Fri Jan 7 16:15:49 2005 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 7 Jan 2005 13:15:49 -0800 Subject: Display Function Code Body? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398132@exchange.hqamor.amorhq.net> Haibao Tang wrote: > Hail Python pals! I played with the R (http://r-project.cran.org) last > night to do some statistics and it has an interactive session too, and > I found a feature that is quite useful. > > I found by actually typing a function name, the R gives you a > code body output. > > > f1 = function(x){x*x} > > f1 > function(x){x*x} ... > What I would like to do is to write a function like disp(), > when typed, it can give you the code infomation. > > >>> disp(f1) > > def f1(x): > return x*x > You can do this with lambdas with my LambdaDecompiler inside: http://www.aminus.org/rbre/dejavu/codewalk.py If you want to extend it to full functions, be my guest. ;) There's also a commercial decompiler out there called "decompyle", and they even have a web service. http://www.crazy-compilers.com/decompyle/ Robert Brewer MIS Amor Ministries fumanchu at amor.org From tech at gpao.cc Mon Jan 31 10:52:24 2005 From: tech at gpao.cc (Olivier Noblanc ATOUSOFT) Date: Mon, 31 Jan 2005 16:52:24 +0100 Subject: import doesn't work as i want Message-ID: <41fe5438$0$18865$8fcfb975@news.wanadoo.fr> Hello, In the botom of this post you will see my source code. The problem is when i launch main.py that doesn't make anything why ? Thanks olivier noblanc Atousoft http://www.logiciel-erp.fr I have main.py : --------------------------------- import wx import inc.importlist ---------------------------------- inc/importlist.py ------------------------------------ import wx.grid import getdata import time import sys ----------------------------------- inc/wxgrid.py ------------------------------------- # -*- coding: cp1252 -*- #starta = time.time() import wx import getdata class MyFrame(wx.Frame): def __init__(self, *args, **kwds): # begin wxGlade: MyFrame.__init__ kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) self.grid_1 = wx.grid.Grid(self, -1, size=(1, 1)) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: MyFrame.__set_properties self.SetTitle("frame_1") self.SetSize((400, 400)) # end wxGlade self.grid_1.CreateGrid(len(db.data), len(db.fields)) # met les labels des colonnes index = 0 for item in db.fields: self.grid_1.SetColLabelValue(index, item[0]) index += 1 # remplissage des donn?es. for row in range(len(db.data)): for col in range(len(db.data[row])): values = db.data[row][col] self.grid_1.SetCellValue(row,col,str(values)) # mise en forme et affichage def __do_layout(self): # begin wxGlade: MyFrame.__do_layout sizer_1 = wx.BoxSizer(wx.VERTICAL) sizer_1.Add(self.grid_1, 1, wx.EXPAND, 0) self.SetAutoLayout(True) self.SetSizer(sizer_1) self.Layout() # end wxGlade # end of class MyFrame if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() frame_1 = MyFrame(None, -1, "") app.SetTopWindow(frame_1) frame_1.Show() #startb = time.time() - starta #print startb app.MainLoop() --------------------------------------- inc/getdata.py ---------------------------------------------- import MySQLdb class Eb_db: def __init__(self): try: connection = MySQLdb.connect(host="dellced", user="ats", passwd="", db="atsmedicdatabase" ) cursor = connection.cursor() cursor.execute( "SELECT * FROM PATIENT " ) except MySQLdb.OperationalError, message: errorMessage = "Error %d:\n%s" % ( message[ 0 ], message[ 1 ] ) return else: self.data = cursor.fetchall() self.fields = cursor.description cursor.close() connection.close() ----------------------------------------- From peter at engcorp.com Thu Jan 13 08:18:25 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 08:18:25 -0500 Subject: Octal notation: severe deprecation In-Reply-To: <1105587098.932273.315230@c13g2000cwb.googlegroups.com> References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> Message-ID: <39ednWfqlrgB6HvcRVn-iA@powergate.ca> and-google at doxdesk.com wrote: > In Mythical Future Python I would like to be able to use any base in > integer literals, which would be better. Example random syntax: > > flags= 2x00011010101001 > umask= 8x664 > answer= 10x42 > addr= 16x0E800004 # 16x == 0x > gunk= 36x8H6Z9A0X I think I kinda like this idea. Allowing arbitrary values, however, would probably be pointless, as there are very few bases in common enough use that a language should make it easy to write literals in any of them. So I think "36x" is silly, and would suggest limiting this to 2, 8, 10, and 16. At the very least, a range of 2-16 should be used. (It would be cute but pointless to allow 1x000000000. :-) -Peter From macrocosm at fastmail.fm Fri Jan 7 22:15:07 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Fri, 07 Jan 2005 22:15:07 -0500 Subject: Python Operating System??? In-Reply-To: <7xk6qoeil9.fsf@ruckus.brouhaha.com> References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xk6qoeil9.fsf@ruckus.brouhaha.com> Message-ID: <41DF503B.8050505@fastmail.fm> An HTML attachment was scrubbed... URL: From rbt at athop1.ath.vt.edu Mon Jan 24 09:04:31 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 24 Jan 2005 09:04:31 -0500 Subject: Memory Usage Message-ID: Would a Python process consume more memory on a PC with lots of memory? For example, say I have the same Python script running on two WinXP computers that both have Python 2.4.0. One computer has 256 MB of Ram while the other has 2 GB of Ram. On the machine with less Ram, the process takes about 1 MB of Ram. On the machine with more Ram, it uses 9 MB of Ram. Is this normal and expected behavior? Thanks, rbt From fccoelho at gmail.com Tue Jan 11 03:17:25 2005 From: fccoelho at gmail.com (Flavio codeco coelho) Date: 11 Jan 2005 00:17:25 -0800 Subject: Python serial data aquisition References: <41e1b833$1_3@omega.dimensional.com> <7x4qhpeggb.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote in message news:<7x4qhpeggb.fsf at ruckus.brouhaha.com>... > or something like that. Hi Paul, thanks for your answer. I Noticed, however that although your solution is almost identical to that of Michael (earlier in the thread) your masking for the second byte is different than the one he used. Since hex numbers get me all confused (and python doesn't convert to binary), I was wondering which one is the correct masking... thnaks, Flavio From rnd at onego.ru Tue Jan 4 15:10:49 2005 From: rnd at onego.ru (Roman Suzi) Date: Tue, 4 Jan 2005 23:10:49 +0300 (MSK) Subject: Python evolution: Unease In-Reply-To: <41DAE9E1.5080105@pythonapocrypha.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> Message-ID: On Tue, 4 Jan 2005, Dave Brueck wrote: >> It may be optional in the sense that the language will >> accept missing declarations but as soon as the feature >> is available it will become "mandatory" to use it >> (peer pressure, workplace practices). What about generic programming coming into fashion anytime soon? >That's my fear - type declarations could become one of the most abused language >features because they'd get used too often. > >-Dave > Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From claird at lairds.us Tue Jan 4 10:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 04 Jan 2005 15:08:03 GMT Subject: How can engineers not understand source-code control? References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41da713a$0$610$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: In article <41da713a$0$610$ed2619ec at ptn-nntp-reader03.plus.net>, Mark Carter wrote: . . . >True story: when I began working for my current employer, there was a >guy there doing some work with a spreadsheet. He was given two weeks to . [tale of atrocity and woe] . . >cell formulae. The rationale behind this is that VBA is too hard for >most people to understand, whereas formulae are easier to understand. . . . Well *that* certainly made my morning unpleasant. I think the point to take away has something to do with maturity or judgment or one of those other difficult qualities. Some of this stuff--"formulae are easy to understand", "you don't need programmers, you just enter what you want the machine to do", "we'll wage war on terrorists by *becoming* terrorists", "Micro- soft has spent more on 'security' than any other vendor"--*sounds* like a useful guide to action. A hard part of our responsibility, though, is articulating for decision-makers that these superficial simplificities truly are superficial, and that they lead to monstrous costs that are hard for "civilians" to anticipate. From sjmachin at lexicon.net Tue Jan 11 18:06:06 2005 From: sjmachin at lexicon.net (John Machin) Date: 11 Jan 2005 15:06:06 -0800 Subject: Importing Problem on Windows References: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> Message-ID: <1105484766.613266.240890@f14g2000cwb.googlegroups.com> brolewis wrote: > I have a directory that has two files in it: > > parse.py > parser.py > > parse.py imports a function from parser.py and uses it to parse out the > needed information. On Linux, the following code works without a > problem: > > parse.py, line 1: > from parser import regexsearch > > However, when I run the same command in Windows, I get the following > error: > > ImportError: cannot import name regexsearch > Any suggestions on why this would work on Linux but not on Windows? Hint for the future: use the -v argument (python -v yourscript.py yourarg1 etc) to see where modules are being imported from. Example (I don't have a module named parser anywhere): python -v [big snip] >>> from parser import regexsearch import parser # builtin <<<<==== aha! Traceback (most recent call last): File "", line 1, in ? ImportError: cannot import name regexsearch >>> From kent3737 at yahoo.com Tue Jan 11 12:21:45 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Tue, 11 Jan 2005 12:21:45 -0500 Subject: Python & unicode In-Reply-To: <1105453488.204651.47870@f14g2000cwb.googlegroups.com> References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> <1105434532.132061.24030@f14g2000cwb.googlegroups.com> <1105434900.511862.54740@f14g2000cwb.googlegroups.com> <41e3cb2a$1_2@newspeer2.tds.net> <1105453488.204651.47870@f14g2000cwb.googlegroups.com> Message-ID: <41e408ec$1_2@newspeer2.tds.net> michele.simionato at gmail.com wrote: > Kent: > >>I don't think so. You have hacked an attribute with latin-1 > > characters in it, but you > >>haven't actually created an identifier. > > > No, I really created an identifier. For instance > I can create a global name in this way: > > >>>>globals()["?"]=1 >>>>globals()["?"] > > 1 Maybe I'm splitting hairs but to me an identifier is a syntactical element that can be used in specific ways. For example the syntax defines attributeref ::= primary "." identifier so if identifiers can contain latin-1 characters you should be able to say C.?=1 Kent > > >>According to the language reference, identifiers can only contain > > letters a-z and A-Z, > >>digits 0-9 and underscore. >>http://docs.python.org/ref/identifiers.html > > > The parser has this restriction, so it gets confused if it finds "?". > But the underlying > implementation just works for generic identifiers. > Michele Simionato > From wweston at att.net Fri Jan 28 15:35:44 2005 From: wweston at att.net (wes weston) Date: Fri, 28 Jan 2005 20:35:44 GMT Subject: Where can I find sample "beginner" programs to study? In-Reply-To: <_6CdnWIOB8AaA2fcRVn-rg@speakeasy.net> References: <_6CdnWIOB8AaA2fcRVn-rg@speakeasy.net> Message-ID: Todd_Calhoun wrote: > I'm trying to learn Python (and programming), and I'm wondering if there are > any places where I can find small, simple programs to study. > > Thanks. > > Todd, Have you been here: http://www.python.org/doc/ and tried the tutorial or beginners guide? The tutorial has all the pieces you use most often. wes From steven.bethard at gmail.com Fri Jan 21 21:46:40 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 19:46:40 -0700 Subject: finding name of instances created In-Reply-To: <1106361238.142879.222100@f14g2000cwb.googlegroups.com> References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106359068.802501.35190@z14g2000cwz.googlegroups.com> <1106361238.142879.222100@f14g2000cwb.googlegroups.com> Message-ID: Andr? wrote: > Steven Bethard wrote: > >>Andr? wrote: >> >>>Using the method suggested by Steven Bethard, I *almost* got it > > working > >>>the way I would like. > > [snip] > >>It looks like you want PrivateClass.dict updated every time that >>globals() is updated. > > > yes, that is what I would like to do. > > >>You can just use globals directly instead: >> >>py> class PrivateClass(object): >>... def __init__(self, globals): >>... self.globals = globals >>... def apparently_simple_method(self): >>... for name, value in self.globals.iteritems(): >>... if value is self: >>... print "instance %s called not so simple" % name >>... >>py> def public_class(): >>... return PrivateClass(globals()) >>... >>py> alpha = public_class() >>py> alpha.apparently_simple_method() >>instance alpha called not so simple >>py> beta = public_class() >>py> beta.apparently_simple_method() >>instance beta called not so simple >> > > That's exactly what I was looking for; thank you! > > >>On the other hand, the iteration in >>PrivateClass.apparently_simple_method has a very bad code smell... >> > > I'm not sure what you mean... > Is it because it makes use of information that is > exterior to the class, which is not passed as a parameter > to the method? > [feel free to ignore this question if you want; you have > already helped me tremendously!!!] There's a couple things I don't like about it: (1) Generally, I don't like passing globals() around. It's probably okay in this scenario though because if you want to have the user code in a different module, you can do something like: def public_class(): return PrivateClass(usermodule.__dict__) (2) The really bad code smell however is having to iterate through all the values in globals to find the key you're looking for... Especially when you have to check the type of each item... In a perfect world, you would already have a PrivateClass->name mapping somewhere and this should be a simple dict lookup instead of an iterative search... See my other post about potentially pre-processing your user input to see how you can convert the iteration to a simple attribute lookup. Steve From rbt at athop1.ath.vt.edu Sat Jan 29 09:32:54 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Sat, 29 Jan 2005 09:32:54 -0500 Subject: The next Xah-lee post contest In-Reply-To: References: Message-ID: Steve wrote: > Hi All, > For sometime now, I have just been a passive lurker on this > list. Of late I saw an increase in the number of posts by Xah Lee, and > I have to admit, what he lacks in understanding of the various > programming languages he talks about, he makes up for in creativity. > So, I was wondering, how would it be to be Mr Lee. That got me > thinking of his next post. Well, I know through my days of lurking > around, a lot of people here love creative challenges ...so here's one > for you. Write up the next Xah Lee post... Unix donkey! You not elegant. You have poor design. Sloppy Perl monkey! You be lazy! You code very very bad. Xah know all! From andre.roberge at gmail.com Sat Jan 22 07:33:38 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 22 Jan 2005 04:33:38 -0800 Subject: finding name of instances created In-Reply-To: References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> Message-ID: <1106397218.724722.172660@c13g2000cwb.googlegroups.com> Jeremy Bowers wrote: > On Fri, 21 Jan 2005 21:01:00 -0400, Andr? Roberge wrote: > > etc. Since I want the user to learn Python's syntax, I don't want to > > require him/her to write > > alex = CreateRobot(name = 'alex') > > to then be able to do > > alex.move() > > This is just my opinion, but I've been involved with teaching new > programmers before so I think it is an informed one. I don't think you > teach a language by hiding how the language works, no matter what the > intentions. > > You should be *minimizing* the magic. You're going to train your students > that Python objects have names (they don't) and that's going to mess them > up later. Actually, it's going to mess them up almost right away, because > how can they have a list of robots like this: > > for robot in robots: > robot.turn_left() They will not be able to do that. > > That can't work, right, the command inside the loop can only affect the > robot named "robot", right? > > You can't teach Python if what you're actually teaching them is a variant > that you have created that is used nowhere else on Earth, and is > internally inconsistent to boot (see loop above, the *real* Python > variable semantics conflict with the semantics you are teaching). > I think you misunderstood my intentions, possibly because I explain things too superficially. > Considering that not a month goes by where someone doesn't post a question > related to this, and it has been a FAQ entry for as long as I've used > Python, I think you are doing a major disservice to your "users" by > training them that objects magically gets the name when assigned. I > strongly urge you to do absolutely no pre-processing of any kind to the > programs they generate. (By which I mean changes to the code; running > pychecker on it would be OK; and I'd urge you to resist the temptation to > process its output, either. Provide a "translation table" if you need to, > but they need to learn to read the real output, too.) > > Programming is hard enough with burdening people with "pleasant > falsehoods". Trust your students to handle the truth (and of course > rationally minimize the truth they have to handle, and by using Python > you're off to a great start there). If they can't handle the truth, with > time, effort, and support, they *sure* as hell can't handle lies! The environment in which students (my kids first, others later :-) will learn is based on Richard Pattis's "Karel the Robot" (adapted for Python in "Guido van Robot"). They are presented with a robot that can do four basic actions, as I described in a previous post. It's been used successfully in many places. The students learn first the procedural aspect of python. Here's a quick example of a program that they can write: .def move_and_turn(): . move() . turn_left() . .def draw_square(): . for i in range(4): . move_and_turn() . .draw_square() ====== At this point, they don't know anything about objects and methods; but they will have learned about functions and variables. This is where 'Guido van Robot (GvR)', which has been used succesfully to teach programming using a syntax somewhat similar to python, but not quite, stops. (Actually, you can't use variables in GvR). I want to move beyond that and introduce objects and classes. So, students will be able to write: pete = CreateRobot(2, 3) pete.move() learning about objects and methods. As for things like for robot in robots: do stuff that will be for my use only: drawing robots on the screen, updating the 'world' when robots pick stuff up, etc. My intention is that the students will use the EXACT python syntax, so that they don't know that *I* have given a *name* to their robot(s) behind the scene. I have to cut this short; I hope it clarifies my intentions. Andr? From cliechti at gmx.net Sat Jan 15 14:38:19 2005 From: cliechti at gmx.net (Chris Liechti) Date: Sat, 15 Jan 2005 19:38:19 +0000 (UTC) Subject: Com port interrupts again References: <154gu09bghnq674s2nqot9si6d50igueq7@4ax.com> Message-ID: engsol wrote in news:154gu09bghnq674s2nqot9si6d50igueq7 at 4ax.com: > I didn't fully think through my application before posting my > question. Async com port routines to handle com port interrups > only work well if one has access to the low level operating > system. In that case the receive buffer interrupt would cause > a jump to an interrupt service routine.. I don't believe that i would not go that route... the operating system provides sync and async methods to access the serial port. it would make sense to use these before hacking the operating system. (also see below) > Python provides that capabilty directly. The solution then would > be to write a C extention? ctypes can do many things without a C compiler. it's a very nice an valuable extension, but i won't like to encurage to use it for this particular problem. > The suggestions offered by respondents to my original post > were almost all of a "Use threads, and poll as needed" flavor. > You're right...I need to learn threads as applied to com ports. if you realy want to do async programming, have a look at twisted (http://twistedmatrix.com). it does not only provide async access to the serial port (trough pyserial + some code in twisted) it also delivers some nice utility functions, classes etc, like the reactor, defereds, thread pools (if you can't resist ;-) and many protocol handlers. chris -- Chris From claird at lairds.us Sun Jan 16 11:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Sun, 16 Jan 2005 16:08:03 GMT Subject: Checking for X availability References: Message-ID: In article , Nils Nordman wrote: >On Tue, Jan 11, 2005 at 03:32:01AM -0800, Flavio codeco coelho wrote: >> So my question is: how can I check for the availability of X? i.e., >> How will my program know if its running in a text only console or in >> console window over X? > >Well, one way to do it is to check whether the environment variable >DISPLAY is set (which it is when running under X, and should not be >otherwise). . . . While there certainly are successful programs that use this approach, it's NOT true in general--at least in the generality I encounter. It can happen, for example, that a user withOUT $DISPLAY in the environment launches interesting_application -display SOME_DISPLAY ... Jeremy Bowers gives excellent advice elsewhere in this thread: try, and use exceptions to learn what's going on; as you learn more, relaunch the application with a refined command-line. From jan.dries at dcube-resource.be Wed Jan 19 02:39:24 2005 From: jan.dries at dcube-resource.be (Jan Dries) Date: Wed, 19 Jan 2005 08:39:24 +0100 Subject: Solutions for data storage? In-Reply-To: <356c7tF4g3f64U1@individual.net> References: <356c7tF4g3f64U1@individual.net> Message-ID: Leif K-Brooks schreef: > > I've looked at SQLObject, and it's very nice, but it doesn't > provide certain features I really want, like the ability to store > lists of strings or integers directly in the database (using commas > in a varchar column or something). What exactly in SQLObject prevents you from doing this? You may have to pack/unpack the list into a comma separated string yourself, but surely the 2 line code function that requires can't be the problem. And SQLObject's support for properties makes this very clean. See: http://www.sqlobject.org/docs/SQLObject.html#adding-magic-attributes-properties Or am I missing something here? Regards, Jan From kendall at monkeyfist.com Sun Jan 2 13:34:02 2005 From: kendall at monkeyfist.com (Kendall Clark) Date: Sun, 2 Jan 2005 13:34:02 -0500 Subject: Continuations Based Web Framework - Seaside. In-Reply-To: References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <7aTBd.11928$H%6.521997@twister1.libero.it> Message-ID: <20050102183402.GC8357@monkeyfist.com> On Sun, Jan 02, 2005 at 10:03:10AM -0500, Steve Holden wrote: > I did actually do some sort-of-related work in this area, which I > presented at PyCon DC 2004 - you can access the paper at > > http://www.python.org/pycon/dc2004/papers/18/Setting_A_Context.pdf > > An audience member mentioned the Smalltalk and Scheme-based work on web > continuation frameworks, and I was sorry my answer at the time seemed > unduly dismissive. That was me, actually. I remain surprised that there isn't a move afoot either to implement something like Seaside or Borges in Python or to adapt one of the existing web frameworks to be modal/continuation style. Between this pressure (which isn't new, since as Steve points out, I was talking about this in Python community last year, and I wasn't nearly the first) and the growing popularity of Ruby on Rails, there's some small hint that Ruby is gaining on Python re: non-Java web app mind share. I think that's a v. important niche for Python and would like to see us remain strong there (though I've not *done* much about this, alas). > There are some interesting similarities, and though > my own implementation is decidedly clunky I like to think the paper > explains some of the advantages of maintaining state and why the "back" > button is an obnoxious anachronism :-) I'd still like to publish a piece on XML.com about modal web app style, preferably with a Python example, though Borges would be fine. Best, Kendall Clark XML.com Managing Editor From peter at engcorp.com Sun Jan 23 18:51:40 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 23 Jan 2005 18:51:40 -0500 Subject: compile python to binary In-Reply-To: References: <1d6cdae3050123080242bf8994@mail.gmail.com> Message-ID: Daniel Bickett wrote: > Fredrik Lundh wrote: > >>oh, you mean that "python compiler" didn't mean "the python compiler". >>[snip] > > I simply inferred that he was using the wrong terminology, being that > he said "binary" twice ;-) While I suspect you've guessed correctly at what the OP meant, one should also consider that the word "binary" can be quite ambiguous in the hands of a newbie. After all, source code is stored in binary too... -Peter From michael.pronath at gmx.de Mon Jan 3 06:47:16 2005 From: michael.pronath at gmx.de (Michael Pronath) Date: 3 Jan 2005 03:47:16 -0800 Subject: Async-signal safe functions in signal handlers (unix) Message-ID: <6942fc70.0501030347.29253110@posting.google.com> Hi, can I make sure that Python uses only async-signal safe glibc functions in signal handlers? For example, you must not call malloc or free in signal handlers, see http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html#tag_02_04_03 The reason is, that if a signal is caught while your program is in the malloc routine, and the signal handler calls malloc or free again, then the heap will be corrupted, probably crashing your program. Using the Python module "signal", I can define signal handlers, but I guess that many statements like assignments to local variables will involve calls to functions like malloc or free. So, is there a) any mechanism inside Python that can detect if the current code is executed in a signal handler, or b) a list of statements that must not be used in a Python signal handler in order to avoid glibc function calls that are not async-signal safe? Regards, Michael From none.by.e-mail Sun Jan 2 06:28:21 2005 From: none.by.e-mail (Mike Thompson) Date: Sun, 02 Jan 2005 22:28:21 +1100 Subject: Continuations Based Web Framework - Seaside. Message-ID: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> 'Seaside' is a Smalltalk framework for what might be called "Modal Web Development" or "Synchronous Web Programming", or even "Continuation Based Web Apps". http://www.beta4.com/seaside2/ Very sexy it looks too. And it seems to be generating a lot of interest - Ruby and Java variants have already sprung up: http://rubyforge.org/projects/borges/ http://lakeshore.sourceforge.net/ I googled for the python spin-off but didn't find one. Closest I found was Imposter (http://csoki.ki.iif.hu/~vitezg/impostor/) which looks like an earlier, partially failed attempt to do what Seaside now seems to be delivering. Anyway, I guess all I'm doing is drawing this to the community's attention. Sophisticated web applications seems to be one of Python's key domains and this looks a significant new development in the area. -- Mike From domma at procoders.net Sun Jan 16 12:45:18 2005 From: domma at procoders.net (Achim Domma (Procoders)) Date: Sun, 16 Jan 2005 18:45:18 +0100 Subject: PythonMagick Update Message-ID: Hi, I'm working on a new version of PythonMagick, a wrapper for GraphicsMagick. A first version is available at: http://public.procoders.net/cgi-bin/trac.cgi/wiki/PythonMagick Any feedback is very appreciated. regards, Achim From robin at reportlab.com Tue Jan 11 13:40:04 2005 From: robin at reportlab.com (Robin Becker) Date: Tue, 11 Jan 2005 18:40:04 +0000 Subject: OT: MoinMoin and Mediawiki? In-Reply-To: <7xsm58lcms.fsf@ruckus.brouhaha.com> References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <34h7m9F43vomsU1@individual.net> <7xsm58lcms.fsf@ruckus.brouhaha.com> Message-ID: <41E41D84.40907@chamonix.reportlab.co.uk> Paul Rubin wrote: > Brion Vibber writes: > >>MediaWiki should run with PHP configured in CGI handler mode, but >>these days mod_php has got its claws just about everywhere anyway. If >>you control your own server and don't have multi-user security >>worries, mod_php is simple enough to install and will probably perform >>better. > > > Thanks, yes, I could run a special apache instance with mod_php > installed. I'm pretty good with apache. I have no MySQL admin > experience but I suppose enough people are using MySQL that the > installation procedures and docs are pretty well developed and I can > follow the instructions. > > What I'm wondering is just how big an adventure I'd be setting off on, > simply to get MediaWiki itself installed, configured, and running. > Any thoughts about that? ..... A few months ago I tried and failed to get squirrelmail/php to run with Apache2 and freeBSD 4.9. It seems that php prefers the old style apache 1.3 work flow. I got some help from the php guys, but not enough. I suppose I could have run a separate apache13 server, but that seems like a cop out to me. We don't want to maintain an extra set of configs etc etc. Mailman, moinmoin and others work fine with apache2 maybe because they use a cgi style interface. I would stick with a pythonic solution unless there's a good reason not too. -too old to learn a new language-ly yrs- Robin Becker From ncoghlan at iinet.net.au Fri Jan 7 23:58:40 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 14:58:40 +1000 Subject: Calling Function Without Parentheses! In-Reply-To: <1105131393.355381.105800@c13g2000cwb.googlegroups.com> References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> <41D8B5F4.1010903@mxm.dk> <1105113743.189469.115440@f14g2000cwb.googlegroups.com> <10tttc6vblse9@corp.supernews.com> <1105131393.355381.105800@c13g2000cwb.googlegroups.com> Message-ID: <41DF6880.4040005@iinet.net.au> Kamilche wrote: > Uh, you're right! I wouldn't want to bog Python down with even more > checking at run time. I guess I'm asking for syntax checks that are > typically done only with compiled languages. In that case, I can suggest having a look at Pychecker, which performs static sanity checks on Python code. http://pychecker.sourceforge.net/ Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ncoghlan at iinet.net.au Wed Jan 5 07:58:02 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 05 Jan 2005 22:58:02 +1000 Subject: why does UserDict.DictMixin use keys instead of __iter__? In-Reply-To: References: Message-ID: <41DBE45A.90005@iinet.net.au> Steven Bethard wrote: > Nick Coghlan wrote: >> .keys() is definitely part of the standard dictionary interface, and >> not something the mixin can derive from the generic container methods. > > > Why is that? Isn't keys derivable as: > > def keys(self): > return list(self) > > if __iter__ is defined? As you may have guessed, I completely forgot about __iter__. . . Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From annaraven at gmail.com Mon Jan 10 06:47:05 2005 From: annaraven at gmail.com (Anna) Date: 10 Jan 2005 03:47:05 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> Message-ID: <1105357625.835608.299560@c13g2000cwb.googlegroups.com> Jacek Generowicz wrote: > "Anna" writes: > > > With class and def, I at least have a *name* to start with - class > > Square pretty obviously is going to have something to do with > > geometric shapes, I would hope (or maybe with boring people...). > > Or maybe with multiplying something by itself. Or maybe the author > made some changes in his program, and forgot to rename the class > sensibly, and the class' functionality has nothing to do with squares > of any sort any more. Or maybe he felt the name "Square" was very > appropriate for something else in his program and inadvertently gave > the same name to two different entities thereby clobbering the one > whose use was intended at this point. Idjits abound. ;-) Can't make anything foolproof because fools are so ingenious. > > Whereas, with lambda - I have *nothing* to go on. > > Aaah. OK, you object to lambda because it gives you no clue as to what > the function does, rather than with the word "lambda" itself? Is that > it? > > So, IIUC, you consider > > def add_one(x): > return x+1 > > map(add_one, seq) > > to be clearer than > > map(lambda x:x+1, seq) Completely, totally, and unambiguously: the version with the defined function is immediately clear to me; the version with the lambda is decipherable, but requires deciphering (even at 2nd and 3rd glance). But first, wouldn't something like: [x+1 for x in seq] be even clearer? Given an example more complex (which you must admit, lambdas usually are) - the name of the function is something my brain can hold on to to represent the group of operations; where with the lambda, I need to mentally go through each operation each time I try to read it. And the more complex f is, the harder time I have holding it all in my head while I figure out how to get from the beginning value x to the ending value f(x). lambda is an O(N*N) problem for my brain. I could see someone more mathematically-minded being happier with lambda. It's not, after all, the word "lambda" itself; I would still have some issues with using, say "function", instead of "lambda", but at least then I would immediately know what I was looking at... Anna From andre.roberge at gmail.com Sat Jan 8 11:14:31 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 8 Jan 2005 08:14:31 -0800 Subject: python3: 'where' keyword In-Reply-To: <1105200103.921226.186930@c13g2000cwb.googlegroups.com> References: <3480qqF46jprlU1@individual.net> <41dfc018.305122743@news.oz.net> <1105200103.921226.186930@c13g2000cwb.googlegroups.com> Message-ID: <1105200871.358802.235240@c13g2000cwb.googlegroups.com> Darn space-eater google groups :-( Here is it again, at teh risk of generating controversy .def gcd(a, b): . where: . a: int, b: int . return c where: . c: int . while a: . a, b = b%a, a . return b more examples can be found at aroberge.blogspot.com Andr? From greg.lindstrom at novasyshealth.com Mon Jan 24 16:32:29 2005 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Mon, 24 Jan 2005 15:32:29 -0600 Subject: Looking for Form Feeds Message-ID: <41F5696D.9030100@novasyshealth.com> Hello- I have a file generated by an HP-9000 running Unix containing form feeds signified by ^M^L. I am trying to scan for the linefeed to signal certain processing to be performed but can not get the regex to "see" it. Suppose I read my input line into a variable named "input" The following does not seem to work... input = input_file.readline() if re.match('\f', input): print 'Found a formfeed!' else: print 'No linefeed!' I also tried to create a ^M^L (typed in as Q M L) but that gives me a syntax error when I try to run the program (re does not like the control characters, I guess). Is it possible for me to pull out the formfeeds in a straightforward manner? Thanks! --greg -- Greg Lindstrom 501 975.4859 Computer Programmer greg.lindstrom at novasyshealth.com NovaSys Health Little Rock, Arkansas "We are the music makers, and we are the dreamers of dreams." W.W. Confidentiality Notice ---------------------- This email and any attachments to it are privileged and confidential and are intended solely for use of the individual or entity to which they are addressed. If the reader of this message is not the intended recipient, any use, distribution, or copying of this communication, or disclosure of all or any part of its content to any other person, is strictly prohibited. If you have received this communication in error, please notify the sender by replying to this message and destroy this message and delete any copies held in your electronic files. Thank you. From ncoghlan at iinet.net.au Tue Jan 11 05:54:53 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 11 Jan 2005 20:54:53 +1000 Subject: Securing a future for anonymous functions in Python In-Reply-To: <1f7befae0501101815572999ae@mail.gmail.com> References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <1105381339.922714.23200@c13g2000cwb.googlegroups.com> <1oFEd.71967$Jk5.45632@lakeread01> <1f7befae0501101815572999ae@mail.gmail.com> Message-ID: <41E3B07D.2080402@iinet.net.au> Tim Peters wrote: > LIke it or not, it doesn't seem as strained as trying to pile more > gimmicks on Python expressions. Some of us are piling gimmicks on statements, not expressions :) And I'm looking for out-of-order code execution as well as local namespaces, so the let/in syntax wouldn't help much. (The out-of-order execution is what really makes the property definition example pretty, IMO) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From cam.ac.uk at mh391.invalid Sat Jan 15 12:52:11 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 15 Jan 2005 17:52:11 +0000 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: Chris Lasher wrote: > I have a rather large (100+ MB) FASTA file from which I need to > access records in a random order. I just came across this thread today and I don't understand why you are trying to reinvent the wheel instead of using Biopython which already has a solution to this problem, among others. But actually I usually use formatdb, which comes with NCBI-BLAST to create blastdb files that can also be used for BLAST. mh5 at ecs4a /data/blastdb/Users/mh5 $ python Python 2.3.3 (#1, Jan 20 2004, 17:39:36) [C] on osf1V5 Type "help", "copyright", "credits" or "license" for more information. >>> import blastdb >>> from tools2 import LightIterator >>> temp_file = blastdb.Database("mammals.peptides.faa").fetch_to_tempfile("004/04/m00404.peptide.faa") >>> LightIterator(temp_file).next() ('lcl|004/04/m00404.peptide.faa ENSMUSG00000022297 peptide', 'MERSPFLLACILLPLVRGHSLFTCEPITVPRCMKMTYNMTFFPNLMGHYDQGIAAVEMGHFLHLANLECSPNIEMFLCQAFIPTCTEQIHVVLPCRKLCEKIVSDCKKLMDTFGIRWPEELECNRLPHCDDTVPVTSHPHTELSGPQKKSDQVPRDIGFWCPKHLRTSGDQGYRFLGIEQCAPPCPNMYFKSDELDFAKSFIGIVSIFCLCATLFTFLTFLIDVRRFRYPERPIIYYSVCYSIVSLMYFVGFLLGNSTACNKADEKLELGDTVVLGSKNKACSVVFMFLYFFTMAGTVWWVILTITWFLAAGRKWSCEAIEQKAVWFHAVAWGAPGFLTVMLLAMNKVEGDNISGVCFVGLYDLDASRYFVLLPLCLCVFVGLSLLLAGIISLNHVRQVIQHDGRNQEKLKKFMIRIGVFSGLYLVPLVTLLGCYVYELVNRITWEMTWFSDHCHQYRIPCPYQANPKARPELALFMIKYLMTLIVGISAVFWVGSKKTCTEWAGFFKRNRKRDPISESRRVLQESCEFFLKHNSKVKHKKKHGAPGPHRLKVISKSMGTSTGATTNHGTSAMAIADHDYLGQETSTEVHTSPEASVKEGRADRANTPSAKDRDCGESAGPSSKLSGNRNGRESRAGGLKERSNGSEGAPSEGRVSPKSSVPETGLIDCSTSQAASSPEPTSLKGSTSLPVHSASRARKEQGAGSHSDA') tools2 has this in it: class LightIterator(object): def __init__(self, handle): self._handle = handle self._defline = None def __iter__(self): return self def next(self): lines = [] defline_old = self._defline while 1: line = self._handle.readline() if not line: if not defline_old and not lines: raise StopIteration if defline_old: self._defline = None break elif line[0] == '>': self._defline = line[1:].rstrip() if defline_old or lines: break else: defline_old = self._defline else: lines.append(line.rstrip()) return defline_old, ''.join(lines) blastdb.py: #!/usr/bin/env python from __future__ import division __version__ = "$Revision: 1.3 $" """ blastdb.py access blastdb files Copyright 2005 Michael Hoffman License: GPL """ import os import sys try: from poly import NamedTemporaryFile # http://www.ebi.ac.uk/~hoffman/software/poly/ except ImportError: from tempfile import NamedTemporaryFile FASTACMD_CMDLINE = "fastacmd -d %s -s %s -o %s" class Database(object): def __init__(self, filename): self.filename = filename def fetch_to_file(self, query, filename): status = os.system(FASTACMD_CMDLINE % (self.filename, query, filename)) if status: raise RuntimeError, "fastacmd returned %d" % os.WEXITSTATUS(status) def fetch_to_tempfile(self, query): temp_file = NamedTemporaryFile() self.fetch_to_file(query, temp_file.name) return temp_file -- Michael Hoffman From fumanchu at amor.org Tue Jan 18 15:59:07 2005 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 18 Jan 2005 12:59:07 -0800 Subject: generator expressions: performance anomaly? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33981F3@exchange.hqamor.amorhq.net> Jeremy Bowers wrote: > On Tue, 18 Jan 2005 14:05:15 +0000, Antoon Pardon wrote: > > I don't see how generating byte code for a = 9; when seeing the > > expression a = 3 + 6, would be a problem for non-functional > > languages. > > Ultimately, the use is fairly limited; I can't imagine the > execution time saved would reach the time of implementation > for weeks after a release, even aggregating across all Python > use in the world, and "real time gained" (i.e., time useful > to a human) would probably never add up to the > implementation time. So why bother? That's a horrid trade off > when there are so many other real gains to be had. Especially since you can already do it explicitly with Raymond Hettinger's cookbook recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 Robert Brewer MIS Amor Ministries fumanchu at amor.org From mhartl at post.harvard.edu Sat Jan 29 20:01:39 2005 From: mhartl at post.harvard.edu (Michael Hartl) Date: 29 Jan 2005 17:01:39 -0800 Subject: naive doc question References: <5175a81c050129163826fcd734@mail.gmail.com> Message-ID: <1107046899.023197.174440@f14g2000cwb.googlegroups.com> i.e., http://docs.python.org/lib/typesmapping.html From thorsten.pferdekaemper at sap.com Wed Jan 12 06:40:14 2005 From: thorsten.pferdekaemper at sap.com (=?iso-8859-1?Q?Thorsten_Pferdek=E4mper?=) Date: Wed, 12 Jan 2005 12:40:14 +0100 Subject: [Ann] Voidspace Pythonutils Website Change and Updates References: Message-ID: "Michael Foord" wrote in message news:mailman.559.1105529220.22381.python-list at python.org... > The Voidspace Pythonutil Pages have had a long overdue overhaul. The url > of the Voidspace Pythonutils homepage has changed. It is now : > http://www.voidspace.org.uk/python/index.html > Hi, do you mean http://www.voidspace.org.uk/python/index.shtml? Regards, Thorsten From lbates at syscononline.com Fri Jan 28 09:37:16 2005 From: lbates at syscononline.com (Larry Bates) Date: Fri, 28 Jan 2005 08:37:16 -0600 Subject: HTML Tree View with

          and In-Reply-To: References: Message-ID: <-JOdnaxXKMmP02fcRVn-oA@comcast.com> While not EXACTLY what you outlined, I've used TreeView http:www.treeview.net along with Python to create the dynamic tree menus you describe. I had to write a couple or very short JavaScript additions, but it is working just fine. All the tree opening and closing is done on the client via-javascript so it is very fast. Larry Bates Gregor Horvath wrote: > Hi, > > Before I reinvent the wheel I`d like to ask if someone has done this > before since I did not find an advice at Google. > > The goal is to create a dynamic Tree View in HTML. > > Say I have a data strucure like this: > > structList = > {'Sun':{'Sun.1':['Sun1.1','Sun1.2'],'Sun.2':['Sun2.1','Sun2.2']},'Kupa':['Kupa1']} > > > I want to transform this into HTML: > >
            >
          1. Sun
          2. >
              >
            1. Sun.1
            2. >
                >
              1. Sun1.1
              2. >
              3. Sun1.2
              4. >
              >
            3. Sun.2
            4. >
                >
              1. Sun2.1
              2. >
              3. Sun2.2
              4. >
              >
            >
          3. Kupa
          4. >
              >
            1. Kupa1
            2. >
            >
          > > If the user clicks on a branch-link say 'Sun.1' then the branch below > opens/closes (not printed by the servlet). Like a tree view control in > an native GUI app. > > Has this, or a similar approach, been done before in python ( I am using > webware/cheetah)? > > -- > Greg From usenet_spam at janc.invalid Fri Jan 14 22:02:15 2005 From: usenet_spam at janc.invalid (JanC) Date: Sat, 15 Jan 2005 03:02:15 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <1105219440.064891.199690@c13g2000cwb.googlegroups.com> Message-ID: jtauber schreef: > see http://cleese.sourceforge.net/ There is not much to see there, most of the wiki is filled with spam... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From aleaxit at yahoo.com Sun Jan 30 04:32:07 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 30 Jan 2005 10:32:07 +0100 Subject: Coding style article with interesting section on white space References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> Message-ID: <1gr74p3.1p45u1v182vecgN%aleaxit@yahoo.com> wrote: > Michael Tobis wrote: > > (unwisely taking the bait...) > > > > If you like your language to look like this > > http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html > > then more power to you. > > Thanks for pointing out that interesting article on Fortran 90 bugs. > How long would a comparable C++ list be? Even Python has gotchas, for > example the difference between deep and shallow copies. C++ "gotchas" spawn whole books. So, once, did C ones -- Koenig's "C Traps and Pitfalls" is a wonderful book; to be honest, that was only partly about the _language_... Koenig's advocacy of half-open loops and intervals is just as valid in any language, but it was still a point WELL worth making. The referenced page, in part, is simply pointing out places where Fortran might prove surprising to a programmer just because it works differently from some other language the programmer might be used to. For example, the very first entry just says that '.and.' does not short-circuit, so when you need guard behavior you should rather use nested IF statements. This is no bug, just a reasonable language design choice; anybody coming from (standard) Pascal would not be surprised; Ada even has two different forms ('and' doesn't short-circuit, if you want short-circuit you use 'and then'). In some sense it can be a gotcha for some programmers, but it would be silly to count it as a "fortran bug"! Or even "wart" for that matter. So, I would try to classify things in three classes: a. some things are important techniques which one may choose to highlight in the context of a given language, yet it would simply be silly to classify as gotchas, warts, or bugs _of that language_; b. some aspects of a language's behavior are surprising to people familiar w/other languages which behave differently, and thus are worth pointing out as "gotchas" though they're surely not bugs (and may or may not be warts); c. lastly, some things are irregularities within the language, or truly unexpected interactions among language features, or vary between implementations in ways most programmers won't expect; these can be described as warts (and maybe even bugs, meaning things that may well be fixed in the next version of a language). The advantages of half-open intervals (per Koenig's book), the fact that copies exist in both shallow and deep senses, or the fact that with pointers to pointers you need to allocate the parent pointers first (the last entry in the referenced page) are really about [a] -- of course if a language doesn't have pointers, or doesn't offer a standardized way to make copies, you won't notice those aspects in that language (the issue of half-open loops and intervals is wider...), but really these kinds of observations apply across broad varieties of languages. Point (b) will always be with us unless all languages work in exactly the same way;-). 'and' will either short-circuit or not (or the language will be more complicated to let you specify), array indices will start from 0 or from 1 (or the language will be more complicated to let you specify, etc etc), default values for arguments will be computed at some specified time -- compile-time, call-time, whatever -- or the language will be poorer (no default values, or only constant ones) or more complicated (to let you specify when the default gets computed). Etc, etc. Point (c) is really the crux of the matter. Generally, simple languages such as C or Python will have relatively few (c)-warts; very big and rich ones such as C++ or Perl will have many; and ones in the middle, as it appears to me that Fortran 90 is, will have middling amounts. I'm not saying that lanugage size/complexity is the only determinant -- there are other aspects which contribute, e.g., the need for backwards compatibility often mandates the presence of legacy features whose interaction with other features may cause (c) moments, so, a language which is older, has evolved a lot, and is careful to keep compatibility, will be more at risk of (c)-level issues. Still, size matters. It's just like saying that a big program is likely to have more bugs than a small one... even though many other factors contribute (backwards compatible evolution from previous versions matters here, too). > > I prefer my languages to be portable, terse and expressive. > > Fortran programmers are generally happy with the portability of the > language. A difficulty with Python portability and maintainability is > that some needed functionality is not in the core language but in C > extensions. For scientific computation, consider the case of Numeric > and Numarray. I don't think Numeric binaries are available for Python > 2.4, ? Just googled and visited the first hit -- I don't currently use Windows so I don't know if it's still there, works well, etc. > The recent "Pystone Benchmark" message says that Python is only 75% as > fast on Linux as on Windows. Fortran programs do not suffer this > performance hit and are in this respect more portable. In theory, as You're saying that using a different and better compiler cannot speed the execution of your Fortran program by 25% when you move it from one platform to another...?! This seems totally absurd to me, and yet I see no other way to interpret this assertion about "Fortran programs not suffering" -- you're looking at it as a performance _hit_ but of course it might just as well be construed as a performance _boost_ depending on the direction you're moving your programs. I think that upon mature consideration you will want to retract this assertion, and admit that it IS perfectly possible for the same Fortran program on the same hardware to have performance that differs by 25% or more depending on how good the optimizers of different compilers happen to be for that particular code, and therefore that, whatever point you thought you were making here, it's in fact totally worthless. > has been mentioned, one could use a faster compiler to compile CPython > on Linux, but AFAIK this has not yet been done. We're cheapskates, so we tend to go for the free compilers -- with the exception of Windows, where I believe Microsoft donated many copies of their newest commercial compiler to Python core developers working on Windows (smart move on MS part, makes their platform look better at no real cost to them). But the more compilers are in use, the LARGER the variation of performance I expect to see for the same code on a given box. There will surely be cheapskates, or underfunded programmers, in the Fortran world, too, using free or very cheap compilers -- or is your claim that anybody using Fortran MUST be so flush with money that they only ever use the costliest tools, and thus that Fortran should not be considered unless your project's budget for programming tools is Rubenesque? Do you think the costliest professional compilers cannot EVER find, on any given benchmark, some optimization worth a 25% speedup wrt the cheapest or free compilers...?! I really can't believe you'd claim any of this. Maybe you will want to clarify what, if anything, you mean here. Alex From aldo at nullcube.com Thu Jan 6 01:44:43 2005 From: aldo at nullcube.com (Aldo Cortesi) Date: Thu, 6 Jan 2005 17:44:43 +1100 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> References: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> Message-ID: <20050106064443.GA14382@nullcube.com> Thus spake wordsender at gmail.com (wordsender at gmail.com): > Hey guys, > > I can't figure this one out, why is this simple script giving me > problems? > > logfile=file(r'test.txt','w') ^^^ You've opened the file in write mode. To read from the file, you'll have to reopen it in read mode ("r"). Also, if the file you're dealing with really is a log file, you probably want don't want to open it in write mode for writing information either, since that will truncate the file and lose previously logged information. Try append mode ("a") instead. Cheers, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com Off: (02) 9283 1131 Mob: 0419 492 863 From zyqnews at 163.net Sat Jan 29 22:13:17 2005 From: zyqnews at 163.net (zyqnews at 163.net) Date: 29 Jan 2005 19:13:17 -0800 Subject: cx_freeze error In-Reply-To: References: <1107048210.548048.152870@z14g2000cwz.googlegroups.com> Message-ID: <1107054796.999110.18380@c13g2000cwb.googlegroups.com> There is no any module like "re.py", I just compiled the hello.py it has only one line: print "hello!" Anyone knows how? From removethis.kartic.krishnamurthy at gmail.com Sun Jan 30 20:21:54 2005 From: removethis.kartic.krishnamurthy at gmail.com (Kartic) Date: Mon, 31 Jan 2005 01:21:54 GMT Subject: Problem with loading textfiles into dictionaries. In-Reply-To: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> References: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> Message-ID: mercuryprey at gmail.com said the following on 1/30/2005 7:43 PM: > Hello, > I want to do the following: > > def do_load(self, arg): > sitefile = file('sitelist', 'r+', 1) > while True: > siteline = sitefile.readline() > site_rawlist = siteline.split() > sitelist[site_rawlist[0]] = site_rawlist[1:] > if len(siteline) == 0: > break > > I want to load a textfile into a dictionaries and use the first word on > a line as the key for the list, then take the remaining words of the > line and make them values of the key. This doesn't work: > > File "ftp.py", line 57, in do_load > sitelist[site_rawlist[0]] = site_rawlist[1:] > IndexError: list index out of range Hi - It looks like your code encountered a blank line when you got this error. You should move "if len(siteline) == 0" part right after your readline. The way you have done it really does not help. def do_load(self, arg): sitefile = file('sitelist', 'r+', 1) while True: siteline = sitefile.readline() if len(siteline) == 0: break site_rawlist = siteline.split() sitelist[site_rawlist[0]] = site_rawlist[1:] Thanks, --Kartic From itsme at yahoo.com Tue Jan 11 18:01:27 2005 From: itsme at yahoo.com (It's me) Date: Tue, 11 Jan 2005 23:01:27 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: You are focusing on computational type applications of complex numbers. For those, you can do it with any languages - including machine language. It's just a matter of how much headache you want. For instance, when constructing "software lego parts" (such as the Matlab/Simulink type), it's very annoying that you need to know what kind of signal comes in and goes out. In Malab/Simulink, for instance, you specify that the signal is of the "inherit" type (meaning you don't care what type it is - just process it). In Python, it's of type "duck", just pass it on...I don't need to care if it's real or complex. I don't need to devise yet another overloaded operator or function whenever I encounter a situation where the native language doesn't handle. "Anno Siegel" wrote in message news:cs17od$ag1$1 at mamenchi.zrz.TU-Berlin.DE... > > What kind of awareness do you mean? > > There are some operations (as comparison) that work for reals, but not > for complex numbers. If you want your program to run with complex input, > you have to avoid such operations, whether the data type is native or not. > > What other considerations are there? A typical numeric program should > just run and give complex output when fed complex input. I made the > experiment with the Perl module Statistics::Descriptive, which was > certainly written without concern for complex input, and it works without > a hitch. I'm not sure if the (complex) variance of several complex > numbers is a reasonably interpretable quantity, but I'm certain the > maths is done right. What else do you want? > > Anno From jerf at jerf.org Thu Jan 20 19:01:59 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 20 Jan 2005 19:01:59 -0500 Subject: xml parsing escape characters References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efedf2$0$11622$9b622d9e@news.freenet.de> <35adg4F4jgvpnU1@individual.net> <41F01A86.2040805@v.loewis.de> Message-ID: On Thu, 20 Jan 2005 21:54:30 +0100, Martin v. L?wis wrote: > Luis P. Mendes wrote: >> When I access the url via the Firefox browser and look into the source >> code, I also get: >> >> > xmlns="http................"><DataSet> ~ <Order> >> ~ <Customer>439</Customer> ~ </Order> >> </DataSet> > > Please do try to understand what you are seeing. This is crucial for > understanding what happens. >From extremely painful and lengthy personal experience, Luis, I ***extremely*** strongly recommend taking the time to nail this down until you really, really, really understand what is going on. Until you can explain it to somebody else coherently, ideally. Mixing escaping levels like this absolutely, positively *must* be done correctly, or extremely-painful-to-debug problems will result. (My painful experience was layering an RPC implementation in plain text on top of IM messages, where I was dealing with everything from the socket level up except the XML parser. Ultimately it turned out there was a problem in the XML parser, it rendered "&amp;" as "&", which is wrong wrong wrong. But that took a *long* time to find, especially as I had other bugs in the way.) Since you're layering XML in XML, test &amp; and &amp;amp; to make sure they work correctly; those usually show encoding errors. And, given your current understanding of the issue, do not write your own decoding function unless you absolutely can't avoid it. From cbfalconer at yahoo.com Sat Jan 29 06:26:07 2005 From: cbfalconer at yahoo.com (CBFalconer) Date: Sat, 29 Jan 2005 11:26:07 GMT Subject: what's OOP's jargons and complexities? References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> <41fb3c85$0$10470$8fcfb975@news.wanadoo.fr> Message-ID: <41FB648B.66BA1AB9@yahoo.com> jacob navia wrote: > > Good post. > > First article that demistifies this OO centered approach > in quite a long time. > > This approach has its strength, but also has it weakness, > it is not the solution for every problem appearing in > data processing. Xah Lee is a known troll, who likes to crosspost to many OT groups and stir up the ants. F'ups set. -- "If you want to post a followup via groups.google.com, don't use the broken "Reply" link at the bottom of the article. Click on "show options" at the top of the article, then click on the "Reply" at the bottom of the article headers." - Keith Thompson From steven.bethard at gmail.com Tue Jan 25 11:45:11 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Jan 2005 09:45:11 -0700 Subject: Classical FP problem in python : Hamming problem In-Reply-To: References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> Message-ID: Nick Craig-Wood wrote: > Thinking about this some more leads me to believe a general purpose > imerge taking any number of arguments will look neater, eg > > def imerge(*generators): > values = [ g.next() for g in generators ] > while True: > x = min(values) > yield x > for i in range(len(values)): > if values[i] == x: > values[i] = generators[i].next() > This kinda looks like it dies after the first generator is exhausted, but I'm not certain. An alternate version that doesn't search for 'i': py> def imerge(*iterables): ... iters = [iter(i) for i in iterables] ... values = [i.next() for i in iters] ... while iters: ... x, i = min((val, i) for i, val in enumerate(values)) ... yield x ... try: ... values[i] = iters[i].next() ... except StopIteration: ... del iters[i] ... del values[i] ... py> list(imerge([1, 4, 7], [2, 5, 8], [3, 6, 9])) [1, 2, 3, 4, 5, 6, 7, 8, 9] py> list(imerge([3, 6, 9], [1, 4, 7], [2, 5, 8])) [1, 2, 3, 4, 5, 6, 7, 8, 9] py> list(imerge([1, 4, 7], [3, 6, 9], [2, 5, 8])) [1, 2, 3, 4, 5, 6, 7, 8, 9] > This means that this can be further simplified thus, > > def hamming(): > def _hamming(): > yield 1 > for n in imerge( imap(lambda h: 2*h, hamming2), > imap(lambda h: 3*h, hamming3), > imap(lambda h: 5*h, hamming5) ): > yield n > hamming2, hamming3, hamming5, result = tee(_hamming(), 4) > return result Nice. Steve From whisper at oz.net Wed Jan 5 18:30:27 2005 From: whisper at oz.net (whisper at oz.net) Date: Wed, 05 Jan 2005 15:30:27 -0800 Subject: Decorators and static typing. Message-ID: <41DC7893.2090707@oz.net> Well, the decorator war is over (Python lost IMO!) and now we've got the static typing war to fight! Both of these seem like syntax sugar to avoid writing good code! One has already introduced ugly coding and the 2nd is likely to do the same! Ok, so how do you do keywords and default values? def myFunc(a=1: int, b="hi": string, people=[]: array[person]): int: yadda yadda yadda So, what is the int or string? the default value or the label? (Of course it's obvious to an experienced programmer - is that the intened audience for Python now and the python in education initiative dead?). The last parameter is particularly arcane (and ugly!). If this mistake looking for a place to happen has to happen, at least put the type before the horse!: def myFunc(int a=1, string b="hi" array[person] people) int: #note lack of first : after "(" yadda yadda yadda Of course, one could not change the language at all!: def myFunc(a, b): assert(type(a) == "int") assert(type(b) == "string") #aggrigates lose here - how do you check the type of every element? (ensure that array[person].__add__ makes sure the rhs is of type person so the problem never comes up in the first place!) yadda yadda yadda I know: this doesn't save you from yourself when calling myFunc from somewhere else, but it does ensure that parameters are of the expected type where it really counts! (People who need saiving from themselves ought not to be programmers in the first place!) Of course, decorators might have been done this last way too - with predefined functions and no needed changes to the language, but maybe that's not as cool for the dev guys. That brings up the larger problem, as alluded to by the "python evolution: unease" thread: the dev guys seem intent on more breadth without focusing on the depth of the language! At some point, someone has to decide that python is feature complete! Lua is looking better and better! ;=) From apardon at forel.vub.ac.be Mon Jan 17 08:15:34 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Jan 2005 13:15:34 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-17, Steve Holden schreef : > Antoon Pardon wrote: > >> Op 2005-01-17, Steve Holden schreef : >> >>>Antoon Pardon wrote: >>>[...] >>> >>>>>"A foolish consistency is the hobgoblin of little minds". Rules are made >>>>>to be broken. >>>> >>>> >>>>Like only use immutables as dictionary keys. >>>> >>> >>>Fair enough, but don;t go advising newbies to do this. >> >> >> How about something like this. >> >> Because of the extra precautions one has to take when >> using mutables as hash keys, we advise newbies >> to stick with immutable keys until they have gathered >> enough knowledge and experience to adequatly weight >> the pro and cons of a mutable key solution against >> an immutable key solution. >> > There you go with the minutiae again. How about: > > "Don't use mutables as hash keys"? That sounds too dogmatic to my ears. I also find it too selective. The problem with mutables as dictionary keys is not specific to dictionaries. Everywhere you have mutables in a container, it is possible that mutating the object in the container will cause problem. Heck even using mutables as arguments can cause trouble. Why else the specific advice against def foo(p = []) type of arguments. So should we adopt the principles: Don't use mutables in containers Don't use mutables as default values for parameters Don't use mutables as arguments. Don't assign one mutable to an other. I don't see a big difference between these principles and the hash key principle, so in the end may be we should just stick with the more general principle: Don't use mutables! and be done with it. -- Antoon Pardon From peter at somewhere.com Thu Jan 27 05:27:40 2005 From: peter at somewhere.com (Peter Maas) Date: Thu, 27 Jan 2005 11:27:40 +0100 Subject: python without OO In-Reply-To: <1106814263.835719.181360@z14g2000cwz.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106814263.835719.181360@z14g2000cwz.googlegroups.com> Message-ID: michele.simionato at gmail.com schrieb: > Davor is right: even if > you do not want to use it, the stuff is *there* and somebody in your > team will. So definitely there is an audience of programmers that just > do not have an use for all the sophistication and actually are > penalized by it. No, because Python does not enforce using advanced concepts. You can write programs that are as simple as in 1991. A group of developers always has to find some kind of common style with a chance that some are penalized. This can happen with every language. > There is not much than can be done at the Python level. But I would > see with interest a Python spinoff geared towards simplicity. I think this would be useless because advanced concepts exist for a reason. A simplified spin-off would aquire advanced concepts over time and would just become a clone of Python. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From alan.ezust at gmail.com Sun Jan 23 11:40:16 2005 From: alan.ezust at gmail.com (alan dot ezust at gmail dot com) Date: 23 Jan 2005 08:40:16 -0800 Subject: debugging xmlrpc servers In-Reply-To: References: <1106442233.305138.24790@f14g2000cwb.googlegroups.com> Message-ID: <1106498416.494928.197360@z14g2000cwz.googlegroups.com> Understandable - i had difficulties understanding my problem too! I don't really understand why I got that error message before - I believe it was due to the fact that some other exception was being raised inside results(). Anyway, the solution was to call rpdb.set_trace() inside the actual method which was being called by xmlrpc, and setting the breakpoint to be the statement following that line (rather than the function itself). cheers --alan From paulo.jpinto at gmail.com Wed Jan 19 06:35:50 2005 From: paulo.jpinto at gmail.com (paulo.jpinto at gmail.com) Date: 19 Jan 2005 03:35:50 -0800 Subject: mod_python friendly isps in europe Message-ID: <1106134550.347891.129260@f14g2000cwb.googlegroups.com> Hello everybody I'm thinking about improving my web site scripts and would like to use Python instead of PHP/Perl. Does anyone know of mod_python friendly ISPs in europe? With prices around 10? ? Thanks in advance, Paulo From tjreedy at udel.edu Thu Jan 13 15:44:59 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Jan 2005 15:44:59 -0500 Subject: sorted (WAS: lambda) References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com><7x7jmh1eek.fsf@ruckus.brouhaha.com> <7xpt09xizb.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7xpt09xizb.fsf at ruckus.brouhaha.com... > Steven Bethard writes: >> Note that sorted is a builtin function, not a method of a list >> object. > > Oh, same difference. I thought it was a method because I'm not using > 2.4 yet. The result is the same, other than that having it as a > function instead of a method is another inconsistency to remember. No, not same difference. A list method would only operate on lists, as is true of all list methods. Being a function lets it work for any iterable, as is true of any function of iterable. Big difference. And consistent. One could argue though that it should have been put into itermethods module instead of builtins. Terry J. Reedy From dbickett at gmail.com Fri Jan 7 16:22:55 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Fri, 7 Jan 2005 16:22:55 -0500 Subject: DOS problem (simple fix??) In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E3398131@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E3398131@exchange.hqamor.amorhq.net> Message-ID: <1d6cdae30501071322666f1ddd@mail.gmail.com> I tend to run "cmd" and "cd" to the directory of the script, then run it. This way, the window doesn't close, and I can read any errors that occur without interruption. Optionally, you can run "cmd" and simply drag the script you want to run into the window. That pastes its path (in quotes) into the command line, and you can just hit enter. I wouldn't recommend this, though, because the cwd wouldn't be that of the script, and it could cause instability for some apps that use relative paths. Daniel Bickett From littlejohn.75 at news.free.fr Fri Jan 14 04:49:15 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 14 Jan 2005 09:49:15 GMT Subject: import problems *newbie* References: <1105682316.601321.118820@f14g2000cwb.googlegroups.com> Message-ID: <41e7959b$0$385$636a15ce@news.free.fr> Le 13 Jan 2005 21:58:36 -0800, mike kreiner a ?crit : > I am having trouble importing a module I created. I'm running PythonWin > on Windows XP if that helps. I saved my module in a folder called > my_scripts in the site-packages directory. I edited the python path to > include the my_scripts folder (it now reads > C:\Python23\Lib;C:\Python23\DLLs;C:\Python23\Lib\lib-tk;C:\Python23\Lib\site-packages\my_scripts). Not a very godd idea to mess with the python path > When I try to import the module, I get this error: > >>>> from PolyDraw import * > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named PolyDraw > > When I select Browse PythonPath from the tools menu, I'm able to locate > my module, PolyDraw.py. > > The problem goes away if I open PolyDraw.py from PythonWin, which I'm > assuming is because opening the module makes my_scripts the current > working directory. This is just a quick workaround, but I'd like to > know how to fix the problem. Thanks. A quick fix is to promote your my_scripts folder to be a python package, by creating a python module (file) named __init__.py right in the package directory. The content of __init__.py can be for instance #!/usr/bin/env python # -*- coding: Latin-1 -*- """ my_scripts package containing miscellaneous modules PolyDraw .... """ __author__ = 'mike kreiner' To import from this package the syntax is from my_scripts import PolyDraw > > -Mike > From usenet_spam at janc.invalid Mon Jan 3 04:26:21 2005 From: usenet_spam at janc.invalid (JanC) Date: Mon, 03 Jan 2005 09:26:21 GMT Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wn8jne.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schreef: > The AOL web server also uses tcl as a built-in dynamic content > generation language (i.e. sort of like mod_python), or at least it > used to. It still does: """ AOLserver is America Online's Open-Source web server. AOLserver is the backbone of the largest and busiest production environments in the world. AOLserver is a multithreaded, Tcl-enabled web server used for large scale, dynamic web sites. """ -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From FBatista at uniFON.com.ar Mon Jan 24 08:12:00 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 24 Jan 2005 10:12:00 -0300 Subject: Help on project, anyone? Message-ID: [Georg Brandl] #- Does anyone run, or participate in, a project looking for fellow #- programmers? I don't have a special area of interest, well, #- perhaps web #- programming... You can join us in SiGeFi: http://sf.net/projects/sigefi ----------- SiGeFi is a Financial Management System, with focus in the needs of the administration of the money in each personal life and house. Always keeping the easy usage and concepts, SiGeFi has features of a complex Management system: - Complies with Double Entry Accounting - Has a Budget-based Money Distribution system - Allow to make Loans between accounts (with associated financial costs) ----------- Any doubt, contact us through sigefi-list or to me personally. Regards, . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stephen.thorne at gmail.com Thu Jan 20 21:32:48 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Fri, 21 Jan 2005 12:32:48 +1000 Subject: Print a string in binary format In-Reply-To: References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> <1106270502.219126.322790@f14g2000cwb.googlegroups.com> Message-ID: <3e8ca5c805012018325b4b2525@mail.gmail.com> On Fri, 21 Jan 2005 01:54:34 GMT, Kartic wrote: > neutrino said the following on 1/20/2005 8:21 PM: > > Mmm, the output format that I want is like: > > 0001110011111111000000001111111100000000.... > > > > I tried your code on Cygwin under Windows 2000, and on Linux, but it > > prints out ASCII characters. > > > > Aha..I guess I posted too soon. > > You might want to take a look at this cookbook entry: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300 > > Defines lambdas to convert integer to binary. The one you probably want is - > >>> bstr = lambda n, l=16: n<0 and binarystr((2L< bstr(n>>1).lstrip('0')+str(n&1) or '0' > >>> bstr(ord('a')) > '1100001' Death to inappropriate usage of lambda. First of all, that lambda is buggy, it doesn't work for negative numbers, but you can't immediately see that because of the compressed nature of the code. The lambda, with the bug corrected, converts to a function that looks like this. def bstr(n, length=16): if n == 0: return '0' if n<0: return bstr((long(2)<>1).lstrip('0') + str(n&1) As you can see, the kwarg used is actually only used for the negative numbers, so we can make this more concise as: def bstr(n): if n == 0: return '0' return bstr(n>>1).lstrip('0') + str(n&1) But this isn't what we want, because we want bstr(1) to == '00000001' not '1'. So lets just throw the POS away and rewrite it, firstly: Test Cases: assert bstr(0) == '00000000' assert bstr(1) == '00000001' assert bstr(255) == '11111111' assert bstr(128) == '10000000' def bstr(n): # n in range 0-255 return ''.join([str(n >> x & 1) for x in (7,6,5,4,3,2,1,0)]) Took me a little bit, and I replaced xrange(7,-1,-1) with the much clearer precomputed tuple, but what we have a recursionless function that actually fulfills the requirements. This can be used in the original poster's situation to output data in (almost) readable binary format using something like the following: f = file('myfile', 'rb') while 1: bytes = f.read(8) if not bytes: break print ' '.join([bstr(ord(c)) for c in bytes]) Regards, Stephen Thorne From gsakkis at rutgers.edu Mon Jan 24 20:37:18 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Mon, 24 Jan 2005 20:37:18 -0500 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> Message-ID: <35lm6dF4hr4t2U1@individual.net> "Jeff Shannon" wrote in message news:10vb3enf8qvld4 at corp.supernews.com... > [My newsreader crapped out on sending this; apologies if it appears > twice.] > > George Sakkis wrote: > > > "Terry Reedy" wrote in message > > news:mailman.1226.1106605134.22381.python-list at python.org... > > > >>Aside from the problem of not being able to delete the underlying object, > >>the view object for a tuple would have to be a new type of object with a > >>new set of methods. > > > > It *could*, but it doesn't have to. One can represent a view as essentially an object with a pointer > > to a memory buffer and a (start,stop,step) triple. Then a "real tuple" is just a "view" with the > > triple being (0, len(sequence), 1). > > Except that that's not how Python tuples *are* constructed, and it'd > be a pretty big deal to redo the architecture of all tuples to support > this relatively special case. > > Even if this re-architecting were done, you're still constructing a > new object -- the difference is that you're creating this > (start,stop,step) triple instead of duplicating a set of PyObject* > pointers, and then doing math based on those values instead of > straightforward pointer access. I'm not at all convinced that this > really saves you a significant amount for tuple slices (really, you're > still constructing a new tuple anyhow, aren't you?), and it's going to > cost a bit in both execution time and complexity in the common case > (accessing tuples without slicing). If there's a big cost in object > construction, it's probably going to be the memory allocation, and for > a reasonable tuple the size of the memory required is not going to > significantly affect the allocation time. > > Jeff Shannon > Technician/Programmer > Credit International > You're probably right about the allocation time, but my main concern is the memory required for each slice, which can be O(n) wrt the length of the whole tuple. I would like this to be constant (at least if there was a way around to the problem of deleting the underlying sequence). George From apardon at forel.vub.ac.be Wed Jan 12 03:50:04 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 Jan 2005 08:50:04 GMT Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> <7xllb2f3z4.fsf@ruckus.brouhaha.com> <1105355380.040837.189270@c13g2000cwb.googlegroups.com> <7xis65a5w6.fsf@ruckus.brouhaha.com> <1105357839.696387.309900@c13g2000cwb.googlegroups.com> <7xr7kt314a.fsf@ruckus.brouhaha.com> <1105364925.848973.73080@c13g2000cwb.googlegroups.com> <7xllb1jsdz.fsf@ruckus.brouhaha.com> <7xpt0ciekk.fsf@ruckus.brouhaha.com> <10u8emr2iaa5k03@corp.supernews.com> Message-ID: Op 2005-01-11, Jeff Shannon schreef : > Paul Rubin wrote: > >> Steve Holden writes: >> >>>[...] and if you think that >>>newbies will have their lives made easier by the addition of ad hoc >>>syntax extensions then you and I come from a different world (and I >>>suspect the walls might be considerably harder in mine than in yours). >> >> I'm saying that many proposals for ad hoc extensions could instead be >> taken care of with macros. Newbies come to clpy all the time asking >> how to do assignment expressions, or conditional expressions, or >> call-by-reference. Sometimes new syntax results. Lots of times, >> macros could take care of it. > > Personally, given the requests in question, I'm extremely thankful > that I don't have to worry about reading Python code that uses them. > I don't *want* people to be able to make up their own > control-structure syntax, because that means I need to be able to > decipher the code of someone who wants to write Visual Basic as > filtered through Java and Perl... No you don't. You could just as well claim that you don't want people to write code in other languages because you then would need to be able to decipher code written in that language. > If I want mental gymnastics when > reading code, I'd use Lisp (or Forth). (These are both great > languages, and mental gymnastics would probably do me good, but I > wouldn't want it as part of my day-to-day requirements...) Your day-to-day requirements are a contract between you and your employer or between you and your clients. That you don't want mental gymnastics as part of that, shouldn't be a concern for how the language develops. -- Antoon Pardon From daranrife at yahoo.com Sat Jan 1 15:05:29 2005 From: daranrife at yahoo.com (drife) Date: 1 Jan 2005 12:05:29 -0800 Subject: Looping using iterators with fractional values Message-ID: <1104609929.888351.8870@c13g2000cwb.googlegroups.com> Hello, Making the transition from Perl to Python, and have a question about constructing a loop that uses an iterator of type float. How does one do this in Python? In Perl this construct quite easy: for (my $i=0.25; $i<=2.25; $i+=0.25) { printf "%9.2f\n", $i; } Thanks in advance for your help. Daran Rife daranrifeUNS at PAMyahoo.com From aahz at pythoncraft.com Wed Jan 5 13:29:28 2005 From: aahz at pythoncraft.com (Aahz) Date: 5 Jan 2005 13:29:28 -0500 Subject: Write some docs already! (was Re: Python evolution: Unease) References: <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> Message-ID: In article <10to8qulnc3vke1 at news.supernews.com>, John Roth wrote: > >I would like to contribute some documentation to Python. I've got >the time, I write quite a bit, etc. I've got fairly strong opinions >about some things that need to be documented, (such as all the new >style class descriptor stuff from 2.2) and I have relatively little >difficulty matching the existing style. > >However, I don't know TEX, Latex, CVS or Sourceforge. (The latter two >are on my "learn sometime soon so I can put PyFIT where it belongs" >list.) > >I have no desire to install Perl to run the documentation toolchain. So don't! The editors for the Python docs are extremely happy to take raw ASCII (or reST if you're up for that) and convert it to Python's formatting rules. See 2.4's "Documenting Python" -- I finally convinced the editors to make the policy explicit. It would be highly desirable for you to learn SourceForge, though; that way it would be easy for you to participate in the bug/patch process. But even that isn't essential. >I also have no particular desire to write up a bunch of final format >stuff and drop it on someone else to put into the latex format so it >can be included. Not clear what you mean here. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From ola.natvig at infosense.no Wed Jan 26 09:56:00 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Wed, 26 Jan 2005 15:56:00 +0100 Subject: 4suite XSLT thread safe ? In-Reply-To: References: <6lkkc2-fbd.ln1@pluto.i.infosense.no> <35pntaF4os76kU1@individual.net> Message-ID: <0lnkc2-pbg.ln1@pluto.i.infosense.no> Istvan Albert wrote: > Diez B. Roggisch wrote: > >> What do you mean by that? You can of course transform xml using xslt >> in as >> many threads as you like > > > It is not unthinkable that some parts of the library would not be > threadsafe. They could have some internal shared global variable > that keeps track of an intermediate state. > Some C string processing functions are not thread safe either. > > > Istvan. It looks like there are some problems with multiple threads accessing the the processor 'at once', think I'll write som kind of syncronizing wrapper or supply multiple processors to the threads. -- -------------------------------------- Ola Natvig infoSense AS / development From jeff at ccvcorp.com Tue Jan 18 17:36:08 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 18 Jan 2005 14:36:08 -0800 Subject: macros In-Reply-To: References: Message-ID: <10ur3gueivenob6@corp.supernews.com> Jeremy Bowers wrote: > On Tue, 18 Jan 2005 12:59:07 -0800, Robert Brewer wrote: > > You know, Guido might as well give in now on the Macro issue. If he > doesn't come up with something himself, apparently we'll just hack > bytecode. I'm not sure that's a gain. I think that this sort of thing is better to have as an explicitly risky hack, than as an endorsed part of the language. The mere fact that this *is* something that one can clearly tell is working around certain deliberate limitations is a big warning sign, and it makes it much less likely to be used extensively. Relatively few people are going to want to use something called "bytecodehacks" in a mission-critical piece of software, compared to the number who'd be perfectly happy to use a language's built-in macro facilities, so at least it keeps the actual usage down to a somewhat more manageable level. To rephrase this a bit more succinctly ;) there's a big difference between having no practical way to prevent something, and actually encouraging it. Jeff Shannon Technician/Programmer Credit International From OmcO at OmclaveauO.com.enleverLesO Fri Jan 21 02:43:53 2005 From: OmcO at OmclaveauO.com.enleverLesO (Do Re Mi chel La Si Do) Date: Fri, 21 Jan 2005 08:43:53 +0100 Subject: [ANN] PyScript 0.5 released References: <61de6b8e.0501201943.3cbc9ec3@posting.google.com> Message-ID: <41f0b5b2$0$25790$8fcfb975@news.wanadoo.fr> Hi ! The good URL is : http://pyscript.sourceforge.net :-) -- Michel Claveau From jeff at ccvcorp.com Thu Jan 27 15:05:57 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 27 Jan 2005 12:05:57 -0800 Subject: inherit without calling parent class constructor? In-Reply-To: References: Message-ID: <10vii1r91ovdv91@corp.supernews.com> Christian Dieterich wrote: > On D? C?adaoin, Ean 26, 2005, at 17:09 America/Chicago, Jeff Shannon wrote: > >> You could try making D a container for B instead of a subclass: > > > Thank you for the solution. I'll need to have a closer look at it. > However it seems like the decision whether to do "some expensive > calculation" or not is delegated to the exterior of class D. Different > classes that instanciate D would need to know what has been going on > elsewhere. That might complicate things. True, in the sense that B is instantiated as soon as a message is sent to D that requires B's assistance to answer. If the "decision" is a case of "only calculate this if we actually want to use it", then this lazy-container approach works well. If the decision requires consideration of other factors, then it's a bit more complex -- though one could write that logic into D, and have D throw an exception (or return a sentinel) if it decides not to instantiate B at that time. This then requires a bit more checking on the client side, but the actual logic is encapsulated in D. And really, I don't see where the container approach shifts the decision any more than the descriptor approach does. In either case, the calculation happens as soon as someone requests D.size ... (However, from your other descriptions of your problem, it does sound like a property / descriptor is a better conceptual fit than a contained class is. I mostly wanted to point out that there are other ways to use OO than inheritance...) Jeff Shannon Technician/Programmer Credit International From D.Sean.Morris at gmail.com Sat Jan 1 15:14:43 2005 From: D.Sean.Morris at gmail.com (Sean) Date: 1 Jan 2005 12:14:43 -0800 Subject: I need some advice/help on running my scripts Message-ID: <1104610483.153374.286730@z14g2000cwz.googlegroups.com> For the last couple of months I have been reading and working throught the examples in Magnus Lie Hetland's Book "Practical Python" This for all practical purposes is the first computer programming language I have spent any time at learning, so much of what I have covered in the book was for the first time. My problem is that many of the example scripts are run on Linux machines and I am using Win XP Pro. Here is a specific example of what is confusing me. If I want to open a file from the dos prompt in some script do I just write the name of the file I want to open (assuming it is in the same directory) after the script name? such as c:\some_script.py some_text_file.txt Does piping work the same way in dos as it does on a linux machine? And last but not least, is there a way to do this all from IDLE? From carribeiro at gmail.com Sat Jan 8 17:17:08 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sat, 8 Jan 2005 20:17:08 -0200 Subject: python3: 'where' keyword In-Reply-To: References: <3480qqF46jprlU1@individual.net> Message-ID: <864d3709050108141713fbcd41@mail.gmail.com> On Sat, 08 Jan 2005 12:53:05 -0500, Peter Hansen wrote: > Andrey Tatarinov wrote: > > >>> print words[3], words[5] where: > > >>> words = input.split() > > > > - defining variables in "where" block would restrict their visibility to > > one expression > > Then your example above doesn't work... print takes a > sequence of expressions, not a tuple as you seem to think. I found it strange that he had chosen to make the example with "print", that is a statement. I'm not sure how could it be made to work with both expressions and statements, it just seems strange... Overall, I found the idea interesting. It seems like a obvious counterpart to "with", in the sense that both act as modifiers to the scoping rules. I think it can be made to work, and that it would lead to elegant & readable code, but there are still lots of things to consider: exception handling, fast name lookup in the "where" block, access to symbols outside the "where" block, just to name a few. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From hwlgw at hotmail.com Thu Jan 13 07:56:49 2005 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 13 Jan 2005 04:56:49 -0800 Subject: newbie q In-Reply-To: <34mku4F4c8bdkU1@individual.net> References: <34mgq0F4dq4buU1@individual.net> <34mku4F4c8bdkU1@individual.net> Message-ID: <1105621009.074787.82420@f14g2000cwb.googlegroups.com> I understand you want to do it in an applicative programming style? Not recommended in general. But here goes: .# c.l.p. question: .# "using map, lambda, reduce, filter and List Comprehensions [x for .# x in []] just don't get how to add string to all elements of list" . .## .# A function that returns a function, taking a function as argument. .def allapply(fn): . def f(seq): return map(fn, seq) . return f . .def add_string_to_element(stringval): . def f(x): return x + stringval . return f . .add_string_to_all = allapply(add_string_to_element('mystring')) . .print add_string_to_all(['d:', 'c:\windows\\','something/']) this outputs: ['d:mystring', 'c:\\windows\\mystring', 'something/mystring'] -- look Ma, no for and no lambda! -- Will Stuyvesant From http Fri Jan 7 00:35:56 2005 From: http (Paul Rubin) Date: 06 Jan 2005 21:35:56 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> <7xk6qrnbum.fsf@ruckus.brouhaha.com> <41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <41dcf582.122188317@news.oz.net> Message-ID: <7xd5wh7qdf.fsf@ruckus.brouhaha.com> bokr at oz.net (Bengt Richter) writes: > I agree 1000% !! Importing a stub should get you an imported stub that > prints info as it imports, so you know its not functional. But I don't even understand why I'd even want to use these stubs, instead of just having the full installation from day 1. > >This may sound a little extreme but my distribution philosophy is I'd > >like to get closer to an environment where users normally never > >install any software of any type, ever. > It makes a lot of sense for a "core" plus a delivered specific application > base, but IMO if you try to cover the world with a monolith you will > inevitably still have the problem of getting the latest version of > particular packages for bug fixes or enhancements. I might want the latest enhancements for particular programs that I'm willing to devote a lot of attention to, but for the most part I don't want to be a beta tester, I only want to use stable software, where the definition of stable is that the latest version isn't much different from the previous version. I try quite hard to avoid ever upgrading software ("upgrade" means replace an existing, working version of something with a newer version) on my PC. I only want new software when I buy a new computer, or at least a new hard drive. I don't try to migrate system or configuration files. I just install the OS distro from scratch and migrate my user files. > There are several parts to those frustrations. But you are presuming > that they would have been solved for you and put on a DVD with all > dependency problems resolved. Ok, let's assume that. In that case, > an installation stub module could just as well have the solution built > into it as to what versions etc are needed to make the module work. How can it work just as well, when it requires a high-speed internet connection which I might not have? And why is "just as well" good enough, given how inconvenient and error-prone it is, compared with just installing from a DVD once and for all? To have any attraction what ever, the installation stub scheme (for me at least) has to work "an order of magnitude better", not "just as well", as a one-time complete install. > To bring a large collection into version-alignment ISTM you need a version > freeze across too many libraries of different kinds with different > development schedules and resources to make it reliable. One part of the problem is excessive version dependence between package X and package Y. That's why I think there should be more integration within packages, i.e. the Python distro should include a lot more modules that you currently have to download from other places. > When your wxPython-using program didn't work, wouldn't it have been nice > to have downloaded a standard stub program (with older stub versions still > available if you have an older system) and have it tell you what > was missing that it needed before you decided to let it continue and > get those things? Or choose not to? Huh? Getting those stubs to work properly has to be even harder than getting the distros to play nice with each other in the first place. So I'd rather that the stub-writing effort instead be put into eliminating the version conflicts. > With broadband most apps will be ready before you can make fresh > coffee, or maybe watch the Simpsons. In reality, whenever I try to install or download anything, something fails as often as not. I don't think I've ever seen a CPAN download work right on the first try. Really, I just want to buy a new computer, turn it on, and have everything there. That's generally impossible without running satanware from Redmond, so I approximate it as best as I can by doing a DVD install on new computers. I don't care if the software I'm running isn't the bleeding-edge latest. GCC today isn't different from GCC five years ago in any way that I care about. With Emacs, it's more like 10 years. I buy a new computer every 2 years or so, which means that any software I'm using by then will be at least 2 years old unless it's something I'm making special effort to stay on top of. If it's already a year or so old when I first start running it, I'm ok with that. > I realize this problem has been "solved" with various RPM and > app-loading methods, but I think python could wrap its solution > nicely. I don't think distutils and setup.py is easy enough to > create (at least I have been somewhat frustrated in using it > effectively), though it deals with a lot of what has to be done. Since all these schemes have failed whenever they've been tried, all I can think is that it's a harder problem than it sounds. From a at b.c Mon Jan 24 10:08:41 2005 From: a at b.c (Doug Holton) Date: Mon, 24 Jan 2005 09:08:41 -0600 Subject: What YAML engine do you use? In-Reply-To: <35fvroF4kngkmU1@individual.net> References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fvroF4kngkmU1@individual.net> Message-ID: <6sydna5ssvPgkmjcRVn-1Q@comcast.com> rm wrote: > Doug Holton wrote: > >> rm wrote: >> >>> this implementation of their idea. But I'd love to see a generic, >>> pythonic data format. >> >> >> >> That's a good idea. But really Python is already close to that. A >> lot of times it is easier to just write out a python dictionary than >> using a DB or XML or whatever. Python is already close to YAML in >> some ways. > > true, it's easy enough to separate the data from the functionality in > python by putting the data in a dictionary/list/tuple, but it stays > source code. Check out JSON, an alternative to XML for data interchange. It is basically just python dictionaries and lists: http://www.crockford.com/JSON/example.html I think I would like this better than YAML or XML, and it looks like it already parses as valid Python code, except for the /* */ multiline comments (which boo supports). It was mentioned in a story about JSON-RPC-Java: http://developers.slashdot.org/article.pl?sid=05/01/24/125236 From ncoghlan at iinet.net.au Sun Jan 9 06:20:20 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 21:20:20 +1000 Subject: python3: 'where' keyword In-Reply-To: <1gq4ebf.17qqy8dk9ccr6N%aleaxit@yahoo.com> References: <3480qqF46jprlU1@individual.net> <1gq4ebf.17qqy8dk9ccr6N%aleaxit@yahoo.com> Message-ID: <41E11374.6070409@iinet.net.au> Alex Martelli wrote: > I wonder if 'with', which GvR is already on record as wanting to > introduce in 3.0, might not be overloaded instead. Perhaps we could steal 'using' from the rejected decorator syntax. x = [f(x) for x in seq] using: def f(x): return x * x Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From bokr at oz.net Sun Jan 16 01:38:01 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 16 Jan 2005 06:38:01 GMT Subject: How to del item of a list in loop? References: Message-ID: <41ea0a87.979537159@news.oz.net> On Sat, 15 Jan 2005 15:27:08 -0500, skull wrote: > >Hi everybody, it is my first post in this newsgroup. >I am a newbie for python though I have several years development experience in c++. >recently, I was stumped when I tried to del item of a list when iteration. > >here is the wrong way I did: > >lst = [1, 2, 3] >for i in lst: > print i > if i == 2: > lst.remove(i) > >the result is: > >1 >2 >>>> > >as you would see, '3' is missing. this problem is caused by 'lst.remove(i)'. >apparently, 'marked-and-sweep' is a solution to deal with this issue. >but I think there SHOULD BE more 'wise' trick. I want to get your help. > >Thanks in advance. > No one seems to have suggested this in-place way yet, so I'll trot it out once again ;-) >>> lst = [1, 2, 3] >>> i = 0 >>> for item in lst: ... if item !=2: ... lst[i] = item ... i += 1 ... >>> del lst[i:] >>> lst [1, 3] Regards, Bengt Richter From srijit at yahoo.com Wed Jan 19 00:54:00 2005 From: srijit at yahoo.com (srijit at yahoo.com) Date: 18 Jan 2005 21:54:00 -0800 Subject: Error in Plex 1.1.4.1 Message-ID: <221d8dbe.0501182154.235a39af@posting.google.com> Hello, I got the following error while using Plex 1.1.4.1 D:\Python24\myfiles>python plex1.py Traceback (most recent call last): File "plex1.py", line 1, in ? from Plex import * File "D:\python24\lib\site-packages\Plex\__init__.py", line 34, in ? from Lexicons import Lexicon, State File "D:\python24\lib\site-packages\Plex\Lexicons.py", line 12, in ? import DFA File "D:\python24\lib\site-packages\Plex\DFA.py", line 9, in ? import Machines File "D:\python24\lib\site-packages\Plex\Machines.py", line 14, in ? from Transitions import TransitionMap File "D:\python24\lib\site-packages\Plex\Transitions.py", line 85 def get_epsilon(self, SyntaxError: Invalid syntax. Assignment to None. The corresponding source code : #file plex1.py from Plex import * lexicon = Lexicon([ (Str("Python"), "my_favourite_language"), (Str("Perl"), "the_other_language"), (Str("rocks"), "is_excellent"), (Str("sucks"), "is_differently_good"), (Rep1(Any(" \t\n")), IGNORE) ]) filename = "plex1.txt" f = open(filename, "r") scanner = Scanner(lexicon, f, filename) while 1: token = scanner.read() print token if token[0] is None: break The error was removed when I used the following code in Transitions.py def get_epsilon(self, none = None): """ Return the mapping for epsilon, or None. """ return self.special.get('', None) Regards, Srijit From steve at holdenweb.com Mon Jan 3 09:25:45 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Jan 2005 09:25:45 -0500 Subject: UserDict deprecated In-Reply-To: References: <1gpqh6l.65jemkskbo5eN%aleaxit@yahoo.com> Message-ID: Wolfgang wrote: > Hello, > > Alex Martelli wrote: > >> The DictMixin class from the UserDict module is *not* deprecated -- only >> the UserDict class from the same module. (If you found info saying >> otherwise pls provide a URL: the info is wrong and I'll try to get it >> fixed -- thanks!). DictMixin's purpose is exactly as you state: letting >> you make a complete mapping class out of one which only supplies the >> very basics, by mix-in inheritance. > > > If UserDict is deprecated why is it still used in the os module ? > (in python V. 2.4) > > The std lib should be a good example for python coding, if something > is deprecated it should not be used in the std lib. > > Some weeks ago I had ten minutes of spare time and rewrote the 'os' > module to use dict and there was no problem with it. > But due to lack of time I was not able to run tests and submitted no > patch. I will try this next week. > > bye by Wolfgang > Good for you! When you've fixed that up, you might want to take a look at cgi.py, dumbdbm.py, shelve.py and weakref.py as well ;-) regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From news at chaos-net.de Mon Jan 17 08:38:08 2005 From: news at chaos-net.de (Martin Kissner) Date: 17 Jan 2005 13:38:08 GMT Subject: [perl-python] 20050117, filter, map References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> Message-ID: Steven Bethard wrote : > Xah Lee wrote: >> ? Note: this post is from the Perl-Python >> ? a-day mailing list at >> ? http://groups.yahoo.com/group/perl-python/ > > Is there any chance you could post these all as part of the same thread? > That would be really nice for those of us who aren't interested -- > then we could just ignore the thread... I would appreciate that, too. But I fear this person doesn't even read the comments on his unwanted load. I guess I'll scorefile the "Subject" of these postings, too, to get rid of this. -- Epur Si Muove (Gallileo Gallilei) From tim.hochberg at ieee.org Tue Jan 4 12:10:30 2005 From: tim.hochberg at ieee.org (Tim Hochberg) Date: Tue, 04 Jan 2005 10:10:30 -0700 Subject: Pythonic search of list of dictionaries In-Reply-To: References: Message-ID: <41DACE06.7060501@ieee.org> Bulba! wrote: > Hello everyone, > > I'm reading the rows from a CSV file. csv.DictReader puts > those rows into dictionaries. > > The actual files contain old and new translations of software > strings. The dictionary containing the row data looks like this: > > o={'TermID':'4', 'English':'System Administration', > 'Polish':'Zarzadzanie systemem'} > > I put those dictionaries into the list: > > oldl=[x for x in orig] # where orig=csv.DictReader(ofile ... > > ..and then search for matching source terms in two loops: > > for o in oldl: > for n in newl: > if n['English'] == o['English']: > ... > > Now, this works. However, not only this is very un-Pythonic, but also > very inefficient: the complexity is O(n**2), so it scales up very > badly. > > What I want to know is if there is some elegant and efficient > way of doing this, i.e. finding all the dictionaries dx_1 ... dx_n, > contained in a list (or a dictionary) dy, where dx_i contains > a specific value. Or possibly just the first dx_1 dictionary. Sure, just do a little preprocessing. Something like (untested): #### def make_map(l): # This assumes that each English key is unique in a given l # if it's not you'll have to use a list of o instead of o itself. map = {} for d in l: if 'English' in d: key = d['English'] map[key] = d old_map = make_map(oldl) new_map = make_map(newl) for engphrase in old_map: if engphrase in new_map: o = old_map[engphrase] n = new_map[engphrase] if n['Polish'] == o['Polish']: status='' else: status='CHANGED' # process.... #### I've assumed that the English key is unique in both the old and new lists. If it's not this will need some adjustment. However, your original algorithm is going to behave weirdly in that case anyway (spitting out multiple lines with the same id, but potentially different new terms and update status). Hope that's useful. -tim > > I HAVE to search for values corresponding to key 'English', since > there are big gaps in both files (i.e. there's a lot of rows > in the old file that do not correspond to the rows in the new > file and vice versa). I don't want to do ugly things like converting > dictionary to a string so I could use string.find() method. > > Obviously it does not have to be implemented this way. If > data structures here could be designed in a proper > (Pythonesque ;-) way, great. > > I do realize that this resembles doing some operation on > matrixes. But I have never tried doing smth like this in > Python. > > > #---------- Code follows --------- > > import sys > import csv > > class excelpoldialect(csv.Dialect): > delimiter=';' > doublequote=True > lineterminator='\r\n' > quotechar='"' > quoting=0 > skipinitialspace=False > > epdialect=excelpoldialect() > csv.register_dialect('excelpol',epdialect) > > > try: > ofile=open(sys.argv[1],'rb') > except IOError: > print "Old file %s could not be opened" % (sys.argv[1]) > sys.exit(1) > > try: > tfile=open(sys.argv[2],'rb') > except IOError: > print "New file %s could not be opened" % (sys.argv[2]) > sys.exit(1) > > > titles=csv.reader(ofile, dialect='excelpol').next() > orig=csv.DictReader(ofile, titles, dialect='excelpol') > transl=csv.DictReader(tfile, titles, dialect='excelpol') > > cfile=open('cmpfile.csv','wb') > titles.append('New') > titles.append('RowChanged') > cm=csv.DictWriter(cfile,titles, dialect='excelpol') > cm.writerow(dict(zip(titles,titles))) > > > print titles > print "-------------" > > oldl=[x for x in orig] > newl=[x for x in transl] > > all=[] > > for o in oldl: > for n in newl: > if n['English'] == o['English']: > if n['Polish'] == o['Polish']: > status='' > else: > status='CHANGED' > combined={'TermID': o['TermID'], 'English': o['English'], > 'Polish': o['Polish'], 'New': n['Polish'], 'RowChanged': status} > cm.writerow(combined) > all.append(combined) > > > # duplicates > > dfile=open('dupes.csv','wb') > dupes=csv.DictWriter(dfile,titles,dialect='excelpol') > dupes.writerow(dict(zip(titles,titles))) > > """for i in xrange(0,len(all)-2): > for j in xrange(i+1, len(all)-1): > if (all[i]['English']==all[j]['English']) and > all[i]['RowChanged']=='CHANGED': > dupes.writerow(all[i]) > dupes.writerow(all[j])""" > > cfile.close() > ofile.close() > tfile.close() > dfile.close() > > > > > > > > > > > -- > > Real world is perfectly indifferent to lies that > are the foundation of leftist "thinking". From http Sat Jan 22 21:24:22 2005 From: http (Paul Rubin) Date: 22 Jan 2005 18:24:22 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> Message-ID: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> Brian van den Broek writes: > no Python expert, just a hobbyist. But, I think I can take this one on: > > Fredrik's contributed a lot to Python. The Standard Library book, > several well know tools, and, I'd wager a finger, a fair bit of code > in the standard lib. I don't think the community gives you a name like > F-bot, but that you know a wee bit about how Python is actually used, etc. If he understood how Python is actually used, he'd understand that any C module is a lot more useful in the core than out of it. His lecture to me about the crypto module was bizarre and inappropriate. The whole purpose of that module was to fix a deficiency of Python, namely the lack of a good crypto module in the core, that people could use without having to install any downloaded C modules. If it doesn't go into the core, the deficiency isn't fixed, so the module has failed in its purpose. There are already tons of 3rd party crypto modules outside the core, and the module I was writing wouldn't add anything useful to those. It only provided AES/DES and the basic FIPS modes, and was designed specifically to be suitable for the core where the other modules were considered too fancy. Also, Guido had expressed interest in having it, before changing heart because of the legal stuff. Where does Frederik get off lecturing me about wanting to get a module into the core, when Guido had invited me to do precisely that with that very module? Frederik has written some pretty good C modules himself, that are a pain in the neck to use because they're not in the core, which means that before they can be used they first have to be compiled and installed. If he wanted to maximize their usefulness, he'd be trying to get them into the core. I don't know what his goals are though. I did release a replacement for the rotor module that's written in Python, which means it's reasonably useable without being in the core. However, while its security should be ok, to provide reasonable performance it had to use a nonstandard algorithm and therefore isn't good for interoperating with anything. To be both acceptably fast and interoperable with other applications, a C module is needed. From rccharles at my-deja.com Sun Jan 30 13:34:35 2005 From: rccharles at my-deja.com (rccharles at my-deja.com) Date: 30 Jan 2005 10:34:35 -0800 Subject: installing tkiner In-Reply-To: References: Message-ID: <1107110075.318882.145770@f14g2000cwb.googlegroups.com> Robert wrote: > I am trying to use tkinter on macos 10.2.6. There is a documented restriction that you cannot run gui programs from the ide. re-installed TclTkAquaBI-8.4.6.1-Jaguar.dmg used the pythonw command. Robert From steve at holdenweb.com Thu Jan 13 09:16:40 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 13 Jan 2005 09:16:40 -0500 Subject: newbie q In-Reply-To: <34mku4F4c8bdkU1@individual.net> References: <34mgq0F4dq4buU1@individual.net> <34mku4F4c8bdkU1@individual.net> Message-ID: <41E682C8.9020804@holdenweb.com> Egor Bolonev wrote: > > "Stephen Thorne" ???????/???????? ? ???????? > ?????????: news:mailman.611.1105598828.22381.python-list at python.org... > On Thu, 13 Jan 2005 15:55:10 +1000, Egor Bolonev wrote: > >> how to get rid of 'for' operator in the code? >> >> import os, os.path >> >> def _test(): >> src = 'C:\\Documents and Settings\\????\\My Documents\\My Music\\' >> >> for i in [x for x in os.listdir(src) if >> os.path.isfile(os.path.join(src, >> x)) and len(x.split('.')) > 1 and x.split('.')[-1].lower() == 'm3u']: >> os.remove(os.path.join(src, i)) >> >> if __name__ == '__main__': >> _test() > > > import glob > for x in glob.glob("*.m3u"): > os.remove(x) > > i want to wipe out 'for x in []: f(x)' using map, lambda, reduce, filter > and List > Comprehensions [x for x in []] > just don't get how to add string to all elements of list > Any statement of the form for i in [x for x in something]: can be rewritten as for i in something: Note that this doesn't mean you never want to iterate over a list comprehension. It's the easiest way, for example, to iterate over the first item of each list in a list of lists: for i in [x[0] for x in something]: regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From tim.peters at gmail.com Sun Jan 23 19:22:05 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 23 Jan 2005 19:22:05 -0500 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <200501232255.08496.francis.girard@free.fr> References: <63b5e209.0501210558.686f5c10@posting.google.com> <200501221106.49241.francis.girard@free.fr> <200501232255.08496.francis.girard@free.fr> Message-ID: <1f7befae050123162254e86fc@mail.gmail.com> [Francis Girard] > ... > In the meantime, I couldn't resist to test the new Python features about > laziness on a classical FP problem, i.e. the "Hamming" problem. ... > Nevertheless, while the Haskell version prints Hamming sequence for as long as > I can stand it, and with very little memory consumation, the Python version > only prints : ... > I think I should not have this kind of behaviour, even using recursion, since > I'm only using lazy constructs all the time. At least, I would expect the > program to produce much more results before surrending. > > What's going on ? You can find an explanation in Lib/test/test_generators.py, which uses this problem as an example; you can also find one efficient way to write it there. From invalidemail at aerojockey.com Sun Jan 9 02:35:29 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 8 Jan 2005 23:35:29 -0800 Subject: python3: accessing the result of 'if' In-Reply-To: <41e0c9cf$1_2@127.0.0.1> References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> <1105236383.521393.40680@c13g2000cwb.googlegroups.com> <41e0c9cf$1_2@127.0.0.1> Message-ID: <1105256129.604415.122030@c13g2000cwb.googlegroups.com> Donn Cave wrote: > If Python 3 is going to get assignment-as-expression, it will be > because GvR accepts that as a reasonable idea. You won't bootleg it > in by trying to hide it behind this "where" notion, and you're not > doing "where" any good in trying to twist it this way either. I suspect you misunderstood me. When proposed this: . if m > 20 where m=something(): . use(m) the "where m=something()" part is NOT part of the if-expression. It is an optional part of the if-statement. A very poor excuse for a BNF grammar of the if-statment would look like this: . "if" expr [ "where" symbol "=" expr ] suite ... In no way, shape, or form did I ever intend for something like this to be possible: . x = (m > 20 where m=something()) Besides, if I had intended it to be an alternately-spelled assignment expression, then it wouldn't have worked as I stated. I wanted the thing being bound to be visible inside the if-expression and the if-block, and to do that it must have the cooperation of the if-block, and therefore must be part of the if-statement. If this were an assigment expression, then m would have to be either be visible within the whole surrounding scope, or just within that expression. What I proposed was really nothing more than a convenient way to sneak an extra binding inside an elif clause. (The real point here is not to use this on if-clauses, but on elif-clauses.) -- CARL BANKS From jeff at ccvcorp.com Thu Jan 6 21:16:22 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 06 Jan 2005 18:16:22 -0800 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> <1gpwrh7.b7z8qtablx7gN%aleaxit@yahoo.com> <41DD4E62.1020404@holdenweb.com> <10tr15fabtpnf97@corp.supernews.com> Message-ID: <10trrv7sum7eoe8@corp.supernews.com> Bulba! wrote: > .... And note that it > was definitely not in his personal interest, whoever that > was, a person or group of persons, as he/they risked getting > fired for that. This doesn't necessarily follow. The decision-maker in question may have received a fat bonus for having found such a technically excellent manufacturing process, and then moved into a different position (or left the corporation altogether) before construction was complete and the power-cost issue was noticed. That person may even have *known* about the power-cost issue, and forged ahead anyhow due to the likelihood of such a personal bonus, with the intention of no longer being in a bag-holding position once the problem became general knowledge. Of course, this discussion highlights the biggest problem with economics, or with any of the other "social sciences" -- there's simply too many open variables to consider. One can't control for all of them in experiments (what few experiments are practical in social sciences, anyhow), and they make any anecdotal evidence hazy enough to be suspect. Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Wed Jan 19 20:55:30 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 19 Jan 2005 17:55:30 -0800 Subject: Zen of Python In-Reply-To: References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> Message-ID: <10uu3iphdr23mf4@corp.supernews.com> Timothy Fitz wrote: > On 19 Jan 2005 15:24:10 -0800, Carl Banks wrote: > >>The gist of "Flat is better than nested" is "be as nested as you have >>to be, no more," because being too nested is just a mess. > > Which I agree with, and which makes sense. However your "gist" is a > different meaning. It's not that "Flat is better than nested" it's > that "Too flat is bad and too flat is nested so be as nested (or as > flat) as you have to be and no more." Perhaps Tim Peters is far too > concise for my feeble mind Well, the way that the Zen is phrased, it implies a bit more than that. We all agree that there's a balance to be found between "completely flat" and "extremely nested"; the specific phrasing of the Zen conveys that (in the Python philosophy at least) the appropriate balance point is much closer to the "completely flat" side of things. It's not "... as nested (or as flat) as you have to be and no more", it's "... as nested as you have to be and no more, but if you need significant nesting, you might want to re-examine your design". ;) Jeff Shannon Technician/Programmer Credit International From aleaxit at yahoo.com Thu Jan 6 12:05:10 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 6 Jan 2005 18:05:10 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> Message-ID: <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> Roel Schroeven wrote: ... > >>Can you point to closed-source licenses that allow using the code *at > >>all*? ... > > Is this what you mean by "allow using the code *at all*"? I think it's > > a pretty common arrangement when the code being sold under closed-source > > terms is a set of libraries, or a development system part of whose value > > is a set of accompanying libraries. > > OK, I've been bitten by my exageration. There are indeed special cases > such as some libraries. > > I was thinking more of end-user packages: if you somehow could lay your > hands on the source code of Visual Studio itself, you're still not > allowed to do anything with it. Yes, apart from libraries and similar cases (frameworks etc), it's no doubt rare for closed-source "end-user packages" to be sold with licenses that include source and allow you to "do anything with it". However, allowing customization (at least for internal use within the customer organization), while rare, is far from unheard of. I used to work for a software house which sold rich and complex packages of software meant for 3D mechanical design. The packages came with tens of thousands of lines of (closed-source) code, in a proprietary scripting language implemented by the package itself, which users (typically mechanical engineers) were _expected_ to tweak to customize the overall product for their specific purposes -- such modified parts of the "scripting source" of the overall product were routinely shared among different customers, and occasionally sold from one to another. The choice of which parts of code in the scripting language were made thus customizable and sharable was quite deliberate: the application contained much more code in that scripting language, but most of it was only distributed in compiled form (or even with the compiled form already turned into data in some library or executable) -- the parts that were sold as sources were picked to be those which would be most useful for customers to customize and share, yet not damage the business model of the software house. (and yes, it WAS closed source software, anyway -- customers were theoretically not permitted to give our source or derived works thereof to others who _weren't_ customers, I think; anyway the engine needed to run the scripts was not redistributable, so that provisions, if there, was of modest value). I wouldn't be surprised if such a mixed model was reasonably common among "end-user packages" which include a substantial proprietary scripting component, particularly if the end-users are expected to be technically skilled (mechanical engineers aren't programmers, but they will probably have some vague clue about it; a consumer product might be different). Just a guess, but, wouldn't, say, Mathematica or some similar closed-source product benefit from this kind of arrangement -- including, as part of the product being sold, some rich amount of scripting code, freely customizable and sharable among customers (perhaps with the license prohibiting giving it away to non-customers)? I believe some (closed-source) games, including ones which use Python as their scripting language, may also do something of the kind -- include Python sources for "scenarios" with full license to tweak and redistribute (making new scenarios which are derived works of ones sold by the games' authors). Here the language is not proprietary but no doubt the scripts use large amounts of calls to proprietary modules, so again there is no damage to the game author's business model anyway. Hmmm, come to think of it, doesn't Apple include very large amount of working Applescript code with many of its closed-source applications? So, although your general point is no doubt sound, almost by definition of closed source, you may perhaps still need to tweak it further, beyond libraries and frameworks, to also exclude that closed source with is a "scripting", "configuration", or otherwise "ancillary" part of the application. One last reflection -- I believe there are or used to be some programs written by people no doubt of very good will, distributed with all sources and often with no profit motive at all, which are NOT open source because they include in the license some restrictive clause, such as "no military use", "no use by organizations which perform testing of cosmetics on animals", or something of that kind. These would be examples of closed-source software which DO allow ALMOST any kind of use -- any EXCEPT the specific one the authors dislike so intensely. While most people may not think of such programs as "closed source", they most definitely ARE: the definition of open source is very strict about this aspect. Alex From sjmachin at lexicon.net Wed Jan 26 18:59:35 2005 From: sjmachin at lexicon.net (John Machin) Date: 26 Jan 2005 15:59:35 -0800 Subject: Browsing text ; Python the right tool? In-Reply-To: <10vfqra5knegoa3@corp.supernews.com> References: <10vdpohm549g44a@corp.supernews.com> <1106707324.874852.208520@z14g2000cwz.googlegroups.com> <10vfqra5knegoa3@corp.supernews.com> Message-ID: <1106783975.472873.21420@z14g2000cwz.googlegroups.com> Jeff Shannon wrote: > John Machin wrote: > > > Jeff Shannon wrote: > > > >> [...] If each record is CRLF terminated, then > >>you can get one record at a time simply by iterating over the file > >>("for line in open('myfile.dat'): ..."). You can have a dictionary > >>classes or factory functions, one for each record type, keyed off > >>of the 2-character identifier. Each class/factory would know the > >>layout of that record type, > > > > This is plausible only under the condition that Santa Claus is paying > > you $X per class/factory or per line of code, or you are so speed-crazy > > that you are machine-generating C code for the factories. > > I think that's overly pessimistic. I *was* presuming a case where the > number of record types was fairly small, and the definitions of those > records reasonably constant. For ~10 or fewer types whose spec > doesn't change, hand-coding the conversion would probably be quicker > and/or more straightforward than writing a spec-parser as you suggest. I didn't suggest writing a "spec-parser". No (mechanical) parsing is involved. The specs that I'm used to dealing with set out the record layouts in a tabular fashion. The only hassle is extracting that from a MSWord document or a PDF. > > If, on the other hand, there are many record types, and/or those > record types are subject to changes in specification, then yes, it'd > be better to parse the specs from some sort of data file. "Parse"? No parsing, and not much code at all: The routine to "load" (not "parse") the layout from the layout.csv file into dicts of dicts is only 35 lines of Python code. The routine to take an input line and serve up an object instance is about the same. It does more than the OP's browsing requirement already. The routine to take an object and serve up a correctly formatted output line is only 50 lines of which 1/4 is comment or blank. > > The O.P. didn't mention anything either way about how dynamic the > record specs are, nor the number of record types expected. My reasoning: He did mention A0 and C1 hence one could guess from that he maybe had 6 at least. Also, files used to "create printed pages by an external company" (especially by a company that had "leaseplan" in its e-mail address) would indicate "many" and "complicated" to me. > I suspect > that we're both assuming a case similar to our own personal > experiences, which are different enough to lead to different preferred > solutions. ;) Indeed. You seem to have lead a charmed life; may the wizards and the rangers ever continue to protect you from the dark riders! :-) My personal experiences and attitudes: (1) extreme aversion to having to type (correctly) lots of numbers (column positions and lengths), and to having to mentally translate start = 663, len = 13 to [662:675] or having ugliness like [663-1:663+13-1] (2) cases like 17 record types and 112 fields in one file, 8 record types and 86 fields in a second -- this being a new relatively clean simple exercise in exchanging files with a government department (3) Past history of this govt dept is that there are at least another 7 file types in regular use and they change the _major_ version number of each file type about once a year on average (3) These things tend to start out deceptively small and simple and turn into monsters. Cheers, John From carribeiro at gmail.com Mon Jan 24 21:19:07 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Tue, 25 Jan 2005 00:19:07 -0200 Subject: pylibpcap and multiple threads In-Reply-To: References: Message-ID: <864d3709050124181928c9046a@mail.gmail.com> On Mon, 24 Jan 2005 15:18:39 +0100, ?rjan Gustavsson wrote: > Hi All! > > Sorry if this is not the correct forum for this kind of question (I did > not find any pylibpcap related lists). > > I am trying to use pylibpcap to capture network traffic from several > ethernet devices at the same time, each nic having a separate thread > assigned to it. > > My problem is that when one thread is blocking inside pcap.loop() for > instance, it seems to have acquired the GIL, so that no other threads > can run. > > Does anyone know a way to do this with threads, or is the only way to > have separate processes for each NIC? >From the top of my head, and without any test. I did use libpcap for some stuff recently. loop() is the primitive that keeps reading and calls the callback, right? I believe that it should release the GIL in the C wrapper code, right before calling the libpcap loop implementation, and re-acquire it before calling the callback. There is a standard way to do it, that is used before blocking calls are issued (file writing, for example). If it fails to release the GIL it will block. I'm also not sure if the libpcap itself is supposed to be used this way - with multiple instances - but I assume that it should work (I never tried to open several instances of tcpdump at the same time). Also, check these links also, as they may be helpful to you: http://libdnet.sourceforge.net/ http://oss.coresecurity.com/projects/pcapy.html -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From nathan_kent_bullock at yahoo.ca Mon Jan 24 23:39:11 2005 From: nathan_kent_bullock at yahoo.ca (nathan_kent_bullock at yahoo.ca) Date: 24 Jan 2005 20:39:11 -0800 Subject: Retrieving modification time of file class was declared in Message-ID: <1106627951.152900.135310@z14g2000cwz.googlegroups.com> Assume I am using a class Foo. I want to find out the modification time of the file that that class was defined in. How would I go about this? If I could find out the name of the file that Foo was defined in then it is easy, I could use os.path.getmtime(), but I can't even figure that out. I realize that this wouldn't be a completely accurate way to tell the last time this class was modified because it could inherit info from other classes, or use functions from other modules that have been modified, etc. Nathan Bullock From fredrik at pythonware.com Sat Jan 22 16:56:42 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 22:56:42 +0100 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> <41F2C840.2050304@comcast.net> Message-ID: Stephen Waterbury wrote: > The premise that XML had a coherent design intent > stetches my credulity beyond its elastic limit. the design goals are listed in section 1.1 of the specification. see tim bray's annotated spec for additional comments by one of the team members: http://www.xml.com/axml/testaxml.htm (make sure to click on all (H)'s and (U)'s in that section for the full story). if you think that the XML 1.0 team didn't know what they were doing, you're seriously mistaken. it's the post-1.0 standards that are problematic... From Scott.Daniels at Acm.Org Tue Jan 11 13:21:14 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 11 Jan 2005 10:21:14 -0800 Subject: Python & unicode In-Reply-To: References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> Message-ID: <41e41633$1@nntp0.pdx.net> P at draigBrady.com wrote: > Because the coding is only supported in string literals. > But I'm not sure exactly why. The why is the same as why we write in English on this newsgroup. Not because English is better, but because that leaves a single language for everyone to use to communicate in. If you allow non-ASCII characters in symbol names, your source code will be unviewable (and uneditable) for people with ASCII-only terminals, never mind how comprehensible it might otherwise be. It is a least-common-denominator argument, not a "this is better" argument. -Scott David Daniels Scott.Daniels at Acm.Org From http Wed Jan 5 10:40:13 2005 From: http (Paul Rubin) Date: 05 Jan 2005 07:40:13 -0800 Subject: is python more popular than coldfusion? References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <1104933800.156835.91350@f14g2000cwb.googlegroups.com> <1104939157.658341.125310@f14g2000cwb.googlegroups.com> Message-ID: <7xk6qrhoki.fsf@ruckus.brouhaha.com> beliavsky at aol.com writes: > But Python IS tied for first. This may indicate that the > relatively small number of jobs listing Python as a requirement is due > in part to a relatively small supply of Python programmers, not lack of > demand for such programmers. I think it mostly means Python programmers tend to be further up the overall experience and proficiency scale than, say, .NET programmers. From rm at rm.net Sun Jan 23 11:46:24 2005 From: rm at rm.net (rm) Date: Sun, 23 Jan 2005 17:46:24 +0100 Subject: What YAML engine do you use? In-Reply-To: <35csm7F4l57inU1@individual.net> References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> Message-ID: <35i2qpF4nd7g0U1@individual.net> rm wrote: > Paul Rubin wrote: > >> Reinhold Birkenfeld writes: >> >>> For those of you who don't know what YAML is: visit http://yaml.org/! >>> You will be amazed, and never think of XML again. Well, almost. >> >> >> >> Oh please no, not another one of these. We really really don't need it. > > > well, I did look at it, and as a text format is more readable than XML > is. Furthermore, XML's verbosity is incredible. This format is not. > People are abusing the genericity of XML to put everything into it. > > Parsing and working with XML are highly optimized, so there's not really > a problem in that sector. But to transfer the same data in a YAML > format, rather than a XML format is much more economic. But networks are > getting faster, right? > > Nowadays, people are trying to create binary XML, XML databases, > graphics in XML (btw, I'm quite impressed by SVG), you have XSLT, you > have XSL-FO, ... . > > And I think, YAML is a nice initiative. > > bye, > rm http://www.theinquirer.net/?article=20868 :-) rm From tim.peters at gmail.com Mon Jan 17 16:05:04 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 17 Jan 2005 16:05:04 -0500 Subject: Py_Object* Py_BuildValue, Py_INCREF necessary? In-Reply-To: References: Message-ID: <1f7befae050117130523c8cb@mail.gmail.com> [Torsten Mohr] > when i write an extension module in C and return a Py_Object* > that i've built with Py_BuildValue, do i need to use Py_INCREF > on that before i return it to python from my extension module > or not? The docs for Py_BuildValue() say it returns a new reference (and it does). So the caller owns the reference, and is responsible for either passing its reference on to someone else, or for giving up its reference (via Py_DECREF). If you pass the result on to your extension module's caller, then you're also transferring ownership of the reference to your extension module's caller (and should not do Py_INCREF -- which would create yet another reference). From ajsiegel at optonline.net Thu Jan 27 12:36:45 2005 From: ajsiegel at optonline.net (ajsiegel at optonline.net) Date: Thu, 27 Jan 2005 12:36:45 -0500 Subject: Another scripting language implemented into Python itself? Message-ID: <13c0ffb13bc230.13bc23013c0ffb@optonline.net> Cameron writes: >Pronouns quickly overload me. On a reread of my post, me, we and they and I all sympathize. >f you're saying that there's hysteria >afoot, much of it about the harm that might come through use of >computers left unprotected from evildoers, well, yes, I'm with you. >Most people have far more important hazards in their lives and work >than "security violations" as we technologists generally conceive them. That is what I am saying, admitted not very well. As it happens, though, I don't particularly finger the technologists as the culprits. Strangely, much of it can be traced to the fallout of Enron, though of course Enron had nothing to do with this realm of evil in any way. Most particularly ironic is the fact that is the same strata of the business community (broadly speaking I am part of that community) that bears a good deal of responsibility for Enron that has jumped on the opportunity to cash in on its fallout. Lovely. Art From ncoghlan at iinet.net.au Fri Jan 14 07:05:08 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 14 Jan 2005 22:05:08 +1000 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: <41E77176.9070002@iinet.net.au> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> <41e6dc9b.771173178@news.oz.net> <41E77176.9070002@iinet.net.au> Message-ID: <41E7B574.90301@iinet.net.au> Nick Coghlan wrote: > as equivalent to: > > def __use_stmt(): > > def _in_clause(): > > return > return _in_clause() > __use_stmt_args = {} > = __use_stmt() > del __use_stmt > The more I think about this return-based approach, the less I like it. It could probably be made to work, but it just feels like a kludge to work around the fact that the only mechanisms available for altering the bindings of local names are assignment and definition statements. For class namespaces, getattr(), setattr() and delattr() work a treat, and globals() works fine for module level name binding. locals() is an unfortunate second class citizen, since it writes to it aren't propagated back to the executing frame. Programmatic interrogation of locals is fine, but update is impossible. What would be interesting is if locals() returned a dictionary whose __setitem__ method invoked PyFrame_LocalsToFast on the relevant frame, instead of a vanilla dictionary as it does now. Then locals()["x"] = foo would actually work properly. Notice that you can get this effect today, by using exec to force invocation of PyFrame_LocalsToFast: Py> def f(): ... n = 1 ... def g(outer=locals()): ... outer["n"] += 1 ... g() # Does not affect n ... print n ... exec "g()" # DOES affect n ... print n ... Py> f() 1 2 (The call to g() has to be inside the exec statement, since the exec statement evaluation starts with a call to PyFrame_FastToLocals). Assuming a writeable locals(), the semantics for the normal case are given by: ============ def __use_stmt(__outer): __inner = locals() for name in : __outer[name] = __inner[name] __use_stmt(locals()) del __use_stmt ============ And for the 'delayed execution' case: ============ def __named_use_stmt(__outer): def __delayed_block(): __inner = locals() for name in : __outer[name] = __inner[name] return __delayed_block = __named_use_stmt(locals()) del __named_use_stmt ============ Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From shoot at the.moon Sat Jan 8 08:34:41 2005 From: shoot at the.moon (Steve Horsley) Date: Sat, 08 Jan 2005 13:34:41 +0000 Subject: The limitation of the Photon Hypothesis In-Reply-To: References: Message-ID: bill wrote: > Please reply to hdgbyi at public.guangzhou.gd.cn, thank you ! No - I'll reply to the newsgroup, if you don't mind. > The limitation of the Photon Hypothesis > THE UNCERTAINTY PRINCIPLE IS UNTENABLE You cannot use classical theory to disprove quantum theory that easily. The uncertainty is quantum in origin, and not just an artifact of classical mechanics applied to clumsy measurement. You don't convince me. Also, I think you probably accidentally posted to the wrong newsgroup. Steve From tom at dtsam.com Tue Jan 18 17:02:04 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Tue, 18 Jan 2005 16:02:04 -0600 Subject: simultaneous multiple requests to very simple database References: Message-ID: "Eric S. Johansson" wrote in message news:mailman.859.1106065617.22381.python-list at python.org... > at this point, I know they will be some kind souls suggesting various > SQL solutions. While I appreciate the idea, unfortunately I do not have > time to puzzle out yet another component. Someday I will figure it out > because I really liked what I see with SQL lite but unfortunately, today > is not that day (unless they will give me their work, home and cell > phone numbers so I can call when I am stuck. ;-) Forgive me if this reply sounds a bit glib. But I do mean it without malice. Do you seriously expect to write your own (database) solution and that this will save you time and effort over learning an existing (SQL) solution? Because - If you are seeking to "save time" on "puzzles", you are certainly going about it the wrong way. Best of luck Thomas Bartkus From frans.englich at telia.com Mon Jan 17 16:00:14 2005 From: frans.englich at telia.com (Frans Englich) Date: Mon, 17 Jan 2005 21:00:14 +0000 Subject: Assigning to self In-Reply-To: <200501172055.33962.frans.englich@telia.com> References: <200501172055.33962.frans.englich@telia.com> Message-ID: <200501172100.14111.frans.englich@telia.com> On Monday 17 January 2005 20:55, Frans Englich wrote: > On Monday 17 January 2005 19:02, Peter Otten wrote: > > Frans Englich wrote: > > > What the code attempts to do is implementing a, to the API user, > > > transparent memory-saver by ensuring that no more than one instance of > > > the class foo exists for a particular id. E.g, the user can simply > > > "create" an instance and if one not already exists, it is created. > > > > By the time __init__() is called, a new Foo instance has already been > > > > created. Therefore you need to implement Foo.__new__(). E. g.: > > >>> class Foo(object): > > > > ... cache = {} > > ... def __new__(cls, id): > > ... try: > > ... return cls.cache[id] > > ... except KeyError: > > ... pass > > ... cls.cache[id] = result = object.__new__(cls, id) > > ... return result > > ... def __init__(self, id): > > ... self.id = id > > ... def __repr__(self): > > ... return "Foo(id=%r)" % self.id > > ... > > I'm not sure, but I think this code misses one thing: that __init__ is > called each time __new__ returns it, as per the docs Peter posted. Ahem, John I ment :) The second typo today.. Cheers, Frans From kartic.krishnamurthy at gmail.com Wed Jan 5 18:39:42 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 5 Jan 2005 15:39:42 -0800 Subject: Another PythonWin Excel question In-Reply-To: References: Message-ID: <1104968382.403653.267060@f14g2000cwb.googlegroups.com> I am not sure about this but I believe you can give a parameter after="sheet1". to Add(), like so, Add(after="sheet1"). Unfortunately I do not have Excel installed on this machine to confirm this. A tip: if you have VBA (which you should if you have Excel) installed, lookup the Add method for the Worksheets collection. VBA will show the code completion, with all the arguments for the method call. Try the same for any of the methods. Thanks, --Kartic From apardon at forel.vub.ac.be Thu Jan 13 02:47:46 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jan 2005 07:47:46 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: Op 2005-01-12, It's me schreef : > Precisely. One have to convert complex number into vectors, and vector of > complex numbers into vector of vectors, list of complex numbers into list of > vectors, ...., you get the idea. Wrong. My vector example was an illustration that you can build a user class that behaves as you want. Python doesn't has a vecor class build in. Yet I could write a vector class that behaved as you wished with regard to your twice function. What can be done for a vector class can be done again for a complex class, no need to use the vector class for complex numbers. > And my code no longer look like the equation I have on paper... > > Like I said, I've travelled down that path before with C++ and Modelica. > It gets ugly. Ugly, where? In the implementation of the class? That is possible. In the use of the class, as you suggest by writing that your code no longer looks like the equation you have on paper. In that case I suggest the class was poorly done. -- Antoon Pardon From alan.gauld at btinternet.com Fri Jan 7 03:55:19 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Jan 2005 08:55:19 +0000 (UTC) Subject: Securing a future for anonymous functions in Python References: Message-ID: On Thu, 06 Jan 2005 21:02:46 -0600, Doug Holton wrote: > used, but there are people who do not like "lambda": > http://lambda-the-ultimate.org/node/view/419#comment-3069 > The word "lambda" is meaningless to most people. Of course so is "def", > which might be why Guido van Robot changed it to "define": > http://gvr.sourceforge.net/screen_shots/ The unfamiliar argument doesn't work for me. After all most people are unfamiliar with complex numbers (or imaginary) numbers but python still provides a complex number type. Just because the name is unfamiliar to some doesn't mean we shouldn't use the term if its the correct one for the concept. Hopefully anyone who wants to use anonymous functions will know that such are called lambdas and hopefully will have studied lambda calculus to at least some level - certainly CS majors and software engineering types should have... > Python is easier for beginners to learn than other mainstream > programming languages Absolutely, but it has to decide (and soon I think) how important that role is in the development of the language. Many of the more recent features are beginner hostile - slots, properties, meta classes, decorators etc... So is Python going to consciously try to remain beginner friendly (which it remains by simply ignoring the newer fatures!) or deliberately go for the "fully featured" general purpose audience? > Yes, I agree, and either keep the "lambda" keyword or else reuse the > "def" keyword for anonymous methods. See this page Steven Bethard > created: http://www.python.org/moin/AlternateLambdaSyntax I agree, I'm much more concerned about the idea of losing anonymous functions (aka lambdas) than about losing the name lambda, its just that the name is so descriptive of what it does! ( In fact it was seeing the name lambda appearing in a Lisp programme I was reading that got me started in Lambda calculus many years ago...) > By the way, you've done great work with your learning to program site > and all the help you've given on the python-tutor list: Aw shucks! Thanks ;-) Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From merman at snafu.de Thu Jan 27 16:24:13 2005 From: merman at snafu.de (merman) Date: Thu, 27 Jan 2005 22:24:13 +0100 Subject: Mac OS and MySQLdb Message-ID: <41f95b17$0$3331$9b622d9e@news.freenet.de> Hi there, is there a MySQLdb-Version for the latest Mac OS (or can I use the Linux-tarball)? I'm a Mac-Newbie. Thanks. o-o Thomas From yaipa at yahoo.com Wed Jan 19 16:12:52 2005 From: yaipa at yahoo.com (yaipa) Date: 19 Jan 2005 13:12:52 -0800 Subject: finding/replacing a long binary pattern in a .bin file In-Reply-To: References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> <3e8ca5c80501122251483f4b8f@mail.gmail.com> Message-ID: <1106169172.214523.33520@z14g2000cwz.googlegroups.com> Thanks Francois, It worked as expected. ------------------------------------------------------------------------------- source_data = open("source_data.bin", 'rb').read() search_data = open("search_data.bin", 'rb').read() replace_data = open("replace_data.bin", 'rb').read() outFile = open("mod.bin", 'wb') file_offset = source_data.find(search_data) print "file_offset:", file_offset outData = source_data.replace(search_data, replace_data) outFile.write(outData) outFile.close print "" From bokr at oz.net Wed Jan 26 02:15:04 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 26 Jan 2005 07:15:04 GMT Subject: delay and force in Python References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> <41EE6658.8000409@iinet.net.au> Message-ID: <41f73df2.1844608046@news.oz.net> On Tue, 25 Jan 2005 23:53:26 +1000, Nick Coghlan wrote: >Peter Otten wrote: >> Nick Coghlan wrote: >> >> >>>>Py> print islice((x for x in xrange(1, 996) if x % 2 == 0), 1, 2).next() >>>>4 >>> >>>Wouldn't it be nice if this could be spelt: >>> >>>print (x for x in xrange(1, 996) if x % 2 == 0)[2] >>> >>>Well, I just put a patch on SF to enable exactly that: >>>http://www.python.org/sf/1108272 >> >> >> I like it. Of course you always have to bear in mind that one giant leap for >> a list could be _many_ small steps for an iterator. > >Indeed. The main cases I am thinking of involve picking off the first few items >of an iterator (either to use them, or to throw them away before using the rest). > >And if an app actually *needs* random access, there's a reason lists still exist ;) > You can bail out of a generator expression with a raise-StopIteration expression spelled iter([]).next() ;-) >>> def show(x): print x,; return x ... >>> list(show(x) for x in xrange(20) if x<8 or iter([]).next()) 0 1 2 3 4 5 6 7 [0, 1, 2, 3, 4, 5, 6, 7] Well, since >>> list(show(x) for x in xrange(20) if x<8) 0 1 2 3 4 5 6 7 [0, 1, 2, 3, 4, 5, 6, 7] this change due to adding iter([]).next() might be more convincing: >>> list(show(x) for x in xrange(20) if x<8 or True) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] >>> list(show(x) for x in xrange(20) if x<8 or iter([]).next() or True) 0 1 2 3 4 5 6 7 [0, 1, 2, 3, 4, 5, 6, 7] Applied to example, >>> print list(x for i,x in enumerate(x for x in xrange(1, 996) if x % 2 ==0) if i<3 or iter([]).next())[2] 6 or in case you just want one item as result, >>> print list(x for i,x in enumerate(x for x in xrange(1, 996) if x % 2 ==0) if i==2 or i==3 and iter([]).next())[0] 6 Regards, Bengt Richter From fu.limin.tao at gmail.com Thu Jan 27 16:54:53 2005 From: fu.limin.tao at gmail.com (Limin Fu) Date: Thu, 27 Jan 2005 22:54:53 +0100 Subject: ANN: Tao Scripting Language 0.8.5 beta released! In-Reply-To: References: Message-ID: > Since you chose to announce it in this mailing list/newsgroup, may I > suggest that a comparison with Python is in order? > To make a reasonable comparison with Python, I need to spend more time to investigate into python, since so far I only know some basic things in Python :-). But I can ensure that Tao is very different from Python, and it will be more different in the future. > Since it is a new scripting language, I'm not suggesting a language war, > but rather a simple statement of how Tao differs from Python, and what > "itch" you were trying to scratch when you designed your new language. Well, I started to design this language, because I work on bioinformatics and I hardly found any language that really satisfied me. I found that, a language with simple syntax, convenient text processing functionality, powerful numeric computation capability, and simple C/C++ interfaces would be very useful in this field. Perl is got out immediately due to its complicated syntax and many possible traps(though there are still many people using it in this field, I think it is due to historical reasons). Though Python is great in many aspects, its syntax is also something I don't really like, and I think its interface to C/C++ is not simple enough. R language is not well designed according to me, though it's more popularly used in bioinformatic than Python. So I decided to design a new language. Though that goal is not reached yet, it is not unreachable either. > Basically, how does your design philosophy differ from that of Guido? I think I agree much of the design philosophy of Guido. But it is just a kind of guide line, it doesn't imply anything about the structure of the language and the interpreter. So the same philosophy can come out completely different language. > Where did you go left when Python went right? I will only point out a few such places. 1. Tao use uniform parenthesis symbol for both list/array and hash/dictionary, that is []. While in Python, [] is used for list, and {} is used for dictionary. 2. In Tao, there is no "self" argument in class methods as in Python. And the class syntax of Tao is more similar to that of C++. 3. Some Matlab features regarding numeric types, multi returned values in functions and multi assignment etc. are integrated into Tao. 4. Tao provides a very convenient way of declaring array/list which, to the best of my knowledge, is not presented in any other language. That is, a=[10][5] : value/arith/function; which will create a 10x5 array with elements resulted from evaluation of the right side of ":". Best regards, Limin -- Homepage for Tao Language: http://taoscript.sourceforge.net Tao Language project at sourceforge.net: http://sourceforge.net/projects/taoscript From Scott.Daniels at Acm.Org Tue Jan 4 14:28:37 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 04 Jan 2005 11:28:37 -0800 Subject: Python design strategy (was Python evolution: Unease) In-Reply-To: References: Message-ID: <41daebb0$1@nntp0.pdx.net> ajsiegel at optonline.net wrote: > Viile writes - > >>Type declarations are a feature that might benefit IronPython and >>Jython more than they would CPython. > > How much is this part of Guido's decisionmaking process? One major reason to allow optional static typing is to aid specializing compilers. A language called "Self" had a type system even more dynamic than Python's, and it was capable of getting to quite reasonable speeds doing dynamic analysis and specialization. In fact, PyPy is quite likely to get great optimization from the declarations as well as IronPython and JPython. If for some reason you know the arguments to a function are all integers, you can create a translation of that function that only operates on integers, and you can often discover that operations not only on the arguments, but on partial results, can all be kept as integers. These operations can be translated into very simple operations that avoid method lookup, and can therefore run much faster. If, conceptually, some set of functions and methods always are called with specific types, those functions and methods can have very high-speed (relatively) implementations for fairly little cost in compiler complexity. Such specifications could be spread through the standard library (if only in the most obvious of places), and provide a _very_ _substantial_ speed improvement for less investment than almost any of the other techniques around. Remember, at the core, all current CPUs operate on one or two data types: integers and floating point. Wherever they must distinguish types they must use conditional branches, the slowest operation on the fastest CPUs being produced today and in the relatively visible future. Even when the type specification is advice about the most common type path, rather than a strict guarantee of the type, code can be generated that does the test before choosing which path to choose, and have fast code on the type-specific path. --Scott David Daniels Scott.Daniels at Acm.Org From deetsNOSPAM at web.de Sat Jan 1 10:19:30 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 01 Jan 2005 16:19:30 +0100 Subject: what is lambda used for in real code? References: Message-ID: > Why not improve your metaclass wrapping so it knows about properties and > replaces them with properties containing wrapped functions? Erg - never thought of that, actually - it was so fast to introduce the lambda... But after some tinkering with metaclasses, I think it can be done - I have to create a mapping between the pure, unwrapped function and the wrapped one so that I can recreate all properties. Thanks for nudging me in that direction :) -- Regards, Diez B. Roggisch From aleaxit at yahoo.com Mon Jan 31 07:16:38 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 31 Jan 2005 13:16:38 +0100 Subject: Nested scopes and class variables References: Message-ID: <1gr97zk.1nm8ijn3art4cN%aleaxit@yahoo.com> Dave Benjamin wrote: > I ran into an odd little edge case while experimenting with functions that > create classes on the fly (don't ask me why): "Why not?". But classes have little to do with it, in my view. > >>> def f(x): > ... class C(object): > ... x = x You bind x, so x is local (to the class), not free. Videat, classless: >>> def f(x): ... def g(): ... x=x ... return x ... return g ... >>> z=f(23) >>> z() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in g UnboundLocalError: local variable 'x' referenced before assignment In this example the error is discovered when the body of g executes; in your case, the body of C executes as part of the class statement, i.e. when f is called, so the error is discovered earlier. > "x" clearly is defined, but apparently Python is not looking at the nested > variable scope to find it. What's stranger is that if I rename the parameter > "x" to "y", the error goes away: Why is this strange? There's no name conflict then. > So, it's not like nested scopes aren't supported in the class block. Rather, > when it sees "x = x", it seems like Python is determining at that point that > "x" is a class variable, and refuses to search any further. That's like saying that nested scopes aren't supported in a function... when Python sees "x = x", etc etc. > At the top-level, it works as expected: > > >>> x = 5 > >>> class C(object): > ... x = x > ... > >>> C.x > 5 > > Any implementation gurus have some insight into what's going on here? Class bodies and function bodies are compiled slightly differently, leading to a "handy specialcasing" of globals in the latter example which is probably what's confusing you. OK, let's try digging into more detail: >>> def f(x): ... class C: ... x = x ... return C ... >>> dis.dis(f) 2 0 LOAD_CONST 1 ('C') 3 BUILD_TUPLE 0 6 LOAD_CONST 2 (", line 2>) 9 MAKE_FUNCTION 0 12 CALL_FUNCTION 0 15 BUILD_CLASS 16 STORE_FAST 1 (C) 4 19 LOAD_FAST 1 (C) 22 RETURN_VALUE this shows you where the codeobject for C's body is kept -- constant number two among f's constants. OK then: >>> dis.dis(f.func_code.co_consts[2]) 2 0 LOAD_GLOBAL 0 (__name__) 3 STORE_NAME 1 (__module__) 3 6 LOAD_NAME 2 (x) 9 STORE_NAME 2 (x) 12 LOAD_LOCALS 13 RETURN_VALUE Compare with: >>> def f(x): ... def g(): ... x = x ... return x ... return g ... >>> dis.dis(f) 2 0 LOAD_CONST 1 (", line 2>) 3 MAKE_FUNCTION 0 6 STORE_FAST 1 (g) 5 9 LOAD_FAST 1 (g) 12 RETURN_VALUE >>> and: >>> dis.dis(f.func_code.co_consts[1]) 3 0 LOAD_FAST 0 (x) 3 STORE_FAST 0 (x) 4 6 LOAD_FAST 0 (x) 9 RETURN_VALUE See the difference? In a function, the 'x = x' compiles into LOAD_FAST, STORE_FAST, which only looks at locals and nowhere else. In a classbody, it compiles to LOAD_NAME, STORE_NAME, which looks at locals AND globals -- but still not at closure cells... Alex From Scott.Daniels at Acm.Org Tue Jan 18 15:05:52 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 18 Jan 2005 12:05:52 -0800 Subject: One-Shot Property? In-Reply-To: <35534hF4ehdtaU1@individual.net> References: <20050118115456510-0500@braeburn.themorgue.org> <35534hF4ehdtaU1@individual.net> Message-ID: <41ed68cf$1@nntp0.pdx.net> Leif K-Brooks wrote: > > class CachingProperty(object): > def __init__(self, attr_name, calculate_function): > self._name = attr_name > self._calculate = calculate_function > def __get__(self, obj, type=None): > if obj is None: > return self > else: > value = self._calculate(obj) > setattr(obj, self._name, value) > return value > > And example code: > >>> class Foo(object): > ... def calculate_value(self): > ... print 'Calculating...' > ... return 42 > ... foo = CachingProperty('foo', calculate_value) > ... > >>> bar = Foo() > >>> bar.__dict__ > {} > >>> bar.foo > Calculating... > 42 > >>> bar.foo # Notice that the print statement doesn't run this time > 42 > >>> bar.__dict__ > {'foo': 42} To build on this for Python 2.4: class Caches(object): def __init__(self, calculate_function): self._calculate = calculate_function def __get__(self, obj, _=None): if obj is None: return self value = self._calculate(obj) setattr(obj, self._calculate.func_name, value) return value class Foo(object): @Caches def foo(self): print 'Calculating...' return 42 --Scott David Daniels Scott.Daniels at Acm.Org From venkatbo at yahoo.com Thu Jan 13 18:15:24 2005 From: venkatbo at yahoo.com (Venkat B) Date: Thu, 13 Jan 2005 15:15:24 -0800 Subject: newbie ?s References: <1105656971.768148@sj-nntpcache-5> <7xekgpgc90.fsf@ruckus.brouhaha.com> Message-ID: <1105658413.536906@sj-nntpcache-3> > > 1) I was wondering if anyone has opinions on the ability of CGIHTTPServer (a > > forking variant) to be able to handle this. > > Why not use apache? Wanted something with less footprint. From newsgroups at jhrothjr.com Fri Jan 14 12:09:06 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 14 Jan 2005 11:09:06 -0600 Subject: (objects as) mutable dictionary keys References: Message-ID: <10ufv6d46sgrl04@news.supernews.com> "Peter Maas" wrote in message news:cs8a7e$t87$1 at swifty.westend.com... >I have summarized the discussion about the usability of lists (and > and other mutable types) as dictionary keys and put it into the > Python wiki.URL: http://www.python.org/moin/DictionaryKeys. > > This summary might be used as a reference should the 'mutable > dictionary keys' issue come up again in c.l.py. The last piece has an incorrect conclusion. Lists are not safe _because_ the cmp function is NOT a compare of id(list), but is based on list contents, which can change at any time. It should also be emphasized that the default instance hash and cmp functions quoted make it impossible for two different instances to compare equal, thus there is no reason to store them as dictionary keys: it's simpler to make the value an attribute of the instance and bypass the additional complexity of the dictionary. John Roth > > -- > ------------------------------------------------------------------- > Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 > E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') > ------------------------------------------------------------------- > From fperez.net at gmail.com Thu Jan 27 20:00:13 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Thu, 27 Jan 2005 18:00:13 -0700 Subject: ANN: IPython 0.6.10 is out. Message-ID: Hi all, I'm glad to announce the release of IPython 0.6.10. IPython's homepage is at: http://ipython.scipy.org and downloads are at: http://ipython.scipy.org/dist I've provided RPMs (for Python 2.3, built under Fedora Core 3), plus source downloads (.tar.gz). We now also have a native win32 installer. Debian, Fink and BSD packages for this version should be coming soon, as the respective maintainers (many thanks to Jack Moffit, Andrea Riciputi and Dryice Liu) have the time to follow their packaging procedures. Many thanks to Enthought for their continued hosting support for IPython, and to all the users who contributed ideas, fixes and reports. What is IPython? ---------------- 1. An interactive shell superior to Python's default. IPython has many features for object introspection, system shell access, and its own special command system for adding functionality when working interactively. 2. An embeddable, ready to use interpreter for your own programs. IPython can be started with a single call from inside another program, providing access to the current namespace. 3. A flexible framework which can be used as the base environment for other systems with Python as the underlying language. Release notes ------------- As always, the NEWS file can be found at http://ipython.scipy.org/NEWS, and the full ChangeLog at http://ipython.scipy.org/ChangeLog. * The major highlight of this release is vastly improved support for Windows users. Thanks to a lot of help from Viktor Ransmayr (installer work) and Gary Bishop (coloring problems), now Windows users finally should have an ipython with all the functionality available under Unix. There is now a true win32 executable installer: http://ipython.scipy.org/dist/ipython-0.6.10.win32.exe This can be double-clicked and it will do a real windows installation, allowing later de-installation via the Control Panel. It will also warn if it detects that ctypes and/or readline are missing (needed for coloring/tab support). Full source syntax highlighting had always been broken under win32, and the bug turned out to be in ipython's formatting code. Thanks to Gary's debugging help, this problem is now fixed. You can test it by typing in ipython: import code code?? You should see properly highligted sources, as shown in this (new) screenshot: http://ipython.scipy.org/screenshots/snapshot6.png Under Win32, ipython will now honor (if it exists) the $HOME environment variable and it will put your .ipython/ directory there. This should be more consistent for Win32 users who have a unix-like setup. If $HOME is not defined, the previous behavior remains (HOMEDRIVE\HOMEPATH). I also fixed a crash for pylab users under win32 with multithreaded backends (GTK/WX). I would appreciate reports of any problems from Win32 users. * (X)Emacs users: I incorporated Alex Schmolck's recent fixes and improvements to ipython.el. Since the python-mode project still hasn't made a release with the changes which IPython needs, I've temporarily copied today's CVS snapshot (v 4.70) of python-mode.el here: http://ipython.scipy.org/tmp/python-mode.el Once they make an official release, I'll remove this. * Small cleanups and improvements to numutils, including new amin/amax and empty_like utility functions. The deprecated spike/spike_odd functions have been removed. * Fix issue 24 from the bug tracker: spurious attribute access on assignment (foo.x=1 would trigger a __getattr__ call on foo). * Fix reporting of compound names in verbose exception reporting mode. This had been broken since the beginning of ipython (the tokenization logic was a bit tricky). * Fix gtk deprecation warnings (A. Straw patch). * Fix crash when inspecting instances without an __init__ method (reported by N. Nemenc). * Fix quote stripping bug in shell access (P. Ramachandran report). * Other minor fixes and cleanups, both to code and documentation. Enjoy, and as usual please report any problems. Regards, Fernando. From steven.bethard at gmail.com Sun Jan 23 16:37:08 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 23 Jan 2005 14:37:08 -0700 Subject: finding name of instances created In-Reply-To: References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> <1106397218.724722.172660@c13g2000cwb.googlegroups.com> Message-ID: Nick Coghlan wrote: > It also directly addresses the question of aliasing. Think about how > Steven's modified dictionary would react to this code: > > pete = CreateRobot(2, 3) > dad = pete > dad.move() > pete.move() If you'd like to handle these cases, but you don't want to have to explain aliasing right off the bat, you could try something like: py> class Robot(object): ... def __init__(self): ... self.names = set() ... def move(self): ... if len(self.names) == 1: ... name, = self.names ... print "robot with name %r moved" % name ... else: ... print "robot with names %r moved" % sorted(self.names) ... py> class RobotDict(dict): ... def __setitem__(self, name, value): ... if isinstance(value, Robot): ... value.names.add(name) ... super(RobotDict, self).__setitem__(name, value) ... py> user_code = """\ ... nick = Robot() ... pete = Robot() ... dad = pete ... nick.move() ... dad.move() ... pete.move()""" py> exec user_code in RobotDict(Robot=Robot) robot with name 'nick' moved robot with names ['dad', 'pete'] moved robot with names ['dad', 'pete'] moved That is, you can just keep track of all the names of a Robot in the Robot object. In the simple case, where there's only one name, you can display it as such. In the more complicated case, where there's some aliasing, you can display the multiple aliases. This means you don't have to teach about aliasing right off the bat, but if a student accidentally discovers it on their own, the machinery's there to explain it... Steve From vze4rx4y at verizon.net Sun Jan 16 17:19:25 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 16 Jan 2005 22:19:25 GMT Subject: generator expressions: performance anomaly? References: <1105854381.117059.59940@c13g2000cwb.googlegroups.com> Message-ID: [Raymond Hettinger] > >List slice assignment is an example of a tool with a special case optimization > >for inputs that know their own length -- that enables the tool to pre-allocate > >its result rather than growing and resizing in spurts. Other such tools include > >tuple(), map() and zip(). [John Machin] > My reading of the source: if the input is not a list or tuple, a > (temporary) tuple is built from the input, using PySequence_Tuple() in > abstract.c. If the input cannot report its own length, then that > function resorts to "growing and resizing in spurts", using the > following code: > > if (j >= n) { > if (n < 500) > n += 10; > else > n += 100; > if (_PyTuple_Resize(&result, n) != 0) { > > Perhaps it could be changed to use a proportional increase, like > list_resize() in listobject.c, which advertises (amortised) linear > time. Check out the current source. The time machine beat you to it. Keep the faith, Raymond Hettinger From simonwittber at gmail.com Wed Jan 12 22:54:06 2005 From: simonwittber at gmail.com (Simon Wittber) Date: Thu, 13 Jan 2005 11:54:06 +0800 Subject: why are people still using classic classes? In-Reply-To: References: Message-ID: <4e4a11f805011219546754406d@mail.gmail.com> > Is there a reason NOT to use them? If a classic class works fine, what > incentive is there to switch to new style classes? Perhaps classic classes will eventually disappear? It seems strange (and is difficult to explain to my peers) that a language offers two different ways to define a standard class. Sw. From mt at 3planes.com Mon Jan 31 11:47:08 2005 From: mt at 3planes.com (Michael Tobis) Date: 31 Jan 2005 08:47:08 -0800 Subject: variable declaration In-Reply-To: References: <1107188359.375703.110590@f14g2000cwb.googlegroups.com> Message-ID: <1107190028.911373.158940@z14g2000cwz.googlegroups.com> > that's a nice theory, but since the decorator line is executed by the inter- > preter, it's a little weak. Well, uh, who else would process it? "use strict' and 'my epsilon' in perl are executed by the perl interpreter as well, but they have a declarative flavor. A decorator is a modifier to a subsequent binding, and it modifies the reference and not the referent. So how is it anythng but declarative? -- mt From vze4rx4y at verizon.net Sun Jan 30 18:08:42 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 30 Jan 2005 23:08:42 GMT Subject: is this sort method the same as the one in python 2.4 References: Message-ID: <_NdLd.263$ya6.170@trndny01> "Lowell Kirsh" > How come you reverse the list twice? And why does this preserve stability? It's easy to see if you trace through the steps: Given sample the following dataset and a desire to sort on the first field: >>> data = [('a', 1), ('a', 2), ('b', 3)] Here are the step: >>> data.reverse() >>> data [('b', 3), ('a', 2), ('a', 1)] >>> data.sort(key=lambda record: record[0]) >>> data [('a', 2), ('a', 1), ('b', 3)] >>> data.reverse() >>> data [('b', 3), ('a', 1), ('a', 2)] Note, in the final result, the two equal records (the ones with 'a') appear in the same order as the original dataset (that is what stability means). Now, try it without the initial reversal and note that stability is not preserved: >>> data = [('a', 1), ('a', 2), ('b', 3)] >>> data.sort(key=lambda record: record[0]) >>> data.reverse() >>> data [('b', 3), ('a', 2), ('a', 1)] Here's another way of accomplishing the original sort and preserving stability: >>> data = [('a', 1), ('a', 2), ('b', 3)] >>> sorted(data, cmp = lambda x,y: cmp(y[0], x[0])) [('b', 3), ('a', 1), ('a', 2)] Raymond Hettinger From irmen at -nospam-remove-this-xs4all.nl Thu Jan 20 13:13:36 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Thu, 20 Jan 2005 19:13:36 +0100 Subject: xml parsing escape characters In-Reply-To: <41efee5d$0$11622$9b622d9e@news.freenet.de> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> <41efb72d$1_2@newspeer2.tds.net> <41efe52f$0$6220$e4fe514c@news.xs4all.nl> <41efee5d$0$11622$9b622d9e@news.freenet.de> Message-ID: <41eff4cf$0$6209$e4fe514c@news.xs4all.nl> Martin v. L?wis wrote: > Irmen de Jong wrote: > >> The unescaping is usually done for you by the xml parser that you use. > > > Usually, but not in this case. If you have a text that looks like > XML, and you want to put it into an XML element, the XML file uses > < and >. The XML parser unescapes that as < and >. However, it > does not then consider the < and > as markup, and it shouldn't. That's also what I said? The unescaping of the XML entities in the contents of the OP's element is done for you by the parser, so you will get a text node with the <,>,&,whatever in there. The OP probably wants to feed that to a new xml parser instance to process it as markup. Or perhaps the way the original XML document is constructed is flawed. --Irmen From aahz at pythoncraft.com Fri Jan 28 14:14:51 2005 From: aahz at pythoncraft.com (Aahz) Date: 28 Jan 2005 14:14:51 -0500 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> Message-ID: In article <1106911061.429966.303510 at f14g2000cwb.googlegroups.com>, wrote: >Aahz wrote: >> In article <1106863164.745581.11920 at f14g2000cwb.googlegroups.com>, >> wrote: >>> >>>Who are the appropriate people to report security problems to in >>>respect of a module included with the Python distribution? I don't >>>feel it appropriate to be reporting it on general mailing lists. >> >> There is no generally appropriate non-public mechanism for reporting >> security issues. If you really think this needs to be handled >> privately, do some research to find out which core developer is most >> likely to be familiar with it. Even before you do that, check >> SourceForge to find out whether anyone else has reported it as a bug. > >I find this response a bit dissappointing frankly. Open Source people >make such a big deal about having lots of people being able to look at >source code and from that discover security problems, thus making it >somehow making it better than proprietary source code. That's generally true, but not universally. The key point you seem to have missed in my response is "non-public mechanism". Historically, Python security issues have been thrashed out in public; the Python project does not have a release cycle that makes it possible to quickly address security concerns, so keeping it private has little point. Your decision to take the private route makes it your responsibility to search for an appropriate mechanism. >I'm sorry, but this isn't really good enough. If Open Source wants to >say that they are better than these proprietary companies, they need >to deal with these sorts of things more professionally and establish >decent channels of communications for dealing with it. As other people said, sounds like you want to volunteer for this. Which would be fine -- but there's still not much point until/unless we get enough volunteers to manage quicker release cycles. Then there's still the problem of getting people to update their local copies of Python. This is a complex issue. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From flamesrock at gmail.com Mon Jan 3 19:03:58 2005 From: flamesrock at gmail.com (flamesrock) Date: 3 Jan 2005 16:03:58 -0800 Subject: Howto Extract PNG from binary file @ 0x80? In-Reply-To: References: <1102753727.706459.105920@f14g2000cwb.googlegroups.com> Message-ID: <1104797038.407042.32580@z14g2000cwz.googlegroups.com> Well, I've been working on getting this code to work, and I think I *almost* have it... First, according to ghex, it seems the PNG starts at the 97th byte of the file infile = open("mysimcityfile.sc4", "rb") infile.seek(97) print (infile.read(4)) output: flamesrock at flames:~/score$ python sc4png.py PNG (for 5 bytes it outputs an extra line, and for 6-  (the biology symbol for a male)) So to debug further, I took out the exception and modified the code like this: #import struct # #def pngcopy(infile, outfile): # # # copy header # header = infile.read(4) # #if header != "\211PNG\r\n\032\n": # # raise IOError("not a valid PNG file") # outfile.write(header) # # # copy chunks, until IEND # while 1: # chunk = infile.read(8) # size, cid = struct.unpack("!l4s", chunk) # outfile.write(chunk) # outfile.write(infile.read(size)) # outfile.write(infile.read(4)) # checksum # if cid == "IEND": # break # # #infile = open("mysimcityfile.sc4", "rb") #infile.seek(97) #outfile = open("myimage.png", "wb") #pngcopy(infile, outfile) #outfile.close() #infile.close() returning the following output: flamesrock at flames:~/score$ python sc4png.py Traceback (most recent call last): File "sc4png.py", line 26, in ? pngcopy(infile, outfile) File "sc4png.py", line 14, in pngcopy size, cid = struct.unpack("!l4s", chunk) struct.error: unpack str size does not match format Any ideas on how to fix it? If I understand this page correctly, http://www.python.org/doc/current/lib/module-struct.html a png is basically a 'big endian string of 14 chars'? Changing it to !14b" gives a"ValueError: unpack tuple of wrong size" -thanks in advance for any help From chris.lasher at gmail.com Thu Jan 13 10:54:51 2005 From: chris.lasher at gmail.com (Chris Lasher) Date: 13 Jan 2005 07:54:51 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: <1105631691.471881.309890@c13g2000cwb.googlegroups.com> Thanks for your reply, Larry. I thought about this, but I'm worried the dictionary will consume a lot of resources. I think my 3GHz/1GB RAM box could handle the load fine, but I'm not sure about others' systems. Chris From eurleif at ecritters.biz Mon Jan 31 19:45:04 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 31 Jan 2005 19:45:04 -0500 Subject: set, dict and other structures In-Reply-To: <1107214762.198058.55680@f14g2000cwb.googlegroups.com> References: <1107214762.198058.55680@f14g2000cwb.googlegroups.com> Message-ID: <3681iiF4u273vU1@individual.net> bearophileHUGS at lycos.com wrote: > I'm frequently using Py2.4 sets, I find them quite useful, and I like > them, even if they seem a little slower than dicts. They look exactly the same speed-wise to me: >>> t1 = Timer('randrange(100) in foo', 'from random import randrange; foo = set(xrange(1000))') >>> t2 = Timer('randrange(100) in foo', 'from random import randrange; foo = dict.fromkeys(xrange(1000))') >>> t1.timeit() 3.0573790073394775 >>> t2.timeit() 3.064924955368042 >>> t2.timeit() 3.0590860843658447 From rbt at athop1.ath.vt.edu Mon Jan 17 09:09:04 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 17 Jan 2005 09:09:04 -0500 Subject: dynamic data types In-Reply-To: <1105969253.296411.301760@f14g2000cwb.googlegroups.com> References: <1105969253.296411.301760@f14g2000cwb.googlegroups.com> Message-ID: Charlie wrote: > Hi, > > The description of Python always mentions "very high level dynamic data > types". Now, I can't seem to find any examples of these (nothing > described with this term anyway). Is this simply refering to built-in > dynamic data structures such as lists and dictionaries, with a great > deal of operators defined on? Or is there something else meant by > "dynamic data types" in Python? > > Regards, > > Charlie > I've always thought of it like this... in C, we have to do something like this when declaring a variable: int x = 0; We had to specifically tell the language compiler that x is an integer. In Python, all we have to do is: x = 0 The interpretor knows that x is an integer. We can also change the type like this: str(x) float(x) long(x) etc... To me, this is why Python types are called dynamic. They are easy to setup and easy to modify when compared to older, more static languages. Bye From b at b.b Sat Jan 8 03:23:33 2005 From: b at b.b (Roose) Date: Sat, 08 Jan 2005 08:23:33 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> Message-ID: <9MMDd.7681$wZ2.149@newssvr13.news.prodigy.com> "Michael Hobbs" wrote in message news:10tteh884ivk6c9 at corp.supernews.com... > David Brown wrote: > > Hello. I recently came across a free operating system called Unununium (or > > something like that) and it was developed in Python and Assembly. > > > > Now, I have been looking for a way to make an operating system for a long > > long time and the only possibilities I could find were C++ and assembly. > > The problem when using Python instead of C for OS development is that > C was *specifically designed* to create an OS, while Python was designed > for completely different purposes. If you want to write an OS, it would > be wise to use a language that is suited for that purpose. If you > dislike C so much and prefer Python so much more, your first step should > be to design a Python dialect that is more appropriate for writing OS's. Yes, that sounds pretty realistic : ) For someone who is choosing the wrong language to write an OS, and who I would guess doesn't understand interrupt programming and the like -- their first task should be to redesign Python!! From sjmachin at lexicon.net Tue Jan 11 21:36:21 2005 From: sjmachin at lexicon.net (John Machin) Date: 11 Jan 2005 18:36:21 -0800 Subject: Help Optimizing Word Search In-Reply-To: <7xacrfl78y.fsf@ruckus.brouhaha.com> References: <1105486769.730769.165710@c13g2000cwb.googlegroups.com> <7xacrfl78y.fsf@ruckus.brouhaha.com> Message-ID: <1105497381.964168.275500@c13g2000cwb.googlegroups.com> Paul Rubin wrote: > "Case Nelson" writes: > > Basically, the program needs to take in a random list of no more than > > 10 letters, and find all possible mutations that match a word in my > > dictionary (80k words). However a wildcard letter '?' is also an > > acceptable character which increases the worst case time significantly. > > For that size pattern and dictionary, simply compiling the pattern to > a regexp, joining the dictionary together into one big string ("abc > def ghijk..."), and matching the regexp against the big string, may > well be faster than using some fancy algorithm coded completely in > python. Paul, given the OP appears to want something like words that match any (per)mutation of any substring of his query string -- and that's before factoring in wildcards -- I'd like to see an example of a regexp that could handle that. Cheers, John From peter at somewhere.com Fri Jan 14 06:23:09 2005 From: peter at somewhere.com (Peter Maas) Date: Fri, 14 Jan 2005 12:23:09 +0100 Subject: (objects as) mutable dictionary keys Message-ID: I have summarized the discussion about the usability of lists (and and other mutable types) as dictionary keys and put it into the Python wiki.URL: http://www.python.org/moin/DictionaryKeys. This summary might be used as a reference should the 'mutable dictionary keys' issue come up again in c.l.py. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From tam at tim.it Wed Jan 26 14:28:50 2005 From: tam at tim.it (Rimmel) Date: Wed, 26 Jan 2005 20:28:50 +0100 Subject: moka Message-ID: <41f7ef70$0$131$5fc30a8@news.tiscali.it> www.falcoinvest.it From golux at comcast.net Mon Jan 3 15:33:36 2005 From: golux at comcast.net (Stephen Waterbury) Date: Mon, 03 Jan 2005 15:33:36 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xacrs230c.fsf@ruckus.brouhaha.com> Message-ID: <41D9AC20.9020107@comcast.net> Steve Holden wrote: > Aahz wrote: >> In article , >> Steve Holden wrote: >>> Aahz wrote: >>>> In article <7xacrs230c.fsf at ruckus.brouhaha.com>, >>>> Paul Rubin wrote: >>>> >>>>> I was pretty skeptical of Java's checked exceptions when I first used >>>>> them but have been coming around about them. [...] >>>> >>>> That's funny -- Bruce Eckel talks about how he used to love checked >>>> exceptions but has come to regard them as the horror that they are. >>>> I've learned to just write "throws Exception" at the declaration of >>>> every method. >>> >>> Pretty sloppy, though, no? And surely the important thing is to have >>> a broad handler, not a broad specification of raisable exceptions? >> >> Yes, it's sloppy, but I Don't Care. I'm trying to write usable code >> while learning a damnably under-documented Java library -- and I'm *not* >> a Java programmer in the first place, so I'm also fighting with the Java >> environment. Eventually I'll add in some better code. > > The road to hell is paved with good intentions. Hmm ... those must be what my bucket keeps bumping over! :) Steve W. From peter at engcorp.com Wed Jan 12 08:50:17 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 Jan 2005 08:50:17 -0500 Subject: Excel module for Python In-Reply-To: References: Message-ID: sam wrote: > I m wondering which Excel module is good to be used by Python? Just use Excel's COM interface. See also this helpful page to improve future responses: http://www.catb.org/~esr/faqs/smart-questions.html -Peter From martin at v.loewis.de Fri Jan 28 18:39:08 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 29 Jan 2005 00:39:08 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7x4qh13o0o.fsf@ruckus.brouhaha.com> References: <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> Message-ID: <41FACD1C.6000301@v.loewis.de> Paul Rubin wrote: > Let's see, the urandom module was recently released in 2.4, I think > initially at my urging. There is no urandom module in Python 2.4. > If you can't speak for others, how can you say there's no policy in > force? I should say I'm not aware of a policy. > If Guido says "no crypto", is that something other than a > policy? And are you speaking for him when you say that? If he had said such a thing in general, it would be a policy (although it best would be documented somewhere). I don't think he said that, in general, and with the intent of stating a policy. > That's much different than merely deciding > that a feature is good and inviting people to work on it. We don't normally invite people to work on anything. People pick the things they work on themselves. > IETF often decides and announces that a feature is good long before > any such details are decided or agreed on. For example, they decided > that IP connection encryption was a good feature, and appointed a > working group a general mandate to go figure out the details (IPSEC) > and write a spec. See? No. They decided that spam machinery in DNS would be a good thing, people started to work on it, and then they decided that it is not such a good thing, after all, because it causes too many problems. So the decision "this is a good thing" is no guarantee for "if it is done, we will publish it as a standard". They might start a process, people might get nearly through it, and then the process stucks or is given up entirely. Happens all the time. > I realize that the difference might > not matter to you, but it does matter to a heck of a lot of other > users. It does matter for me, yet Python is still more than the core. You might be ignoring that, but it surely is more to the many developers which create Python libraries and distribute them themselves, see http://www.python.org/pypi THIS IS ALL PYTHON. > Obviously those require a different type of consideration. I'm > talking about patches where there's a core developer with an interest. I though you were talking about the AES module... Regards, Martin From rnd at onego.ru Thu Jan 20 13:41:57 2005 From: rnd at onego.ru (Roman Suzi) Date: Thu, 20 Jan 2005 21:41:57 +0300 (MSK) Subject: RuntimeError: dictionary changed size during iteration In-Reply-To: References: Message-ID: On Thu, 20 Jan 2005, Batista, Facundo wrote: >For me, the point is: vars() returns the local variables as a list or is a >generator? > >In the docs don't say nothing about this. > >If it returns a list, it should NOT raise an error; if it's a generator, the >error is fine. > >. Facundo > Probably, e need not appear in vars() at all... This is why generator closure works fine. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From ramagnus at t-online.de Tue Jan 4 18:38:00 2005 From: ramagnus at t-online.de (Rolf Magnus) Date: Wed, 05 Jan 2005 00:38:00 +0100 Subject: Embedding a restricted python interpreter Message-ID: Hi, I would like to embed a python interpreter within a program, but since that program would be able to automatically download scripts from the internet, I'd like to run those in a restricted environment, which basically means that I want to allow only a specific set of modules to be used by the scripts, so that it wouldn't be possible for them to remove files from the hard drive, kill processes or do other nasty stuff. Is there any way to do that with the standard python interpreter? From ncoghlan at iinet.net.au Tue Jan 11 05:12:34 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 11 Jan 2005 20:12:34 +1000 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: <41E39F80.5050001@iinet.net.au> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> <41E39F80.5050001@iinet.net.au> Message-ID: <41E3A692.4050200@iinet.net.au> Nick Coghlan wrote: > Nick Coghlan wrote: > >> Semantics >> --------- >> The code:: >> >> with: >> >> >> translates to:: >> >> def unique_name(): >> >> >> unique_name() >> > > Bleh. Not only was my proposed grammar change wrong, my suggested > semantics are wrong, too. > > Raise your hand if you can see the problem with applying the above > semantics to the property descriptor example. Eh, never mind. The following works today, so the semantics I proposed are actually fine. (This is exactly the semantics proposed for the property example) Py> class C(object): ... def _x(): ... def get(self): ... print "Hi!" ... def set(self, value): ... print "Hi again!" ... def delete(self): ... print "Bye" ... return property(get, set, delete) ... x = _x() ... Py> C.x Py> C().x Hi! Py> C().x = 1 Hi again! Py> del C().x Bye Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ark at acm.org Sat Jan 22 11:54:02 2005 From: ark at acm.org (Andrew Koenig) Date: Sat, 22 Jan 2005 16:54:02 GMT Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com><797fe3d405011911465ab59acd@mail.gmail.com><1106177050.630141.33090@c13g2000cwb.googlegroups.com><972ec5bd0501191641166972b0@mail.gmail.com><7xis5szpdj.fsf@ruckus.brouhaha.com><7xekggbrns.fsf@ruckus.brouhaha.com><7x651rwbib.fsf@ruckus.brouhaha.com><7xfz0uqe1d.fsf@ruckus.brouhaha.com><1gqsayh.th49i518ixczeN%aleaxit@yahoo.com><7xpszxljra.fsf@ruckus.brouhaha.com><7x4qh9pqhw.fsf@ruckus.brouhaha.com> Message-ID: "Fredrik Lundh" wrote in message news:mailman.1069.1106400356.22381.python-list at python.org... > in some early C++ compilers, the scope for "x" was limited to the scope > containing the for loop, not the for loop itself. some commercial > compilers > still default to that behaviour. Indeed--and the standards committee dithered far too long before correcting it. The argument that finally swayed them was this: If you change it, you will be ridiculed for a few years. If you do not change it, you will be ridiculed for the rest of your careers. From lbates at syscononline.com Mon Jan 24 19:50:41 2005 From: lbates at syscononline.com (Larry Bates) Date: Mon, 24 Jan 2005 18:50:41 -0600 Subject: Help with saving and restoring program state In-Reply-To: <85b54e91.0501241556.d281f90@posting.google.com> References: <85b54e91.0501241556.d281f90@posting.google.com> Message-ID: <2OCdndf8hbt9CmjcRVn-jQ@comcast.com> Take a look at Zope. The ZODB is a highly optimized object database that handles the pickling, loading, saving, etc. of Python objects for restoring program state. A ZODB beginner's tutorial is available here: http://www.h7.dion.ne.jp/~harm/ZODB-Tutorial.py Other info at: http://zope.org/Members/adytumsolutions/HowToLoveZODB_PartII/HowToLoveZODB_PartI http://zope.org Hope information helps. Larry Bates Jacob H wrote: > Hello list... > > I'm developing an adventure game in Python (which of course is lots of > fun). One of the features is the ability to save games and restore the > saves later. I'm using the pickle module to implement this. Capturing > current program state and neatly replacing it later is proving to be > trickier than I first imagined, so I'm here to ask for a little > direction from wiser minds than mine! > > When my program initializes, each game object is stored in two places > -- the defining module, and in a list in another module. The following > example is not from my actual code, but what happens is the same. > > (code contained in "globalstate" module) > all_fruit = [] > > (code contained in "world" module) > class Apple(object): # the class hierarchy goes back to object, anyway > def __init__(self): > self.foo = 23 > self.bar = "something" > globalstate.all_fruit.append(self) > apple = Apple() > > I enjoy the convenience of being able to refer to the same apple > instance through world.apple or globalstate.all_fruit, the latter > coming into play when I write for loops and so on. When I update the > instance attributes in one place, the changes are reflected in the > other place. But now comes the save and restore game functions, which > again are simplified from my real code: > > (code contained in "saveload" module) > import pickle > import world > def savegame(path_to_name): > world_data = {} > for attr, value in world.__dict__.items(): > # actual code is selective about which attributes > # from world it takes -- I'm just keeping this > # example simple > world_data[attr] = value > fp = open(path_to_name, "w") > pickle.dump(world_data, fp) > fp.close() > > def loadgame(path_to_name): > fp = open(path_to_name, "r") > world_data = pickle.load(fp) > for attr, value in world_data.items(): > setattr(world, attr, value) > fp.close() > > The problem is that the game objects only get overwritten in the world > module. The instances in the globalstate.all_fruit list remain > unchanged, which is not the behaviour I want. I started to write code > to get around this. I figured that with each loadgame call, I could > reset all the lists in globalstate to empty, then reappend each game > object to the appropriate list. But this possibility got complicated > fast, because all game objects belong to more than one list. My apple > instance alone would belong to globalstate.all_things, > globalstate.all_fruit, globalstate.all_items, and perhaps others. Some > of the game objects contained in these lists don't need to be a part > of capturing program state in the first place! But I'm stuck, because > unpickling (so far as I understand it) creates a brand new instance > that doesn't know it used to have references to itself in the > globalstate lists. > > Any advice out there? I'm looking for a clean, elegant way to > overwrite the same class instance in two arbitrary places at once. > Perhaps the example code I've provided isn't even the best way of > saving and restoring program state. Perhaps I can easily update my > globalstate lists and I'm just overlooking the simple way. Or perhaps > the solution lies in abandoning the concepts of referencing my game > objects through module attributes and lists. I'm open to any > suggestions. > > Thanks in advance for any help! > > Jacob From sylvain.thenault at nospam.logilab.fr Fri Jan 21 07:24:57 2005 From: sylvain.thenault at nospam.logilab.fr (Sylvain Thenault) Date: Fri, 21 Jan 2005 13:24:57 +0100 Subject: [ANN] PyLint 0.6 Message-ID: Hi there, I'm very pleased to announce the 0.6 release of PyLint. This release fix a lot of bugs and should be much more stable than the 0.5 release where stopping actual import of analyzed modules has been introduced (and that's really a huge improvment, since this was potentialy introducing some side effects). There are also more documentation, a better test suite, and also minor new features was added. Every users of pylint should update to 0.6. Notice that Logilab's common library 0.9 is required (http://www.logilab.org/projects/common). Enjoy ! What's new ? ------------ * refix pylint emacs mode * no more traceback when just typing "pylint" * fix a bug which may cause crashes on resolving parent classes * fix problems with the format checker: don't chock on files containing multiple CR, avoid C0322, C0323, C0324 false positives with triple quoted string with quote inside * correctly detect access to member defined latter in __init__ method * now depends on common 0.8.1 to fix problem with interface resolution (close #8606) * new --list-msgs option describing available checkers and their messages * added windows specific documentation to the README file, contributed by Brian van den Broek * updated doc/features.txt (actually this file is now generated using the --list-msgs option), more entries into the FAQ * improved tests coverage What is pylint ? ---------------- Pylint is a python tool that checks if a module satisfy a coding standard. Pylint can be seen as another pychecker since nearly all tests you can do with pychecker can also be done with Pylint. But Pylint offers some more features, like checking line-code's length, checking if variable names are well-formed according to your coding standard, or checking if declared interfaces are truly implemented, and much more (see http://www.logilab.org/pylint/ for the complete check list). The big advantage with Pylint is that it is highly configurable, customizable, and you can easily write a small plugin to add a personal feature. The usage it quite simple : $ pylint mypackage.mymodule This command will output all the errors and warnings related to the tested code (here : mypackage.mymodule), will dump a little summary at the end, and will give a mark to the tested code. Pylint is free software distributed under the GNU Public Licence. Home page --------- http://www.logilab.org/projects/pylint Download -------- ftp://ftp.logilab.org/pub/pylint Mailing list ------------ mailto://python-projects at lists.logilab.org -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From grahamd at dscpl.com.au Thu Jan 6 05:10:25 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 6 Jan 2005 02:10:25 -0800 Subject: Contributor's List References: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> Message-ID: <1105006225.344735.294800@z14g2000cwz.googlegroups.com> Anand wrote: > A list of contributors to Python Cookbook (Second Edition) is available > at the following links. Original list courtesy Alex Martelli. > > Since the book is not yet in print, the lists are still tentative > because of potential last minute editing changes. > > List of first authors > o http://harvestman.freezope.org/cookbook/credau.html > > List of all authors > o http://harvestman.freezope.org/cookbook/creds.html Is this mean't to only cover additional entries which were added in the 2nd edition, or is it also mean't to encompass entries which were carried over from the 1st edition as well. If it is both, then the editing must have been quite cut throat as I dropped from 3 entries in the 1st edition to 0 in the 2nd edition. I can sort of understand if the intent was to get rid of entries which referenced packages which weren't regarded as mainstream. I guess it is only 14 years of work down the drain. ;-( From fuzzyman at gmail.com Tue Jan 4 07:39:16 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 Jan 2005 04:39:16 -0800 Subject: How do I make Windows Application with Python ? In-Reply-To: <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> Message-ID: <1104842356.208340.284840@z14g2000cwz.googlegroups.com> You need py2exe to bundle applications so they can be used on machines without python. When you do that you have a choice of whether or not your application should have a console box or not. In order to use buttons and other widgets you will need to choose a GUI toolkit. I recommend starting with Tkinter - but others would recommend wxPython. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From skip at pobox.com Sat Jan 29 15:32:00 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 29 Jan 2005 14:32:00 -0600 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xzmysqmxk.fsf@ruckus.brouhaha.com> References: <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <7xzmysqmxk.fsf@ruckus.brouhaha.com> Message-ID: <16891.62144.742487.218810@montanaro.dyndns.org> Paul> I've had this discussion here before, maybe not with you. What I Paul> really want is zero installations of anything. Fine. Go build a sumo distribution and track the normal CPython. The problem isn't all that new. (Take a look at scipy.org for one take on that theme. Of course Linux distros have been doing their take on this forever.) >> If everyone adopted your position that it wasn't Python unless it had >> been added to the core, we'd all be reinventing lots of wheels or >> tackling much less challenging tasks, if we programmed in Python at >> all. Here's an incomplete list of stuff not in the core I have used >> happily over the past several years to do my jobs using Python: Paul> That makes no sense at all. That list is a list of programs Paul> written in the Python language. They are Python programs, where Paul> Python is an adjective. No, many of them are just modules or programming frameworks. >> * SpamBayes Paul> I have the impression this is an application and not a module, Yes, you're correct. >> * Quixote Paul> Don't know what this is. Web app framework. >> * Docutils Paul> Should be in the core if it's what I think it is. Probably will be someday. >> * MoinMoin Paul> Application, should be separate. Also, GPL'd, I think. Can't be Paul> distributed under PSF license. Sure. >> * Psyco Paul> I think this isn't ready for prime time yet. Should go into the Paul> core once it is. It's getting close for those of us with Intel chips in our boxes. >> * PyInline Paul> Not sure what this is. A module for inlining C code within a Python module. Also see Weave from the scipy.org folks. It was inspired by the Perl Inline::C module. >> * PyGTK Paul> wxPython might be a better choice. Doesn't matter. At work they decreed GTK as the GUI platform long before I came along (they also use gtkmm for C++ apps). It's still an example of a broadly useful package available outside the core distribution. >> * xmlrpclib before it was in the core Paul> 1. Did you really need this, instead of some more reasonable rpc Paul> format? Yes, for several years I used a homegrown RPC solution behind the Musi-Cal website that was Python only. Eventually Mojam (a Perl shop) bought Musi-Cal (a Python shop). I switched to XML-RPC with little effort. At one point we also had Java talking XML-RPC. Paul> xdrlib has been in the core forever. Sure. But it's somewhat lower level than XML-RPC and isn't really an RPC protocol. It's just a marshalling protocol and is probably not as flexible as XML-RPC at that. Paul> 2. Isn't xmlrpclib written in Python? Yes. The implementation language is just a detail. I also use Fredrik Lundh's sgmlop library to accelerate XML-RPC and play some other games when I know I'm talking Python-to-Python (marshal my args, then XML-RPC the result passing a single argument between the client and server). >> * MAL's mx.DateTime before the core datetime module was available Paul> See, as Python improved, those things went into the core. Sure, than that's what Martin has been trying to tell you about your AES proposal. Put it out there, refine it, and get it into the core when it's mature. >> * timeout_socket before sockets supported timeouts Paul> Could you use sigalarm instead? I suppose. That's not the point though. I'm not married to the concept as you seem to be that something has to be in the core distribution to be of use to me. I'm perfectly happy incorporating solutions other people provide. I believe you will find I am in the majority in this regard. >> Many of those things I could never have written myself, either for >> lack of time, lack of skill or both. I'm grateful they were >> available when I needed them and feel no qualms about using them even >> though they are not distributed with Python proper. Paul> Sure, it's fine if you have all those modules and you write a Paul> Python program that uses, say, five of them. External modules Paul> aren't so bad when the developer and the end user are the same Paul> person. What happens if you send your Python program to a Paul> nonprogrammer friend who has just a vanilla Python installation? I figure out some other packaging solution. In my world most of the software I write is for my employer, so this is not a problem I face very often. People use freeze, py2exe, py2app or other packaging solutions to solve most/all of these problems. Paul> Now he has to download and install those five modules too. You Paul> send him the url's where you got the modules a year ago. What are Paul> the chances that the 5 url's even all still work, much less the Paul> chance of him being able to install and run all 5 of the modules Paul> without needing help? What if the versions he downloads (from Paul> separate developers) have gotten out of sync with each other and Paul> can't interoperate any more? This is the well-known "CPAN in Python" problem. People are working on it. Perhaps you would like to spend some energy helping solve it. If so, join the catalog-sig. >> Notice another interesting feature of several of those items: csv, >> xmlrpclib, mx.DateTime, timeout_socket. They were all modules I used >> that eventually wound up in the core in some fashion. They didn't go >> in the core first, then demonstrate their usefulness. It was the >> other way around. Paul> I'm not sure about timeout_socket and it sounds like it should Paul> have just been a patch to the socket module, not a new module. Sure, but a shim between the socket module and Python modules that used it was a good first approximation to the problem. (I am also a firm believer in successive approximation to problem solving, especially when I don't know enough about the problem to know precisely what form the final solution will take.) Paul> csv is quite a complex module and took a lot of tweaking and PEP Paul> editing before standardization. But the need for it was obvious; Paul> the only good reason it wasn't in the core ages ago was that no Paul> one had done the work of writing it and shaking it out. Actually, there were at least two fairly mature implementations of CSV modules out there before the PEP was a twinkle in anyone's eye. The authors of those modules got together and wrote the current PEP and module from scratch based upon their collective experience. I think the effort of having a couple versions out in the field followed by joint effort to produce something worthy of inclusion in the core is an excellent demonstration of what Martin has been saying all along. Paul> xmlrpclib, not sure. How long was it in separate distribution? Not all that long. XML-RPC itself hadn't been around very long before Fredrik wrote xmlrpclib. Both the protocol and xmlrpclib (as well as similar modules for other languages) caught on pretty quickly. Skip From skip at pobox.com Mon Jan 17 22:54:46 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 17 Jan 2005 21:54:46 -0600 Subject: strange note in fcntl docs In-Reply-To: <20050117192327.GA4723@grulic.org.ar> References: <20050117053949.GA28456@grulic.org.ar> <16875.54085.712019.524951@montanaro.dyndns.org> <20050117192327.GA4723@grulic.org.ar> Message-ID: <16876.34950.976819.654894@montanaro.dyndns.org> John> And, even if they were, the note is *still* wrong and misleading: John> fcntl is available on Windows, and os.open's flags won't be. Does this read better? Skip ---------- *** /tmp/skip/ediffdJAG2X Mon Jan 17 21:53:05 2005 --- /Users/skip/src/python/head/dist/src/Doc/lib/libfcntl.tex Mon Jan 17 21:52:50 2005 *************** *** 165,173 **** better. \begin{seealso} ! \seemodule{os}{The \function{os.open()} function supports locking flags ! and is available on a wider variety of platforms than ! the \function{lockf()} and \function{flock()} ! functions, providing a more platform-independent file ! locking facility.} \end{seealso} --- 165,172 ---- better. \begin{seealso} ! \seemodule{os}{If the \module{os} module supports the \var{O_SHLOCK} ! and \var{O_EXLOCK} locking flags, the \function{os.open()} function ! provides an alternative to the \function{lockf()} and ! \function{flock()} functions.} \end{seealso} From xah at xahlee.org Wed Jan 12 01:53:23 2005 From: xah at xahlee.org (Xah Lee) Date: 11 Jan 2005 22:53:23 -0800 Subject: 20050111: list basics Message-ID: <1105512803.304386.229260@f14g2000cwb.googlegroups.com> # in Python, list can be done this way: a = [0, 1, 2, 'more',4,5,6] print a # list can be joined with plus sign b = a + [4,5,6] print b # list can be extracted by appending a square bracket with index # negative index counts from right. print b[2] print b[-2] # sublist extraction print 'element from 2 to 4 is', a[2:4] # replacing elements can be done like a[2]='two' print '2nd element now is:', a[2] # sequence of elements can be changed by assiging to sublist directly # the length of new list need not match the sublist b[2:4]=['bi','tri','quad','quint', 'sex'] print 'new a is', b # list can be nested a = [3,4,[7,8]] print 'nested list superb!', a # append extra bracket to get element of nested list print a[2][1] # gives 8 ---------------------------------------- # in perl, list is done with paren (). # the at sign in front of variable is necessary. # it tells perl that it is a list. @a = (0,1,2,'three',4,5,6,7,8,9); # perl can't print lists. To show a list content, # load the package Data::Dumper, e.g. use Data::Dumper; print '@a is:', Dumper(\@a); # the backslash in front of @a is to tell Perl # that "get the "address" of the "array" @a". # it is necessary in Dumper because Dumper is # a function that takes a memory address. # see perldoc -t Data::Dumper for the intricacies # of the module. # to join two lists, just enclose them with () @b = (3,4); @c = (@a, at b); print '\@c is', Dumper \@c; # note: this does not create nested list. # to extrat list element, append with [index] # the index can be multiple for multiple elements @b = @a[3,1,5]; print Dumper \@b; # to replace parts, do $a[3]= 333; print ' is', Dumper \@a; # note the dollar sign. # this tells Perl that this data is a scalar # as opposed to a multiple. # in perl, variable of scalars such as numbers and strings # starts with a dollar sign, while arrays (lists) starts with # a at @ sign. (and harshes/dictionaries starts with %) # all perl variables must start with one of $,@,%. # one creates nested list by # embedding the memory address into the parent list @a=(1,2,3); @b = (4,5, \@a, 7); print 'nested list is', Dumper \@b; # to extrat element from nested list, $c = $b[2]->[1]; print '$b[2]=>[1] is', $c; # the syntax of nested lists in perl is quite arty, see # perldoc -t perldata Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From steve at holdenweb.com Thu Jan 20 09:07:39 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 20 Jan 2005 09:07:39 -0500 Subject: iteritems() and enumerate() In-Reply-To: <1106206068.867004.195010@f14g2000cwb.googlegroups.com> References: <1106206068.867004.195010@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > Python has iteritems() and enumerate() to be used in for loops. > > can anyone tell me what these are by themselves, if anything? > > are they just for idiom? No, anyone can use them, not just idioms like you. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From pedro.werneck at terra.com.br Sun Jan 30 17:31:57 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Sun, 30 Jan 2005 20:31:57 -0200 Subject: how do i create such a thing? In-Reply-To: References: Message-ID: <20050130203157.5feebe8a.pedro.werneck@terra.com.br> Hi, If you need direct access to some atribute, use object.__getattribute__. >>> class DefaultAttr(object): ... def __init__(self, default): ... self.default = default ... def __getattribute__(self, name): ... try: ... value = object.__getattribute__(self, name) ... except AttributeError: ... value = self.default ... return value ... >>> x = DefaultAttr(99) >>> >>> print x.a 99 >>> x.a = 10 >>> print x.a 10 >>> On Sun, 30 Jan 2005 13:54:38 -0800 Lowell Kirsh wrote: > I want to create a class called DefaultAttr which returns a default > value for all attributes which haven't been given values yet. It will > work like this: > > >> x = DefaultAttr(99) > >> print x.foo > 99 > >> print x.bar > 99 > >> x.foo = 7 > >> print x.foo > 7 > > I already have a similar class called DefaultDict which works > similarly which I assume would be a good thing to use. > > Lowell > -- > http://mail.python.org/mailman/listinfo/python-list From itsme at yahoo.com Wed Jan 5 19:31:53 2005 From: itsme at yahoo.com (It's me) Date: Thu, 06 Jan 2005 00:31:53 GMT Subject: Another PythonWin Excel question References: <1104968382.403653.267060@f14g2000cwb.googlegroups.com> Message-ID: Ah, this work: self.xlbook.Worksheets.Add(None,sht) got it from: http://mail.python.org/pipermail/python-list/2003-September/183367.html Thanks again. -- Me "It's me" wrote in message news:ou%Cd.8515$5R.6706 at newssvr21.news.prodigy.com... > > "Kartic" wrote in message > news:1104968382.403653.267060 at f14g2000cwb.googlegroups.com... > > I am not sure about this but I believe you can give a parameter > > after="sheet1". to Add(), like so, Add(after="sheet1"). > > > > I get a "got an expected keyword argument 'after'" from Add(). > > > Unfortunately I do not have Excel installed on this machine to confirm > > this. > > > > A tip: if you have VBA (which you should if you have Excel) installed, > > lookup the Add method for the Worksheets collection. VBA will show the > > code completion, with all the arguments for the method call. Try the > > same for any of the methods. > > > > Yes, I read about that but unfortunately I have no experience with VBA *at > all*. :=( > > > Thanks, > > --Kartic > > > > From fredrik at pythonware.com Thu Jan 20 02:17:03 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jan 2005 08:17:03 +0100 Subject: ElementTree cannot parse UTF-8 Unicode? References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> <1106181323.553028.290370@z14g2000cwz.googlegroups.com> Message-ID: Erik Bethke wrote: > 2) You are right in that the print of the file read works just fine. but what does it look like? I saved a raw copy of your original mail, fixed the quoted-printable encoding, and got an UTF-8 encoded file that works just fine. the thing you've been parsing, and that you've cut and pasted into your mail, must be different, in some way. > 3) You are also right in that the digitally encoded unicode also works > fine. However, this solution has two new problems: that was just a test to make sure that your version of elementtree could handle Unicode characters on your platform. > 1) The xml file is now not human readable > 2) After ElementTree gets done parsing it, I am feeding the text to a > wx.TextCtrl via .SetValue() but that is now giving me an error message > of being unable to convert that style of string on my machine, the L1 attribute contains a Unicode string: >>> print repr(root.find("Word").get("L1")) u'\uc5b4\ub155\ud558\uc138\uc694!' what does it give you on your machine? (looks like wxPython cannot handle Unicode strings, but can that really be true?) > So it seems to me, that ElementTree is just not expecting to run into > the Korean characters for it is at column 16 that these begin. Am I > formatting the XML properly? nobody knows... From snacktime at gmail.com Sun Jan 23 21:44:39 2005 From: snacktime at gmail.com (snacktime) Date: Sun, 23 Jan 2005 18:44:39 -0800 Subject: Quoting sql queries with the DB-API In-Reply-To: <35j0nlF4nni9gU1@individual.net> References: <35j0nlF4nni9gU1@individual.net> Message-ID: <1f060c4c05012318448908de8@mail.gmail.com> > > Also, is this a good way to use variables in an insert/update > > statement, or is there a better way? > > > > sql = "insert into test(a,b) values('%s','%s')" % (a,b) > > cursor.execute(sql) > > If you do it like this: > > sql = "INSERT INTO test(a, b) VALUES(%s, %s)" # no quotes around the %s > cursor.execute(sql, (a, b)) > > Then the quoting will be handled automatically for you. Ah makes sense, thanks for the tip that was exactly what I needed. Chris From FBatista at uniFON.com.ar Thu Jan 20 07:28:41 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 20 Jan 2005 09:28:41 -0300 Subject: RuntimeError: dictionary changed size during iteration Message-ID: [Robert Brewer] #- > >>> [e for e in vars()] #- > Traceback (most recent call last): #- > File "", line 1, in ? #- > RuntimeError: dictionary changed size during iteration #- > >>> e = None #- > >>> [e for e in vars()] #- > ['e', '__builtins__', 'rlcompleter', '__file__', '_[1]', #- > 'atexit', '__name__', #- > 'readline', '__doc__'] #- #- But not unexpected, since vars() returns a dictionary, and #- binding 'e' #- changes that dictionary while you are iterating over it. Try either: For me, the point is: vars() returns the local variables as a list or is a generator? In the docs don't say nothing about this. If it returns a list, it should NOT raise an error; if it's a generator, the error is fine. . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stach at fr.pl Mon Jan 24 15:40:33 2005 From: stach at fr.pl (Krzysztof Stachlewski) Date: Mon, 24 Jan 2005 21:40:33 +0100 Subject: Instances of class object not modifiable? Message-ID: I tried to run the following piece of code: Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> o = object() >>> o.a = 5 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'object' object has no attribute 'a' But if I do: >>> class c(object): >>> pass >>> o = c() >>> o.a = 5 ...then it, of course, works. So what's wrong with the first example? -- Stach Tlen: stachobywatelpl, GG: 1811474 Jabber: stach at jabber atman pl From knguyen at megisto.com Sun Jan 9 09:27:09 2005 From: knguyen at megisto.com (knguyen at megisto.com) Date: 9 Jan 2005 06:27:09 -0800 Subject: pyparsing: how to negate a grammar References: <1105229039.136595.180640@c13g2000cwb.googlegroups.com> Message-ID: <1105280829.930207.169770@c13g2000cwb.googlegroups.com> Hi Paul, I am trying to extract HTTP response codes from a HTTP page send from a web server. Below is my test program. The program just hangs. Thanks, Khoa ################################################## #!/usr/bin/python from pyparsing import ParseException, Dict, CharsNotIn, Group,Literal,Word,ZeroOrMore,OneOrMore, Suppress,nums,alphas,alphanums,printables,restOfLine data = """HTTP/1.1 200 OK body line some text here body line some text here HTTP/1.1 400 Bad request body line some text here body line some text here HTTP/1.1 500 Bad request body line some text here body line some text here """ print "=================" print data print "=================" HTTPVersion = (Literal("HTTP/1.1")).setResultsName("HTTPVersion") StatusCode = (Word(nums)).setResultsName("StatusCode") ReasonPhrase = restOfLine.setResultsName("ReasonPhrase") StatusLine = Group(HTTPVersion + StatusCode + ReasonPhrase) nonHTTP = ~Literal("HTTP/1.1") BodyLine = Group(nonHTTP + restOfLine) Response = OneOrMore(StatusLine + ZeroOrMore(BodyLine)) respFields = Response.parseString(data) print respFields From apardon at forel.vub.ac.be Fri Jan 28 04:19:46 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 28 Jan 2005 09:19:46 GMT Subject: A proposal idea for string.split with negative maxsplit Message-ID: I was wondering what people whould think about a change of behaviour in the split method fo strings. The idea would be that if maxsplit was negative then abs(maxsplit) splits would be done, but splitting would start from the right instead of the left. Now we have. >>> "st1:st2:st3:st4:st5".split(':',2) ["st1" , "st2" , "st3:st4:st5"] This behaviour would remain but additionally we would have the following. >>> "st1:st2:st3:st4:st5".split(':',-2) ["st1:st2:st3" , "st4" , "st5"] What do people think here? -- Antoon Pardon From vegeta.z at gmail.com Wed Jan 12 10:36:55 2005 From: vegeta.z at gmail.com (vegetax) Date: Wed, 12 Jan 2005 11:36:55 -0400 Subject: java 5 could like python? Message-ID: I was a java developer one year ago ,before i moved to python i realy liked it at the beggining, but i got very disapointed lately since my previus two python proyects where relatively big,and python didnt feel well suited for the task. The reasons are mainly due to the standard library,the language performance was aceptable, but the library, in my opinion has several grave issues: -No naming convention. The speech of "it fits in my head" is no longer valid when i use a lot of functionality,modules,classes in a large proyect. For example if i remember a function i want ie:get attribute, i dont remember if the module implementer coded it as getAttribute,GetAttribute,get_attribute, then i have to go and check the doc, every time,which is a waste of time. -library Organization,we have modules that can have 20 classes(I imagine that is because of the commodity of having all in one file) which makes reading the doc horribly painfull and is very hard to find the stuff coupled with the "pool" of modules that is the python installation directory,all throwed away at the installation directory without a categorization. -Is python library half object oriented? half functional oriented? I can understand that python allows some functional programing components when they are necesary,but there are libraries that totaly ignore object orientation which makes them problematic to use.for example,Whats with the os.path module and files? why do i have to say os.path.getfilesize(f.name) all the time? why cant i say f.size? Why does urlparse returns a tuple of 7 items instead of an URL object? why there isnt an URL object? and so on.. I havent figured out a way to overcome those factors,the delaying and lost of focus that is having to check the docs all the time,every 5 seconds and having to make object oriented wrapers for several libraries or having to go and read the source code to know what the heck a function returns or what are its arguments makes coding unpleasant an very slow , i often have 15 pydocs windows open at the same time. What should i do? -Realying on ides is imposible due to python dinamic nature,very litle(next to nothing) assistance can be espected from them. -Memorazing all the function names,parameters,return values,conventions of the modules i use doesnt look like a good solution. Join it with poor and outdated documention and we have a very unpleasant standard library. In the other hand, with the recent changes in java 5 i can pythonize java,And take advantage of a well designed library that coupled with the "apache commons" libraries has no match,not even .Net. for example with the static import feature i can say: import static mylib.Toolbox.print; import static mylib.Console.run; // or import static mylib.Toolbox.*; class C{ public void func(){ print("hello world"); // instead of System.out.println("hello world"); print(run("ls /tmp")); } } Same for almost all python builtin functions. The new for statement : for (int i : mylist) print(i); I guess i could use a cleaver hack to also include the map,filter and other nice functional components python has. Also there is the generics support and so on.. But for some reason i dont know,the switch back feels wrong =( ,would it be posible to imitate python's behavior with the new java features and some hacks? would be worth the effort? If not what can i do to use efficiently python modules and libraries? I recall, i didnt had this problem when doing small applications with a small set of modules. Sorry for my bad english. From sjmachin at lexicon.net Sat Jan 15 21:22:40 2005 From: sjmachin at lexicon.net (John Machin) Date: 15 Jan 2005 18:22:40 -0800 Subject: How to del item of a list in loop? In-Reply-To: References: <34rvjqF4f6l70U1@individual.net> <34s7omF4emdsaU1@individual.net> Message-ID: <1105842160.134808.236480@z14g2000cwz.googlegroups.com> Nick Coghlan wrote: > I think this is about the best you can do for an in-place version: > for i, x in enumerate(reversed(lst)): > if x == 2: > del lst[-i] I think del lst[-i-1] might be functionally better. From jacob at jacob.remcomp.fr Sat Jan 29 02:34:30 2005 From: jacob at jacob.remcomp.fr (jacob navia) Date: Sat, 29 Jan 2005 08:34:30 +0100 Subject: what's OOP's jargons and complexities? In-Reply-To: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> Message-ID: <41fb3c85$0$10470$8fcfb975@news.wanadoo.fr> Good post. First article that demistifies this OO centered approach in quite a long time. This approach has its strength, but also has it weakness, it is not the solution for every problem appearing in data processing. From fredrik at pythonware.com Mon Jan 31 02:04:24 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 31 Jan 2005 08:04:24 +0100 Subject: Regarding exception handling References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> <41FDD5F4.8030507@gmail.com> Message-ID: "Bryan" wrote > the above is not the same. make the a = ... raise an exception and you'll see the difference. > > s = ... # > a = 1/0 > s.close() > > as you can see, s.close() will never be called. also, in this example, i intentionally didn't put > the extra try/except around the try/finally statement. file handles and sockets are closed when the objects are garbage collected. under CPython, they're usually closed when they go out of scope. using try/finally on files and sockets are usually overkill. From ncoghlan at iinet.net.au Sun Jan 9 07:43:44 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 22:43:44 +1000 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: <34cieoF489ejfU1@individual.net> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> Message-ID: <41E12700.8000106@iinet.net.au> Andrey Tatarinov wrote: > So it seems that people loved the idea of 'where' keyword, may be it's > time to think about PEP draft? I appreciate any help (cause my english > is not that good =)). There's certainly a PEP in the idea. Here's a summary of what we have so far in this thread in a PEPish format. Any reference implementation should definitely wait for the compiler upgrade to hit the main development branch in CVS though (or be based on ast-branch if someone gets inspired in the interim). Cheers, Nick. Abstract -------- The proposal is to add the capacity for statement local namespaces to Python. This allows a statement to be placed at the current scope, while the statement's 'setup code' is indented after the statement:: with: The main benefit is the avoidance of namespace pollution in the outer scope. Sections of the statement can be extracted and named in the statement's local namespace without any inadvertent side effects due to name conflicts. The second benefit is that it can improve readability by allow easy grouping of the setup code for a given expression (see the examples section) Thirdly, it provides full-fledged effectively anonymous functions (just define them in the statement's local namespace). The idea is inspired by Haskell's where clause, as posted to python-list by Andrey Tatarinov. Alex Martelli suggested using the 'with' keyword. Grammar Change -------------- Current:: statement ::= stmt_list NEWLINE | compound_stmt New:: statement ::= (stmt_list NEWLINE | compound_stmt) [local_namespace] local_namespace ::= "with" ":" suite Semantics --------- The code:: with: translates to:: def unique_name(): unique_name() Assignment statements (including augmented assignment) require special handling. The original assignment statement is translated to a return statement in the inner scope:: with: translates to:: def unique_name(): return unique_name() Function and class definitions will also require special casing, so that the created function or class is returned from the inner-scope and the name bound correctly in the outer scope. Note that calling locals() inside a statement with a local namespace will refer to the statement's locals, rather than those of the containing function. Keyword Choice -------------- The original suggestion on python-list used the 'where' keyword. Alex Martelli pointed out that this could be misleading for anyone with expectations based on SQL's WHERE clause. He suggested 'with' as an alternative spelling, as 'with' is already planned as a keyword for Python3k. Even for with clauses associated with compound statements, there should be no ambiguity, given that the with statement will have an expression between it and the colon, while the with clause does not. Open Issues ----------- Is it actually possible to make it work? Keyword choice Should the clause be allowed on any statement (as described), or restricted to ones where it "makes sense"? Examples -------- # Statement local functions (from Andrey Tatarinov) # aka How to cope if lambda goes away :) res = [ f(i) for i in objects ] with: def f(x): #do something # Declaring properties (from Nick Coghlan) class C(object): x = property(get, set) with: def get(self): pass def set(self, value): pass # Design by contract (from Nick Coghlan) @dbc(pre, post) def foo(): pass with: def pre(): pass def post(): pass # Singleton classes (from Paul Rubin) C = C() with: class C: pass # Complex default values (from Carlos Ribeiro) def f(x=default()): pass with: def default(): pass -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From davidf at sjsoft.com Wed Jan 26 11:22:09 2005 From: davidf at sjsoft.com (David Fraser) Date: Wed, 26 Jan 2005 18:22:09 +0200 Subject: module for 'po' files In-Reply-To: References: Message-ID: Sara Fwd wrote: > Hi all > Is there a module for processing & handling '.po' > files in python? If you want to do anything beyond standard gettext (which is handled by the gettext module) there's lots of code at translate.sourceforge.net ... David From cjw at sympatico.ca Sat Jan 15 20:04:36 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 15 Jan 2005 20:04:36 -0500 Subject: The First International Conference on Open Source Systems - OSS 2005 - Main In-Reply-To: References: Message-ID: <41E9BDA4.8080001@sympatico.ca> I haven't spotted a posting on c.l.p but someone here may be interested. Colin W. http://oss2005.case.unibz.it/ From bit_bucket5 at hotmail.com Mon Jan 10 09:54:24 2005 From: bit_bucket5 at hotmail.com (bit_bucket5 at hotmail.com) Date: 10 Jan 2005 06:54:24 -0800 Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: <1105368864.795524.18190@c13g2000cwb.googlegroups.com> See http://www.journynx.com/ Commercial timesheet app written in Python. eeykay at gmail.com wrote: > Hello All, > I am trying to convince my client to use Python in his new product. He > is worried about the license issues. Can somebody there to point me any > good commercial applications developed using python ?. The licence > clearly says Python can be used for commercial applications. Is there > any other implications like that of GPL to make the source open ? > Thanks for any help. > eeykay From just at xs4all.nl Mon Jan 3 04:47:19 2005 From: just at xs4all.nl (Just) Date: Mon, 03 Jan 2005 10:47:19 +0100 Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <87u0py6elt.fsf@sme.intra.citec.fi> Message-ID: In article <87u0py6elt.fsf at sme.intra.citec.fi>, Simo Melenius wrote: > I've sometimes replaced sys.stdout (and/or sys.stderr) to > capture/redirect debugging information in existing code that has > unwisely just "print"ed error and warning messages, instead of using > sys.stderr or error logging modules. > > py> def with_output_to_string (func): > ... try: > ... sys.stdout = StringIO.StringIO () > ... func () > ... return sys.stdout.getvalue () > ... finally: > ... sys.stdout = sys.__stdout__ Aargh, I can't believe how widespread this idiom is :-(. See my other reply in this thread: DON'T use sys.__stdout__. Ever. Just From ncoghlan at iinet.net.au Fri Jan 28 20:31:28 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 29 Jan 2005 11:31:28 +1000 Subject: limited python virtual machine In-Reply-To: <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> Message-ID: <41FAE770.50806@iinet.net.au> Alex Martelli wrote: > Steven Bethard wrote: > ... > >>If I could see how to go from 'object' (or 'int', 'str', 'file', etc.) >>to 'eval' or '__import__', that would help out a lot... > > >>>>object.__subclasses__() > > [, , , , > , , , 'module'>, , , > , , , 'site._Printer'>, , , ] > > Traipse through these, find one class that has an unbound method, get > that unbound method's func_globals, bingo. So long as any Python modules are imported using the same restricted environment their func_globals won't contain eval() or __import__ either. And C methods don't have func_globals at all. However, we're talking about building a custom interpreter here, so there's no reason not to simply find the dangerous functions at the C-level and replace their bodies with "PyErr_SetString(PyExc_Exception, "Access to this operation not allowed in restricted build"); return NULL;". Then it doesn't matter *how* you get hold of file(), it still won't work. (I can hear the capabilities folks screaming already. . .) Combine that with a pre-populated read-only sys.modules and a restricted custom interpreter would be quite doable. Execute it in a separate process and things should be fairly solid. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From matternc at comcast.net Sun Jan 30 10:00:42 2005 From: matternc at comcast.net (Chris Mattern) Date: Sun, 30 Jan 2005 10:00:42 -0500 Subject: [perl-python] sending email References: <1107041765.890014.112530@c13g2000cwb.googlegroups.com> Message-ID: YYusenet wrote: > Xah Lee wrote: > [snip] >> >> The first two has glaring problems. I'm sorry i forgot what they > ^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^ >> are. > ^^^^ > [snip] > > How can you complain about *Mail::Mailer* and *Mail::Send* when you > don't even know what they are? > You know, I started to make fun of that, but then decided there was nothing I could say that it doesn't say for itself. -- Christopher Mattern "Which one you figure tracked us?" "The ugly one, sir." "...Could you be more specific?" From alipolatel at yahoo.com Sun Jan 23 13:28:47 2005 From: alipolatel at yahoo.com (Ali Polatel) Date: Sun, 23 Jan 2005 10:28:47 -0800 (PST) Subject: on the way to find pi! Message-ID: <20050123182847.74790.qmail@web61009.mail.yahoo.com> dear friends , I found a code which calculates pi with an interesting algorithm the programme code is below: from sys import stdout def f((q,r,t,k)): n = (3*q+r) / t if (4*q+r) / t == n: return (10*q,10*(r-n*t),t,k,n) else: return (q*k, q*(4*k+2)+r*(2*k+1),t*(2*k+1),k+1) # Call pi(20) for first 20 digits, or pi() for all digits def pi(n=-1): printed_decimal = False r = f((1,0,1,1)) while n != 0: if len(r) == 5: stdout.write(str(r[4])) if not printed_decimal: stdout.write('.') printed_decimal = True n -= 1 r = f(r[:4]) #stdout.write('\n') if __name__ == '__main__': from sys import argv try: digit_count = long(argv[1]) except: digit_count=int(raw_input('How many digits? :')) pi(digit_count) This code gives the number in an unusual format like "3.1415'None'" it has a number part and a string part . I want to seperate these from easc other but I couldn't manage. I mean when I try to turn it into string format then try to use things like [:4] or like that they don't work.Any idea how to seperate this 'None' from the number and make it a real normal number on which I can do operations like +1 -1 or like that :) Regards __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From info at frengky.no Sun Jan 9 13:15:38 2005 From: info at frengky.no (Øystein Western) Date: Sun, 9 Jan 2005 19:15:38 +0100 Subject: read numbers from file and covert to integer Message-ID: I got a file with a lot blocks of numbers that are strings. I'd like to read all this numbers and convert them to numbers for futher compareation. How can I convert all this numbers to integer? Do I have to put all numbers into a list? regards frengky -- Organisation nr: 983063349 Frengky, Olsokveien 65,1727 Sarpsborg, Norway Tel: +47 92611725 Fax: +47 69152017 Email: oystein.western at frengky.no Web: www.frengky.no From __peter__ at web.de Mon Jan 31 03:09:34 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 31 Jan 2005 09:09:34 +0100 Subject: variable declaration References: Message-ID: Alexander Zatvornitskiy wrote: > epsilon=0 > S=0 > while epsilon<10: > S=S+epsilon > epselon=epsilon+1 > print S > > It will print zero, and it is not easy to find such a bug! pychecker may help you find misspelled variable names. You have to move the code into a function, though: $ cat epsilon.py def loop(): epsilon=0 S=0 while epsilon<10: S=S+epsilon epselon=epsilon+1 print S $ pychecker epsilon.py Processing epsilon... Warnings... epsilon.py:6: Local variable (epselon) not used Peter From bokr at oz.net Thu Jan 13 00:18:57 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 05:18:57 GMT Subject: Refactoring; arbitrary expression in lists References: <41e5cb07.701137402@news.oz.net> Message-ID: <41e5fdce.714136143@news.oz.net> On Thu, 13 Jan 2005 12:19:06 +1000, Stephen Thorne wrote: >On Thu, 13 Jan 2005 01:24:29 GMT, Bengt Richter wrote: >> extensiondict = dict( >> php = 'application/x-php', >> cpp = 'text/x-c-src', >> # etcetera >> xsl = 'test/xsl' >> ) >> >> def detectMimeType(filename): >> extension = os.path.splitext(filename)[1].replace('.', '') extension = os.path.splitext(filename)[1].replace('.', '').lower() # better >> try: return extensiondict[extension] >> except KeyError: >> basename = os.path.basename(filename) >> if "Makefile" in basename: return 'text/x-makefile' # XXX case sensitivity? >> raise NoMimeError > >Why not use a regexp based approach. ISTM the dict setup closely reflects the OP's if/elif tests and makes for an efficient substitute for the functionality when later used for lookup. The regex list is O(n) and the regexes themselves are at least that, so I don't see a benefit. If you are going to loop through extensionlist, you might as well write (untested) flowerew = filename.lower().endswith for ext, mimetype: if flowerew(ext): return mimetype else: if 'makefile' in filename.lower(): return 'text/x-makefile' raise NoMimeError using a lower case extension list including the dot. I think it would run faster than a regex, and not scare anyone unnecessarily ;-) The dict eliminates the loop, and is easy to understand, so IMO it's a better choice. >extensionlist = [ >(re.compile(r'.*\.php') , "application/x-crap-language"), >(re.compile(r'.*\.(cpp|c)') , 'text/x-c-src'), >(re.compile(r'[Mm]akefile') , 'text/x-makefile'), >] >for regexp, mimetype in extensionlist: > if regexp.match(filename): > return mimetype > >if you were really concerned about efficiency, you could use something like: >class SimpleMatch: > def __init__(self, pattern): self.pattern = pattern > def match(self, subject): return subject[-len(self.pattern):] == self.pattern I'm not clear on what you are doing here, but if you think you are going to compete with the timbot's dict efficiency with a casual few lines, I suspect you are PUI ;-) (Posting Under the Influence ;-) Regards, Bengt Richter From orjang at gondolin.umunet.org Tue Jan 25 10:58:08 2005 From: orjang at gondolin.umunet.org (=?ISO-8859-1?Q?=D6rjan_Gustavsson?=) Date: Tue, 25 Jan 2005 16:58:08 +0100 Subject: pylibpcap and multiple threads In-Reply-To: <864d3709050124181928c9046a@mail.gmail.com> References: <864d3709050124181928c9046a@mail.gmail.com> Message-ID: Hi Carlos, I looked in the source code for pylibpcap, and it does not release the GIL, hence my problem. I found a solution though, the pcap object has a fileno member so I could use select to wait for a packet, then call loop without blocking. Problem solved! :) And since it is only a thin wrapper over the pcap library it (seems to be) ok to open multiple instances of pcap, at least so long the different istances does select a separate interface. At least it works for me now! And thank you for the link to http://libdnet.sourceforge.net it solved my next problem to send raw packets from python. /?rjan Gustavsson Carlos Ribeiro wrote: > On Mon, 24 Jan 2005 15:18:39 +0100, ?rjan Gustavsson > wrote: > >>Hi All! >> >>Sorry if this is not the correct forum for this kind of question (I did >>not find any pylibpcap related lists). >> >>I am trying to use pylibpcap to capture network traffic from several >>ethernet devices at the same time, each nic having a separate thread >>assigned to it. >> >>My problem is that when one thread is blocking inside pcap.loop() for >>instance, it seems to have acquired the GIL, so that no other threads >>can run. >> >>Does anyone know a way to do this with threads, or is the only way to >>have separate processes for each NIC? > > >>From the top of my head, and without any test. I did use libpcap for > some stuff recently. loop() is the primitive that keeps reading and > calls the callback, right? I believe that it should release the GIL in > the C wrapper code, right before calling the libpcap loop > implementation, and re-acquire it before calling the callback. There > is a standard way to do it, that is used before blocking calls are > issued (file writing, for example). If it fails to release the GIL it > will block. > > I'm also not sure if the libpcap itself is supposed to be used this > way - with multiple instances - but I assume that it should work (I > never tried to open several instances of tcpdump at the same time). > > Also, check these links also, as they may be helpful to you: > > http://libdnet.sourceforge.net/ > http://oss.coresecurity.com/projects/pcapy.html > From apardon at forel.vub.ac.be Tue Jan 18 07:04:48 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Jan 2005 12:04:48 GMT Subject: lambda References: <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-18, Simon Brunning schreef : > On 18 Jan 2005 07:51:00 GMT, Antoon Pardon wrote: >> 3 mutating an item in a sorted list *does* *always* cause problems > > No, it doesn't. It might cause the list no longer to be sorted, but > that might or might no be a problem. Than in the same vain I can say that mutating a key in a dictionary doesn't always cause problems either. Sure it may probably make a key unaccessible directly, but that might or might not be a problem. >> More specific the Decimal class is mutable and usable as dict key. > > Decimal objects are immutable, so far as I know. > >>>> from decimal import Decimal >>>> spam = Decimal('1.2') >>>> eggs = spam >>>> eggs is spam > True >>>> eggs += 1 >>>> eggs is spam > False > >>> from decimal import Decimal >>> spam = Decimal('1.2') >>> egg = spam >>> spam._int = (1, 3) >>> spam Decimal("1.3") >>> spam is egg True -- Antoon Pardon From google_groups_usa at yahoo.com Sun Jan 23 11:35:35 2005 From: google_groups_usa at yahoo.com (google_groups_usa at yahoo.com) Date: 23 Jan 2005 08:35:35 -0800 Subject: Have you heard the GOOD NEWS? Message-ID: <1106498135.037805.29930@c13g2000cwb.googlegroups.com> http://www3.boxke.net << click link for the good news From sjmachin at lexicon.net Tue Jan 25 17:47:09 2005 From: sjmachin at lexicon.net (John Machin) Date: Wed, 26 Jan 2005 09:47:09 +1100 Subject: How to input one char at a time from stdin? References: Message-ID: On Wed, 26 Jan 2005 01:15:10 +0530, Swaroop C H wrote: >On Tue, 25 Jan 2005 12:38:13 -0700, Brent W. Hughes > wrote: >> I'd like to get a character from stdin, perform some action, get another >> character, etc. If I just use stdin.read(1), it waits until I finish typing >> a whole line before I can get the first character. How do I deal with this? > >This is exactly what you need: >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 >Title: "getch()-like unbuffered character reading from stdin on both >Windows and Unix" Nice to know how, but all those double underscores made my eyes bleed. Three classes? What's wrong with something simple like the following (not tested on Unix)? import sys bims = sys.builtin_module_names if 'msvcrt' in bims: # Windows from msvcrt import getch elif 'termios' in bims: # Unix import tty, termios def getch(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch else: raise NotImplementedError, '... fill in Mac Carbon code here' From drs at remove-to-send-mail-ecpsoftware.com Wed Jan 12 13:02:54 2005 From: drs at remove-to-send-mail-ecpsoftware.com (drs) Date: Wed, 12 Jan 2005 18:02:54 GMT Subject: Newbie: Pythonwin References: Message-ID: "Brent W. Hughes" wrote in message news:B_SdndbY0-_w0nncRVn-3A at comcast.com... > 1) I'm running a program within Pythonwin. It's taking too long and I want > to stop/kill it. What do I do (other than ctrl-alt-del)? > Right click on the little python icon in the sys tray and select break into running code From jfj at freemail.gr Fri Jan 28 01:49:37 2005 From: jfj at freemail.gr (jfj) Date: Thu, 27 Jan 2005 22:49:37 -0800 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: <41F9E081.6050008@freemail.gr> Francis Girard wrote: > Wow ! What is it that are compared ? I think it's the references (i.e. the > adresses) that are compared. The "None" reference may map to the physical 0x0 > adress whereas 100 is internally interpreted as an object for which the > reference (i.e. address) exists and therefore greater than 0x0. > > Am I interpreting correctly ? > > Not really. If objects of different types are compared (like compare a string with a list), then no matter what, all strings but be "smaller" than all lists. Or the oposite. So the fast way to accomplish this is to compare the addresses of the object's method table. Something which is common for all objects of the same type. G. From skullw at sina.com.cn Sat Jan 15 19:48:31 2005 From: skullw at sina.com.cn (skull) Date: Sat, 15 Jan 2005 19:48:31 -0500 Subject: How to del item of a list in loop? References: Message-ID: skull writes: Thank you for your replys. lst[:] is did a solution, it makes a copy of list specially for iteration and removes items from the original one. but I still have an other thing to worry about coming with this way: does performance sucks when the list is big enough? It makes a copy operation! here is a faster and 'ugly' solution: lst = [1, 2, 3] i = 0 while i < len(lst): if lst[i] == 2: lst.remove(i) else: i += 1 > Hi everybody, it is my first post in this newsgroup. > I am a newbie for python though I have several years development experience in c++. > recently, I was stumped when I tried to del item of a list when iteration. > > here is the wrong way I did: > > lst = [1, 2, 3] > for i in lst: > print i > if i == 2: > lst.remove(i) > > the result is: > > 1 > 2 >>>> > > as you would see, '3' is missing. this problem is caused by 'lst.remove(i)'. > apparently, 'marked-and-sweep' is a solution to deal with this issue. > but I think there SHOULD BE more 'wise' trick. I want to get your help. > > Thanks in advance. > > - skull From grante at visi.com Tue Jan 18 14:18:17 2005 From: grante at visi.com (Grant Edwards) Date: 18 Jan 2005 19:18:17 GMT Subject: hex notation funtion References: Message-ID: <41ed60f9$0$29427$a1866201@visi.com> On 2005-01-18, tertius wrote: > Is there a builtin function that will enable me to display the hex > notation of a given binary string? (example below) ' '.join('%02x' % ord(b) for b in s) -- Grant Edwards grante Yow! This is a NO-FRILLS at flight -- hold th' CANADIAN visi.com BACON!! From xah at xahlee.org Mon Jan 17 12:38:36 2005 From: xah at xahlee.org (Xah Lee) Date: 17 Jan 2005 09:38:36 -0800 Subject: [perl-python] 20050116 defining a function In-Reply-To: <1105886753.149519.194980@z14g2000cwz.googlegroups.com> References: <1105886753.149519.194980@z14g2000cwz.googlegroups.com> Message-ID: <1105983516.736238.314050@f14g2000cwb.googlegroups.com> errata: * the variables in the perl section should be declared inside the subroutine. * the @_[0] should've been $_[0] thanks for Dave Cross for pointing them out. * the Mathematica Apply should be Select... Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From tjreedy at udel.edu Fri Jan 14 12:05:31 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Jan 2005 12:05:31 -0500 Subject: how to stop google from messing Python code References: <1105620098.878376.110250@z14g2000cwz.googlegroups.com><1105666406.272397.170730@c13g2000cwb.googlegroups.com> <1105704548.146263.229220@f14g2000cwb.googlegroups.com> Message-ID: "Fuzzyman" wrote in message news:1105704548.146263.229220 at f14g2000cwb.googlegroups.com... > > Xah Lee wrote: >> gmane is great! > I guess that most people use google to post to newsgroups is that they > don't have nntp access. Anyone with a normal internet connection has nntp access. What some do not get from their ISP is 'free' access to a full newsite, and they may not feel like paying extra $$ to one when they can get free access to non-binary groups via Google that is better in regards to retention and search, Google just happens to not work well for posting Python code. What most of those people may not know is that there is free access to a restricted news site (gmane) which mirrors a large number of mailing lists, one of which is the Python mailing list, which mirrors the Python newsgroup. So I help them by giving them this information. Xah Lee used the information I shared, as have many other people, and even, in effect, thanked me for doing so. Gmane also gives a Pythoneer easy access to about 50 specialized Python-related mailing lists (and 1000s not related to Python). > Telling htem to use a newsreader is facetious and unhelpful. Telling someone to stop sharing sharing useful information is nasty and unhelpful. You owe me an apology. Terry J. Reedy From ian at kirbyfooty.com Tue Jan 4 00:29:51 2005 From: ian at kirbyfooty.com (ian at kirbyfooty.com) Date: 3 Jan 2005 21:29:51 -0800 Subject: ctypes NULL pointers; was: Python To Send Emails Via Outlook Express References: <41d8f228$0$2742$8fcfb975@news.wanadoo.fr> Message-ID: <1104816591.567668.212260@z14g2000cwz.googlegroups.com> Hi Lenard Hopefully I have understood you properly. The updated script is now as follows, or you can download it from http://www.kirbyfooty.com/simplemapi.py Thanks again for all your help!!! Kindest regards Ian Cook -------------------------------------------------------------------------- import os from ctypes import * FLAGS = c_ulong LHANDLE = c_ulong LPLHANDLE = POINTER(LHANDLE) # Return codes SUCCESS_SUCCESS = 0 # Recipient class MAPI_ORIG = 0 MAPI_TO = 1 class STRUCT(Structure): _fields_ = [('voidptr', c_void_p)] #NULL = c_void_p(None) NULL=STRUCT( None ) # Create an instance with voidptr field NULL class MapiRecipDesc(Structure): _fields_ = [('ulReserved', c_ulong), ('ulRecipClass', c_ulong), ('lpszName', c_char_p), ('lpszAddress', c_char_p), ('ulEIDSize', c_ulong), ('lpEntryID', c_void_p), ] lpMapiRecipDesc = POINTER(MapiRecipDesc) class MapiFileDesc(Structure): _fields_ = [('ulReserved', c_ulong), ('flFlags', c_ulong), ('nPosition', c_ulong), ('lpszPathName', c_char_p), ('lpszFileName', c_char_p), ('lpFileType', c_void_p), ] lpMapiFileDesc = POINTER(MapiFileDesc) class MapiMessage(Structure): _fields_ = [('ulReserved', c_ulong), ('lpszSubject', c_char_p), ('lpszNoteText', c_char_p), ('lpszMessageType', c_char_p), ('lpszDateReceived', c_char_p), ('lpszConversationID', c_char_p), ('flFlags', FLAGS), ('lpOriginator', lpMapiRecipDesc), # ignored? ('nRecipCount', c_ulong), ('lpRecips', lpMapiRecipDesc), ('nFileCount', c_ulong), ('lpFiles', lpMapiFileDesc), ] lpMapiMessage = POINTER(MapiMessage) MAPI = windll.mapi32 MAPISendMail=MAPI.MAPISendMail MAPISendMail.restype = c_ulong # Error code MAPISendMail.argtypes = (LHANDLE, # lhSession c_ulong, # ulUIParam lpMapiMessage, # lpMessage FLAGS, # lpFlags c_ulong, # ulReserved ) def SendMail(recipient, subject, body, attachfiles): """Post an e-mail message using Simple MAPI Special thanks to Lenard Lindstrom! recipient - string: address to send to (multiple address sperated with a semicolin) subject - string: subject header body - string: message text attach - string: files to attach (multiple attachments sperated with a semicolin) Example usage import simplemapi simplemapi.SendMail("to1address at server.com;to2address at server.com","My Subject","My message body","c:\attachment1.txt;c:\attchment2") """ # get list of file attachments attach = [] AttachWork = attachfiles.split(';') #verify the attachment file exists for file in AttachWork: if os.path.exists(file): attach.append(file) attach = map( os.path.abspath, attach ) nFileCount = len(attach) if attach: MapiFileDesc_A = MapiFileDesc * len(attach) fda = MapiFileDesc_A() for fd, fa in zip(fda, attach): fd.ulReserved = 0 fd.flFlags = 0 fd.nPosition = -1 fd.lpszPathName = fa fd.lpszFileName = None fd.lpFileType = None lpFiles = fda else: # No attachments lpFiles = cast(NULL, lpMapiFileDesc) # Make NULL # Get the number of recipients RecipWork = recipient.split(';') RecipCnt = len(RecipWork) # Formulate the recipients MapiRecipDesc_A = MapiRecipDesc * len(RecipWork) rda = MapiRecipDesc_A() for rd, ra in zip(rda, RecipWork): rd.ulReserved = 0 rd.ulRecipClass = MAPI_TO rd.lpszName = None rd.lpszAddress = ra rd.ulEIDSize = 0 rd.lpEntryID = None recip = rda # send the message msg = MapiMessage(0, subject, body, None, None, None, 0, cast(NULL, lpMapiRecipDesc), RecipCnt, recip, nFileCount, lpFiles) rc = MAPISendMail(0, 0, byref(msg), 0, 0) if rc != SUCCESS_SUCCESS: raise WindowsError, "MAPI error %i" % rc -------------------------------------------------------------------------------- From jdhunter at ace.bsd.uchicago.edu Wed Jan 26 23:28:10 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 26 Jan 2005 22:28:10 -0600 Subject: python without OO In-Reply-To: <1106798140.896125.187850@f14g2000cwb.googlegroups.com> (beliavsky@aol.com's message of "26 Jan 2005 19:55:40 -0800") References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> <1106798140.896125.187850@f14g2000cwb.googlegroups.com> Message-ID: >>>>> "beliavsky" == beliavsky writes: beliavsky> I think the OO way is slightly more obscure. It's beliavsky> obvious what x = reverse(x) does, but it is not clear beliavsky> unless you have the source code whether x.reverse() You don't need to read the src, you just need to read the docs >>> help([].reverse) Help on built-in function reverse: reverse(...) L.reverse() -- reverse *IN PLACE* beliavsky> reverses x or if it returns a reversed list. If beliavsky> x.reverse() does the former, a disadvantage relative to beliavsky> the procedural approach is that a function can be used beliavsky> in an expression. It is clearer and more concise to beliavsky> write beliavsky> z = reverse(x) + reverse(y) The distinction is not OO versus procedural, it is a decision about how you choose to write "reverse". The python list implementers of the reverse object method could have decided to return a new reversed list rather than do the reverse in place and return None. Then you could have done z = x.reverse() + y.reverse() They could have chosen to reverse the list *in place* and also returned a reference to self rather than None, in which case you could do the above as well. w/o digging up the transcripts from the python-dev mailing list, my guess is that they choose to do it in place for efficiency in memory and cpu, and chose not to return self to prevent user confusion. Ie, if a user was allowed to do 'z = x.reverse() + y.reverse()' they might be surprised to find the side effect of in place modification. Likewise, I could easily write a procedural "in place" reverse that returns None, in which case 'z = reverse(x) + reverse(y)' would not do what you suggest. My point is that whether a function/method such as reverse operates in place or on a copy, and whether it returns None or a reference to a list is independent of OO vs procedural style and is motivated by considerations of efficiency, readability, and usability. beliavsky> Furthermore, if in Python the algorithm for the reverse beliavsky> function applies to many kinds of objects, it just beliavsky> needs to be coded once, whereas a reverse method would beliavsky> have to provided for each class that uses it (perhaps beliavsky> through inheritance). True, a generic reverse procedure/function can be applied to any data structure that supports iteration. In the case of python, however, some iterable data structures are mutable (lists, dicts) and some are not (strings, tuples). For mutable sequences, an in place reverse is likely to be more efficient in memory and perhaps CPU than a generic reverse which returns a new copy. So a specialized method "reverse" applicable to lists (but not strings and tuples) can be a big win. Fortunately, python supports both, allowing you to define a general "reverse" that works for any object that supports the sequence protocol, as well as to define an object specific reverse method that may be faster in time and space. JDH From strombrg at dcs.nac.uci.edu Wed Jan 12 00:20:35 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Tue, 11 Jan 2005 21:20:35 -0800 Subject: Checking for X availability References: Message-ID: On Tue, 11 Jan 2005 03:32:01 -0800, Flavio codeco coelho wrote: > I have a program that uses pythondialog for its UI. > > Pythondialog is a wrapper of the shell dialog and xdialog libs. > > But I would like for it to switch between using Dialog ( when X is not > available ) and xdialog (when X is available) > > So my question is: how can I check for the availability of X? i.e., > How will my program know if its running in a text only console or in > console window over X? > > thanks, > > Fl?vio If there's interest, I could make available my "pdialog" module, which is also a wrapper around *dialog, but uses X when available, and curses when it is not. From iketo2 at netscape.net Thu Jan 27 01:05:31 2005 From: iketo2 at netscape.net (Isaac To) Date: 27 Jan 2005 14:05:31 +0800 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> <1106798140.896125.187850@f14g2000cwb.googlegroups.com> Message-ID: <87llaf8l04.fsf@sinken.local.csis.hku.hk> >>>>> "beliavsky" == beliavsky writes: beliavsky> I think the OO way is slightly more obscure. It's beliavsky> obvious what x = reverse(x) does, but it is not clear beliavsky> unless you have the source code whether x.reverse() beliavsky> reverses x or if it returns a reversed list. What make it so clear to you that reverse(x) will always return a reversed list rather than reversing x in place and return nothing? beliavsky> It is clearer and more concise to write beliavsky> z = reverse(x) + reverse(y) beliavsky> than beliavsky> x.reverse() beliavsky> y.reverse() beliavsky> z = x + y This isn't anything to do with OO programming. It is something about using in interface that your audience expects. You have exactly the same problem whether you are using procedural or OO style. It might be a case for functional programming, but that's something off-topic. beliavsky> Furthermore, if in Python the algorithm for the reverse beliavsky> function applies to many kinds of objects, it just beliavsky> needs to be coded once, whereas a reverse method would beliavsky> have to provided for each class that uses it (perhaps beliavsky> through inheritance). That the reverse() wants to be a function doesn't mean that the thing that reverse() operate on doesn't want to be an object. So this isn't very clear a problem about OO style vs. procedural style, but instead a problem about "generic" programming style vs. "concrete" programming style. On the other hand, if the thing that reverse() operate on isn't an object sharing the same interface, it will be more clumsy to implement a generic reverse() that works for all the different kinds of object---even if they share similar interfaces. Try to implement a generic "reverse" in C when the different type of containers are encoded as different style struct's accessible from different function, and you will understand what I mean. So this is, marginally, a case *for* OO style. Regards, Isaac. From ncoghlan at iinet.net.au Sat Jan 8 03:30:25 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 18:30:25 +1000 Subject: python3: accessing the result of 'if' In-Reply-To: <1105169372.800346.298830@f14g2000cwb.googlegroups.com> References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> Message-ID: <41DF9A21.2000907@iinet.net.au> Carl Banks wrote: > Right. But you know that as soon as you add this to simple > expressions, a bunch of people are going to come here whining about how > they don't get to use where with if-expressions. > > Frankly, they might have a point here. Although we have replacing > lambda expressions on our minds, I have in mind a different problem > that a where-statement would solve perfectly. But it would have to be > used with an if-expression. I have a different suggestion for this. 'as' is used for renaming in import statements. 'as' will be used for exception naming in Python 3k. So let's use it for expression naming in 'if' statements, too. if someregexp.match(s) as m: # blah using m elif someotherregexp.match(s) as m: # blah using m Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From michele.simionato at gmail.com Sat Jan 8 02:04:26 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 7 Jan 2005 23:04:26 -0800 Subject: python3: 'where' keyword In-Reply-To: <7xmzvl0vzy.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <7xmzvl0vzy.fsf@ruckus.brouhaha.com> Message-ID: <1105167866.412240.243980@f14g2000cwb.googlegroups.com> > But we're talking about the mythical/hypothetical Python 3, so maybe > there's a chance of fixing the scoping rules, which it seems to me are > currently pretty badly broken. I don't think the current scoping rules will be changed in Python 3.0. I can't give you the link right now, but there are threads about the scope rules in python-dev, with various people protesting and Guido saying that he wants to keep them as they are. Michele Simionato From psimmo60 at hotmail.com Mon Jan 17 21:42:57 2005 From: psimmo60 at hotmail.com (Paul Simmonds) Date: 17 Jan 2005 18:42:57 -0800 Subject: dynamic data types References: <1105969253.296411.301760@f14g2000cwb.googlegroups.com> Message-ID: <1106016177.518013.138980@c13g2000cwb.googlegroups.com> I would assume that they're refering to the fact that even the basic data types such as int are derived from object, and hence have methods: >>> int.__class__.__base__ Java, for example, has both an Integer object and a basic int data type. One word. Yuck. Paul S. From esj at harvee.org Tue Jan 18 11:00:44 2005 From: esj at harvee.org (Eric S. Johansson) Date: Tue, 18 Jan 2005 11:00:44 -0500 Subject: how to find site-packages path In-Reply-To: References: Message-ID: Michael Hoffman wrote: > Philippe C. Martin wrote: > >> I am using my own install script for my software and am looking for a >> flawless way to figure out where python, and more specifically >> site-packages is installed. > > > The flawless way would be to use distutils. In fact you shouldn't even > need your own install script--it should do most of the work for you. can distutils install in any directory? for example, an application which has its own modules should be completely isolated from the general Python module namespace. how would you make distutils install in a completely separate directory hierarchy and not touch any of the site-packages directories or files? it looked like that was impossible from the documentation which is why I wrote my own installer. ---eric From devries at idolstarastronomer.com Wed Jan 12 10:34:19 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: 12 Jan 2005 07:34:19 -0800 Subject: distutils linux script installation broken? References: <1105535625.443343.326560@z14g2000cwz.googlegroups.com> Message-ID: <1105544059.595961.157780@c13g2000cwb.googlegroups.com> I've got python 2.3.3, 2.4, and 1.5.2 (which came preinstalled) on my linux box. It's redhat 7.2 (I know... I would upgrade, but it would void my service contract, so I just install things in /usr/local). You can check if PYTHONHOME or PYTHONPATH are set, which may somehow be interfering. I don't have those variables set. If they are set, you could try running: python -E setup.py install The -E option should make python ignore those environment variables. Good luck, I hope this helps. Chris From steve at holdenweb.com Mon Jan 3 19:14:54 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Jan 2005 19:14:54 -0500 Subject: input record sepArator (equivalent of "$|" of perl) In-Reply-To: References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> <1103657476.495700.191020@f14g2000cwb.googlegroups.com> <1103671235.093738.198680@z14g2000cwz.googlegroups.com> <86wtuup21t.fsf@guru.mired.org> Message-ID: Andrew Dalke wrote: > Mike Meyer: > >>Trivia question: Name the second most powerfull country on earth not >>using the metric system for everything. > > > The UK? > > Before going there I thought they were a fully metric country. > But I saw weather reports in degrees F, distances in yards > and miles, and of course pints of beer. > > Andrew > dalke at dalkescientific.com > Plus the builders quite routinely ask suppliers for things like "a meter of two (inches) by four (inches)". They don;t care that they're getting the closest metric equivalent, to them a 2 x 4 is still a 2 x 4. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From steve at holdenweb.com Mon Jan 17 06:19:52 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 06:19:52 -0500 Subject: import problems *newbie* In-Reply-To: <1105924229.092194.326610@f14g2000cwb.googlegroups.com> References: <1105682316.601321.118820@f14g2000cwb.googlegroups.com> <41e7959b$0$385$636a15ce@news.free.fr> <1105919586.453157.42550@c13g2000cwb.googlegroups.com> <1105924229.092194.326610@f14g2000cwb.googlegroups.com> Message-ID: <41EB9F58.3040801@holdenweb.com> Grig Gheorghiu wrote: > In my experience (as a tester), it is easier to deal with PYTHONPATH > than to add the my.pth file to the site-packages directory. The main > reason is that I have my custom packages and modules in a directory > tree that I deploy on many clients/servers/platforms/OS versions, some > running different versions of Python. I found that I solve my import > problems by adding one line to .bash_profile, which sets PYTHONPATH to > the parent directory of my custom directory tree. Or, on Windows, I add > an Environment variable, call it PYTHONPATH, and set it to the > necessary directory. The alternative would be to hunt for the > site-packages directory (of which there might be several) on all my > systems. > > I guess it's a matter of taste in the end, but I do find the PYTHONPATH > approach more suitable for automation and scripting, particularly when > dealing with a large number of systems. > > Grig > In the long term it doesn't really matter: the fact that my suggestion to use a .pth file worked does leave me still wondering why a PYTHONPATH setting didn't. The advantage of using a .pth file *in the site-packages directory* is that it only applies to the version that picks up that site-packages directory, while PYTHONPATH applies to any Python you happen to run. In the case of libraries this will lead to recompilation of the bytecode (.pyc) files each time a different-version interpreter is used to run the program. Unless Skip Montanaro's ideas about directing bytecode files to specific locations are picked up, it would seem like a good idea to point out the desirability of using separate copies of Python module sources for different interpreters. Anyway Mike, I'm glad you have a reliable solution to your problem. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From ianb at colorstudy.com Sun Jan 2 21:50:58 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Sun, 02 Jan 2005 20:50:58 -0600 Subject: Continuations Based Web Framework - Seaside. In-Reply-To: References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <7aTBd.11928$H%6.521997@twister1.libero.it> Message-ID: <41D8B312.9080903@colorstudy.com> Steve Holden wrote: > I did actually do some sort-of-related work in this area, which I > presented at PyCon DC 2004 - you can access the paper at > > http://www.python.org/pycon/dc2004/papers/18/Setting_A_Context.pdf > > An audience member mentioned the Smalltalk and Scheme-based work on web > continuation frameworks, and I was sorry my answer at the time seemed > unduly dismissive. There are some interesting similarities, and though > my own implementation is decidedly clunky I like to think the paper > explains some of the advantages of maintaining state and why the "back" > button is an obnoxious anachronism :-) I think the technique you talked about is an easier way to achieve a similar goal as the continuation-based frameworks. While using continuations for web applications is an interesting idea, I don't think it's been shown to be successful. It's certainly not something I'd want to implement on Python (even given the actual features to make it possible), and from what I've read of the Ruby projects that use it (Borges and Wee?), they aren't ready to implement production applications either. The technique you present could be implemented on any framework, right now, with the expectation that it would work in a production situation. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From deetsNOSPAM at web.de Mon Jan 31 12:28:34 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 31 Jan 2005 18:28:34 +0100 Subject: variable declaration References: <1107188359.375703.110590@f14g2000cwb.googlegroups.com> <1107190028.911373.158940@z14g2000cwz.googlegroups.com> Message-ID: <367816F4t92dfU1@individual.net> > A decorator is a modifier to a subsequent binding, and it modifies the > reference and not the referent. So how is it anythng but declarative? I learned the hard way that it still is simply interpreted - its a pretty straight forward syntactic sugaring, as this shows: foo = classmethod(foo) becomes: @classmethod Now @classmethod has to return a callable that gets passed foo, and the result is assigned to foo - not more, not less, so it becomes equivalent to the older type of creating a class method. Is this a declaration? I'd personally say and think "practically, yes", as I also view class Bar: .... as a declaration. But obviously some people like Alex Martelli have different views on this (and are right), because you can do this in python: if condition: class Foo: def bar(self): pass else: class Foo: def schnarz(self): pass So that makes class statements not as declarative as they are in languages like java. So to sum it up (for me at least): things like metaclasses, decorators and so on make me write code more declarative - if they are a declaration in the strict sense, I don't bother. -- Regards, Diez B. Roggisch From ed at leafe.com Thu Jan 27 20:23:45 2005 From: ed at leafe.com (Ed Leafe) Date: Thu, 27 Jan 2005 20:23:45 -0500 Subject: Tkinter vs wxPython In-Reply-To: <2814F26DA6908F41927A81C410C4991A02079C77@siamun.server.bl.corp.intranet> References: <2814F26DA6908F41927A81C410C4991A02079C77@siamun.server.bl.corp.intranet> Message-ID: On Jan 27, 2005, at 12:17 PM, Gabriel Cosentino de Barros wrote: > Now going back on topic: A think that neighter Tk nor wxWindow is a > good choice for python. They both suck much of it when it came to > abstraction. They're still better than glade or gtk. But could improve > a lot. wxWindow has simple an ugly API, and Tk has a huge sin in the > syntax to pass actions to the buttons. I agree with that assessment, although I preferred wxPython over Tk. One of the fundamental design goals of the Dabo framework is to wrap the UI toolkits to hide all that ugliness, and present a uniform, simple API for all the UI controls. We are using wxPython initially as our UI toolkit of choice, but the long-term plan is to wrap Tk, too, so that the interface to both is the same. IOW, the same app code will work with wxPython or Tk. That's a lofty goal, but one that I think is essential to bring Python UI development up to level available to other languages. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From dalke at dalkescientific.com Sun Jan 9 13:11:41 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sun, 09 Jan 2005 18:11:41 GMT Subject: Pre/Postconditions with decorators References: <1105094828.619317.315340@z14g2000cwz.googlegroups.com> <34814fF43bm4cU1@individual.net> <7x1xcvwkdj.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > [Type checking] should be left on. Leaving it in for development > and turning it off for production is like wearing a parachute > during ground training and taking it off once you're in the air. Why isn't it like practicing the trapeze with a net but going without a net when performing for a big circus? Why isn't it like using training wheels when learning to ride bicycle but getting rid of them once you've got the idea down? Or like using a map when you get to a new city but gradually stop as you know the place? Fighting analogies with analogies :) Andrew dalke at dalkescientific.com From sese at 263.net Mon Jan 3 00:03:17 2005 From: sese at 263.net (SeSe) Date: Mon, 03 Jan 2005 13:03:17 +0800 Subject: [Twisted-Python] Problem with Echoserver (TCP), Help! Message-ID: Hi, I am new to Twisted. I use a Twisted 1.3.0 on MS Windows XP Home Edition, my python version is 2.3 I try the TCP echoserv.py and echoclient.py example. But the client always fail with following message: Unhandled error in Deferred: Traceback (most recent call last): File "D:\PYTHON23\Lib\site-packages\twisted\internet\default.py", line 134, in mainLoop self.runUntilCurrent() File "D:\PYTHON23\Lib\site-packages\twisted\internet\base.py", line 423, in ru nUntilCurrent call.func(*call.args, **call.kw) File "D:\PYTHON23\Lib\site-packages\twisted\internet\tcp.py", line 384, in res olveAddress d.addCallbacks(self._setRealAddress, self.failIfNotConnected) File "D:\PYTHON23\Lib\site-packages\twisted\internet\defer.py", line 205, in a ddCallbacks self._runCallbacks() --- --- File "D:\PYTHON23\Lib\site-packages\twisted\internet\defer.py", line 338, in _ runCallbacks self.result = callback(self.result, *args, **kw) File "D:\PYTHON23\Lib\site-packages\twisted\internet\tcp.py", line 388, in _se tRealAddress self.doConnect() File "D:\PYTHON23\Lib\site-packages\twisted\internet\tcp.py", line 403, in doConnect r, w, e = select.select([], [], [self.fileno()], 0.0) select.error: (10022, '') What is the matter? Thanks. -SeSe From rickard.lind at ntier.se Mon Jan 17 04:49:55 2005 From: rickard.lind at ntier.se (Rickard Lind) Date: Mon, 17 Jan 2005 10:49:55 +0100 Subject: Static executable with shared modules In-Reply-To: <41e80078$0$1518$9b622d9e@news.freenet.de> References: <41e80078$0$1518$9b622d9e@news.freenet.de> Message-ID: <41EB8A43.2030901@ntier.se> Martin v. L?wis wrote: > I'm not what "build statically" means; if you talking about > building a statically linked interpreter binary - then no, > this is not possible. At a minimum, you need to link with -ldl, > or else you cannot perform dlopen(3). I'll be more specific: when I build python 2.3.4 on FreeBSD 4.9, the interpreter binary is linked against three shared libraries: libutil.so.3, libm.so.2 and libc_r.so.4. Now, these libraries are not present on the TARGET system (which is distinct from the build system, but based on the same version of FreeBSD) so I add "-static" to LDFLAGS. This produces an interpreter that runs on the target system (no dependency on shared libc etc) but it also cannot load modules compiled as shared libraries. Man page for dlopen(3) says it is located in libc (and consquently there seems to be no libdl), and anyway I'd expect to get a link error if the dl* functions were not present. What I DO get is an ImportError exception. At present I see no other option than to link the modules into the interpreter which is very inconvenient since I'll have to rebuild the every time a module changes :-( /r From mercuryprey at gmail.com Sun Jan 30 12:48:03 2005 From: mercuryprey at gmail.com (mercuryprey at gmail.com) Date: 30 Jan 2005 09:48:03 -0800 Subject: Disassembling strings and turning them into function parameters Message-ID: <1107107283.694377.286360@c13g2000cwb.googlegroups.com> Hi, I'm pretty new to Python, to programming overall...so how would I make something where the user inputs multiple words in a string - like "connect 123.123.123.123 21 user password" or similar, and then I can split this string up to pass these arguments to a function like ftp_connect(ip, port, user, pw) etc...? I have no idea how to "break" the string up so I can get these out of it.. thanks for answers, munin From roccomoretti at hotpop.com Tue Jan 25 14:25:57 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Tue, 25 Jan 2005 13:25:57 -0600 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: Message-ID: Bob Smith wrote: > Rocco Moretti wrote: > >> Python's also dangerous. Every time you do an "import module", you put >> your system at risk of crashing, having the hard-drive wiped > > Have you been drinking again? No, not really. The "every time" comment should be viewed in the same light as "Every time you step outside, you risk being hit by a bus." "import module" executes Python code. As such it can do anything Python can do. Crash your system, wipe the hard drive, etc. And there is nothing the importing code can do to stop it. Now, if you limit yourself to known and trusted modules, that risk virtually disappears, just like staying on the sidewalk virtually eliminates the chances of getting hit by a bus. Not completely, mind you, since someone could have altered the standard library modules/changed the import path such that you're importing an unknown module. But most people would argue if someone has that power, they probably can do anything they want with your system without you doing "import module." Bottom line: Don't exec or eval untrusted code. Don't import untrusted modules. From dbickett at gmail.com Sun Jan 23 18:08:49 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 23 Jan 2005 18:08:49 -0500 Subject: how to write a tutorial In-Reply-To: References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: <1d6cdae305012315086a6b32c2@mail.gmail.com> Lucas Raab wrote: > Daniel Bickett wrote: > >>Most texts in computing are written by authors to defend and showcase > >>their existence against their peers. > > > > > > When you aren't busy `showcasing' your ignorance, this is *all* i see > > in everything you write. > > > > Um, maybe that was his point... It was a critical comment -- meant to be derogatory. I pointed out that that is exactly what he does. Daniel Bickett From ncoghlan at iinet.net.au Fri Jan 7 12:28:34 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 03:28:34 +1000 Subject: Notification of PEP Updates Message-ID: <41DEC6C2.8030904@iinet.net.au> I can't recall which thread this came up in, so I'm starting a new one. . . Barry Warsaw has kindly added a "peps" topic to the python-checkins mailing list. If you want to be notified only when PEP's get updated, then subscribe to python-checkins and edit your settings to select just the 'peps' topic. Let us know if it does anything odd (e.g. sending updates about other checkins) The URL for the mailing list is: http://mail.python.org/mailman/listinfo/python-checkins I believe the mail you receive should contain the checkin messages, along with a summary of the differences between the old version and the new version (handy if you can read a context diff, not so handy otherwise). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From bill.mill at gmail.com Fri Jan 28 15:00:57 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 28 Jan 2005 15:00:57 -0500 Subject: Dynamic class methods misunderstanding In-Reply-To: References: <1106928492.114459.191320@c13g2000cwb.googlegroups.com> Message-ID: <797fe3d405012812005c7555bd@mail.gmail.com> On Fri, 28 Jan 2005 14:41:16 -0500, Terry Reedy wrote: > > "Kamilche" wrote in message > news:1106928492.114459.191320 at c13g2000cwb.googlegroups.com... > >I see what you're attempting to do. However, your code, if it DID run, > > would result in a method being added to the object, not the object's > > class! Modify the class itself, not the object, as follows: > > > > |class Test: > > | def __init__(self): > > | self.method() > > | > > |def m(self): > > | print self > > | > > |setattr(Test, 'method', m) > > # this is a longwinded way to say > Test.method = m That is the blindingly simple method that I wanted. I didn't know before that I wanted it, but I'm sure of it now. Thank you very much, terry. > > setattr is for when you do *not* know the attribute name at coding time but > will have it in a string at run time, as in > > methodname = 'method' > ......# some time later > setattr(Test, methodname, m) > > Sometime Python makes things easier than people are initially willing to > believe ;-) I felt like there had to be a simpler solution. Peace Bill Mill bill.mill at gmail.com From cartermark46 at ukmail.com Tue Jan 11 05:06:13 2005 From: cartermark46 at ukmail.com (Mark Carter) Date: Tue, 11 Jan 2005 10:06:13 +0000 Subject: Port blocking In-Reply-To: References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> <34f8ovF47d783U1@individual.net> Message-ID: <34hmokF4bd7i7U1@individual.net> Ed Leafe wrote: > On Jan 10, 2005, at 8:00 PM, Steve Holden wrote: >> >> There isn't, IMHO, anything with the polish of (say) Microsoft Access, >> or even Microsoft SQL Server's less brilliant interfaces. Some things >> Microsoft *can* do well, it's a shame they didn't just stick to the >> knitting. > > > Though it's certainly not anywhere near the polish > of Access, you should check out Dabo. Thanks. I'll look into it. From danperl at rogers.com Sat Jan 29 20:41:57 2005 From: danperl at rogers.com (Dan Perl) Date: Sat, 29 Jan 2005 20:41:57 -0500 Subject: naive doc question References: <5175a81c050129163826fcd734@mail.gmail.com> <1107046899.023197.174440@f14g2000cwb.googlegroups.com> Message-ID: "Michael Hartl" wrote in message news:1107046899.023197.174440 at f14g2000cwb.googlegroups.com... > i.e., http://docs.python.org/lib/typesmapping.html > If you look on the index page of the Python Library Reference (http://docs.python.org/lib/genindex.html), you will find "dictionary object", which will take you exactly to the page above. From frans.englich at telia.com Wed Jan 12 13:16:23 2005 From: frans.englich at telia.com (Frans Englich) Date: Wed, 12 Jan 2005 18:16:23 +0000 Subject: Refactoring; arbitrary expression in lists Message-ID: <200501121816.23776.frans.englich@telia.com> As continuation to a previous thread, "PyChecker messages", I have a question regarding code refactoring which the following snippet leads to: > > runner.py:200: Function (detectMimeType) has too many returns (11) > > > > The function is simply a long "else-if" clause, branching out to > > different return statements. What's wrong? It's simply a "probably ugly > > code" advice? > > That is also advice. Generally you use a dict of functions, or some other > structure to lookup what you want to do. More specifically, my function looks like this: #-------------------------------------------------------------- def detectMimeType( filename ): extension = filename[-3:] basename = os.path.basename(filename) if extension == "php": return "application/x-php" elif extension == "cpp" or extension.endswith("cc"): return "text/x-c++-src" # etcetera elif extension == "xsl": return "text/xsl" elif basename.find( "Makefile" ) != -1: return "text/x-makefile" else: raise NoMimeError #-------------------------------------------------------------- (don't bother if the MIME detection looks like stone age, it's temporary until PyXDG gets support for the XDG mime type spec..) I'm now wondering if it's possible to write this in a more compact way, such that the if-clause isn't necessary? Of course, the current code works, but perhaps it could be prettier. I'm thinking along the lines of nested lists, but what is the obstacle for me is that both the test and return statement are simple expressions; not functions or a particular data type. Any ideas? Cheers, Frans From esosman at acm-dot-org.invalid Fri Jan 28 20:19:19 2005 From: esosman at acm-dot-org.invalid (Eric Sosman) Date: Fri, 28 Jan 2005 20:19:19 -0500 Subject: what's OOP's jargons and complexities? In-Reply-To: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > [...] > Tomorrow i shall cover more manmade jargons and complexities arising > out of the OOP hype, in particular Java. [...] I hope you will not, or that if you do so you will do it elsewhere. Go pound sand. -- Eric Sosman esosman at acm-dot-org.invalid From elephantum at dezcom.mephi.ru Mon Jan 17 08:22:58 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Mon, 17 Jan 2005 16:22:58 +0300 Subject: protecting the python code. In-Reply-To: <1105893393.214111.227550@f14g2000cwb.googlegroups.com> References: <1105884196.461107.28120@z14g2000cwz.googlegroups.com> <41EA92A7.3080706@holdenweb.com> <1105893393.214111.227550@f14g2000cwb.googlegroups.com> Message-ID: <351shiF4hht1kU1@individual.net> nell wrote: > First the "10x in advance" means thanks in advance. > The main importance of protecting my code is to save headache of > customers that want to be smart and change it and then complain on bugs also you can try to use py2exe From gharper at medplus.com Wed Jan 12 13:19:35 2005 From: gharper at medplus.com (Harper, Gina) Date: Wed, 12 Jan 2005 13:19:35 -0500 Subject: Why would I get a TypeEror? Message-ID: <4D97153E7D88F44FB6B534C661EE42900300A581@medexch1.medplus.com> Because you can't take the len() of an integer. Try casting a as a str: b=(1,len(str(a)))[isinstance(a,(list,tuple,dict))] -----Original Message----- From: It's me [mailto:itsme at yahoo.com] Sent: Wednesday, January 12, 2005 12:35 PM To: python-list at python.org Subject: Why would I get a TypeEror? For this code snip: a=3 .... b=(1,len(a))[isinstance(a,(list,tuple,dict))] Why would I get a TypeError from the len function? Thanks, From beliavsky at aol.com Fri Jan 21 11:41:51 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 21 Jan 2005 08:41:51 -0800 Subject: problems with duplicating and slicing an array In-Reply-To: References: <7cffadfa05012017337858d171@mail.gmail.com> Message-ID: <1106325711.782439.305360@c13g2000cwb.googlegroups.com> Yun Mao wrote: >Thanks for the help. numarray doesn't provide what I look for either. e.g. >a = array( [[1,2,3],[4,5,6]] ) >I sometimes what this: a[ [1,0], :], or even >a[ [1,0], [0,1] ] , which should give me >[[4, 5], [1,2]] I think Fortran 90 and 95 have the array slicing you want. For example, if imat = 11 12 13 21 22 23 then imat([2,1,2],:)) = 21 22 23 11 12 13 21 22 23 and imat([2,1,2],[1,3]) = 21 23 11 13 21 23 Like Matlab, Fortran arrays by default start with 1, and x(i:j) gives a slice of elements including x(j). There are free compilers g95 (in beta) and gfortran (in alpha). From aleaxit at yahoo.com Sun Jan 30 11:23:37 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 30 Jan 2005 17:23:37 +0100 Subject: Coding style article with interesting section on white space References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> <1107053300.326925.183080@z14g2000cwz.googlegroups.com> <1107059169.510996.262480@z14g2000cwz.googlegroups.com> <1gr74p3.1p45u1v182vecgN%aleaxit@yahoo.com> <1107100318.251828.86360@c13g2000cwb.googlegroups.com> Message-ID: <1gr7p3d.1lqttxmh1d3nsN%aleaxit@yahoo.com> wrote: > I had in mind the Polyhedron Fortran 90 benchmarks for Windows and > Linux on Intel x86 at > http://www.polyhedron.co.uk/compare/linux/f90bench_p4.html and > http://www.polyhedron.co.uk/compare/win32/f90bench_p4.html . The speed > differences of Absoft, Intel, and Lahey between Linux and Windows for > individual programs, not to mention the average differential across all > programs, is much less than 25%. The differences on a single OS between > compilers can be much larger, but that has less bearing on portability > across OS's. So, you think that comparing a single commercial compiler for code generation on Windows vs Linux (which _should_ pretty obviously be pretty much identical) is the same thing as comparing the code generation of two DIFFERENT compilers, a commercial one on Windows vs a free one on Linux?! This stance sounds singularly weird to me. If on one platform you use a compiler that's only available for that platform (such as Microsoft's), then "portability across OS's" (in terms of performance, at least) can of course easily be affected. If you care so much, splurge for (say) the commercial compilers that Intel will be quite happy to sell you for both platforms -- the one for Windows is a plug-in replacement for Microsoft's, inside MS Visual Studio (at least, it used to be that way, with VS 6.0; I don't know if that's still the case), the one for Linux is usable in lieu of the free gcc. So, each should compile Python without any problem. Presumably, the optimizer and code generator will be essentially unchanged across platforms, as they are in the offerings of other vendors of commercial compilers -- it would seem silly for any vendor to do otherwise! If one has no funding to purchase commercial compilers for several platforms, or one doesn't care particularly about the differences in speed resulting from different compilers' optimizers, then, surprise surprise, one's programs are quite liable to have different performance on different platforms. Trying to imply that this has ANYTHING to do with the LANGUAGE the programs are coded in, as opposed to the compilers and expenses one is willing to incur for them, is either an extremely serious error of logic, if incurred in good faith, or else is an attempt to "score points" in a discussion, and then good faith is absent. Alex From steven.bethard at gmail.com Sun Jan 16 16:08:38 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 16 Jan 2005 14:08:38 -0700 Subject: Executing a script created by the end user In-Reply-To: References: Message-ID: Craig Howard wrote: > I am working on a python project where an object will have a script that > can be edited by the end user: object.script > > If the script is a simple one with no functions, I can easily execute it > using: > exec object.script > > But if the object script is a bit more complicated, such as the example > below, my approach does not work: > > def main(): > hello1() > hello2() > > def hello1(): > print 'hello1' > > def hello2(): > print 'hello2' What do you want to do if you get a script like this? Run main? You could do something like: py> s = """ ... def main(): ... hello1() ... hello2() ... ... def hello1(): ... print 'hello1' ... ... def hello2(): ... print 'hello2' ... """ py> d = {} py> exec s in d py> d["main"]() hello1 hello2 (Actually, you don't need to exec it in d, that's probably just good practice.) Steve From alan.gauld at btinternet.com Sat Jan 1 18:24:25 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Jan 2005 23:24:25 +0000 (UTC) Subject: What can I do with Python ?? References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> Message-ID: On Sat, 1 Jan 2005 21:57:32 +0100, BOOGIEMAN < > (let's say C#). Can you make fullscreen game with it (for example) ? You can but please don't! Make your game run fast in a window. I hate fascist games programmers who insist on monopolising a 21 inch 1600x1200 display and assuming I have nothing better to do than play their game. If that's all I wanted to do I'd stick with DOS, or buy a Nintendo... I have a multi tasking PC please let me multi task! ;-) Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From jeff at ccvcorp.com Wed Jan 12 18:36:02 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 12 Jan 2005 15:36:02 -0800 Subject: reference or pointer to some object? In-Reply-To: References: Message-ID: <10ubcp136drsu97@corp.supernews.com> Torsten Mohr wrote: > I still wonder why a concept like "references" was not > implemented in Python. I think it is (even if small) > an overhead to wrap an object in a list or a dictionary. Because Python uses a fundamentally different concept for variable names than C/C++/Java (and most other static languages). In those languages, variables can be passed by value or by reference; neither term really applies in Python. (Or, if you prefer, Python always passes by value, but those values *are* references.) Python doesn't have lvalues that contain rvalues; Python has names that are bound to objects. Passing a parameter just binds a new name (in the called function's namespace) to the same object. It's also rather less necessary to use references in Python than it is in C et. al. The most essential use of references is to be able to get multiple values out of a function that can only return a single value. Where a C/C++ function would use the return value to indicate error status and reference (or pointer) parameters to communicate data, a Python program will return multiple values (made quick & easy by lightweight tuples and tuple unpacking) and use exceptions to indicate error status. Changing the value of a parameter is a side-effect that complicates reading and debugging code, so Python provides (and encourages) more straightforward ways of doing things. Jeff Shannon Technician/Programmer Credit International From steven.bethard at gmail.com Wed Jan 12 16:55:24 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 14:55:24 -0700 Subject: dict.updated In-Reply-To: References: Message-ID: Rick Morrison wrote: > Would there be any way to add a method to all dict objects that operated > like the .update() method, but also returned a reference to the updated > dict? Are you looking for updated() to parallel sorted(), where sorted() returns a *new* list? I doubt you'll be able to rally much support for a method that changes an object and returns a reference to it -- check the archives to see these kind of things getting rejected over and over. Could you do something like: py> import itertools py> d1 = dict(a=1, b=2) py> d2 = dict(c=3, d=4) py> d3 = dict(itertools.chain(d1.iteritems(), d2.iteritems())) py> d3 {'a': 1, 'c': 3, 'b': 2, 'd': 4} Steve From ncoghlan at iinet.net.au Wed Jan 26 06:04:59 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 21:04:59 +1000 Subject: Tuple slices In-Reply-To: <41F7F5CF.5040902@freemail.gr> References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> <1106669254.838248.317170@z14g2000cwz.googlegroups.com> <10vdj4s9ib19fe3@corp.supernews.com> <41F7F5CF.5040902@freemail.gr> Message-ID: <41F7795B.7040505@iinet.net.au> jfj wrote: > Actually, i think that slices with step, is a bad feature in general > and i think I will write a PEP to suggest their removal in python3k. I wouldn't bother. Extended slicing was added to support those doing serious numerical work in Python, and it won't get removed for all the reasons it was added in the first place. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From phil at riverbankcomputing.co.uk Fri Jan 28 18:23:59 2005 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Fri, 28 Jan 2005 23:23:59 +0000 Subject: example needed: sip + Qt In-Reply-To: References: Message-ID: <200501282323.59622.phil@riverbankcomputing.co.uk> So have you created the library you are trying to wrap? The documentation is describing how to wrap a library and describes a fictional library as the basis for the example. Phil On Friday 28 January 2005 11:02 pm, Uwe Mayer wrote: > Friday 28 January 2005 23:39 pm Uwe Mayer wrote: > > Friday 28 January 2005 23:18 pm Uwe Mayer wrote: > >> Traceback (most recent call last): > >> File "", line 1, in ? > >> ImportError: ./hello.so: undefined symbol: _ZTV5Hello > >> > >> $ c++filt _ZTV5Hello > >> vtable for Hello > >> > >> The compilation did not give any warnings or error messages. Any ideas? > > > > $ ldd -d hello.so > > libqt-mt.so.3 => /usr/lib/libqt-mt.so.3 (0x40057000) > > libXext.so.6 => /usr/X11R6/lib/libXext.so.6 (0x4190c000) > > libX11.so.6 => /usr/X11R6/lib/libX11.so.6 (0x4154e000) > > libpthread.so.0 => /lib/tls/libpthread.so.0 (0x41173000) > > libstdc++.so.5 => /usr/lib/libstdc++.so.5 (0x40743000) > > libm.so.6 => /lib/tls/libm.so.6 (0x4114f000) > > libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x407fd000) > > libc.so.6 => /lib/tls/libc.so.6 (0x41019000) > > libfontconfig.so.1 => /usr/lib/libfontconfig.so.1 (0x418d8000) > > libaudio.so.2 => /usr/lib/libaudio.so.2 (0x40807000) > > libXt.so.6 => /usr/X11R6/lib/libXt.so.6 (0x4191c000) > > libpng12.so.0 => /usr/lib/libpng12.so.0 (0x4081c000) > > libz.so.1 => /usr/lib/libz.so.1 (0x41856000) > > libXrender.so.1 => /usr/lib/libXrender.so.1 (0x41749000) > > libXrandr.so.2 => /usr/X11R6/lib/libXrandr.so.2 (0x40842000) > > libXcursor.so.1 => /usr/lib/libXcursor.so.1 (0x41734000) > > libXft.so.2 => /usr/lib/libXft.so.2 (0x416e1000) > > libfreetype.so.6 => /usr/lib/libfreetype.so.6 (0x42487000) > > libSM.so.6 => /usr/X11R6/lib/libSM.so.6 (0x42583000) > > libICE.so.6 => /usr/X11R6/lib/libICE.so.6 (0x4256a000) > > libdl.so.2 => /lib/tls/libdl.so.2 (0x41184000) > > /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x80000000) > > libexpat.so.1 => /usr/lib/libexpat.so.1 (0x40847000) > > undefined symbol: _ZTV5Hello (./hello.so) > > undefined symbol: _ZNK5Hello9classNameEv (./hello.so) > > undefined symbol: _ZN5Hello7qt_castEPKc (./hello.so) > > undefined symbol: _ZN5Hello9qt_invokeEiP8QUObject (./hello.so) > > undefined symbol: _ZN5Hello7qt_emitEiP8QUObject (./hello.so) > > undefined symbol: _ZN5Hello11qt_propertyEiiP8QVariant (./hello.so) > > undefined symbol: _ZTI5Hello (./hello.so) > > > > undefined symbol: _Py_NoneStruct (./hello.so) > > undefined symbol: PyCObject_Type (./hello.so) > > Those last two can be removed if you link against libpython2.3.so and by > appending -lpython2.3 to the libs in the Makefile. > > Uwe From fperez.net at gmail.com Wed Jan 5 16:22:17 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Wed, 05 Jan 2005 14:22:17 -0700 Subject: Readline configuration References: Message-ID: Mark Roach wrote: > I have readline set up pretty much the same way as in the example in the > python docs (http://docs.python.org/lib/readline-example.html) and > something I find myself doing fairly often is > > type some code > more code > more code > ... > > and then wanting to scroll back through the history to run the same code > again after a module = reload(module). In Windows, this is pretty > convenient as I can use up to move to point x in the history, press enter, > and press down to move to point x+1 in history. Is there any way to get > the same behavior with readline? > > It would be great to be able to ctrl+r then just > hit down+enter to reenter the rest of the code. See ipython (http://ipython.scipy.org). It provides mostly what you want: In [1]: for i in range(3): ...: print i, ...: 0 1 2 In [2]: print 'hello' hello In [3]: exec In[1] 0 1 2 Readline history search is bound to Ctrl-P/N (type a few characters, then hit Ctrl-P/N to get previous/next lines with those matching chars). Ctrl-r search is also configured by default. HTH, f From Sonny.Baillargeon at bmonb.com Tue Jan 4 11:42:47 2005 From: Sonny.Baillargeon at bmonb.com (Baillargeon, Sonny) Date: Tue, 4 Jan 2005 11:42:47 -0500 Subject: Pexpect getting a defuct process Message-ID: <453D335C35136F4B8163C281D58BBD884D0E69@NBNUNYCEXCH1.nesbittburns.ca> I am trying to use a pexpect script using python v2.3.4 with pexpect module .999 on Solaris 8. I try to execute this script. #!/usr/bin/env python '''This runs "ls -l" on a remote host using SSH. At the prompts enter hostname, user, and password. ''' import pexpect logfile = open('sshls.log', 'w') child = pexpect.spawn('ssh user at server ls -la') child.setlog(logfile) child.setmaxread(1000) child.expect(pexpect.EOF, timeout=180) print child.before This used to work before but now I get a defunct process after it runs. Any ideas? Thanks, Sonny **************************************************************************** This e-mail and any attachments may contain confidential and privileged information. If you are not the intended recipient, please notify the sender immediately by return e-mail, delete this e-mail and destroy any copies. Any dissemination or use of this information by a person other than the intended recipient is unauthorized and may be illegal. Unless otherwise stated, opinions expressed in this e-mail are those of the author and are not endorsed by the author's employer. From mesteve_bpleaseremovethis at hotmail.com Wed Jan 26 08:59:04 2005 From: mesteve_bpleaseremovethis at hotmail.com (StvB) Date: Wed, 26 Jan 2005 13:59:04 GMT Subject: HAVE YOU HEARD THE GOOD NEWS! References: <1106701661.128249.250310@c13g2000cwb.googlegroups.com> Message-ID: I felt very evil after trying to figure out why my py program wouldn't work when I began a year ago: I do Delphi at work, and at home I was missing the () after the functions. I was ready to sell my sou.. well nevermind.. it's all good now. wrote in message news:1106701661.128249.250310 at c13g2000cwb.googlegroups.com... > Good News! > > > Do you know how simple it is to go to Heaven after this life has ended? > > > Some people believe that belonging to a local church, temple, mosque or > synagogue will get them to Heaven. > > > Others believe that water baptism, obeying the ten commandments or just > being a good person will get them to Heaven. > > > There are many other beliefs as well, but the good news about God's way > to Heaven is found in the Holy Bible. > > > The good news is that God came from Heaven to earth in the person of > Jesus Christ over 2000 years ago and died for our sins(misdeeds). He > was born in the land of Israel supernaturally to a virgin Jewish woman > named Mary. He lived a sinless life for thirty-three years and then > sacrificed His sinless blood and died on a cross to pay the death > penalty for our sins. After Jesus was placed in a tomb He rose from the > dead three days later as He said He would. The Holy Bible also tells us > that Jesus Christ ascended into Heaven and that all who accept Him as > their Lord and Saviour will live forever with Him in Heaven where there > is no more death, sorrow, sickness and pain. > > > The Bible says, "For the wages of sin is death, but the gift of God is > eternal life through Christ Jesus our Lord." (Romans 6:23) > > > This verse in the Bible says, "For ALL HAVE SINNED, and come short of > the glory of God." (Romans 3:23) > > > This verse says, "But God demonstrates his own love for us in this: > While we were still sinners, Christ died for us." (Romans 5:8) > > > In this passage the Bible clearly explains how simple it is to be saved > and on your way to Heaven, "For if you confess with your mouth, "Jesus > is Lord," and believe in your heart that God raised him from the dead, > you WILL BE SAVED." (Romans 10:9) > > > You can be saved right now and on your way to Heaven if you will open > your heart to Jesus and pray the following prayer: > > Dear Jesus Christ, I want to be saved so that I can have a home in > Heaven when I die. I agree with You that I am a sinner. > I believe You love me and want to save me. I believe that You bled and > died on the cross to pay the penalty for my sins. I believe that You > rose from the dead. Please forgive my sins and come into my heart and > be my Lord and Saviour. Thank You Lord Jesus Christ for forgiving me > and saving me through Your merciful grace. Amen. > > > You are now a Christian if you said the prayer and allowed God to save > you. Welcome to the family of God. > > > Salvation is not a reward but a gift. The Bible says it this way, "For > it is by GRACE you have been SAVED, through FAITH and this not from > yourselves, it is the GIFT of God." (Ephesians 2:8) > > > Nothing in the world is more important than your eternal destiny. > > > The Bible says, "In Him(Jesus) we have redemption through His blood, > the forgiveness of sins..." (Ephesians 1:7) > > > If you have not yet made a decision to be saved, please do so now > before it is too late. The reason why it is so important to be saved > now is because you do not know exactly when you will die. You may die > prematurely in a traffic accident, terrorist attack or some other way > before you get another chance to be saved. > > > The Bible tells us that we will spend eternity in Heaven or a place of > eternal torment called Hell. It would be terrible to die and go to Hell > when all you have to do is accept Jesus Christ as your personal Lord > and Saviour. > > > Some people that have already made Jesus Christ their Lord and Saviour > worry about losing their salvation. The Bible teaches Christians that > we can never lose our salvation no matter what happens. > > > The Bible says it this way, "My dear children, I write this to you so > that you will not sin. But if anybody does sin, we have one who speaks > to the Father in our defense Jesus Christ, the Righteous One." > > > Yes my friend, Jesus Christ is able to save you and keep you saved. > > > Please tell your family and friends, thanks! > > > Have a great day! > Internet Evangelist R.L. Grossi > > > > > > 1. http://www.biblegateway.com << Free Online Bible > 2. http://www.free-hoster.com/goodnews << Passion of the Christ > 3. http://www.carm.org/cults/cultlist.htm << Beware Of Cults > 4. http://www.equip.org/free/DH198.htm << About Hell > 5. http://www.powertochange.com/questions/qna2.html << Is Jesus God? > From Scott.Daniels at Acm.Org Wed Jan 19 17:37:05 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 19 Jan 2005 14:37:05 -0800 Subject: [OT] Good C++ book for a Python programmer In-Reply-To: References: <1106136496.719185.87850@c13g2000cwb.googlegroups.com> Message-ID: <41eeddb9$1@nntp0.pdx.net> John Hunter wrote: >>>>>>"Philippe" == Philippe C Martin writes: > > > Philippe> I suggest you google 'C++ tutorial' Regards, > > Stroustup's "The C++ Programming Language" is the best C++ book I've > read. It is at a fairly high level, and I already had read several > C++ books before reading it, so it may be tough sledding. But I would > try this first since you are an experienced programmer and know OO > concepts, and if it fails to satisfy try something lighter. > Unfortunately, I didn't like any of the other kinder, gentler overview > books I read on C++, so can't really recommend anything along those > lines, though I'm sure they are out there. > > JDH For a rationale as to why the language developed the way it did, you can read Stroustrup's "The Design and Evolution of C++". This is no good for learning the language, but it might be a good library borrow to find out why the language is the way it is. -Scott David Daniels Scott.Daniels at Acm.Org From elephantum at dezcom.mephi.ru Fri Jan 7 12:56:41 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Fri, 07 Jan 2005 20:56:41 +0300 Subject: python3: 'where' keyword Message-ID: <3480qqF46jprlU1@individual.net> Hi. It would be great to be able to reverse usage/definition parts in haskell-way with "where" keyword. Since Python 3 would miss lambda, that would be extremly useful for creating readable sources. Usage could be something like: >>> res = [ f(i) for i in objects ] where: >>> def f(x): >>> #do something or >>> print words[3], words[5] where: >>> words = input.split() - defining variables in "where" block would restrict their visibility to one expression - it's more easy to read sources when you know which part you can skip, compare to >>> def f(x): >>> #do something >>> res = [ f(i) for i in objects ] in this case you read definition of "f" before you know something about it usage. From http Wed Jan 5 06:55:35 2005 From: http (Paul Rubin) Date: 05 Jan 2005 03:55:35 -0800 Subject: Concepts RE: Python evolution: Unease References: <20050105002302.542768387.EP@zomething.com> Message-ID: <7xr7l06qfc.fsf@ruckus.brouhaha.com> Roman Suzi writes: > As for concepts, they are from Generic Programming (by Musser and > Stepanov) and I feel that Python is in position to implement them to > the fullest extent. And IMHO it will be nicer than just Java-like > interfaces or Eiffel's contract approach. I keep hearing that term (GP). Can someone explain in a few sentences what it means, without resorting to marketing buzzwords? There is nothing in Wikipedia about it. From quentel.pierre at wanadoo.fr Tue Jan 4 16:28:37 2005 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Tue, 04 Jan 2005 22:28:37 +0100 Subject: Hlelp clean up clumpsy code In-Reply-To: References: Message-ID: <41db0a86$0$3519$8fcfb975@news.wanadoo.fr> You can also do it in a more pythonic way but without generators : # a = [[1,5,2], 8, 4] # l = [] # for item in a: # if isinstance(item, (int, long)): # l.append(item) # else: # l+=item # print dict([(item,i+1) for (i,item) in enumerate(l)]) It works in the same conditions as your original code (no nested lists) A few other things : - you don't have to type a comma for one-item lists : x = [x] works - you probably confused with tuples where you must do x=(x,) - instead of # for w in [y for y in x]: just do # for w in x: - for "i = i+1" there is a shortcut : i+=1 (see "l+=item" above) Regards, Pierre From tjreedy at udel.edu Sat Jan 15 14:23:39 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 15 Jan 2005 14:23:39 -0500 Subject: Pointer or unique id References: <1q9pydh06wjuk.fexsf964ckya$.dlg@40tude.net> <41e94d40$0$29202$636a15ce@news.free.fr> Message-ID: "Bruno Desthuilliers" wrote in message news:41e94d40$0$29202$636a15ce at news.free.fr... >id(object) -> integer >Return the identity of an object. This is guaranteed to be unique among >simultaneously existing objects. This is part of the language specification. Also, the identity of an object must remain the same for its entire lifetime. > (Hint: it's the object's memory address.) This is an implementation detail of CPython. It cannot be true if the garbage collector moves objects around. Or if the object lives elsewhere (and is accessed thru a proxy). Terry J. Reedy From macrocosm at fastmail.fm Thu Jan 6 21:01:13 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Thu, 06 Jan 2005 21:01:13 -0500 Subject: Python Operating System??? In-Reply-To: <1105056774.393244.199250@f14g2000cwb.googlegroups.com> References: <10trb0mgiflcj4f@corp.supernews.com> <1105056774.393244.199250@f14g2000cwb.googlegroups.com> Message-ID: <41DDED69.4060707@fastmail.fm> An HTML attachment was scrubbed... URL: From michael.bierenfeld at web.de Thu Jan 13 03:37:26 2005 From: michael.bierenfeld at web.de (michael.bierenfeld at web.de) Date: 13 Jan 2005 00:37:26 -0800 Subject: property () for Java Programmers ? References: Message-ID: <1105605446.803163.84240@f14g2000cwb.googlegroups.com> > Note that I used 'c = C()' instead of 'c = C' as in your code. Hello, thanks that was the problem. *hmpf* :-) Michael From fredrik at pythonware.com Fri Jan 14 13:27:47 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 14 Jan 2005 19:27:47 +0100 Subject: how to stop google from messing Python code References: <1105620098.878376.110250@z14g2000cwz.googlegroups.com><1105666406.272397.170730@c13g2000cwb.googlegroups.com> <1105704548.146263.229220@f14g2000cwb.googlegroups.com> Message-ID: Fuzzyman wrote: > I guess that most people use google to post to newsgroups is that they > don't have nntp access. Telling htem to use a newsreader is facetious > and unhelpful. if you have internet access, you have NNTP access. gmane.org provides access to more than 6,500 mailing lists via NNTP, including all relevant Python forums. From steve at holdenweb.com Mon Jan 3 14:41:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Jan 2005 14:41:05 -0500 Subject: Continuations Based Web Framework - Seaside. In-Reply-To: References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <7aTBd.11928$H%6.521997@twister1.libero.it> Message-ID: <5hhCd.67873$Jk5.55592@lakeread01> Kendall Clark wrote: > On Sun, Jan 02, 2005 at 10:03:10AM -0500, Steve Holden wrote: > > >>I did actually do some sort-of-related work in this area, which I >>presented at PyCon DC 2004 - you can access the paper at >> >> http://www.python.org/pycon/dc2004/papers/18/Setting_A_Context.pdf >> >>An audience member mentioned the Smalltalk and Scheme-based work on web >>continuation frameworks, and I was sorry my answer at the time seemed >>unduly dismissive. > > > That was me, actually. I remain surprised that there isn't a move > afoot either to implement something like Seaside or Borges in Python > or to adapt one of the existing web frameworks to be > modal/continuation style. > Ah, glad to make your acquaintance again - I lost your email address in a disk crash shortly after PyCon DC 2004. [...] >>There are some interesting similarities, and though >>my own implementation is decidedly clunky I like to think the paper >>explains some of the advantages of maintaining state and why the "back" >>button is an obnoxious anachronism :-) > > > I'd still like to publish a piece on XML.com about modal web app > style, preferably with a Python example, though Borges would be fine. > Would an adaptation of the PyCon paper be any use in this context? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From rm at rm.net Fri Jan 21 12:30:47 2005 From: rm at rm.net (rm) Date: Fri, 21 Jan 2005 18:30:47 +0100 Subject: What YAML engine do you use? In-Reply-To: <7x1xcfwbab.fsf@ruckus.brouhaha.com> References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> Message-ID: <35csm7F4l57inU1@individual.net> Paul Rubin wrote: > Reinhold Birkenfeld writes: > >>For those of you who don't know what YAML is: visit http://yaml.org/! >>You will be amazed, and never think of XML again. Well, almost. > > > Oh please no, not another one of these. We really really don't need it. well, I did look at it, and as a text format is more readable than XML is. Furthermore, XML's verbosity is incredible. This format is not. People are abusing the genericity of XML to put everything into it. Parsing and working with XML are highly optimized, so there's not really a problem in that sector. But to transfer the same data in a YAML format, rather than a XML format is much more economic. But networks are getting faster, right? Nowadays, people are trying to create binary XML, XML databases, graphics in XML (btw, I'm quite impressed by SVG), you have XSLT, you have XSL-FO, ... . And I think, YAML is a nice initiative. bye, rm From get at bent.com Tue Jan 25 20:35:04 2005 From: get at bent.com (nobody) Date: Wed, 26 Jan 2005 11:35:04 +1000 Subject: MySQLdb References: Message-ID: <1106703298.349594@chloe.intranet> > The problem I have is that it takes just over two minuted to execute the > 3000 insert statements which seems really slow! Are you creating a new DB connection for every insert? I just did a test on my system (Athlon 2500+), 3000 rows with an auto_increment field and a randomly generated 128 character field. 1.9 seconds. From martin at v.loewis.de Sat Jan 29 12:42:54 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 29 Jan 2005 18:42:54 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xacqsbfk2.fsf@ruckus.brouhaha.com> References: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> <7xacqsbfk2.fsf@ruckus.brouhaha.com> Message-ID: <41fbcb11$0$12030$9b622d9e@news.freenet.de> Paul Rubin wrote: > An AES or DES addition to an existing module that implements just one > call: > ECB(key, data, direction) > would be a huge improvement over what we have now. Apparently, people disagree on what precisely the API should be. E.g. cryptkit has obj = aes(key) obj.encrypt(data) I think I would prefer explicit encrypt/decrypt methods over a direction parameter. Whether or not selection of mode is a separate parameter, or a separate method, might be debatable - I'ld personally prefer a separate method. However, we would have to ask users. > If you think a function like that could be added to some existing > module with less hassle than adding a new module, then I can write one > and submit it. I would trust my intuition more for a single function than for an entire API. In this specific proposal, I think I would trust my intuition and reject the ECB function because of the direction argument. > Come on, you're being deliberately obtuse, we've discussed this over > and over. There are plenty of AES modules that people can get from > somewhere. The topic is what it takes to have an AES module that > people don't NEED to get from anywhere, because they already have it > from having Python installed. Do I have to keep repeating "batteries > included" until you understand what it means? I fully understand what you desire - to include the module "as a battery". What makes this decision difficult is that you fail to understand that I don't want included batteries so much that I would accept empty or leaking batteries. >>http://sourceforge.net/projects/cryptkit/ > Well, that code has been around for over a year, people are using it, > etc. Are you saying you'll support its inclusion if Bryan offers to > contribute it? *Now* you get it. Precisely that. I would ask the users what they think about the API (shouldn't be too difficult because the module does have users) and what they think about other aspects (performance, stability, and so on). > I've examined that module, I wouldn't consider it > ideal for the core (besides AES, it has some complicated additional > functions that aren't useful to most people) Ok, that would be a problem. If this is a simple removal of functions that you'ld request (which functions?), I'ld try to collect opinions on that specific issue, and ask Bryan whether he could accept removal of these functions. > So if the module was primarily written to be included in the core, I > would initially reject it for that very reason. After one year or so > in its life, and a recognizable user base, inclusion can be considered. > > The context was new modules in general, not specifically an AES > module. Since "considered" means "thought about", so you said > inclusion shouldn't even be thought about until the module is already > done. That's completely in conflict with the idea of inviting anyone > to work on a new module, since inviting means that there's been some > thought. I rarely invite people to work on new modules. For new modules, I normally propose that they develop the module, and ship it to users for some time. I may have made exceptions to this rule in the past, e.g. when the proposal is to simply wrap an existing C API in a Python module (like shadow passwords). In this case, both the interface and the implementation are straight-forward, and I expect no surprises. For an AES module (or most other modules), I do expect surprises. > I would say there's an implied promise of something more than a code > review. There's an implied statement that you agree that the proposed > new functionality is useful, which means the patch has a good chance > of being accepted to the stdlib if it's not too messy or cumbersome. I have said many times that I am in favour of including an AES implementation in the Python distribution, e.g. in http://mail.python.org/pipermail/python-dev/2003-April/034963.html What I cannot promise is to include *your* AES implementation, not without getting user feedback first. The whole notion of creating the module from scratch just to include it in the core strikes me as odd - when there are so many AES implementations out there already that have been proven useful to users. > So let me just ask you one final question: suppose I do all that > stuff. The question: in your personal opinion, based on the best > information you have, what is the your own subjective estimate of the > probability? Eventually, with hard work, I estimate the chances at, say, 90%. That is, eventually, unless the code itself shows flaws, the module *will* be included. However, initially, when first proposed, the chances are rather like 10%. I.e. people will initially object. Decision processes take their time, and valid concerns must be responded to. I personally think that there is a good response to each concern, but it will take time to find it. Before that, it will take time to find out what precisely the concern is. Regards, Martin From jonathan.burd at REMOVEMEgmail.com Mon Jan 24 05:34:23 2005 From: jonathan.burd at REMOVEMEgmail.com (Jonathan Burd) Date: Mon, 24 Jan 2005 16:04:23 +0530 Subject: how to write a tutorial In-Reply-To: <1106472508.591411.40140@c13g2000cwb.googlegroups.com> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: <35k13gF4nvosaU1@individual.net> Xah Lee wrote: > adding to my previosu comment... *plonk* -- "Women should come with documentation." - Dave From merkosh at hadiko.de Sun Jan 16 04:35:38 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Sun, 16 Jan 2005 10:35:38 +0100 Subject: accessing class variables of private classes Message-ID: Hi, I need to access class variables of a class I'd like to make private: i.e. class __Bar(object): pass class __Foo(__Bar): def __init__(self): super(__Foo, self).__init__() >>> __Foo() Name Error: global name '_Foo__Foo' is not defined Here I want to prevent the user of instanciating __Foo from outside of the module. i.e. class __A: a_list = [] def __init__(self): __A.a_list.append(self) >>> __A() NameError: global name '_A__A' is not defined Here I want to keep a list of instanciated objects of class __A, so I can update internal values if they are changed. Any ideas? Thanks Uwe From steve at holdenweb.com Fri Jan 14 11:46:06 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 11:46:06 -0500 Subject: newbie ?s In-Reply-To: <1105656971.768148@sj-nntpcache-5> References: <1105656971.768148@sj-nntpcache-5> Message-ID: <41E7F74E.6030009@holdenweb.com> Venkat B wrote: > Hi folks, > > I'm looking build a CGI-capable SSL-enabled web-server around Python 2.4 on > Linux. > It is to handle ~25 hits possibly arriving "at once". Content is non-static > and built by the execution of py cgi-scripts talking to a few backend > processes. > > 1) I was wondering if anyone has opinions on the ability of CGIHTTPServer (a > forking variant) to be able to handle this. I wouldn't even consider it. The *HTTPServer modules aren't really intended to be much beyond a proof-of-concept, IMHO. Certainly you'd be likely to stress the system having 25 requests arrive in a bunch, though a modern computer would probably handle it. > 2) If so, would something like pyOpenSSL be useful to make such a webserver > SSL-enabled. > There is a *lot* to do to SSL-enable a server. Since you advertise yourself as a newbie, I'd suggest there were better places to focus your efforts. > I checked out John Goerzen's book: Foundations of Python Network Programming > (ISBN 1590593715) and searched around. While I found how one can write py > scripts that could communicate with SSL-enabled webservers, tips on building > SSL-enabled webservers isn't obvious. > > I was hoping to build a cleaner solution around the CGIHTTPServer variant > instead of say something like mini-httpd/OpenSSL/Python. I'd appreciate any > pointers. > I believe the Twisted package may be your best alternative, though this is at best hearsay since I am not (yet) an active user. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From mahs at telcopartners.com Mon Jan 24 13:47:32 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Mon, 24 Jan 2005 10:47:32 -0800 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7xoefhtavd.fsf@ruckus.brouhaha.com> Message-ID: Fredrik Lundh wrote: > Sion Arrowsmith wrote: >>I'm probably not thinking deviously enough here, but how are you >>going to exploit an eval() which has very tightly controlled >>globals and locals (eg. eval(x, {"__builtins__": None}, {}) ? > > try this: > > eval("'*'*1000000*2*2*2*2*2*2*2*2*2") > I updated the safe eval recipe I posted yesterday to add the option of reporting unsafe source, rather than silently ignoring it. Is this completely safe? I'm interested in feedback. Michael Some source to try: >>> goodsource = """[1, 2, 'Joe Smith', 8237972883334L, # comment ... {'Favorite fruits': ['apple', 'banana', 'pear']}, # another comment ... 'xyzzy', [3, 5, [3.14159, 2.71828, []]]]""" ... Unquoted string literal >>> badsource = """[1, 2, JoeSmith, 8237972883334L, # comment ... {'Favorite fruits': ['apple', 'banana', 'pear']}, # another comment ... 'xyzzy', [3, 5, [3.14159, 2.71828, []]]]""" ... Non-constant expression >>> effbot = "'*'*1000000*2*2*2*2*2*2*2*2*2" >>> safe_eval(good_source) [1, 2, 'Joe Smith', 8237972883334L, {'Favorite fruits': ['apple', 'banana', 'pear']}, 'xyzzy', [3, 5, [3.1415899999999999, 2.71828, []]]] >>> assert _ == eval(good_source) >>> safe_eval(bad_source) Traceback (most recent call last): [...] Unsafe_Source_Error: Line 1. Strings must be quoted: JoeSmith >>> safe_eval(bad_source, fail_on_error = False) [1, 2, None, 8237972883334L, {'Favorite fruits': ['apple', 'banana', 'pear']}, 'xyzzy', [3, 5, [3.1415899999999999, 2.71828, []]]] >>> safe_eval(effbot) Traceback (most recent call last): [...] Unsafe_Source_Error: Line 1. Unsupported source construct: compiler.ast.Mul >>> safe_eval(effbot, fail_on_error = False) ... '*' >>> Source: import compiler class Unsafe_Source_Error(Exception): def __init__(self,error,descr = None,node = None): self.error = error self.descr = descr self.node = node self.lineno = getattr(node,"lineno",None) def __repr__(self): return "Line %d. %s: %s" % (self.lineno, self.error, self.descr) __str__ = __repr__ class AbstractVisitor(object): def __init__(self): self._cache = {} # dispatch table def visit(self, node,**kw): cls = node.__class__ meth = self._cache.setdefault(cls, getattr(self,'visit'+cls.__name__,self.default)) return meth(node, **kw) def default(self, node, **kw): for child in node.getChildNodes(): return self.visit(child, **kw) visitExpression = default class SafeEval(AbstractVisitor): def visitConst(self, node, **kw): return node.value def visitDict(self,node,**kw): return dict([(self.visit(k),self.visit(v)) for k,v in node.items]) def visitTuple(self,node, **kw): return tuple(self.visit(i) for i in node.nodes) def visitList(self,node, **kw): return [self.visit(i) for i in node.nodes] class SafeEvalWithErrors(SafeEval): def default(self, node, **kw): raise Unsafe_Source_Error("Unsupported source construct", node.__class__,node) def visitName(self,node, **kw): raise Unsafe_Source_Error("Strings must be quoted", node.name, node) # Add more specific errors if desired def safe_eval(source, fail_on_error = True): walker = fail_on_error and SafeEvalWithErrors() or SafeEval() try: ast = compiler.parse(source,"eval") except SyntaxError, err: raise try: return walker.visit(ast) except Unsafe_Source_Error, err: raise From daniel at bowettsolutions.com Thu Jan 13 15:23:11 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Thu, 13 Jan 2005 20:23:11 +0000 Subject: News Reader Message-ID: <41E6D8AF.6050702@bowettsolutions.com> Is anyone reading this list through thunderbird as news? If so - how did you set it up? From richie at entrian.com Tue Jan 25 07:40:49 2005 From: richie at entrian.com (Richie Hindle) Date: Tue, 25 Jan 2005 12:40:49 +0000 Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) In-Reply-To: References: Message-ID: [Steven] > Can someone give me an example of where __-mangling really solved a problem > for them, where a simple leading underscore wouldn't have solved the > same problem? http://cvs.sourceforge.net/viewcvs.py/spambayes/spambayes/spambayes/Dibbler.py?r1=1.13&r2=1.13.4.1 That's a bugfix to SpamBayes, where I'd inadvertently named an instance variable '_map' without realising that the base class (asynchat.async_chat) also had an instance variable of that name. Using double underscores fixed it, and had I used them from the beginning the bug would never have cropped up (even if asynchat.async_chat had an instance variable named '__map', which is the whole point (which you know, Steven, but others might not)). -- Richie Hindle richie at entrian.com From tjreedy at udel.edu Wed Jan 5 19:44:53 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 5 Jan 2005 19:44:53 -0500 Subject: Python evolution: Unease References: <41DC4BA2.3090107@bowettsolutions.com> Message-ID: "Daniel Bowett" wrote in message news:41DC4BA2.3090107 at bowettsolutions.com... >Thanks, typically how long does it take for any documentation to be >considered and implemented? Right now, rough guess, based on my haphazard collection of knowledge and experience, I would anticipate 1 to 60 days for up to a paragraph. Terry J. Reedy From none.by.e-mail Thu Jan 6 17:03:02 2005 From: none.by.e-mail (Mike Thompson) Date: Fri, 07 Jan 2005 09:03:02 +1100 Subject: Another PythonWin Excel question In-Reply-To: References: Message-ID: <41ddb59e$0$8338$afc38c87@news.optusnet.com.au> It's me wrote: > I followed the example in > http://stompstompstomp.com/weblog/technical/2004-05-20 and learned that to > add a new worksheet to an Excel workbook, you would use the > workbook.Worksheets.Add() method. That works. However, the new worksheet > got added *in front* of the last worksheet I was at. How can I get it to > add *after*? > > Thanks, > > -- > Me > > Does this help? http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_wrcore/html/wrtskhowtomoveworksheetswithinworkbooks.asp -- Mike From simon.brunning at gmail.com Wed Jan 12 08:03:39 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 12 Jan 2005 13:03:39 +0000 Subject: Python Installation In-Reply-To: References: <1105220812.579690.292260@c13g2000cwb.googlegroups.com> <1105232505.142279.85810@c13g2000cwb.googlegroups.com> <41E15306.7090108@holdenweb.com> Message-ID: <8c7f10c6050112050359e52633@mail.gmail.com> On Tue, 11 Jan 2005 21:00:40 +0100, Fredrik Lundh wrote: > Steve Holden wrote: > > > Hmm, effbot.org seems to be down just now. Sure it'll be back soon, though. > > http://news.bbc.co.uk/2/hi/europe/4158809.stm Good to see that it was effbot.org that was down, rather that the effbot himself. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From manatlan_no_s_p_a_m at free.fr Mon Jan 31 17:46:24 2005 From: manatlan_no_s_p_a_m at free.fr (manatlan) Date: Mon, 31 Jan 2005 23:46:24 +0100 Subject: "Mail receiver server" In-Reply-To: References: <41feaff2$0$2068$626a14ce@news.free.fr> Message-ID: <41feb541$0$27942$636a15ce@news.free.fr> Mitja a ?crit : > On Mon, 31 Jan 2005 23:23:46 +0100, manatlan > wrote: > >> in fact, i'd like to control "computer A" by sending smtp email from >> "computer B". >> >> What kind of server should i write on computer "B", a smtp server ? a >> pop server ? > > > It would be easier if you used an existing mail server (which OS are > you running on comp B?), then use its redirecting features to pipe the > incoming mail to your python script. AFAIK most servers support that. > Less hassle, though probably a wee bit more intensive for the computer. the OS is a win32 (w2k), with IIS ... there is a "Virtual SMTP server" in IIS ... I like the idea, but how to connect the virtual smtp and a python script ? but ... There should be a way to be python only ... because i don't want to be very complex, i just want to get the subject of the email, to run some commands (and perhaps get a attachment file) ... but that's all i am pretty sure that a recipe exists ... that a man has already done that ! But i don't know what to query on google ... From wrightca at hotmail.com Fri Jan 28 08:59:45 2005 From: wrightca at hotmail.com (Chris Wright) Date: Fri, 28 Jan 2005 13:59:45 GMT Subject: a sequence question Message-ID: Hi, 1) I want to iterate over a list "N at a time" sort of like: # Two at a time... won't work, obviously >>> for a, b in [1,2,3,4]: ... print a,b ... Traceback (most recent call last): File "", line 1, in ? TypeError: unpack non-sequence >>> Is there a nifty way to do with with list comprehensions, or do I just have to loop over the list ? cheers and thanks chris wright From ncoghlan at iinet.net.au Mon Jan 10 08:25:52 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 10 Jan 2005 23:25:52 +1000 Subject: Python3: on removing map, reduce, filter In-Reply-To: References: <34csn1F4a46hqU1@individual.net> Message-ID: <41E28260.4080506@iinet.net.au> Terry Reedy wrote: > "Andrey Tatarinov" wrote in message > news:34csn1F4a46hqU1 at individual.net... > >>How does GvR suggestions on removing map(), reduce(), filter() > > > While GvR *might* prefer removing them completely on any given day, I think > moving them to a functional module, as others have suggested and requested, > is currently more likely. I believe that GvR has indicated at times that > this would be an acceptible compromise. > > I am one of those who think the list of builtins is currently too long to > be easily grasped and should be shrunk. Heh. When PEP 309 hits CVS (with functional.partial), maybe it can grow aliases for the three of them so people can get used to the idea. It might keep partial from getting too lonely. . . :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From fredrik at pythonware.com Fri Jan 21 12:01:08 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 21 Jan 2005 18:01:08 +0100 Subject: Funny Python error messages References: <1106315907.551660.276380@c13g2000cwb.googlegroups.com> Message-ID: Peter Hansen wrote: >> My first one (i'm learning, i'm learning) is >> >> TypeError: 'callable-iterator' object is not callable >> >> # >>> it = iter(lambda:0, 0) >> # >>> it() >> # TypeError: 'callable-iterator' object is not callable > > Given that the supposed humour depends on the *name* of > the object, which is "callable-iterator", I'd say it's > probably not hard to come up with lots of "funny" error > messages this way. note that will didn't name the type himself. someone callously thought it would be a cool idea to have a non-callable type called callable in python, rather than, say, call it "iterator-that-dances-with-callables". From ncoghlan at iinet.net.au Tue Jan 25 09:53:01 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 00:53:01 +1000 Subject: Another scripting language implemented into Python itself? In-Reply-To: <1106643765.733317.27440@f14g2000cwb.googlegroups.com> References: <1106643765.733317.27440@f14g2000cwb.googlegroups.com> Message-ID: <41F65D4D.4070708@iinet.net.au> Fuzzyman wrote: > An implementation of the core language semantics - without any modules > or file operations would be dead useful. > > It could replace some of the function of the long dead rexec modules as > well as support projects like this. Securing a custom build of the CPython interpreter would probably be significantly easier than designing a 'secure mode' that ran on top of the standard version. The former might even be a stepping stone towards the latter. Still not easy though (the main task would be to prevent Python code from accessing the OS, while still allowing module imports to work). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From fredrik at pythonware.com Mon Jan 17 16:23:32 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Jan 2005 22:23:32 +0100 Subject: supplying constants in an extension module References: Message-ID: Torsten Mohr wrote: > i write an extension module in C at the moment. > > I want to define some constants (integer mainly, > but maybe also some strings). > > How do i do that best within this extension module > in C? Do i supply them as RO attributes? > > What's the best way for it? reading the source for existing modules will teach you many useful idioms. here's how this is currently done: PyMODINIT_FUNC initmymodule(void) { PyObject *m; m = Py_InitModule(...); PyModule_AddIntConstant(m, "int", value); PyModule_AddStringConstant(m, "string", "string value"); } (both functions set the exception state and return -1 if they fail, but you can usually ignore this; the importing code will check the state on return from the init function) if you want to support older versions of Python, you need to add stuff to the module dictionary yourself. an example: #if PY_VERSION_HEX < 0x02030000 DL_EXPORT(void) #else PyMODINIT_FUNC #endif initmymodule(void) { PyObject* m; PyObject* d; PyObject* x; m = Py_InitModule(...); d = PyModule_GetDict(m); x = PyInt_FromLong(value); if (x) { PyDict_SetItemString(d, "INT", x); Py_DECREF(x); } x = PyString_FromString("string value"); if (x) { PyDict_SetItemString(d, "STRING", x); Py_DECREF(x); } } From ncoghlan at iinet.net.au Fri Jan 21 09:45:19 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 22 Jan 2005 00:45:19 +1000 Subject: Print a string in binary format In-Reply-To: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> Message-ID: <41F1157F.4060300@iinet.net.au> neutrino wrote: > Greetings to the Python gurus, > > I have a binary file and wish to see the "raw" content of it. So I open > it in binary mode, and read one byte at a time to a variable, which > will be of the string type. Now the problem is how to print the binary > format of that charater to the standard output. It seems a common task > but I just cannot find the appropriate method from the documentation. > Thanks a lot. > FWIW, I work with serial data a lot, and I find the following list comprehension to be a handy output tool for binary data: print " ".join(["%0.2X" % ord(c) for c in data]) The space between each byte helps keep things from degenerating into a meaningless mass of numbers, and using 2-digit hex instead of binary works towards the same purpose. (I actually currently use the hex() builtin, but the above just occurred to me, and it will give nicer formatting, and avoids the C-style "0x" prefixing each byte) Here's an interesting twiddle, though (there's probably already something along these lines in the cookbook): Py> def show_base(val, base, min_length = 1): ... chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" ... if base < 2: raise ValueError("2 is minimum meaningful base") ... if base > len(chars): raise ValueError("Not enough characters for base") ... new_val = [] ... while val: ... val, remainder = divmod(val, base) ... new_val.append(chars[remainder]) ... result = "".join(reversed(new_val)) ... return ("0" * (min_length - len(result))) + result ... Py> show_base(10, 2) '1010' Py> show_base(10, 2, 8) '00001010' Py> show_base(10, 16, 2) '0A' Py> show_base(254, 16, 2) 'FE' Py> show_base(0, 16) '0' Py> for base in range(2, 36): ... for testval in range(1000): ... assert testval == int(show_base(testval, base), base) ... Py> Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From claudio.grondi at freenet.de Fri Jan 21 03:18:02 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 21 Jan 2005 08:18:02 -0000 Subject: [ANN] PyScript 0.5 released References: <61de6b8e.0501201943.3cbc9ec3@posting.google.com> Message-ID: <35c0hcF4jnr7pU2@individual.net> http://sourceforge.net/project/showfiles.php?group_id=50346 shows the date of release of pyscript-0.5 as: 2004-05-11 07:00 What is then the reason for this [ANN] ? Claudio "Paul Cochrane" schrieb im Newsbeitrag news:61de6b8e.0501201943.3cbc9ec3 at posting.google.com... > PyScript is a python module for producing high quality postscript > graphics. Rather than use a GUI to draw a picture, the picture is > programmed using python and the PyScript objects. > > Some of the key features are: > * All scripting is done in python, which is a high level, easy to > learn, well developed scripting language. > * All the objects can be translated, scaled, rotated, ... in fact > any affine transformation. > * Plain text is automatically kerned. > * You can place abritrary LaTeX expressions on your figures. > * You can create your own figure objects, and develop a library of > figure primitives. > * Output is publication quality. > > LICENSE: Released under the GPL > > The major change in this release is a complete rewrite of the Path > object. The internals have completely changed and there have been > some incompatible changes with previous versions but it's now much > closer to what was envisaged for the object. There have also been > many bug fixes and minor other improvements. For details see the > PyScript web page: > pyscript.sourceforge.net. > >

          PyScript 0.5 - a > python module for producing high quality postscript graphics; rather > than use a GUI to draw a picture, the picture is programmed using > python and the pyscript objects. (10-Jan-05) > > -- > paultcochrane at users.sourceforge.net From annaraven at gmail.com Mon Jan 10 13:22:19 2005 From: annaraven at gmail.com (Anna) Date: 10 Jan 2005 10:22:19 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> Message-ID: <1105381339.922714.23200@c13g2000cwb.googlegroups.com> You cut something from that... """It's not, after all, the word "lambda" itself; I would still have some issues with using, say "function", instead of "lambda", but at least then I would immediately know what I was looking at...""" I would have fewer ambiguities about using, say "func" rather than lambda. Lambda always makes me feel like I'm switching to some *other* language (specifically, Greek - I took a couple of semesters of Attic Greek in college and quite enjoyed it.) But, the fact that lambda doesn't MEAN anything (and has come - I mean - DELTA at least has a fairly commonly understood meaning, even at high-school level math. But, lambda? If it was "func" or "function" or even "def", I would be happier. At least that way I'd have some idea what it was supposed to be... BTW - I am *quite* happy with the proposal for "where:" syntax - I think it handles the problems I have with lambda quite handily. Anna From cdieterich at geosci.uchicago.edu Wed Jan 26 13:59:10 2005 From: cdieterich at geosci.uchicago.edu (Christian Dieterich) Date: Wed, 26 Jan 2005 12:59:10 -0600 Subject: inherit without calling parent class constructor? In-Reply-To: Message-ID: <5C81D022-6FCC-11D9-8B47-000A9582377C@geosci.uchicago.edu> On D? C?adaoin, Ean 26, 2005, at 11:46 America/Chicago, Steven Bethard wrote: > I'm confused as to how you can tell when it's avoidable... Do you > mean you don't want to call 'method' if you don't have to? Could you > make size a property, e.g. > Then 'size' won't be calculated until you actually use it. If 'size' > is only to be calculated once, you might also look at Scott David > Daniels's lazy property recipe: On D? C?adaoin, Ean 26, 2005, at 12:03 America/Chicago, Daniel Dittmar wrote: > - rename B to A > - class B (A) > - move the costly constructor from A to B > - class D (A) > > You can now move some parts from B.__init__ to A.__init__ if they are > really needed by D as well. Thanks for the input. Yes, I see. I should have been more specific about 'when it's avoidable'. I guess this was part of my question: Is it avoidable? Steven, your solution works fine, as long as I don't access the size attribute. However, my instances of A use their size attributes quite often within other methods of A (not listed in my example). So, I'd just postpone the execution of the expensive part until later. Daniel, maybe I should have made it clearer in my example. The "A"-objects actually need the size attribute. If I'd outsource the size attribute (and its computation) to a class I don't inherit from, the "A"-objects won't have access to it. Or did I miss something in your solution? The size attribute only needs to be computed once and stays constant after that. The lazy property recipe of Scott David Daniels looks promising. I'll try that, when I've installed Python 2.4. However, I need my package to work on machines where there is Python 2.2 and 2.3 only. Thanks for more ideas, Christian From s_david_rose at hotmail.com Thu Jan 6 13:49:07 2005 From: s_david_rose at hotmail.com (GMane Python) Date: Thu, 6 Jan 2005 13:49:07 -0500 Subject: Download .jpg from web Message-ID: Hello All. Using a network camera with built-in webserver, I'd like to have a python program download .jpg files on a local lan. the location is http:///jpg/image.jpg. Currently, I'm importing urllib and using urlopen to the address, then read()-ing it, saving it to a binary file. All that is working great, but maybe a bit slowly. I'm getting ~2.3 frames per second, and would like between 5-10 frames per second. Am I approaching this incorrectly? I have to do a urlopen, then .read() for each image. Is there any way to 'persist' the urlopen so I just have to keep read()-ing or maybe is there a type of streaming read? I have many cameras, so there are many threads simultaneously reading and dropping them in a central Queue for saving later. I appreciate it! -Dave WebImage = urllib.urlopen("http:///jpg/image.jpg").read() QueuePacket = [] QueuePacket.append(WebImage) From rkern at ucsd.edu Wed Jan 5 20:25:08 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 05 Jan 2005 17:25:08 -0800 Subject: Python evolution: Unease In-Reply-To: References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <16859.16548.249527.30210@montanaro.dyndns.org> <864d37090501050117761a32e6@mail.gmail.com> Message-ID: Bulba! wrote: > On Wed, 5 Jan 2005 07:37:25 -0600, Skip Montanaro > wrote: > I've never needed numeric stuff either. I just need to do things like: > > .>>> table.sort(column_name) # that obviously would sort rows of table > by the values of column column_name [snip for brevity] > Now suppose a programmer could write a custom complement function > that detects all the irregularly distributed "anomalous" data points > (be it whatever, missing surnames from personnel records or values > from a physical experiments that are below some threshold) in this > table and returns, say, a list of tuples that are coordinates of those > data points. Getting it from a specific table would be a matter of one > instruction! > > Yes, I know, it can be written by hand. But by this line of logic why > bother learning VHLL and not just stay with C? I'm not sure what you mean by "written by hand." Someone is going to have to write the functions in the first place. Sure, they can be written once, well, and placed in the standard library so they don't have to be *re*written by anyone else again. I still think numarray is a good start for this. It handles more than just numbers. And RecArray (an array that has different types in each column, as you seem to require) can be subclassed to add these methods to it. >>If it's deemed useful I'm sure someone from that >>community could whip something out in a few minutes. The concepts >>represented by the csv module are a lot shallower than those represented by >>Numarray. > > > True, and I may scratch enough time together to learn all the > necessary stuff (I'm not even half done in learning Python) > to write it myself. > > That is not the point, however: the biggest boost and one of the > main points of getting into Python, at least for me, but I'm sure > this is also motivation for quite a lot of other people, is precisely > the ease of exploiting capabilities of data structures like > dictionaries and lists, which when coupled with this data structure's > object-style .method are simply very convenient and fast. This is > where IMHO Python excels among the VHLL languages. > > I'm about to post reworked version of my program that doesn't > use a _single_ traditional loop to do all the data transformations > I need (I just still need to solve some problems there / polish > it). > > This is not just about that damn CSV file that I already have > the way I wanted it and sent it to customer, this is about _terse > and clear_ manipulations of rich data structures in Python. Why not > extend them with flexible tables / matrices / arrays that would work > in as "Pythonic" ways as dictionaries and lists already do? Sure. We're working on it! Come check out numarray; I think you'll like it. And if, along the way, you write a CSV-to-RecArray converter, we'd *love* to include it in the distribution. I think that a more complete integration with the other core Python facilities like the csv module will help numarray become more suited for inclusion into the standard library. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From Scott.Daniels at Acm.Org Wed Jan 5 15:48:58 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 05 Jan 2005 12:48:58 -0800 Subject: Python 2.4 on Windows XP In-Reply-To: <10toje56oiebq24@corp.supernews.com> References: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> <10toje56oiebq24@corp.supernews.com> Message-ID: <41dc4ffd$1@nntp0.pdx.net> Jeff Shannon wrote: > DavidHolt wrote: >> I have a problem that I see on two different machines, one running XP >> SP1 and one XP SP 2.... On both I installed Python 2.4. >> I can't seem to start IDLE. When I try to start it, I get an hourglass >> cursor for a short time then nothing more happens. This happens whether >> I click the IDLE shortcut or click the pythonw.exe directly, or attempt >> to launch pythonw from a command line. > > Maybe I'm misinterpreting you, here, but pythonw.exe is *not* IDLE. It > is, instead, a console-less version of the Python interpreter, which can > run the Python scripts for IDLE (among other things). > > My version of Python is older, but in %pythondir%/Tools/idle, there is > an idle.pyw file. Try running that. On 2.4, the directory is: %pythondir%/Lib/idlelib Remember that for Windows, \ is the separator. SO, change an idle shortcut to, for example: C:\Python24\Python.exe C:\Python24\Lib\idlelib\idle.pyw I suspect your real problem is the internal firewall in XP, in which case you'll need to allow building sockets to LOCALHOST (127.0.0.1) on port 8833, or, alternatively, start idle with the "-n" flag. --Scott David Daniels Scott.Daniels at Acm.Org From peter at engcorp.com Sat Jan 8 12:41:02 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Jan 2005 12:41:02 -0500 Subject: 2 versions of python on 1 machine In-Reply-To: References: <0fydnX5CmoCCwkDcRVn-2w@powergate.ca> Message-ID: flupke wrote: > I used the 2 batch files technique and removed c:\python23 from my > path var and all is fine now. > Where did you find more info on PYTHONHOME and PYTHONPATH because > the docs don't seem to contain a whole lot of info. Typing "python -h" gives a good start. I'm sorry, I don't recall where else there is useful info on those, though I'm pretty sure Google could help. (I'm not sure there's much to add to what the "-h" option tells you, however.) -Peter From aorfanakos at gmail.com Sun Jan 30 14:54:26 2005 From: aorfanakos at gmail.com (Aggelos I. Orfanakos) Date: 30 Jan 2005 11:54:26 -0800 Subject: Regarding exception handling In-Reply-To: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> Message-ID: <1107114866.965331.158950@f14g2000cwb.googlegroups.com> (I don't know why, but indentation was not preserved once I posted.) From matt.torment at gmail.com Fri Jan 21 22:32:48 2005 From: matt.torment at gmail.com (torment) Date: 21 Jan 2005 19:32:48 -0800 Subject: Determining if a client PC has an Internet connection References: <1095578301.31957.263.camel@devilbox.devilnet.internal> Message-ID: <1106364768.871474.92810@z14g2000cwz.googlegroups.com> Have you tried just parsing the output from the command "ipconfig"? It's pretty obvious from the output that might give you if a connection is availible. I hope it helps. -Matt Dave Brueck wrote: > Cliff Wells wrote: > > I'm writing an application that needs to know if an Internet connection > > is available. > [snip] > > Is there any way to reliably determine the state of the client's > > internet connectivity? > > Hi Cliff, > > On a Win32 system you can reliably determine the state of the Internet > connection but it requires a fair amount of work. Here's the recipe I use: > > 1) If the user has a modem and is connected via a modem, you know for sure that > the user is online (use ctypes to call rasapi32.RasEnumEntriesA to see if the > user has a modem, and rasapi32.RasEnumConnectionsA to see if the user is > connected via a modem) > > 2) If that test fails, next check for open connections to remote hosts. If there > are any open connections to public IP addresses, the user is "online". (use > iphlpapi.GetTcpTable to get a list of connections, and keep only those where > dwState is MIB_TCP_STATE_ESTAB. Remove any addresses that are 127.0.0.1, 10.*, > 192.168.*, or 172.16-31.*). If after all this the list is non-empty, you're > probably online. > > 3) Still no luck? Call IcmpSendEcho to a well-known server - this sends a "ping" > packet, which won't bring up the dial-up networking box to annoy your users. I > usually start with a list of all the DNS root servers as well as pingable > company IP addresses, and randomly choose one of them. Then, anytime I make a > connection to the Internet, I save the results of the hostname lookup and use > them in my list as well (so that very few pings actually go to the DNS root > servers). Also, it's good to make sure that your code has restrictions in place > to prevent it from pinging anything too often. Due to instant messengers & email > clients, step #2 usually detects when the user is online, so the need for an > actual ping is greatly reduced. > > Anyway, after doing the above you know with a high degree of certainty whether > or not the user is online. > > The above approach is obviously a lot of work, but once you take the time to do > it you can just stick it in a library somewhere and not have to think about it > again. On import of the library, I start up a background thread that updates a > status variable every second or so, so that any time my app can query to see the > state of the Internet connection. Although it's a lot of work, I've found that > (1) it's pretty accurate and (2) it's non-intrusive (it doesn't e.g. pop up the > dial-up networking dialog box if the user is offline). > > Hope at least some of this helps, > Dave From bokr at oz.net Fri Jan 7 18:34:16 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 07 Jan 2005 23:34:16 GMT Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <7xis6930ah.fsf@ruckus.brouhaha.com> <7xvfa90w6g.fsf@ruckus.brouhaha.com> Message-ID: <41df17a6.262000737@news.oz.net> On 07 Jan 2005 13:24:39 -0800, Paul Rubin wrote: >Nick Coghlan writes: >> Add in the fact that there are many, many Python programmers with >> non-CS backgrounds, and the term 'lambda' sticks out like a sore thumb >> from amongst Python's other English-based keywords. 'def' is probably >> the second-most cryptic when you first encounter it, but it is a good >> mnemonic for "define a function", so it's still easy to parse. "Lambda >> is the term mathematicians use to refer to an anonymous function" is >> nowhere near as grokkable ;) > >Richard Feynman told a story about being on a review committee for >some grade-school science textbooks. One of these book said something >about "counting numbers" and it took him a while to figure out that >this was a new term for what he'd been used to calling "integers". > >"Integer" is a math term but I think that if we need to use the >concept of integers with someone unfamiliar with the term, it's best >to just introduce the term and then use it, rather than make up new >terminology like "counting numbers" even if those words sound more >like conversational English. It's an example of the educational establishment's conspiracy to keep children from too quickly outshining teachers who feel threatened by raw intelligence rather than elated at the opportunity to help it form. Forcing kids to learn a throwaway baby-goo language before they get the real thing is a kind of abuse IMO. > >For the same reason I don't have any problem with "lambda", though >it's not that big a deal. > >I also just can't believe that Pythonistas keep getting into these >arguments over whether lambda is too confusing, while at the same time >there's no such discussion over far more abstruse Python features like >metaclasses. Some things are considered to be behind the pythonostasis and only for the priests? ;-) Regards, Bengt Richter From steven.bethard at gmail.com Tue Jan 4 17:20:27 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 04 Jan 2005 22:20:27 GMT Subject: why does UserDict.DictMixin use keys instead of __iter__? In-Reply-To: <1104871215.023027.46040@f14g2000cwb.googlegroups.com> References: <1104836152.639270.196200@z14g2000cwz.googlegroups.com> <1RxCd.847728$8_6.18665@attbi_s04> <1104871215.023027.46040@f14g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > OK, I'll rephrase: what is your interest in DictMixin? > > My interest: I'm into mappings that provide an approximate match > capability, and have a few different data structures that I'd like to > implement as C types in a unified manner. The plot includes a base type > that, similarly to DictMixin, provides all the non-basic methods. I was recently trying to prototype a simple mapping type that implements the suggestion "Improved default value logic for Dictionaries" from http://www.python.org/moin/Python3_2e0Suggestions You can't just inherit from dict and override dict.__getitem__ because dict.__getitem__ isn't always called: py> class D(dict): ... def __init__(*args, **kwds): ... self = args[0] ... self.function, self.args, self.kwds = None, None, None ... super(D, self).__init__(*args[1:], **kwds) ... def setdefault(self, function, *args, **kwds): ... self.function, self.args, self.kwds = function, args, kwds ... def __getitem__(self, key): ... if key not in self: ... super(D, self).__setitem__( ... key, self.function(*self.args, **self.kwds)) ... return super(D, self).__getitem__(key) ... py> d = D() py> d.setdefault(list) py> d['c'].append(2) py> d {'c': [2]} py> print d.get('d') # should print [] None This, of course, is exactly the kind of thing that DictMixin is designed for. =) Of course, it's no trouble for me to implement keys(). I was just wondering why that design decision was made when it seems like __iter__ is more integral to the mapping protocol. And if you want efficient iteration over your mapping type, you're going to have to define __iter__ too... Steve From steven.bethard at gmail.com Thu Jan 6 23:53:45 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 06 Jan 2005 21:53:45 -0700 Subject: what is lambda used for in real code? In-Reply-To: References: Message-ID: <-rmdnWR7E9ZKiEPcRVn-gg@comcast.com> I wrote: > * Functions I don't know how to rewrite > Some functions I looked at, I couldn't figure out a way to rewrite them > without introducing a new name or adding new statements. > [snip] > > inspect.py: def formatargspec(args, varargs=None, varkw=None, > ... > formatvarargs=lambda name: '*' + name, > formatvarkw=lambda name: '**' + name, > formatvalue=lambda value: '=' + repr(value), > inspect.py: def formatargvalues(args, varargs, varkw, locals, > ... > formatvarargs=lambda name: '*' + name, > formatvarkw=lambda name: '**' + name, > formatvalue=lambda value: '=' + repr(value), Realized today that I do know how to rewrite these without a lambda, using bound methods: def formatargspec(args, varargs=None, varkw=None, ... formatvarargs='*%s'.__mod__, formatvarkw='**%s'.__mod__, formatvalue='=%r'.__mod__, I like this rewrite a lot because you can see that the function is basically just the given format string. YMMV, of course. Similarly, if DEF_PARAM, DEF_BOUND and glob are all ints (or supply the int methods), I can rewrite > symtable.py: self.__params = self.__idents_matching(lambda x: > x & DEF_PARAM) > symtable.py: self.__locals = self.__idents_matching(lambda x: > x & DEF_BOUND) > symtable.py: self.__globals = self.__idents_matching(lambda x: > x & glob) with the bound methods of the int objects: self.__params = self.__idents_matching(DEF_PARAM.__rand__) self.__locals = self.__idents_matching(DEF_BOUND.__rand__) self.__globals = self.__idents_matching(glob.__rand__) (Actually, I could probably use __and__ instead of __rand__, but __rand__ was the most direct translation.) Ahh, the glory of bound methods... ;) Steve From luismgz at gmail.com Tue Jan 11 22:32:04 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 11 Jan 2005 19:32:04 -0800 Subject: Python.org, Website of Satan In-Reply-To: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: <1105500724.648914.213880@z14g2000cwz.googlegroups.com> humblythegreat... at usa.com wrote: > python.org = 194.109.137.226 > > 194 + 109 + 137 + 226 = 666 > > What is this website with such a demonic name and IP address? What > evils are the programmers who use this language up to? You dared to unveil our secret. Now we'll have to kill you... From rparnes at megalink.net Tue Jan 25 21:03:12 2005 From: rparnes at megalink.net (Bob Parnes) Date: Wed, 26 Jan 2005 02:03:12 -0000 Subject: Maximum Number of Class Attributes Message-ID: In its default configuration, my version of pylint (0.5.0) sets the maximum number of class attributes at 7. This seems low to me, but I can see how an excessive number might make maintenance more difficult. Is this indeed the best value for a maximum under ordinary conditions? If not, can anyone suggest a more reasonable value? Thanks in advance. Bob Parnes -- Bob Parnes rparnes at megalink.net From michele.simionato at gmail.com Tue Jan 11 04:04:41 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 11 Jan 2005 01:04:41 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <10u5fu3o7v4h9e3@corp.supernews.com> Message-ID: <1105434281.780099.326350@f14g2000cwb.googlegroups.com> Jacek: > Given a population with previous exposure to computer programming, my > money is on the map-lambda version. But this last point is mostly > irrelevant. The fact is that you cannot program computers without > doing a bit of learning ... and the lambda, map and friends really do > not take any significant learning. This kind of "sociological" study would be pretty interesting to me ;-) Personally, I find out that my mind manage pretty well one-level of indirection at time, not two. Consider for instance def add1(x): return x+1 map(add1, mylist) Here there are *two* levels of indirection: first, I need to define add1; second I need to translate mentally map to a loop. Using lambda does not help: map(lambda x: x+1, mylist) still would require two levels for me, one to recognize the lambda and one to convert map to a loop. This is too much for me, so I just write [x+1 for x in mylist] where everything is explicit (or if you wish, I have just to recognize that there is a loop going on, pretty easy). However, if I can skip a level of indirection (i.e. I do not need to define a function) I just prefer map: map(int, mylist) is simpler for me than [int(x) for x in mylist] since the latter introduces an useless x (which is also polluting my namespace, but this not my point, I could use a generator-expression instead). So, in practice, I only use map with built-in or with predefined functions, i.e. functions which are already there for some other purpose; I do not like to be forced to write a function (or a lambda) for the only purpose of using map (at least in Python). Incidentally, I am not fond of the name "lambda" too. "fn", as Paul Graham says, looks much better. What I would like, in Python, is some facility to manage callbacks in the standard library, then I would live pretty well without lambdas. Just IMHO, YMMV, etc. Michele Simionato From jeff at ccvcorp.com Thu Jan 13 19:39:33 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 13 Jan 2005 16:39:33 -0800 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: <1105651353.769879.229690@f14g2000cwb.googlegroups.com> References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <41e5ebee.709560864@news.oz.net> <1105632841.461042.68310@c13g2000cwb.googlegroups.com> <10udfj4c4rgkvcc@corp.supernews.com> <1105651353.769879.229690@f14g2000cwb.googlegroups.com> Message-ID: <10ue4s49jl8s6d7@corp.supernews.com> Chris Lasher wrote: >>And besides, for long-term archiving purposes, I'd expect that zip et >>al on a character-stream would provide significantly better >>compression than a 4:1 packed format, and that zipping the packed >>format wouldn't be all that much more efficient than zipping the >>character stream. > > This 105MB FASTA file is 8.3 MB gzip-ed. And a 4:1 packed-format file would be ~26MB. It'd be interesting to see how that packed-format file would compress, but I don't care enough to write a script to convert the FASTA file into a packed-format file to experiment with... ;) Short version, then, is that yes, size concerns (such as they may be) are outweighed by speed and conceptual simplicity (i.e. avoiding a huge mess of bit-masking every time a single base needs to be examined, or a human-(semi-)readable display is needed). (Plus, if this format might be used for RNA sequences as well as DNA sequences, you've got at least a fifth base to represent, which means you need at least three bits per base, which means only two bases per byte (or else base-encodings split across byte-boundaries).... That gets ugly real fast.) Jeff Shannon Technician/Programmer Credit International From db3l at fitlinxx.com Tue Jan 18 17:36:47 2005 From: db3l at fitlinxx.com (David Bolen) Date: 18 Jan 2005 17:36:47 -0500 Subject: lambda References: <41EBA021.5060903@holdenweb.com> Message-ID: Antoon Pardon writes: > Op 2005-01-18, Simon Brunning schreef : > > On 18 Jan 2005 07:51:00 GMT, Antoon Pardon wrote: > >> 3 mutating an item in a sorted list *does* *always* cause problems > > > > No, it doesn't. It might cause the list no longer to be sorted, but > > that might or might no be a problem. > > Than in the same vain I can say that mutating a key in a dictionary > doesn't always cause problems either. Sure it may probably make a > key unaccessible directly, but that might or might not be a problem. Well, I'd definitely consider an inaccessible key as constituting a problem, but I don't think that's a good analogy to the list case. With the dictionary, the change can (though I do agree it does not have to) interfere with proper operation of the dictionary, while a list that is no longer sorted still functions perfectly well as a list. That is, I feel "problems" are more guaranteed with a dictionary since we have affected base object behavior, whereas sorted is not an inherent attribute of the base list type but something the application is imposing at a higher level. For example, I may choose to have an object type that is mutable (and not worthy for use as a dictionary key) but maintains a logical ordering so is sortable. I see no problem with sorting a list of such objects, and then walking that list to perform some mutation to each of the objects, even if along the way the mutation I am doing results in the items so touched no longer being in sorted order. The act of sorting was to provide me with a particular sequence of objects, but aside from that fact, the list continues to perform perfectly well as a list even after the mutations - just no longer delivering objects in sorted order. -- David From fredrik at pythonware.com Tue Jan 25 03:02:51 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 25 Jan 2005 09:02:51 +0100 Subject: error References: Message-ID: "me" wrote: > whenever i try and run my Python GUI, my computer thinks for a sec, then > drops the process, without ever displaying the window. the command prompt > window seems to work fine, but the IDLE GUI won't start. > > i'm running Windows 2K professional and python 2.4, so any advice help would > be appreciated. i've already tried reinstalling and use a thread response, > as the e-mail on this account is bogus. have you tried tweaking your firewall settings? idle uses socket communication between its processes, and some firewalls may interfere with this. see: http://www.python.org/2.4/bugs.html as a last resort, there's also a way to run idle in "single process" mode: http://article.gmane.org/gmane.comp.python.general/383376 From ksenia.marasanova at gmail.com Sat Jan 8 16:26:01 2005 From: ksenia.marasanova at gmail.com (Ksenia Marasanova) Date: Sat, 8 Jan 2005 23:26:01 +0200 Subject: escape string for command line In-Reply-To: References: Message-ID: <130df19305010813265d55c955@mail.gmail.com> > > > > I was wondering, is there a general way to escape the string entered > > by the user, to prevent code injection into command line? > > Take a look at the "string-escape" encoding: > > >>> evil = "'; rm -rf /;" > >>> command = "echo '%s'" > >>> print command % evil.encode('string-escape') > echo '\'; rm -rf /;' Cool, thanks! Next time I'll study stdlib better before asking the question :) -- Ksenia From beliavsky at aol.com Mon Jan 17 09:54:43 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 17 Jan 2005 06:54:43 -0800 Subject: OCAMl a more natural extension language for python? References: <41ebb95e$0$6625$8fcfb975@news.wanadoo.fr> Message-ID: <1105973683.624738.268960@f14g2000cwb.googlegroups.com> Jelle Ferringa wrote: >Since I haven't got actual experience programming CAML I'd like to speculate >that OCAML would be a very pythonic way of extending python: its >open-source, object oriented, as fast as C, and ! garbage collecting! The open source g95 Fortran 95 compiler is already usable and will be officially released this year. Fortran and C are comparable in speed, and if one uses allocatable arrays rather than pointers, memory leaks should not occur. Fortran 2003 supports OOP with inheritance, and a few F95 compilers already have this functionality. >That's depending on how you compare; I find OCAML quite readable compared to C / Fortran . Have you ever used Fortran 90 or 95? I don't use OCAML, so I looked at some OCAML code to multiply matrices at http://shootout.alioth.debian.org/benchmark.php?test=matrix&lang=ocaml&id=0&sort=cpu from the Computer Language Shootout . To create a matrix the OCAML code is 7 let mkmatrix rows cols = 8 let count = ref 1 and last_col = cols - 1 9 and m = Array.make_matrix rows cols 0 in 10 for i = 0 to rows - 1 do 11 let mi = m.(i) in 12 for j = 0 to last_col do mi.(j) <- !count; incr count done; 13 done; In Python with Numeric it's just x = zeros([nrow,ncol],Float) and in Fortran 90/95 it's just real, allocatable :: x(:,:) allocate (x(nrow,ncol)) There appears not to be a built-in function for matrix multiplication in OCAML. There is in Python with Numeric or Numarray or Fortran 90/95. For problems where the main data structures are arrays, OCAML seems to be considerably more low-level than Python with Numeric/Numarray or Fortran 90/95. Also, there exists a vast computational infrastructure in Fortran and C (see http://www.netlib.org). Does OCAML have this? From FBatista at uniFON.com.ar Mon Jan 10 11:34:53 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 10 Jan 2005 13:34:53 -0300 Subject: Writing huge Sets() to disk Message-ID: [Martin MOKREJ?] #- > At least you'll need a disk of 34694 EXABYTES!!! #- #- Hmm, you are right. So 20E15 then? I definitely need to be Right. Now you only need 355 PETABytes. Nowadays disk is cheap, but... #- in range 1-14. ;-) Why? . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From joh12005 at yahoo.fr Fri Jan 21 08:58:03 2005 From: joh12005 at yahoo.fr (Joh) Date: 21 Jan 2005 05:58:03 -0800 Subject: need help on generator... Message-ID: <63b5e209.0501210558.686f5c10@posting.google.com> hello, i'm trying to understand how i could build following consecutive sets from a root one using generator : l = [1,2,3,4] would like to produce : [1,2], [2,3], [3,4], [1,2,3], [2,3,4] but unfortunately can not, i guess i can do it by using sub generator and maybe enumerate, please if you help could you explain a bit the trick ? looks like this sub generator thing mess me up. (i think it should may be also have [1,], [2,], [3,], [1,2,3,4] , and then be filtered) bests From JoshuaACohen at gmail.com Thu Jan 6 13:06:29 2005 From: JoshuaACohen at gmail.com (Josh) Date: 6 Jan 2005 10:06:29 -0800 Subject: File Handling Problems Python I/O In-Reply-To: References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> Message-ID: <1105034789.700445.291380@z14g2000cwz.googlegroups.com> Peter, Thank you for the rookie correction. That was my exact problem. I changed the address to use forward slashes and it works perfect. I did not know that a backslash had special meaning within a string, but now I do! Thanks again Josh From grante at visi.com Wed Jan 12 23:05:07 2005 From: grante at visi.com (Grant Edwards) Date: 13 Jan 2005 04:05:07 GMT Subject: pyserial and com port interrupts References: <24lbu0htudrc9ir4b0na3r1m6g09qlbck4@4ax.com> Message-ID: <41e5f373$0$78846$a1866201@visi.com> On 2005-01-13, engsol wrote: > I'm not sure what timeout value I'd use. Using threads, and re-loading the > timeout values on the fly may be a solution, but I'm not experienced with > threads....and was hoping to avoid them. Using threads in Python is really, really painless. -- Grant Edwards grante Yow! Someone is DROOLING at on my collar!! visi.com From spambucket at intensity.org.uk Sat Jan 29 17:07:17 2005 From: spambucket at intensity.org.uk (Andrew Collier) Date: Sat, 29 Jan 2005 22:07:17 +0000 Subject: scope rules in nested functions Message-ID: Hello, I was writing a program which used some nested functions, and came across a behaviour which I was unable to explain. I can summarise it with the example below: #!/usr/bin/env python def evalfunction0(a): print "Call by eval - Success! arg =",a def evalfunction3(a): def evalfunction1(a): string = "evalfunction0(a+1)" eval(string) def evalfunction2(a): string = "evalfunction1(a+1)" eval(string) # uncomment the next line to make the PREVIOUS line work! # evalfunction1(-1) string = "evalfunction2(a+1)" eval(string) def callfunction0(a): print "Function call - Success! arg =",a def callfunction3(a): def callfunction1(a): callfunction0(a+1) def callfunction2(a): callfunction1(a+1) callfunction2(a+1) callfunction3(0) evalfunction3(0) What I see (although I've only been able to test it in Python version 2.3 so far) is that the eval() call in evalfunction2, is unable to resolve the symbol name evalfunction1 - even though it would be possible to call that function directly. But it is even stranger to me that, if evalfunction1() is called directly, then calling that function using eval() from the same function also works. I had previously assumed that the symbols available to eval() would be the symbols available as literals, but it seems not. Is this a designed feature, and if so would somebody be kind enough to describe why it occurs? More practically, if there are a large number of functions at the same nesting level as evalfunction1(), is it possible for me to allow evalfunction2() to access all of them without explicitly naming each one as a literal? Thanks, Andrew -- --- Andrew Collier ---- To reply by email, please use: ---- http://www.intensity.org.uk/ --- 'andrew {at} intensity.org.uk' -- Have you lost your Marbles? http://www.marillion.com/ From bokr at oz.net Wed Jan 26 05:12:29 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 26 Jan 2005 10:12:29 GMT Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> <1106669254.838248.317170@z14g2000cwz.googlegroups.com> <10vdj4s9ib19fe3@corp.supernews.com> <35o6cdF4qe45fU1@individual.net> Message-ID: <41f76c97.1856549026@news.oz.net> On Tue, 25 Jan 2005 19:25:55 -0500, "George Sakkis" wrote: >"Jeff Shannon" wrote in message news:10vdj4s9ib19fe3 at corp.supernews.com... >> George Sakkis wrote: >> >> > An iterator is perfectly ok if all you want is to iterate over the >> > elements of a view, but as you noted, iterators are less flexible than >> > the underlying sequence. The view should be (or at least appear) >> > identical in functionality (i.e. public methods) with its underlying >> > sequence. >> >> So, what problem is it, exactly, that you think you'd solve by making >> tuple slices a view rather than a copy? >> >> As I see it, you get the *possibility* of saving a few bytes (which > >It all comes down on what you mean by "a few bytes". Since many (most?) slices are linear wrt to the >original sequence's length, it is not hard to think of algorithms that involve the creation of >*many* slices (e.g. most recursive divide-and-conquer algorithms). Implementing these using slices >simply does not scale as the input sequence gets larger. Of course, you can always use the standard >C/C++ approach and pass the original sequence along with the (start,stop,step) indices of the slice, >as Terry Reedy mentioned, but then you lose in expressiveness. I didn't see the leadup to this, but what is the problem with just subclassing tuple to give you the views you want? Regards, Bengt Richter From danperl at rogers.com Wed Jan 26 18:25:09 2005 From: danperl at rogers.com (Dan Perl) Date: Wed, 26 Jan 2005 18:25:09 -0500 Subject: exclude binary files from os.walk References: Message-ID: "rbt" wrote in message news:ct94j7$15a$1 at solaris.cc.vt.edu... > Is there an easy way to exclude binary files (I'm working on Windows XP) > from the file list returned by os.walk()? > > Also, when reading files and you're unsure as to whether or not they are > ascii or binary, I've always thought it safer to 'rb' on the read, is this > correct... and if so, what's the reasoning behind this? Again all of this > pertains to files on Windows XP and Python 2.4 Please clarify: is your question about identifying binary (non-ascii) files or about using os.walk? From g.franzkowiak at web.de Sat Jan 15 15:11:51 2005 From: g.franzkowiak at web.de (G.Franzkowiak) Date: Sat, 15 Jan 2005 21:11:51 +0100 Subject: interpret 4 byte as 32-bit float (IEEE-754) In-Reply-To: <41e964bc$1@nntp0.pdx.net> References: <34t1p2F4foiplU1@individual.net> <41e952b9$1@nntp0.pdx.net> <41E96302.4020003@web.de> <41e964bc$1@nntp0.pdx.net> Message-ID: <41E97907.9070709@web.de> Scott David Daniels schrieb: > G.Franzkowiak wrote: > >> Scott David Daniels schrieb: >> >>> franzkowiak wrote: >>> >>>> I've read some bytes from a file and just now I can't interpret 4 >>>> bytes in this dates like a real value. An extract from my program: >>>> def l32(c): >>>> return ord(c[0]) + (ord(c[1])<<8) + (ord(c[2])<<16) + >>>> (ord(c[3])<<24) >>>> ... >>>> value = l32(f.read(4)) <--- 3F 8C CC CD should be 1.11 >>>> >>> OK, here's the skinny (I used blocks & views to get the answer): >>> >>> import struct >>> bytes = ''.join(chr(int(txt, 16)) for txt in '3F 8C CC CD'.split()) >>> struct.unpack('>f', bytes) >>> >>> I was suspicious of that first byte, thought it might be an exponent, >>> since it seemed to have too many on bits in a row to be part of 1.11. >>> >>> -Scott David Daniels >>> Scott.Daniels at Acm.Org >> >> >> >> Ok, I the string exist with "mystr = f.read(4)" and the solution for >> this case is in your line "struct.unpack('>f', bytes)" >> But what can I do when I want the interpret the content from the >> Integer myInt (*myInt = 0x3F8CCCCD) like 4-byte-real ? >> This was stored with an othes system in a binary file to >> CD CC 8C 3F and now is it in python in value. The conversion is not >> possible. It's right... one of this bytes is an exponent. >> I want copy the memory content from the "value address" to "myReal >> address" and use print "%f" %myReal. >> Is myReal then the right format ? >> What can I do with python, in FORTH is it simple >> ( >f f. ) >> >> gf >> >> >> > If you really want to do this kind of byte fiddling: > http://members.dsl-only.net/~daniels/block.html > > Then: > from block import Block, View > b = Block(4) # enough space for one float (more is fine) > iv = View('i', b) # getting to it as an integer > fv = View('f', b) # same memory as floating point > iv[0] = 0x3F8CCCCD # Here is a sample just using the integer > print fv[0] > > On an Intel/Amd/Generic "PC" machine, you should get 1.1 > > -Scott David Daniels > Scott.Daniels at Acm.Org That's good :-)) I'm missing the makefile ;-) I'm using the other world... right Thank you From petite.abeille at gmail.com Sat Jan 29 08:46:04 2005 From: petite.abeille at gmail.com (PA) Date: Sat, 29 Jan 2005 14:46:04 +0100 Subject: The next Xah-lee post contest In-Reply-To: <5a309bd305012905357e14df62@mail.gmail.com> References: <5a309bd305012905357e14df62@mail.gmail.com> Message-ID: <154dcd68a20fa7294999305fef1a0f27@gmail.com> On Jan 29, 2005, at 14:35, Steve wrote: > Write up the next Xah Lee post ! The requirement are: > a) The post should talk about a single language, although the example > code needn't adhere to that restriction. > b) It should explain the style, structure and design of some code > snippet/program, though not necessarily of the same code > snippet/program mentioned in the post. > c) Should be written in English ... respect to English grammar is not > mandatory. > d) It *must* be flammable. Oh, my... this is going to be so much fun 8^) > Here's my contribution (tho' I'm not really in my most creative frame > of mind): Master the ways of the Xah, young Steve: "Pathetically Elational Regex Language, aka Pathological Euphoric Retching Language (A commentary on Perl)" http://www.xahlee.org/UnixResource_dir/perlr.html Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Mon Jan 17 08:10:43 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Do Re Mi chel La Si Do) Date: Mon, 17 Jan 2005 14:10:43 +0100 Subject: OCAMl a more natural extension language for python? References: Message-ID: <41ebb95e$0$6625$8fcfb975@news.wanadoo.fr> Hi ! OCAML is very complementary at Python : unreadable vs readable functionnel vs procedural/POO/etc. compiled vs interpreted (or compil JIT) very fast vs mean velocity hard to learn vs easy to easy to learn Yes, OCAML is very complementary, too much, much too, complementary at Python... But, C is not complementary to Python (in the same state of mind). And, what do you think of... Erlang ? @-salutations -- Michel Claveau From stephen.thorne at gmail.com Thu Jan 27 04:01:43 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 27 Jan 2005 19:01:43 +1000 Subject: String Fomat Conversion In-Reply-To: References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> Message-ID: <3e8ca5c805012701013e97fb7@mail.gmail.com> On Thu, 27 Jan 2005 00:02:45 -0700, Steven Bethard wrote: > Stephen Thorne wrote: > > f = file('input', 'r') > > labels = f.readline() # consume the first line of the file. > > > > Easy Option: > > for line in f.readlines(): > > x, y = line.split() > > x = float(x) > > y = float(y) > > > > Or, more concisely: > > for line in f.readlines(): > > x, y = map(float, line.split()) > > Somewhat more memory efficient: > > lines_iter = iter(file('input')) > labels = lines_iter.next() > for line in lines_iter: > x, y = [float(f) for f in line.split()] > > By using the iterator instead of readlines, I read only one line from > the file into memory at once, instead of all of them. This may or may > not matter depending on the size of your files, but using iterators is > generally more scalable, though of course it's not always possible. I just did a teensy test. All three options used exactly the same amount of total memory. I did all I did in the name of clarity, considering the OP was on his first day with python. How I would actually write it would be: inputfile = file('input','r') inputfile.readline() data = [map(float, line.split()) for line in inputfile] Notice how you don't have to call iter() on it, you can treat it as an iterable to begin with. Stephen. From http Sat Jan 29 04:55:40 2005 From: http (Paul Rubin) Date: 29 Jan 2005 01:55:40 -0800 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <7xu0p0yin0.fsf@ruckus.brouhaha.com> Message-ID: <7xpszo36g3.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > Fair cop on the C thing, but that example otherwise illustrates my > point perfectly. I'm not sure what point you mean. > Unpickling untrusted data is just as dangerous as evaluating or > executing untrusted data. > > This is *still* dangerous, because there *is no patch* to fix the > problem. Pickle is now documented as being unsafe for untrusted data. It's just like eval now. Nobody is going to make a patch for eval that makes it safe for untrusted data. It would be nice if there were a pickle alternative that's safe to use with untrusted data, but that's sort of a separate issue (see the marshal doc thread referenced earlier). > There are only documentation changes to highlight the security risks > associated with unpickling, and I would say that unpickle's feature set actually changed incompatibly, since (see analysis in the sf bug thread) unpickle was originally designed to be safe. > Deprecation Warnings on the Cookie classes which use this unsafe feature. Yes, that means as soon as someone uses Cookie.Cookie, their application will throw a DeprecationWarning and they have to fix the error before the app can run. > So, the only effective mechanism is to get the word out to Python > *users* that the feature is unsafe, and should be used with care, > which basically requires telling the world about the problem. That's true, but the problem still has to be analyzed and a recommendation formulated, which can take a little while. > Any time Python has a problem of this sort, there is going to be at > least one solution, and only possibly two: > > 1. Avoid the feature that represents a security risk > 2. Eliminate the security risk in a maintenance update. You forgot 3. install a patch as soon as you become aware of the problem, without waiting for a maintenance update. > By keeping the process public, and clearly identifying the problematic > features, application developers can immediately start working on > protecting themselves, in parallel with the CPython developers > (possibly) working on a new maintenance release. The hope is that during the short period in which there's a confidential bug report in the system, the number of exploits in the wild won't change. Either attackers knew about the bug already and have exploits out before the bug is even reported, or they don't know about it yet. Either way, random application developers get the bug report at the same time as attackers. So the choices are that app developers get a raw bug report and have to figure out a solution while at the same time attackers who saw the same announcement are starting to launch new exploits, or else when the app developers get the bug report, they also get a bunch of analysis from the Python developers, which can help them decide what to do next. I think they benefit from the analysis, if they can get it. Keep in mind also that the submitters of the bug reports often don't see the full implications, that the app developers also might not see, but that attackers are likely to figure out instantly. So again, it helps if the Python developers can supply some analysis of their own. Finally, some reports of security bugs turn out to not really be bugs (I've submitted a few myself that have turned out that way). That kind of thing can panic an application developer into shutting down a service unnecessarily while figuring out what to do next, often at a cost of kilobucks or worse per minute of downtime, or maybe having some lesser fire drill to figure out that the problem is a non-problem. Better to let the Python developers explain the problem and close the bug before publishing it. > To go with the 72 hours + 8 example you gave - what if you could work > around the broken feature in 6? If 6 hours from seeing the raw bug report are enough to analyze the problem and develop a workaround, then given not only the raw bug report but also 72 hours worth of analysis and recommendations/fixes from the developers, I should need even less than 6 hours to install a patch. > I suspect we'll have to agree to disagree on this point. Where we can > agree is that I certainly wouldn't be unhappy if SF had a feature like > Bugzilla's security flag. I do have to say that developer responsiveness to security issues varies from one program to another. It's excellent for OpenBSD and reasonably good for Mozilla; but for Python, it's something of a weak spot, as we're seeing. From beliavsky at aol.com Sun Jan 2 13:11:04 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 2 Jan 2005 10:11:04 -0800 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> Message-ID: <1104689464.828070.309990@c13g2000cwb.googlegroups.com> Roy Smith wrote: >I think you've hit the nail on the head. In awk (and perl, and most >shells, and IIRC, FORTRAN), using an undefined variable silently gets >you a default value (empty string or zero). This tends to propagate >errors and make them very difficult to track down. You may recall correctly, but Fortran compilers have improved. The following Fortran 90 program integer, parameter :: n = 1 real :: x,y=2.0,z(n) print*,"dog" print*,x z(n+1) = 1.0 print*,z end has 3 errors, all detected at compile time by the Lahey/Fujitsu Fortran 95 compiler, with the proper options: 2004-I: "xundef.f", line 2: 'y' is set but never used. 2005-W: "xundef.f", line 4: 'x' is used but never set. 2153-W: "xundef.f", line 5, column 1: Subscript out of range. At run time, the output is dog The variable (x) has an undefined value. Error occurs at or near line 4 of _MAIN__ Running Python 2.4 on the Python analog, n = 1 y = 2.0 z = range(n) print "dog" print x z[n] = 1.0 print z one error is caught: dog Traceback (most recent call last): File "xundef.py", line 5, in ? print x NameError: name 'x' is not defined You will see the out-of-bounds error for z only after fixing the undefined-x error. No warning is ever given about y, which is set but never used. In practice, 'print "dog"' could be some operation taking hours. Can PyChecker find all the problems in a single run, without executing 'print "dog"'? If so, it would be great if it were integrated with the CPython interpreter. One reason interpreted languages like Python are recommended to beginners is to avoid the edit/compile/debug cycle. But I think it is faster and less frustrating to have many errors caught in one shot. From deetsNOSPAM at web.de Tue Jan 18 08:30:13 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 18 Jan 2005 14:30:13 +0100 Subject: generator expressions: performance anomaly? References: <377Hd.77904$Jk5.30235@lakeread01> <354gj7F4etgn8U1@individual.net> Message-ID: <354h9gF4fgsqgU1@individual.net> > Would it be a bad solution to make that a list or tuple of ten > time.time() calls, you could also restrict what theese prebuilding > sequenses could contain, or perhaps try to prebuild them, and then fail > if it's impossible. I don't fully understand what you mean. Restricting them would mean to add static declarations that say "I return the same whenever you call me" - which is even more than the already fragile "const" declaration of c++ allows. And for your second suggestion - how exactly do you check for failing? Generating 2 elements and checking if they are equal to the first two of the old list? What about overloaded __cmp__/__eq__, or just the last element differing? This problem is too complex to solve automatically - domain knowledge is needed. As the code Antoon presented also suggests the simple solution: lst = list(time.time() for i in xrange(10)) tpl = tuple(lst) I don't see why this is a desirable feature at all. Keep in mind that putting statements or even stackframes between those two statements above utterly complicates things. And we even didn't dig into the dynamic features of python that for example make it possible to alter time.time like this time.time = random.random() so that it behaves totally different - while the syntactically equivalence still holds. No chance of catching that. -- Regards, Diez B. Roggisch From philippecmartin at sbcglobal.net Wed Jan 5 06:34:38 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Wed, 05 Jan 2005 12:34:38 +0100 Subject: smtp: one more question Message-ID: <1104924878.21010.25.camel@localhost> >Email client = Evolution: the "From" field is blank >Email client = KMail: the "To" field is blank I also notice that emails sent to myself get trashed by my provider - could that be related ? -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From cpl.19.ghum at spamgourmet.com Wed Jan 26 15:06:31 2005 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Wed, 26 Jan 2005 20:06:31 +0000 (UTC) Subject: py2exe problem References: <41f7213c$0$2343$a1866201@visi.com> Message-ID: Thomas Heller wrote in news:zmywh4yx.fsf at python.net: >> >> A software development system which REALLY solves the encodings >> problem WITHOUT creating a swarm of new ones could would challange >> even my devotedness to Python :)))) > > AFAIK, McMillan Installer solves this by including all the encodings > stuff by default, and it has a --ascii flag to override this > behaviour. Would that be a solution? Thomas, I solved the headaches with py2exe and encodings, again and again ... even documented some of these steps within the wiki. But encodings still give me new pain any day: storing filenames to databases, displaying filenames in windows-controls, sending database-extracts to excel or word ... time on time encodings and/or unicode errors pop up and cause me misery. So my cryout is for a solution for all encoding-problems like the python for-loop or list-comprehensions: elegant, simple, robust, flexible. Easy to use, easy to implement. Harald From phr at localhost.localdomain Thu Jan 27 10:54:26 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Thu, 27 Jan 2005 15:54:26 GMT Subject: Please suggest on the book to follow References: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> Message-ID: "santanu" writes: > I know a little python (not the OOP part) learnt by studying the online > tutorial. Now I would like to learn it more thoroughly. I think there's supposed to be a new version of Python in a Nutshell coming. That's a more serious book than Learning Python. From anthony at python.org Wed Jan 26 03:51:55 2005 From: anthony at python.org (Anthony Baxter) Date: Wed, 26 Jan 2005 19:51:55 +1100 Subject: RELEASED Python 2.3.5, release candidate 1 Message-ID: <200501261952.06150.anthony@python.org> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.3.5 (release candidate 1). Python 2.3.5 is a bug-fix release. See the release notes at the website (also available as Misc/NEWS in the source distribution) for details of the bugs squished in this release. Assuming no major problems crop up, a final release of Python 2.3.5 will follow in about a week's time. Python 2.3.5 is the last release in the Python 2.3 series, and is being released for those people who still need to use Python 2.3. Python 2.4 is a newer release, and should be preferred if possible. From here, bugfix releases are switching to the Python 2.4 branch - a 2.4.1 will follow 2.3.5 final. For more information on Python 2.3.5, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.3.5 Highlights of this new release include: - Bug fixes. According to the release notes, more than 50 bugs have been fixed, including a couple of bugs that could cause Python to crash. Highlights of the previous major Python release (2.3) are available from the Python 2.3 page, at http://www.python.org/2.3/highlights.html Enjoy the new release, Anthony Anthony Baxter anthony at python.org Python Release Manager (on behalf of the entire python-dev team) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From crap1234 at hotmail.com Sun Jan 2 06:38:29 2005 From: crap1234 at hotmail.com (Stefan Axelsson) Date: Sun, 02 Jan 2005 12:38:29 +0100 Subject: The Industry choice In-Reply-To: <7xacrs230c.fsf@ruckus.brouhaha.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> Message-ID: <33q4plF410bo2U1@individual.net> Paul Rubin wrote: > I do believe that it's a horrible deficiency in Python that it has no > declarations at all, even optional ones, like "perl -w" or "use > strict". Python's scoping hacks that result from the lack of > declarations just seem to me like pure insanity. Yes, ignoring most of the debate about static vs. dynamic typing, I've also longed for 'use strict'. Sure Python isn't as bad as (say) Awk in this respect; you have to at least assign a variable to make it spring into existence, but I've been bitten by typos there as well. Same when it comes to object methods (I can often never remember my method names). Pychecker helps to some extent, but I wouldn't mind a compiler that only accepted identifiers that had been declared. I don't think that anyone could argue that typing 'use apa' before the first actual use (or words to that effect) would 'slow them down', or be very onerous. Stefan, -- Stefan Axelsson (email at http://www.cs.chalmers.se/~sax) From mfuhr at fuhr.org Mon Jan 10 16:21:06 2005 From: mfuhr at fuhr.org (Michael Fuhr) Date: 10 Jan 2005 14:21:06 -0700 Subject: Reading Fortran binary files References: <1105385733.855390.83220@c13g2000cwb.googlegroups.com> Message-ID: <41e2f1c2$1_1@omega.dimensional.com> "drife" writes: > I need to read a Fortran binary data file in Python. > The Fortran data file is organized thusly: > > nx,ny,nz,ilog_scale # Record 1 (Header) > ihour,data3D_array # Record 2 > > Where every value above is a 2 byte Int. Have you looked at the struct module? http://www.python.org/doc/2.4/lib/module-struct.html -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From spam-trap-095 at at-andros.demon.co.uk Tue Jan 18 16:26:40 2005 From: spam-trap-095 at at-andros.demon.co.uk (Andrew McLean) Date: Tue, 18 Jan 2005 21:26:40 +0000 Subject: Fuzzy matching of postal addresses References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <$aq2IQPQ8X7BFwRy@at-andros.demon.co.uk> Thanks for all the suggestions. There were some really useful pointers. A few random points: 1. Spending money is not an option, this is a 'volunteer' project. I'll try out some of the ideas over the weekend. 2. Someone commented that the data was suspiciously good quality. The data sources are both ones that you might expect to be authoritative. If you use as a metric, having a correctly formatted and valid postcode, in one database 100% the records do in the other 99.96% do. 3. I've already noticed duplicate addresses in one of the databases. 4. You need to be careful doing an endswith search. It was actually my first approach to the house name issue. The problem is you end up matching "12 Acacia Avenue, ..." with "2 Acacia Avenue, ...". I am tempted to try an approach based on splitting the address into a sequence of normalised tokens. Then work with a metric based on the differences between the sequences. The simple case would look at deleting tokens and perhaps concatenating tokens to make a match. -- Andrew McLean From charlotte.herzeel at gmail.com Mon Jan 17 08:40:53 2005 From: charlotte.herzeel at gmail.com (Charlie) Date: 17 Jan 2005 05:40:53 -0800 Subject: dynamic data types Message-ID: <1105969253.296411.301760@f14g2000cwb.googlegroups.com> Hi, The description of Python always mentions "very high level dynamic data types". Now, I can't seem to find any examples of these (nothing described with this term anyway). Is this simply refering to built-in dynamic data structures such as lists and dictionaries, with a great deal of operators defined on? Or is there something else meant by "dynamic data types" in Python? Regards, Charlie From steve at holdenweb.com Sat Jan 15 22:12:28 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 15 Jan 2005 22:12:28 -0500 Subject: python mode indentation problem In-Reply-To: <1105842678.044409.270450@z14g2000cwz.googlegroups.com> References: <1105802644.939051.229990@f14g2000cwb.googlegroups.com> <1105842678.044409.270450@z14g2000cwz.googlegroups.com> Message-ID: Xah Lee wrote: [...] > ? > ? who the fuck coded the python mode in emacs? fuckhead please peruse: > ? http://xahlee.org/UnixResource_dir/writ/responsible_license.html > ? Pure egotism. Not to mention bad language. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From dalke at dalkescientific.com Mon Jan 3 17:09:17 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Mon, 03 Jan 2005 22:09:17 GMT Subject: emulating an and operator in regular expressions References: Message-ID: Craig Ringer wrote: > My first thought would be to express your 'A and B' regex as: > > (A.*B)|(B.*A) > > with whatever padding, etc, is necessary. You can even substitute in the > sub-regex for A and B to avoid writing them out twice. That won't work because of overlaps. Consider barkeep with a search for A='bark' and B='keep'. Neither A.*B nor B.*A will match because the 'k' needs to be in both A and B. The OP asked for words, so consecutive letters separated by non-letters or end of string. With that restriction this solution will work. Another possibility is to use positive assertions, as in (?=A)(?=.*B)|(?=B)(?=.*A) The best solution is to do a string.find and not worry about implementing this as a regexp. Andrew dalke at dalkescientific.com From olafzeta at yahoo.com Wed Jan 19 12:00:13 2005 From: olafzeta at yahoo.com (Olaf Zetanien) Date: Wed, 19 Jan 2005 18:00:13 +0100 Subject: simultaneous multiple requests to very simple database References: <3A81C87DC164034AA4E2DDFE11D258E33981ED@exchange.hqamor.amorhq.net> Message-ID: On Tue, 18 Jan 2005 12:57:21 -0500, Eric S. Johansson wrote: > Robert Brewer wrote: >> Eric S. Johansson wrote: >> >>> I have an application where I need a very simple database, effectively >>> a very large dictionary. The very large >>> dictionary must be accessed from multiple processes >>> simultaneously. I need to be able to lock records within >>> the very large dictionary when records are written to. >> Just to clarify, you want shared-read until a write, at which point >> you >> want to lock just the item being written? Or would page or table locking >> be acceptable at that point? > > just the item/record. I'm doing arrival rate calculations. each record > contains a set of arrival times and I am rewriting the record every time > a new entry arrives. complete page or table locking will work in the > sense that it will prevent collisions but it will have an increasing > impact as load and simultaneous table but not record accesses increase. > > ---eric > Use Firebird as sql backend. Is designed as you request (readers not lock writers and writers not lock readers). Google for "firebird optimistic lock". Off course, you have python driver: http://kinterbasdb.sf.net and can deploy on windows and linux with a very little footprint. -- Olaf Zetanien From john at grulic.org.ar Fri Jan 14 01:23:18 2005 From: john at grulic.org.ar (John Lenton) Date: Fri, 14 Jan 2005 03:23:18 -0300 Subject: What strategy for random accession of records in massive FASTA file? In-Reply-To: References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Message-ID: <20050114062318.GA4976@grulic.org.ar> On Thu, Jan 13, 2005 at 12:19:49AM +0100, Fredrik Lundh wrote: > Chris Lasher wrote: > > > Since the file I'm working with contains tens of thousands of these > > records, I believe I need to find a way to hash this file such that I > > can retrieve the respective sequence more quickly than I could by > > parsing through the file request-by-request. However, I'm very new to > > Python and am still very low on the learning curve for programming and > > algorithms in general; while I'm certain there are ubiquitous > > algorithms for this type of problem, I don't know what they are or > > where to look for them. So I turn to the gurus and accost you for help > > once again. :-) If you could help me figure out how to code a solution > > that won't be a resource whore, I'd be _very_ grateful. (I'd prefer to > > keep it in Python only, even though I know interaction with a > > relational database would provide the fastest method--the group I'm > > trying to write this for does not have access to a RDBMS.) > > keeping an index in memory might be reasonable. the following class > creates an index file by scanning the FASTA file, and uses the "marshal" > module to save it to disk. if the index file already exists, it's used as is. > to regenerate the index, just remove the index file, and run the program > again. the problem caught my interest, and the way you used a non-mmaped file in a place where using mmap was pretty much obvious (IMVHO) bothered me enough to overcome my laziness. It didn't overcome it by *much*, mind you, so the following probably only works on python 2.3, on Linux, in Argentina, and with FASTA data that looks like the sample I was able to download. However, having said that, the sample I downloaded was one 46MiB file, and reading it in on my notebook was fast enough that I ripped out the saving/reloading of the index and just reindex it every time. Adding back the persistant index is trivial. [ time passes ] In fact, I just found a several-gigabyte fasta file, and I guess you'd want the index for that one; I put the code back in. And now I should really go to bed, because this is very interesting but won't pay the bills. import os, mmap, marshal from UserDict import DictMixin class FASTA(DictMixin): def __init__(self, filename): self.file = f = open(filename) fno = f.fileno() stat = os.fstat(fno) self.map = mmap.mmap(fno, stat.st_size, access=mmap.ACCESS_COPY) self.checkindex() def __getitem__(self, key): p0, pf = self.index[key] m = self.map return m[p0:pf] def keys(self): return self.index.keys() def __contains__(self, key): return self.index.__contains__(key) def checkindex(self): indexfile = self.file.name + ".idx" if os.path.exists(indexfile): # and os.stat(indexfile).st_mtime > os.stat(self.file.name).st_mtime: self.index = marshal.load(open(indexfile, "rb")) else: print 'generating index...' self.genindex() marshal.dump(self.index, open(indexfile, "wb")) print 'done.' def genindex(self): index = {} m = self.map last = None while 1: pos = m.find('>') if last is not None: index[last] = (index[last], pos) if pos == -1: break m.seek(pos) line = m.readline() pos = m.tell() # this is the bit that probably only works with FASTA # files like I was able to find on the 'net. sep = line.index(' ') if sep == -1: name = line[1:].strip() else: name = line[1:sep].strip() index[name] = pos last = name self.index = index db = FASTA("/home/john/tmp/uniprot_sprot.fasta") print db["104K_THEPA"] -- John Lenton (john at grulic.org.ar) -- Random fortune: "Those who believe in astrology are living in houses with foundations of Silly Putty." - Dennis Rawlins, astronomer -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From cookedm+news at physics.mcmaster.ca Wed Jan 12 00:13:30 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 12 Jan 2005 00:13:30 -0500 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> <1g4nx7m906q79$.dlg@usenet.alexanderweb.de> <7xekgr7lpy.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > Alexander Schremmer <2004b at usenet.alexanderweb.de> writes: >> > lists of incoming links to wiki pages, >> >> It does. > > Huh? I don't see those. How does it store them, that's resilient > across crashes? Or does it just get wedged if there's a crash? Most Wiki implementations (MoinMoin included) have this, by using a search. Usually, following the original Wiki (http://c2.com/cgi/wiki) model, you get at it by clicking on the title of the page. Searching instead of indexing makes it very resilient :-) -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From jerf at jerf.org Sun Jan 30 23:42:19 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 30 Jan 2005 23:42:19 -0500 Subject: next line, new line References: <1107142942.626773.131980@c13g2000cwb.googlegroups.com> <1107145309.922093.295360@c13g2000cwb.googlegroups.com> Message-ID: On Sun, 30 Jan 2005 20:21:49 -0800, rasdj wrote: > Thanks Jeremy, something like this would work: > > try: > lines = [ line.replace(",\n;", ")\n;") for line in input ] > > If I could figgure out how to: > > IF ':' in line > READ next line in > lines = [ line.replace(",\n;", ")\n;") for line in input ] > output.write(str.join('', lines)) > > because there are lots of "comma newline" but the only ones I want are > the ones that follow the semicolon. > > RasDJ My apologies, I was unclear when I said "suck the whole file in"; a little too colloquial. ------------- filename = "YOUR_FILENAME_HERE.sql" output = "YOUR_DESTINATION_HERE.sql" f = open(filename) contents = f.read() f.close() contents = contents.replace(",\n;", ")\n;") # optionally, the \n in the second string may be dropped, it isn't # necessary f = open(output, "w") f.write(contents) f.close() ------------ In other words, no mucking around with "lines" at all. You're better off thinking of the file as a flat stream of bytes in this case. From skip at pobox.com Wed Jan 5 08:42:32 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 5 Jan 2005 07:42:32 -0600 Subject: Concepts RE: Python evolution: Unease In-Reply-To: <7xwtus9jbn.fsf@ruckus.brouhaha.com> References: <20050105002302.542768387.EP@zomething.com> <7xr7l06qfc.fsf@ruckus.brouhaha.com> <7xwtus9jbn.fsf@ruckus.brouhaha.com> Message-ID: <16859.61128.32551.597215@montanaro.dyndns.org> Paul> Oops: http://en.wikipedia.org/wiki/Generic_programming Paul> This helps. But I don't see how it's different from what used to Paul> be called polymorphism. I think of generic programming as polymorphism for statically typed languages. Using the example from the Wikipedia reference, you can't have a generic List class that can hold a list of ints as well as a list of animals without using templates. Skip From fumanchu at amor.org Mon Jan 31 00:33:22 2005 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 30 Jan 2005 21:33:22 -0800 Subject: variable declaration Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33982EF@exchange.hqamor.amorhq.net> AlexanderZatvornitskiy wrote: > I'am novice in python, and I find one very bad thing (from my > point of view) in > language. There is no keyword or syntax to declare variable, > like 'var' in > Pascal, or special syntax in C. It can cause very ugly > errors,like this: > > epsilon=0 > S=0 > while epsilon<10: > S=S+epsilon > epselon=epsilon+1 > print S > > It will print zero, and it is not easy to find such a bug! > > Even Visual Basic have 'Option Explicit' keyword! May be, > python also have such > a feature, I just don't know about it? The feature is called "pychecker", and, although it isn't included in the standard distribution, it's readily available: http://pychecker.sourceforge.net/ Robert Brewer MIS Amor Ministries fumanchu at amor.org From rbt at athop1.ath.vt.edu Mon Jan 10 16:37:08 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Mon, 10 Jan 2005 16:37:08 -0500 Subject: exceptions and items in a list In-Reply-To: <34g8i6F4ad39oU1@individual.net> References: <34g8i6F4ad39oU1@individual.net> Message-ID: Andrey Tatarinov wrote: > rbt wrote: > >> If I have a Python list that I'm iterating over and one of the objects >> in the list raises an exception and I have code like this: >> >> try: >> do something to object in list >> except Exception: >> pass >> >> Does the code just skip the bad object and continue with the other >> objects in the list, or does it stop? > > > # skip bad object and continue with others > for object in objects: > try: > #do something to object > except Exception: > pass > > # stop at first bad object > try: > for object in objects: > #do something to object > except Exception: > pass Thanks Andrey. That's a great example of how to do it. From godoy at ieee.org Tue Jan 4 12:06:24 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Tue, 04 Jan 2005 15:06:24 -0200 Subject: Pexpect getting a defuct process References: Message-ID: <7520558.gsEKbpAYTf@strongwill.g2ctech> Baillargeon, Sonny, Ter?a 04 Janeiro 2005 14:42, wrote: > This used to work before but now I get a defunct process after it runs. > Any ideas? "before" what? What has changed in your environment to make it stop working? -- Godoy. From http Wed Jan 12 12:32:41 2005 From: http (Paul Rubin) Date: 12 Jan 2005 09:32:41 -0800 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> <1g4nx7m906q79$.dlg@usenet.alexanderweb.de> <7xekgr7lpy.fsf@ruckus.brouhaha.com> <7x4qhn9q3g.fsf@ruckus.brouhaha.com> Message-ID: <7xr7kq1rk6.fsf@ruckus.brouhaha.com> Alexander Schremmer <2004b at usenet.alexanderweb.de> writes: > > How does it do that? It has to scan every page in the entire wiki?! > > That's totally impractical for a large wiki. > > So you want to say that c2 is not a large wiki? :-) I don't know how big c2 is. My idea of a large wiki is Wikipedia. My guess is that c2 is smaller than that. From tonino.greco at gmail.com Tue Jan 25 08:18:43 2005 From: tonino.greco at gmail.com (Tonino) Date: 25 Jan 2005 05:18:43 -0800 Subject: tkinter socket client ? References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> <35cae5F4jvrirU1@individual.net> <1106311130.446259.30710@f14g2000cwb.googlegroups.com> <1106318469.311179.126140@c13g2000cwb.googlegroups.com> <1106319270.932204.180590@c13g2000cwb.googlegroups.com> Message-ID: <1106659122.977876.234250@z14g2000cwz.googlegroups.com> Hi, thanks for this info - I had to abandon the createfilehandler() method as it is not supported in windows and the GUI "might" be used there at some time ... So - I went the threading route - works well - for now - so I will stick to it ... BUT - the next question: In the Text() widget - why - when the text scrolls off the screen - does the window not follow it ? I have added a scrollbar to it : self.center_frame = Frame(self.top_frame, background="tan", relief=RIDGE) self.text=Text(self.center_frame,background='white') scroll=Scrollbar(self.center_frame) self.text.configure(yscrollcommand=scroll.set) self.text.pack(side=LEFT, fill=BOTH, expand=YES) scroll.pack(side=RIGHT,fill=Y) self.center_frame.pack(side=RIGHT, expand=YES, fill=BOTH) but the window does not scroll to follow the text ? Any ideas ? Thanks Tonino From ncoghlan at iinet.net.au Thu Jan 13 10:48:48 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 14 Jan 2005 01:48:48 +1000 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: <41E12700.8000106@iinet.net.au> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> Message-ID: <41E69860.8080000@iinet.net.au> Nick Coghlan wrote: > Semantics > --------- > The code:: > > with: > > > translates to:: > > def unique_name(): > > > unique_name() I've come to the conclusion that these semantics aren't what I would expect from the construct. Exactly what I would expect can't really be expressed in current Python due to the way local name bindings work. The main thing to consider is what one would expect the following to print: def f(): a = 1 b = 2 print 1, locals() print 3, locals() using: a = 2 c = 3 print 2, locals() print 4, locals() I think the least suprising result would be: 1 {'a': 1, 'b': 2} # Outer scope 2 {'a': 2, 'c': 3} # Inner scope 3 {'a': 2, 'b': 2, 'c': 3} # Bridging scope 4 {'a': 1, 'b': 2} # Outer scope In that arrangement, the statement with a using clause is executed normally in the outer scope, but with the ability to see additional names in its local namespace. If this can be arranged, then name binding in the statement with the using clause will work as we want it to. Anyway, I think further investigation of the idea is dependent on a closer look at the feasibility of actually implementing it. Given that it isn't as compatible with the existing nested scope structure as I first thought, I suspect it will be both tricky to implement, and hard to sell to the BDFL afterwards :( Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From nick at craig-wood.com Sat Jan 22 14:30:04 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 22 Jan 2005 19:30:04 GMT Subject: default value in a list References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> <1gqsi0i.12qbij5okovdeN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Nick Craig-Wood wrote: > ... > > Or this version if you want something other than "" as the default > > > > a, b, b = (line.split(':') + 3*[None])[:3] > > Either you mean a, b, c -- or you're being subtler than I'm > grasping. Just a typo - I meant c! > > BTW This is a feature I miss from perl... > > Hmmm, I understand missing the ``and all the rest goes here'' feature > (I'd really love it if the rejected > a, b, *c = whatever > suggestion had gone through, ah well), but I'm not sure what exactly > you'd like to borrow instead -- blissfully by now I've forgotten a lot > of the perl I used to know... care to clarify? I presume your construct above is equivalent to my ($a, $b, @c) = split /.../; which I do indeed miss. Sometimes I miss the fact that in the below any unused items are set to undef, rather than an exception being raised my ($a, $b, $c) = @array; However, I do appreciate the fact (for code reliability) that the python equivalent a, b, c = array will blow up if there aren't exactly 3 elements in array. So since I obviously can't have my cake an eat it here, I'd leave python how it is for the second case, and put one of the suggestions in this thread into my toolbox / the standard library. BTW I've converted a lot of perl programs to python so I've come across a lot of little things like this! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From newsgroups at jhrothjr.com Mon Jan 17 19:59:44 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Mon, 17 Jan 2005 18:59:44 -0600 Subject: Fuzzy matching of postal addresses References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <10uonsvtcdl0339@news.supernews.com> "Andrew McLean" wrote in message news:96B2w2E$HF7BFwSq at at-andros.demon.co.uk... >I have a problem that is suspect isn't unusual and I'm looking to see if >there is any code available to help. I've Googled without success. There isn't any publically availible code that I'm aware of. Companies that do a good job of address matching regard that code as a competitive advantage on a par with the crown jewels. > Basically, I have two databases containing lists of postal addresses and > need to look for matching addresses in the two databases. More precisely, > for each address in database A I want to find a single matching address in > database B. > > I'm 90% of the way there, in the sense that I have a simplistic approach > that matches 90% of the addresses in database A. But the extra cases could > be a pain to deal with! >From a purely pragmatic viewpoint, is this a one-off, and how many non-matches do you have to deal with? If the answers are yes, and not all that many, I'd do the rest by hand. > It's probably not relevant, but I'm using ZODB to store the databases. I doubt if it's relevant. > The current approach is to loop over addresses in database A. I then > identify all addresses in database B that share the same postal code > (typically less than 50). The database has a mapping that lets me do this > efficiently. Then I look for 'good' matches. If there is exactly one I > declare a success. This isn't as efficient as it could be, it's O(n^2) for > each postcode, because I end up comparing all possible pairs. But it's > fast enough for my application. > > The problem is looking for good matches. I currently normalise the > addresses to ignore some irrelevant issues like case and punctuation, but > there are other issues. I used to work on a system that had a reasonably decent address matching routine. The critical issue is, as you suspected, normalization. You're not going far enough. You've also got an issue here that doesn't exist in the States - named buildings. > > Here are just some examples where the software didn't declare a match: > > 1 Brantwood, BEAMINSTER, DORSET, DT8 3SS > THE BEECHES 1, BRANTWOOD, BEAMINSTER, DORSET DT8 3SS The first line is a street address, the second is a named building and a street without a house number. There's no way of matching this unless you know that The Beaches doesn't have flat (or room, etc.) numbers and can move the 1 to being the street address. On the other hand, this seems to be a consistent problem in your data base - in the US, the street address must be associated with the street name. No comma is allowed between the two. > Flat 2, Bethany House, Broadwindsor Road, BEAMINSTER, DORSET, DT8 3PP > 2, BETHANY HOUSE, BEAMINSTER, DORSET DT8 3PP The first is a flat, house name and street name, the second is a number and a house name. Assuming that UK postal standards don't allow more than one named building in a postal code, this is easily matchable if you do a good job of normalization. > Penthouse,Old Vicarage, 1 Clay Lane, BEAMINSTER, DORSET, DT8 3BU > PENTHOUSE FLAT THE OLD VICARAGE 1, CLAY LANE, BEAMINSTER, DORSET DT8 3BU The issue here is to use the words "flat" and "the" to split the flat name and the house name. Then the house number is in the wrong part - it shoud go with the street name. See the comment above. > > St John's Presbytery, Shortmoor, BEAMINSTER, DORSET, DT8 3EL > THE PRESBYTERY, SHORTMOOR, BEAMINSTER, DORSET DT8 3EL This one may not be resolvable, unless there is only one house name with "presbytery" in it within the postal code. Notice that "the" should probably be dropped when normalizing. > The Pinnacles, White Sheet Hill, BEAMINSTER, DORSET, DT8 3SF > PINNACLES, WHITESHEET HILL, BEAMINSTER, DORSET DT8 3SF Spelling correction needed. > The challenge is to fix some of the false negatives above without > introducing false positives! > > Any pointers gratefully received. If, on the other hand, this is a repeating problem that's simply going to be an ongoing headache, I'd look into commercial address correction software. Here in the US, there are a number of vendors that have such software to correct addresses to the standards of the USPS. They also have data bases of all the legitimate addresses in each postal code. They're adjuncts of mass mailers, and they exist because the USPS gives a mass mailing discount based on the number of "good" addresses you give them. I don't know what the situation is in the UK, but I'd be surprised if there wasn't some availible address data base, either commercial or free, possibly as an adjunct of the postal service. The later, by the way, is probably the first place I'd look. The postal service has a major interest in having addresses that they can deliver without a lot of hassle. Another place is google. The first two pages using "Address Matching software" gave two UK references, and several Australian references. John Roth > > -- > Andrew McLean From tchur at optushome.com.au Tue Jan 18 19:06:51 2005 From: tchur at optushome.com.au (Tim Churches) Date: Wed, 19 Jan 2005 11:06:51 +1100 Subject: Fuzzy matching of postal addresses Message-ID: <200501190006.j0J06pV8025974@mail09.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From tjreedy at udel.edu Mon Jan 3 14:44:19 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 3 Jan 2005 14:44:19 -0500 Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1104750017.235937.181370 at c13g2000cwb.googlegroups.com... > I am trying to convince my client to use Python in his new product. He > is worried about the license issues. Can somebody there to point me any > good commercial applications developed using python ?. The licence > clearly says Python can be used for commercial applications. We are in a weird catch-22 type situation here. Because the license is so open, companies that use Python just use it. No payment, no curtesy registration, no verifiable trace unless they care to disclose (and most don't). The license could be paraphrased as "Don't sue us or do anything that would cause anyone else to sue us and we won't sue you." There is a posted request for thank you donations but not enough commercial users do so to even hire one full time programmer, let alone a lawyer (above the bare minimum required for PSF to legally function). The PSF is about as far from the RIAA and MPAA as possible. There are Python Success Stories at the Python site and elsewhere (try Google on the newsgroup. You could also agree to be responsible for any legal action initiated by the PSF not due to obvious malfeance, like trying to register a copyright on the Python source. Or you could suggest that they purchase a license with a donation to the PSF. Terry J. Reedy From aleaxit at yahoo.com Tue Jan 18 15:51:40 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 18 Jan 2005 21:51:40 +0100 Subject: pickling extension class References: <1gqlpxp.g66j8sl6zkutN%aleaxit@yahoo.com> Message-ID: <1gqltfu.yiiqig17t6w5vN%aleaxit@yahoo.com> harold fellermann wrote: ... > Here it goes...: > OOPS, error (exceptions.ImportError): No module named hyper So, the __import__ in pickle fails -- indeed, __import__('foo') when 'foo' ``is imported from a subpackage'' is _supposed_ to fail, as 'hyper' is not the name you SHOULD be importing. For example, __import__('email.Encoders') is fine, but just __import__('Encoders') fails with ImportError -- there IS no toplevel module by that name! > I have noticed that the error does not occur, when the imported module > ('hyper') is in the same directory as the script that pickles. When it > is imported from a subpackage (like in the code > I sent you) it goes wrong. If you can't fix the modulename given by your type, you can perhaps kludge things up by (e.g.) import the.real.hyper sys.modules['hyper']=the.real.hyper before you pickle; but I suspect UNpickling would fail in that case. Using the standard library copy_reg module to register your way to pickle and recover instances of your type might work better. Alex From steve at holdenweb.com Tue Jan 18 07:12:18 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Jan 2005 07:12:18 -0500 Subject: generator expressions: performance anomaly? In-Reply-To: References: Message-ID: <377Hd.77904$Jk5.30235@lakeread01> Antoon Pardon wrote: > Op 2005-01-18, Nick Coghlan schreef : > >>Raymond Hettinger wrote: >> >>>[Delaney, Timothy C] >>> >>> >>>>Nick's other suggestion - that genexps propagate __len__ - might >>>>still be interesting. Of course, it would only be applicable for >>>>unconditional genexps(i.e. no if clause). >>> >>>Length transparency for iterators is not as general as one would expect. I once >>>spent a good deal of effort exploring where it made sense, and I was surprised >>>to find that it only rarely works out. Length transparency is an unexpectedly >>>thorny subject with many dead-ends which precludes a fully general solution such >>>as that proposed by Nick. >>> >>>For a recap of my research, see the docstring for Lib/test/test_iterlen.py . >> >>"""The situation slightly more involved whenever an object allows length >>mutation during iteration. """ >> >>Ouch. Nice understatement. >> >>It's rather unfortunate that we can't make use of the length information even >>when the source *doesn't* mutate, though. I'll have to think some more to see if >>I can come up with any concrete ideas for you to shoot down :) > > > Something else I was thinking about. I think it would be nice if the > python compilor could figure out whether a genexp in a list or tuple > expression always generates the same list or tuple and then instead > of generating code would generate the list or tuple in place. > Since it doesn't yet optimize 2+5 to a constant-folded 7 you should realize that you are suggesting a large increase in the compiler's analytical powers. I agree it would be nice under certain circumstances, but don't forget that unlike list comprehensions (for which it would be even nicer) the whole point of generator expressions is often to defer the generation of the individual items until they are required and thereby relieve stress on memory. As an edge case to demonstrate the point, what about a constant but infinite sequence? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From peter at engcorp.com Wed Jan 26 21:08:05 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 Jan 2005 21:08:05 -0500 Subject: Responding to trollish postings. In-Reply-To: <1106784553.583222.218950@f14g2000cwb.googlegroups.com> References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <41F7F520.8040706@po-box.mcgill.ca> <1106784553.583222.218950@f14g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > Indeed. Let's just nominate XL to the "Full Canvas Jacket" website > (http://www.ratbags.com/ranters/) and move on. I'm not sure how reliable that site could be. After all, it contains no articles with the words "autocoding", "threeseas", or "rue" (other than as the French "street"). Sad, really. ;-) (Neither has it been updated in the last two years. :-( ) -Peter From benji at zope.com Wed Jan 19 00:15:56 2005 From: benji at zope.com (Benji York) Date: Wed, 19 Jan 2005 00:15:56 -0500 Subject: Employablity of python programmers In-Reply-To: References: <1105974549.835152.280590@z14g2000cwz.googlegroups.com> Message-ID: <41EDED0C.6050305@zope.com> Mir Nazim wrote: > I am in a fix what skill set I must choose to be safe as > far as job openings are concerned. > 1) C/C++ and Python. > 2) Java and Python. > 3) Pure Python. As for pure employability, I'd choose option 2, but as a person that wants something more than employment from my work life, I'd like to share something with you: A while ago I decided that to be happy I had to decide what I wanted, *really* go after those things, and believe that the rewards would follow. For me Python had a big part to play in that, so I recently started looking for a new job, even though I already had one that was promising and secure. It also meant being willing to move myself and my family far from or home, friends, and other family members to take that new job. If we were willing to make big changes (and the accompanying sacrifices), we were going to make the most of it: I wouldn't accept anything but the right job, at the right company, with the right environment where they really needed *me*. I spent hours researching openings and companies and sent out many resumes with the hopes of finding that *one* job. Two weeks later, I was fortunate enough to begin talks with *two* very interested (and more importantly, interesting) companies. I've been at my new job (in a new house, in a new city) for about six weeks now. It's not perfect (nothing is), but I'm enjoying the job, like the people I work with, and the area we live in. We made the right choice. Go after what you really want, and you will too. -- Benji York Sr. Software Engineer Zope Corporation From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 13:34:55 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?ISO-8859-2?Q?Martin_MOKREJ=A9?=) Date: Mon, 10 Jan 2005 19:34:55 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E339814F@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E339814F@exchange.hqamor.amorhq.net> Message-ID: <41E2CACF.6030405@ribosome.natur.cuni.cz> Robert Brewer wrote: > Martin MOKREJ? wrote: > >>Robert Brewer wrote: >> >>>Martin MOKREJ? wrote: >>> >>> >>>> I have sets.Set() objects having up to 20E20 items, >>>>each is composed of up to 20 characters. Keeping >>>>them in memory on !GB machine put's me quickly into swap. >>>>I don't want to use dictionary approach, as I don't see a sense >>>>to store None as a value. The items in a set are unique. >>>> >>>> How can I write them efficiently to disk? >>> >>> >>>got shelve*? >> >>I know about shelve, but doesn't it work like a dictionary? >>Why should I use shelve for this? Then it's faster to use >>bsddb directly and use string as a key and None as a value, I'd guess. > > > If you're using Python 2.3, then a sets.Set *is* implemented with Yes, I do. > a dictionary, with None values. It simply has some extra methods to > make it behave like a set. In addition, the Set class already has > builtin methods for pickling and unpickling. Really? Does Set() have such a method to pickle efficiently? I haven't seen it in docs. > > So it's probably faster to use bsddb directly, but why not find out > by trying 2 lines of code that uses shelve? The time-consuming part Because I don't know how can I afect indexing using bsddb, for example. For example, create index only for say keysize-1 or keysize-2 chars of a keystring. How to delay indexing so that index isn't rebuild after every addiotion of a new key? I want to do it a the end of the loop adding new keys. Even better, how to turn off indexing completely (to save space)? > of your quest is writing the timed test suite that will indicate > which route will be fastest, which you'll have to do regardless. Unfortunately, I'm hoping to get first an idea what can be made faster and how when using sets and dictionaries. M. From roy at panix.com Tue Jan 11 08:50:15 2005 From: roy at panix.com (Roy Smith) Date: Tue, 11 Jan 2005 08:50:15 -0500 Subject: Exception not captured References: Message-ID: In article , Miki Tebeka wrote: > print SCMError is e.__class__ > raise SystemExit > > I get to the second "except" clause, and the printout is: > /home/mikit/work/nightly/scm/common.py:3 > /home/mikit/work/nightly/scm/common.py:3 > False > > How is this possible? I suspect you meant to do: print "SCMError is", e.__class__ The way you have it now, it's printing out the result of the "is" operator, which tests for identity. From aahz at pythoncraft.com Mon Jan 3 16:24:48 2005 From: aahz at pythoncraft.com (Aahz) Date: 3 Jan 2005 16:24:48 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: In article , Steve Holden wrote: >Aahz wrote: >> In article , >> Steve Holden wrote: >>>Aahz wrote: >>>> >>>>That's funny -- Bruce Eckel talks about how he used to love checked >>>>exceptions but has come to regard them as the horror that they are. >>>>I've learned to just write "throws Exception" at the declaration of >>>>every method. >>> >>>Pretty sloppy, though, no? And surely the important thing is to have a >>>broad handler, not a broad specification of raisable exceptions? >> >> Yes, it's sloppy, but I Don't Care. I'm trying to write usable code >> while learning a damnably under-documented Java library -- and I'm *not* >> a Java programmer in the first place, so I'm also fighting with the Java >> environment. Eventually I'll add in some better code. > >The road to hell is paved with good intentions. So's the road to unfinished software projects. The question, as always, becomes how best to balance the competing requirements and resources. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From miki.tebeka at zoran.com Wed Jan 26 05:34:06 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 26 Jan 2005 12:34:06 +0200 Subject: python without OO In-Reply-To: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <20050126103405.GH3332@zoran.com> Hello Davor, > Also, is anyone aware of any scripting language that could be considered > as "Python minus OO stuff"? Maybe Lisp (http://clisp.cons.org/, http://www.paulgraham.com/onlisp.html) or Scheme (http://www.plt-scheme.org/software/mzscheme/, http://mitpress.mit.edu/sicp/full-text/book/book.html) will be better for you mind :-) HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From erikbethke at gmail.com Sun Jan 2 04:25:09 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 2 Jan 2005 01:25:09 -0800 Subject: Python! Is! Truly! Amazing! In-Reply-To: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: <1104657909.340055.283710@z14g2000cwz.googlegroups.com> Oh yeah, and farmer, no I didn't yet get back to making an exe by fixing the problem with pygame2exe i just got disctracted getting other things done so fast! -Erik www.gopetslive.com From chrisdewinN0SPAM at yahoo.com.au Wed Jan 19 22:37:16 2005 From: chrisdewinN0SPAM at yahoo.com.au (Dfenestr8) Date: Thu, 20 Jan 2005 13:37:16 +1000 Subject: python/cgi/html bug References: <1106137924.918776.9090@f14g2000cwb.googlegroups.com> <7xmzv5yy3t.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 19 Jan 2005 12:15:18 -0800, Paul Rubin wrote: > Dfenestr8 writes: >> No glaring security holes that you noticed? Other than being able to >> hide things in html tags? > > Looks like you can also embed arbitrary javascript (I just tried it). I > haven't looked at the script itself yet. fixed that. try doing it now...... http://funkmunch.net/~pirch/cgi-bin/betaforum/pptopic.py From tjreedy at udel.edu Mon Jan 24 20:57:27 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Jan 2005 20:57:27 -0500 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net><35l5d9F4licj2U1@individual.net> <35lbvdF4k3ss4U1@individual.net> Message-ID: "George Sakkis" wrote in message news:35lbvdF4k3ss4U1 at individual.net... > Actually my initial motivation was not a huge tuple I had to slice many > times. It was something much > less extraordinarily unlikely, a recursive function with a sequence > parameter: > > def foo(sequence): > # base_case > # do_stuff() > combine(foo(sequence[:n]), > foo(sequence[n:])) > > Having each slice be a view of the original sequence instead of a fresh > copy would be a Good Thing Why? To save time? memory? Either would require more that a few bytes per slice. If they are, you can probably use virtual slices as follows. def foo(sequence): def _foo(seq, start, stop) # base_case # do_stuff() combine(_foo(seq, start, n), _foo(seq, n, stop)) _foo(sequence, 0, len(sequence) In other words, if you don't really want slices copied out of the sequence, then don't slice! Just use 2 ints to indicate the working region or view. Both this and using a nested function with additional params are standard techniques. This also works when the seq is mutable and you want changes to the 'slice' to change the original, as in quicksort. Terry J. Reedy From levub137 at wi.rr.com Sat Jan 8 09:49:47 2005 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sat, 08 Jan 2005 08:49:47 -0600 Subject: DOS problem (simple fix??) In-Reply-To: References: Message-ID: <6oSDd.92329$NO5.22356@twister.rdc-kc.rr.com> Robert Brewer wrote: > Gavin Bauer wrote: > >>My DOS window (running in windows ME) closes the second it finishes >>running my programs. As you can imagine, this makes it hard to see the >>results. I've gotten in the habit of putting raw_input("Press enter to >>exit") at the end of every program, and in addition to being pain in >>the butt, it often fails to work. Being new to programming in general, >>I make more mistakes than most people. My programs often have errors >>before they get to my raw_input command. They then display the error >>and immediately close. It is naturally a lot easier to fix an error >>when you know what the error is. This makes debugging even more >>annoying than it ordinarily would be, if you can imagine that. I've >>heard that it should be a simple preference fix, but I've asked around >>and no one seems to know how. >> >>Thank you, and please make all answers simple enough to be understood >>by a highschool student and his father :) . For another solution try: http://www.24help.info/showthread.php?t=149725 From eurleif at ecritters.biz Thu Jan 13 17:08:18 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Thu, 13 Jan 2005 17:08:18 -0500 Subject: how to control the mouse pointer with python? In-Reply-To: <1105650438.311153.167410@f14g2000cwb.googlegroups.com> References: <1105650438.311153.167410@f14g2000cwb.googlegroups.com> Message-ID: <34o9npF4et4hiU1@individual.net> oglycans at yahoo.com wrote: > Anybody know a way to control the mouse pointer > (move it around and click on things) using python? It depends on your operating system. For Windows, you'll want to use a Python module to access the Win32 API. The relevant API function is documented at . From aahz at pythoncraft.com Thu Jan 13 08:49:03 2005 From: aahz at pythoncraft.com (Aahz) Date: 13 Jan 2005 08:49:03 -0500 Subject: why are people still using classic classes? References: <7x6522gegg.fsf@ruckus.brouhaha.com> Message-ID: In article , Peter Hansen wrote: > >Unfortunately, if we should follow the recent advice about always using >"super()" in the __init__ method, it's hard to do what you suggest >(though it sounds like good advice) without resorting to extreme >ugliness: > > >>> class Classic: >... def __init__(self): >... super(Classic, self).__init__() >... > >>> c = Classic() >Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in __init__ >TypeError: super() argument 1 must be type, not classobj > >Could classic classes ever be removed without us having manually >to fix all __init__ calls to the superclass? Maybe. If you follow the python-dev thread about "super() considered harmful", you'll learn that Guido believes super() should only be used with class hierarchies explicitly designed for the purpose. Given that, you'd have to do a lot of other changes to support super() and it's less outrageous. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From phr at localhost.localdomain Tue Jan 25 17:58:58 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Tue, 25 Jan 2005 22:58:58 GMT Subject: Crypto in Python: (Was: What's so funny? WAS Re: rotor replacement) References: Message-ID: "Philippe C. Martin" writes: > I do not know in which country the python.msi is compiled (Deuchland ?), > but most likely, the county has rules like most other as far as crypto > code in binary format export (especially if distributed as part of a > commercial package): for instance, if you want to export a .exe in > France, you usually have to go through the DCSSI, in the USA, the > BIS ..... It is a _long_ and tedious process. In the USA, it's pretty simple, you just send an email to an address at the BXA telling them what you're exporting. See http://www.bxa.doc.gov/Encryption for info. From francis.girard at free.fr Fri Jan 28 09:10:18 2005 From: francis.girard at free.fr (Francis Girard) Date: Fri, 28 Jan 2005 15:10:18 +0100 Subject: Question about 'None' In-Reply-To: <41FAB4AF.3090200@freemail.gr> References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> <41FAB4AF.3090200@freemail.gr> Message-ID: <200501281510.18375.francis.girard@free.fr> Le vendredi 28 Janvier 2005 22:54, jfj a ?crit?: > Francis Girard wrote: > > What was the goal behind this rule ? > > If you have a list which contains integers, strings, tuples, lists and > dicts and you sort it and print it, it will be easier to detect what > you're looking for:) > > > G. Mmm. Certainly not one of my top requirements. Anyway, it would be better to separately provide a compare function that orders elements according to their types instead of making the comparison operators default semantics somewhat obscure (and dangerous). Thank you Francis Girard From xah at xahlee.org Sat Jan 15 10:24:04 2005 From: xah at xahlee.org (Xah Lee) Date: 15 Jan 2005 07:24:04 -0800 Subject: python mode indentation problem Message-ID: <1105802644.939051.229990@f14g2000cwb.googlegroups.com> does anyone know why the Python mode in emacs uses spaces for first level indentation but one tab for second level? i'm using emacs 21.3.50.1. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From godoy at ieee.org Wed Jan 19 13:01:53 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Wed, 19 Jan 2005 16:01:53 -0200 Subject: Accessing MDB files on Windows References: <1635068.ZTfiooUzB4@strongwill.g2ctech> <4262806.PViGKJWPeZ@strongwill.g2ctech> <57wHd.80954$Jk5.41342@lakeread01> <1116749.2eGh3JeIRy@strongwill.g2ctech> Message-ID: <2958131.FJ5Qp3qFnC@strongwill.g2ctech> Jorge Luiz Godoy Filho, Quarta 19 Janeiro 2005 15:17, wrote: > Hmmm... I see. I'm trying to avoid having to install external modules > at > my client's server. Should I use, given that both DAO and ODBC are > available with the win32all extensions, DAO or ODBC? > > Or would ADO give me so much more performance that I should really use it? I've also made it work with ADO... It doesn't require me to use the 'makepy' on it, so this might be a better choice if I have to deploy for more machines. I think I'll go with ADO. Thanks Larry and Steve. -- Godoy. From fabioz at esss.com.br Fri Jan 21 14:15:58 2005 From: fabioz at esss.com.br (Fabio Zadrozny) Date: Fri, 21 Jan 2005 16:15:58 -0300 Subject: Pydev 0.8.5 released! Message-ID: <20050121191620.8B4B4143142@ironman.esss.com.br> Hi All, PyDev - Python IDE (Python development enviroment for Eclipse) version 0.8.5 has just been released. This release has as its main feature a new Code Completion. Check the homepage for more details (http://pydev.sourceforge.net/). Other things in the release include some bugs corrected, and some patches: - Scott Schlesier has provided a patch to configure the editor background and color of the highlighted line. - Sebastian Tusk provided a patch to see watch expressions on debug. Hope you enjoy it... Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software www.esss.com.br From craig at postnewspapers.com.au Fri Jan 21 19:29:24 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 22 Jan 2005 08:29:24 +0800 Subject: finding name of instances created In-Reply-To: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> Message-ID: <1106353764.19065.89.camel@bucket.localnet> On Fri, 2005-01-21 at 16:13 -0800, Andr? wrote: > Short version of what I am looking for: > > Given a class "public_class" which is instantiated a few times e.g. > > a = public_class() > b = public_class() > c = public_class() > > I would like to find out the name of the instances so that I could > create a list of them e.g. > ['a', 'b', 'c'] > > I've read the Python Cookbook, Python in a Nutshell, Programming > Python, Learning Python, ... googled (probably missed something > obvious), all to no avail. Yep. The short answer is that the instances don't have names - they're just bound to names in a particular scope. They can be bound to different names in the same scope or in other scopes. You can get a dictionary for a particular scope using locals() then search it to find the key for a given value. That key will be the name the object is bound to in that scope. In general, you won't want to do that - the need to do so probably suggests a design issue in what you're trying to do. > If I can do the above, I believe I could do the following thing which > is what I am really after eventually. > > Given the statement > > >> a = public_class() > > I would like to generate > > >> my_dict['a'] = private_class() > > so that one could write > > >> a.apparently_simple_method() > > and that, behind the scene, I could translate that as > > >> my_dict['a'].not_so_simple_method() I'm not clear as to why you can't do this as part of the class of which 'a' is an instance. > as well as do things like > > >> for name in my_dict: > >> do_stuff(name) > > Any help, pointers, sketches or outline of solution would be greatly > appreciated. I'm not really able to grasp what you're trying to do (but others might). It wouldn't hurt if you could post a description of what you're actually trying to achieve - /why/ you want this - as that can often be very helpful both in understanding what you're thinking and in suggesting a suitable approach or alternative. -- Craig Ringer From aleaxit at yahoo.com Sat Jan 22 04:20:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 10:20:36 +0100 Subject: need help on need help on generator... References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> <200501211605.40696.francis.girard@free.fr> Message-ID: <1gqsc51.1rjuhl111onjbxN%aleaxit@yahoo.com> Nick Coghlan wrote: > 5. Several builtin functions return iterators rather than lists, specifically > xrange(), enumerate() and reversed(). Other builtins that yield sequences > (range(), sorted(), zip()) return lists. Yes for enumerate and reversed, no for xrange: >>> xx=xrange(7) >>> xx.next() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'xrange' object has no attribute 'next' >>> it SHOULD return an iterator, no doubt, but it doesn't (can't, for backwards compatibility reasons). Neither does it return a list: it returns "an `xrange' object", a specialized type that's not an iterator, though it's iterable. It's a type, btw: >>> xrange >>> so it's not surprising that calling it returns instances of it (enumerate and reversed are also types, but *WITH* 'next'...). Alex From stephen.thorne at gmail.com Thu Jan 13 01:51:46 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 16:51:46 +1000 Subject: finding/replacing a long binary pattern in a .bin file In-Reply-To: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> Message-ID: <3e8ca5c80501122251483f4b8f@mail.gmail.com> On 12 Jan 2005 22:36:54 -0800, yaipa wrote: > What would be the common sense way of finding a binary pattern in a > .bin file, say some 200 bytes, and replacing it with an updated pattern > of the same length at the same offset? > > Also, the pattern can occur on any byte boundary in the file, so > chunking through the code at 16 bytes a frame maybe a problem. The > file itself isn't so large, maybe 32 kbytes is all and the need for > speed is not so great, but the need for accuracy in the > search/replacement is very important. Okay, given the requirements. f = file('mybinfile') contents = f.read().replace(oldbinstring, newbinstring) f.close() f = file('mybinfile','w') f.write(contents) f.close() Will do it, and do it accurately. But it will also read the entire file into memory. Stephen. From announce at altova.com Tue Jan 18 09:58:12 2005 From: announce at altova.com (Altova Announcements) Date: Tue, 18 Jan 2005 09:58:12 -0500 Subject: ANNOUNCE: Altova DiffDog 2005 - the dedicated differencing utility for developers and power users Message-ID: <8u9Hd.344$Jg7.182@fe51.usenetserver.com> Altova Unveils DiffDog(tm) 2005 ------------------------------- This week, Altova added a new dedicated differencing utility to its award-winning product line. DiffDog 2005 is a powerful, easy-to-use synchronization tool that facilitates the comparison and merging of files, folders, and directories for application developers and power users. DiffDog 2005 Standard and Professional editions allow users to quickly compare source code files, HTML files, or any text-based files then merge changes with a click of the mouse. Both editions deliver versatile comparison and merging options for all file directories as well. Uniquely, DiffDog 2005 Professional Edition also provides advanced XML-aware differencing and editing capabilities based on those popularized in Altova XMLSpy. DiffDog 2005 integrates with any version control system that supports external differencing applications. For optimal efficiency, you can edit content directly within its differencing display, merge changes, and instantly re-compare the edited files. Intelligent syntax-coloring, line numbering, indentation guides, folding margins, and other innovative features are provided to assist in comparing source-code and XML files. DiffDog 2005 also provides powerful capabilities for directory comparisons, allowing you to compare and merge directories, and open and edit file pairs directly from the directory comparison view. You can instantly identify the differences in two versions of a large directory, open and edit files side-by-side, then move what you want into your target directories. With all this you can reconcile source code versions, synch-up files on your laptop and desktop computers, or even modify and merge your play lists or photo collections in a matter of seconds. DiffDog 2005 is the latest in Altova's line of award-winning developer tools. Let DiffDog 2005 track down the differences in your development and integration projects. Download a 30-day FREE trial today: http://www.altova.com/download_diffdog.html. For more information on Altova DiffDog 2005 please visit: http://www.altova.com/products_diffdog.html. From abpillai at gmail.com Thu Jan 6 05:22:29 2005 From: abpillai at gmail.com (Anand) Date: 6 Jan 2005 02:22:29 -0800 Subject: Contributor's List In-Reply-To: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> References: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> Message-ID: <1105006949.581350.40090@c13g2000cwb.googlegroups.com> Please direct all queries to the Cookbook editors! Thanks -Anand From vmlinuz at tuxfamily.org Wed Jan 12 06:39:18 2005 From: vmlinuz at tuxfamily.org (ToYKillAS) Date: Wed, 12 Jan 2005 12:39:18 +0100 Subject: Python.org, Website of Satan In-Reply-To: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: <41e50c0f$0$17416$4d4efb8e@read.news.be.uu.net> humblythegreatest at usa.com wrote: > python.org = 194.109.137.226 > > 194 + 109 + 137 + 226 = 666 > > What is this website with such a demonic name and IP address? What > evils are the programmers who use this language up to? > damn Franc Ma?ons -- Even though I walk through the valley of the shadow of death, I will fear no evil, for you are with me; your rod and your staff, they comfort me. From bokr at oz.net Fri Jan 7 18:06:58 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 07 Jan 2005 23:06:58 GMT Subject: OT: google groups bug, or worse? References: <1105127965.616198.302710@z14g2000cwz.googlegroups.com> Message-ID: <41df13b7.260993058@news.oz.net> On 7 Jan 2005 11:59:25 -0800, aaronwmail-usenet at yahoo.com wrote: >I'm concerned that google groups is not correctly reflecting the >python lists. A month ago I announced the xsdbXML framework to the >python list and the python-announce list. As you can see from the >links >below the python announce submission was approved by the moderators >(thanks!) >and the python list submission also went out, but the messages cannot >be found at google groups. > >http://mail.python.org/pipermail/python-list/2004-December/254479.html >http://mail.python.org/pipermail/python-announce-list/2004-December/003583.html > >Is it a google bug? Or is it something darker, like an anti-Python >conspiracy at google? > >Inquiring minds want to know. > What did you google with? Is this it? http://groups-beta.google.com/groups?hl=en&ie=UTF-8&q=%22The+xsdbXML+framework+provides+a+flexible+and+well+defined+infrastructure%22&qt_s=Search+Groups I.e., searching for one of the first lines in your references "The xsdbXML framework provides a flexible and well defined infrastructure" in google groups. Regards, Bengt Richter From franz.steinhaeusler at utanet.at Tue Jan 18 08:40:06 2005 From: franz.steinhaeusler at utanet.at (Franz Steinhaeusler) Date: Tue, 18 Jan 2005 14:40:06 +0100 Subject: [wxpython] exclude files in a wx.FileDialog? References: <41ed0dcc$0$73526$abc4f4c3@news.wanadoo.nl> Message-ID: On 18 Jan 2005 13:23:24 GMT, John Field wrote: >Hello, > >Is it possible to exclude certain files in a wx.FileDialog, so that the user >won't see them and can't select them with the mouse in de File open window? > >I was thinking of somehow extending the class FileDialog(Dialog) >in the wx module _windows.py to a subclass, but I'm not sure how to do that >(if feasible). > > >cheers wx.FileDialog is only a wrapper for the api FileDialog (at least this applies for windows) and therefore it is not possible to derive from it. Really exclude, I think, is not possible. You can put a mask wx.FileDialog(...wildcard = "BMP files (*.bmp)|*.bmp|GIF files (*.gif)|*.gif") Otherwise you have to create your own FileDialog. -- Franz Steinhaeusler From philippecmartin at sbcglobal.net Wed Jan 19 04:46:14 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Wed, 19 Jan 2005 10:46:14 +0100 Subject: how to find site-packages path (Michael Hoffman) - use distutils/modified Message-ID: <1106127974.11037.1.camel@localhost> Thanks David. Philippe >>Hi Philippe >>You may want to have a look at >>https://sourceforge.net/tracker/?func=detail&atid=305470&aid=793070&group_id=5470 >>This was originally a patch to distutils which enabled removing the >>source (i.e. only distributing compiled files). I have now attached a >>file there which enables you to do the same thing, but without patching >>distutils - it just wraps functions etc from outside. >>Basically you call allow_distutils_remove_source in the module and it >>does the neccessary changes. Then you get a --remove-source options to >>most of the commands. You can also selectively override what gets >>removed if you want by changing the is_removable function >>I hope this is useful for what you're wanting to do >>David -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From xah at xahlee.org Sat Jan 29 18:36:05 2005 From: xah at xahlee.org (Xah Lee) Date: 29 Jan 2005 15:36:05 -0800 Subject: [perl-python] sending email Message-ID: <1107041765.890014.112530@c13g2000cwb.googlegroups.com> # -*- coding: utf-8 -*- # Python # Suppose you want to spam your friend, and you have lots of # friends. The solution is to write a program to do it. After a gander # at python docs, one easily found the module for the job. # see http://python.org/doc/2.3.4/lib/SMTP-example.html # the code is a bit long with the command line, but the key lies at # the bottom four lines. The gist is this: import smtplib smtpServer='smtp.yourdomain.com'; fromAddr='xah at xahlee.org'; toAddr='xah at xahlee.org'; text='''Subject: newfound love Hi friend, long time no write, i have a new manifesto i think it would be of interest for you to peruse. ... ''' server = smtplib.SMTP(smtpServer) server.set_debuglevel(1) server.sendmail(fromAddr, toAddr, text) server.quit() # save this file as x.py and run it. # it should send out the mail. # the set_debuglevel() is nice because you see all the interactions # with the smtp server. Useful when you want to see what's going on # with a smtp server. ------------------------- in Perl, there are not just one, two, or 3 modules that does the job, each with slight problems. Here's how the situation stands as of 2001 March: For Perl libraries that deals with RFC 821, I personally know of three: * Mail::Mailer. Mentioned in most Perl books. Written or maintained by Graham Barr. * Mail::Send, maintained by Graham Barr , originally written by Tim Bunce. * Mail::Sendmail by Milivoj Ivkovic. The first two has glaring problems. I'm sorry i forgot what they are. I think Mail::Mailer has a bug on the from field. i.e. it ignores what you gave. I'm currently using Mail::Sendmail, and according to a ex-colleague, it has problems with some DNS mail exchange entries. for some discussion of the plethora of Perl mail modules and their short-cummings, see http://alma.ch/perl/mail.htm -------------------- Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From a at b.c Sat Jan 22 15:14:08 2005 From: a at b.c (Doug Holton) Date: Sat, 22 Jan 2005 14:14:08 -0600 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> Message-ID: Fredrik Lundh wrote: > and trust me, when things are hard to get right for developers, users will > suffer too. That is exactly why YAML can be improved. But XML proves that getting it "right" for developers has little to do with getting it right for users (or for saving bandwidth). What's right for developers is what requires the least amount of work. The problem is, that's what is right for end-users, too. From marklists at mceahern.com Tue Jan 11 13:40:34 2005 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 11 Jan 2005 12:40:34 -0600 Subject: Time script help sought! In-Reply-To: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> Message-ID: <41E41DA2.5010806@mceahern.com> kpp9c wrote: >The input would like so: > > [...] Attached is a first cut at a parser that actually uses the raw content of your original email. You'll notice that the net effect is that the parser instance's items attribute contains the source ordered list of items with attributes for each of the various parts of the line. From this, it should be pretty easy to adjust the times and what not. Cheers, // m -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: parser.py URL: From kartic.krishnamurthy at gmail.com Sat Jan 8 20:13:49 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 8 Jan 2005 17:13:49 -0800 Subject: Windows XP Installation In-Reply-To: References: Message-ID: <1105233229.420502.134120@c13g2000cwb.googlegroups.com> Smitsky, Did you at least visit python.org, Python main website? Step 1: Visit www.python.org Step 2: Click on the download link Step 3: Located Windows Binary in the list of downloads (choose the first link - http://python.org/ftp/python/2.4/python-2.4.msi - if you dont know what Itanium is) Step 4: Click on the link. Step 5: Follow browsers instructions to save or open. The installer will launch and you are on your way to installing Python on your XP machine. It installs just fine! Please note that it may ask for Admin rights..if you have it on your PC, use it or else install it non-admin, meaning the environment will be set up only for your userid and the DLLs will be in the Python install location rather than %WINNDIR% Please note that you may be interested in the win32all extensions if you want to use COM with your python applications. (http://sourceforge.net/projects/pywin32/) Good luck and python your way! Thanks, --Kartic From jzgoda at gazeta.usun.pl Sat Jan 1 16:46:23 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Sat, 01 Jan 2005 22:46:23 +0100 Subject: PyQT installation In-Reply-To: References: <1104370062.562575.88620@f14g2000cwb.googlegroups.com> <1104417268.153983.71970@z14g2000cwz.googlegroups.com> <8SVAd.64014$Jk5.26087@lakeread01> <1gpo9ow.7zqmxi1rwc564N%aleaxit@yahoo.com> <871xd5hzfc.fsf@pobox.com> Message-ID: Ken Godee wrote: > I believe the book "C++ GUI programming Qt3" comes > with a windows Qt gpl 3.x version. Just have to buy > the book. No PyQt version to match thou. No, Sir. It's a "non-commercial" edition. At the request from Trolltech, there's no PyQt-nc available for this version of Qt. > Blackadder from the Kompany, while not free, is still > a pretty good deal. Like < $100 for personal and around > $350 for commercial version. Include current windows/linux > versions of (Qt)PyQt along with converted Qt C++ to PyQt docs. This is much better way to get PyQt for Windows! -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From aorfanakos at gmail.com Sun Jan 30 18:19:39 2005 From: aorfanakos at gmail.com (Aggelos I. Orfanakos) Date: 30 Jan 2005 15:19:39 -0800 Subject: Regarding exception handling References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> Message-ID: <1107127179.863445.55310@c13g2000cwb.googlegroups.com> Thanks. This should now be OK: #try: # try: # s = ... # socket opens # # # various code ... # except socket.error, x: # # exception handling #finally: # s.close() # socket closes From notvalid at email.com Wed Jan 26 17:52:15 2005 From: notvalid at email.com (Ala Qumsieh) Date: Wed, 26 Jan 2005 22:52:15 GMT Subject: 20050126 find replace strings in file In-Reply-To: <1106776836.679242.167880@c13g2000cwb.googlegroups.com> References: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> <1106776836.679242.167880@c13g2000cwb.googlegroups.com> Message-ID: takarov2003 at yahoo.com wrote: > Xah Lee wrote: >>close(F1) or die "Perl fucked up. Reason: $!"; >>close(F2) or die "Perl fucked up. Reason: $!"; > > > Same here. Never seen Perl fuck up on closing a file. Usually > something in the OS or file system that does it. In this case, I'm pretty sure it's the user. --Ala From evan at tokenexchange.com Fri Jan 14 17:26:02 2005 From: evan at tokenexchange.com (Evan Simpson) Date: Fri, 14 Jan 2005 16:26:02 -0600 Subject: Producer/consumer Queue "trick" Message-ID: WEBoggle needs a new game board every three minutes. Boards take an unpredictable (much less than 3min, but non-trivial) amount of time to generate. The system is driven by web requests, and I don't want the request that happens to trigger the need for the new board to have to pay the time cost of generating it. I set up a producer thread that does nothing but generate boards and put them into a length-two Queue (blocking). At the rate that boards are pulled from the Queue, it's almost always full, but my poor consumer thread was still being blocked for "a long time" each time it fetched a board. At this point I realized that q.get() on a full Queue immediately wakes up the producer, which has been blocked waiting to add a board to the Queue. It sets about generating the next board, and the consumer doesn't get to run again until the producer blocks again or is preempted. The solution was simple: have the producer time.sleep(0.001) when q.put(board) returns. Cheers, Evan @ 4-am From bingham at cenix-bioscience.com Thu Jan 6 10:55:27 2005 From: bingham at cenix-bioscience.com (Aaron Bingham) Date: Thu, 06 Jan 2005 16:55:27 +0100 Subject: 2 versions of python on 1 machine In-Reply-To: References: Message-ID: <41DD5F6F.2090203@cenix-bioscience.com> flupke wrote: > I have version 2.3.4 and 2.4 installed on windows and i thought that by > switching the PYTHONPATH parameter to the dir of the 2.4 version that > that would make python 2.4 active. > > However when i envoke python from the commandline, it still runs 2.3.4 > Is it possible to have 2 versions installed and switching versions when > you need to? > > How can i do that? You need to put the path to the desired version in the PATH environment variable. You shoudn't need to change PYTHONPATH at all. -- -------------------------------------------------------------------- Aaron Bingham Application Developer Cenix BioScience GmbH -------------------------------------------------------------------- From aahz at pythoncraft.com Sat Jan 1 19:23:43 2005 From: aahz at pythoncraft.com (Aahz) Date: 1 Jan 2005 19:23:43 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xacrs230c.fsf@ruckus.brouhaha.com> Message-ID: In article <7xacrs230c.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > >I was pretty skeptical of Java's checked exceptions when I first used >them but have been coming around about them. There's just been too >many times when I wrote something in Python that crashed because some >lower-level function raised an exception that the upper level hadn't >been expecting, after the program had been in use for a while. I'd >sure rather find out about that at compile time. That's funny -- Bruce Eckel talks about how he used to love checked exceptions but has come to regard them as the horror that they are. I've learned to just write "throws Exception" at the declaration of every method. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From ncoghlan at iinet.net.au Sat Jan 8 02:58:07 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 17:58:07 +1000 Subject: "A Fundamental Turn Toward Concurrency in Software" In-Reply-To: References: Message-ID: <41DF928F.1020201@iinet.net.au> Steve Horsley wrote: > But my understanding is that the current Python VM is single-threaded > internally, > so even if the program creates multiple threads, just one core will be > dividing > its time between those "threads". Not really. The CPython interpreter does have a thing called the 'Global Interpreter Lock' which synchronises access to the internals of the interpreter. If that wasn't there, Python threads could corrupt the data structures. In order to do anything useful, Python code must hold this lock, which leads to the frequent misapprehension that Python is 'single-threaded'. However, the threads created by the Python threading mechanism are real OS threads, and the work load can be distributed between different cores. In practice, this doesn't happen for a pure Python program, since any running Python code must hold the interpreter lock. The Python threads end up getting timesliced instead of running in parallel. Genuine concurrency with pure Python requires running things in separate processes (to reliably get multiple instances of the Python interpreter up and running). Python threads are mainly intended to help deal with 'slow' I/O operations like disk and network access - the C code that implements those operations *releases* the GIL before making the slow call, allowing other Python threads to run while waiting for the I/O call to complete. This behaviour means threading can give *big* performance benefits on even single-CPU machines, and is likely to be the biggest source of performance improvements from threading. However, on multi-processor machines, it is also handy if a CPU-intensive operation can be handled on one core, while another core keeps running Python code. Again, this is handled by the relevant extension releasing the GIL before performing its CPU-intensive operations and reacquiring the GIL when it is done. So Python's concurrency is built in a couple of layers: Python-level concurrency: Multiple processes for true concurrency Time-sliced concurrency within a process (based on the GIL) C-level concurrency: True concurrency if GIL is released when not needed In some cases, problems with multi-threading are caused by invocation of extensions which don't correctly release the GIL, effectively preventing *any* other Python threads from running (since the executing extension never releases it). As an example, I frequently use SWIG to access hardware API's from Python. My standard 'exception translator' (which SWIG automatically places around every call to the extension) now looks something like: %exception { Py_BEGIN_ALLOW_THREADS try { $action } except (...) { Py_BLOCK_THREADS SWIG_exception(SWIG_RuntimeError, "Unexpected exception") } Py_END_ALLOW_THREADS } The above means that every call into my extension releases the GIL automatically, and reacquires it when returning to Python. I usually don't call the Python C API from the extension, but if I did, I would need to reacquire the GIL with PyGILState_Ensure() before doing so. Without those threading API calls in place, operations which access the hardware always block the entire program, even if the Python program is multi-threaded. See here for some more info on Python's threading: http://www.python.org/doc/2.4/api/threads.html Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jgrahn-nntq at algonet.se Sun Jan 9 14:29:13 2005 From: jgrahn-nntq at algonet.se (Jorgen Grahn) Date: 9 Jan 2005 19:29:13 GMT Subject: "A Fundamental Turn Toward Concurrency in Software" References: <7x4qhs52rq.fsf@ruckus.brouhaha.com> Message-ID: On 07 Jan 2005 13:48:41 -0800, Paul Rubin <> wrote: > aurora writes: >> Just gone though an article via Slashdot titled "The Free Lunch Is >> Over: A Fundamental Turn Toward Concurrency in Software" >> [http://www.gotw.ca/publications/concurrency-ddj.htm]. It argues that >> the continous CPU performance gain we've seen is finally over. And >> that future gain would primary be in the area of software concurrency >> taking advantage hyperthreading and multicore architectures. > > Well, another gain could be had in making the software less wasteful > of cpu cycles. > > I'm a pretty experienced programmer by most people's standards but I > see a lot of systems where I can't for the life of me figure out how > they manage to be so slow. It might be caused by environmental > pollutants emanating from Redmond. Yeah, and possibly by overuse of IPC mechanisms, gratituous threading et cetera ... Concurrency is hard and complex. I'd prefer to see it as rarely as possible. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From iizogii at gmail.com Tue Jan 18 05:26:37 2005 From: iizogii at gmail.com (Mike McGavin) Date: Tue, 18 Jan 2005 23:26:37 +1300 Subject: Problem parsing namespaces with xml.dom.minidom In-Reply-To: References: <41eca38d@clear.net.nz> Message-ID: <41ece45f@clear.net.nz> Hi Fredrik. Fredrik Lundh wrote: >>I'm not terribly experienced with XML in general, so it's possible that I'm just incorrectly >>interpreting how things are supposed to work to begin with. If this is the case, please accept my >>apologies, but I'd like any suggestions for how I should be doing it. I'd really just like to be >>able to parse an XML document into a DOM, and then be able to pull out elements relative to their >>namespaces. > is the DOM API an absolute requirement? It wouldn't need to conform to the official specifications of the DOM API, but I guess I'm after some comparable functionality. In particular, I need to be able to parse a namespace-using XML document into some kind of node tree, and then being able to query the tree to select elements based on their namespace and local tag names, and so on. I don't mind if the methods provided don't conform exactly to DOM specifications. I guess I could write my own code to build a namespace-recognising DOM from an XML file, but it seems as if that's already been done and I'd be very surprised if it hadn't. I just can't figure out why minidom doesn't seem to be working properly for me when namespaces are involved. Thanks. Mike. From dbickett at gmail.com Sat Jan 1 15:06:36 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sat, 1 Jan 2005 15:06:36 -0500 Subject: Which blog tool In-Reply-To: <41d6a22f$0$42579$ed2619ec@ptn-nntp-reader03.plus.net> References: <41d6a22f$0$42579$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: <1d6cdae3050101120644f2643a@mail.gmail.com> There's actually a very simple way to achieve this. In your blogger settings you can specify an email address to which you can email blog posts. Using this, you can simply mail the content from within your python script. I think that's probably the most hassle-free way. Blogger help article: http://help.blogger.com/bin/answer.py?answer=135 Daniel Bickett On Sat, 01 Jan 2005 13:14:23 +0000, Mark Carter wrote: > I currently use python to automatically summarise a certain newsgroup > daily, and post the findings that it makes. Someone has suggested that > they would like a to see a blog of the posts. I wondered if there was a > python tool/library that could automate the blog postings. Any ideas? > > Some details: > * the summaries are basically just text files > * I already have a blog at www.blogger.com > (http://markcarterturriff.blogspot.com/), so I would like to use that if > possible; although any alternative free one that I can use to achieve my > objective would be OK, too. > * I do have my own hosted website, which can use perl but not python; > but I'd rather use a freebie blog site > * the whole thing must be scriptable, because it will run daily. A GUI > would therefore likely get in the way. > * generating an RSS feed would be nice > -- > http://mail.python.org/mailman/listinfo/python-list > From blade8472 at yahoo.com Sat Jan 29 13:12:34 2005 From: blade8472 at yahoo.com (blade8472) Date: Sat, 29 Jan 2005 18:12:34 -0000 Subject: Independence of programs! Message-ID: Hey all, hope all is fine, I have a question; I am new in python programming, I write the programs to a text doc then I run them with the interpreter, so I wanna know whether I can save the programs as exe so that they can be run independently on other PCs without the python interpreter. hope you help me, thanks alot! From elephantum at dezcom.mephi.ru Sun Jan 9 09:17:05 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 17:17:05 +0300 Subject: Python3: on removing map, reduce, filter Message-ID: <34csn1F4a46hqU1@individual.net> Hi. How does GvR suggestions on removing map(), reduce(), filter() correlate with the following that he wrote himself (afaik): http://www.python.org/doc/essays/list2str.html ? From josh at yucs.org Mon Jan 10 21:11:52 2005 From: josh at yucs.org (Joshua Spoerri) Date: Mon, 10 Jan 2005 21:11:52 -0500 Subject: why not datetime.strptime() ? Message-ID: <20050111021152.GA20127@yucs.org> Skip Montanaro pobox.com> writes: > josh> Shouldn't datetime have strptime? > If someone wants to get their feet wet with extension module > programming > this might be a good place to start. Mostly, I think nobody who has > needed/wanted it so far has the round tuits available to spend on the > task. OK, it was pretty straightforward. Thanks for the direction. To whom should I send the patch (attached)? -------------- next part -------------- --- Modules/datetimemodule.c.orig 2003-10-20 10:34:46.000000000 -0400 +++ Modules/datetimemodule.c 2005-01-10 20:58:38.884823296 -0500 @@ -3774,6 +3774,32 @@ return result; } +/* Return new datetime from time.strptime(). */ +static PyObject * +datetime_strptime(PyObject *cls, PyObject *args) +{ + PyObject *result = NULL, *obj, *module; + const char *string, *format; + + if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format)) + return NULL; + if ((module = PyImport_ImportModule("time")) == NULL) + return NULL; + obj = PyObject_CallMethod(module, "strptime", "ss", string, format); + Py_DECREF(module); + + result = PyObject_CallFunction(cls, "iiiiiii", + PyInt_AsLong(PySequence_GetItem(obj, 0)), + PyInt_AsLong(PySequence_GetItem(obj, 1)), + PyInt_AsLong(PySequence_GetItem(obj, 2)), + PyInt_AsLong(PySequence_GetItem(obj, 3)), + PyInt_AsLong(PySequence_GetItem(obj, 4)), + PyInt_AsLong(PySequence_GetItem(obj, 5)), + PyInt_AsLong(PySequence_GetItem(obj, 6))); + Py_DECREF(obj); + return result; +} + /* Return new datetime from date/datetime and time arguments. */ static PyObject * datetime_combine(PyObject *cls, PyObject *args, PyObject *kw) @@ -4385,6 +4411,11 @@ PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp " "(like time.time()).")}, + {"strptime", (PyCFunction)datetime_strptime, + METH_VARARGS | METH_CLASS, + PyDoc_STR("strptime -> new datetime parsed from a string" + "(like time.strptime()).")}, + {"combine", (PyCFunction)datetime_combine, METH_VARARGS | METH_KEYWORDS | METH_CLASS, PyDoc_STR("date, time -> datetime with same date and time fields")}, From macrocosm at fastmail.fm Mon Jan 10 00:09:31 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Mon, 10 Jan 2005 00:09:31 -0500 Subject: Python Operating System??? In-Reply-To: <7xvfa53obd.fsf@ruckus.brouhaha.com> References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> <7xvfa53obd.fsf@ruckus.brouhaha.com> Message-ID: <41E20E0B.8020509@fastmail.fm> Paul Rubin wrote: >Arich Chanachai writes: > > >>>Yes, compiled Lisp. There are Python compilers too.\ >>> >>> >>> >>??? You mean like Pyrex or some such? I wouldn't exactly call these >>"Python" compilers, as that kind of obscures some underlying >>(critical) facts. >> >> > >Also psyco. > Directly to machine code---- how could anyone say this is not compiled Python. I am right with you. On the other hand however, its compilation occurs on-the-fly (JIT) and is no more compiled than Java. There is an argument either way. I have heard of Java OSs in the works and possibly already existing...are these pure Java? > And I think Pypy is currently set up to compile Python >into Pyrex and then run the Pyrex results through GCC. > > But of course, who's going to argue that Pyrex produces "compiled Python"? I expect many would beg to differ, and in fact might like to kiss your toes just for the mere pleasure of contradicting and arguing against any assertion that Pyrex produces "compiled Python". From apardon at forel.vub.ac.be Wed Jan 19 04:21:45 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Jan 2005 09:21:45 GMT Subject: generator expressions: performance anomaly? References: <354esdF4fouh0U1@individual.net> Message-ID: Op 2005-01-18, Steve Holden schreef : > Antoon Pardon wrote: > >> Op 2005-01-18, Steve Holden schreef : >> >> >>>Python is *designed* as a dynamic language. I wish you would embrace >>>this aspect rather than continually trying to shoehorn it into a static >>>straitjacket. Efficiency is good. Flexibility is better. >> >> >> Flexibility is better? IMO flexibilty implies more than one way to do >> things. But that is a big no no here in c.l.py. >> > Become one with the language. That is difficult if I hear so many contradictionary things about it. Sometimes I have the feeling that the Zen of python is more for poet like people, not for the extreme analytical kind, like me. >> I also see a lot of remarks that go: "Don't do this!" when some of >> the more dynamic aspects are talked about, because there are >> security risks involved. One of the results was that I ended up >> writing a parser for some kind of game instead of just dumping the >> structure in textual form and doing an eval of the file when reading >> it in. But if I need a parser I could just as well used a static >> language. >> > Wow, you mean you actually *took* some advice? :-) Perhaps this whole > thing has arisen because you feel you were badly advised. It looks as > though your programming skill level might have been underestimated. Your > ability to wring an argument to a merciless death could never be. Again the problem is the many contradictionary arguments I get from this group. My impression is that any time I do a suggestion here or make a remark sooner or later someone will quote one of the rules of python and will consider the matter closed by that. But those rules can be used to support or reject any proposition. If someone proposes to introduce an exception, the rule quoted is: No exception is so importan to break the rule. If someone proposes to make python more consistent, the rule quoted is: practicallity beats purity. So in the end I get the feelings that the strengths of arguments doesn't matter here. If someone doesn't like a proposition, he just looks for the rule it will break (and since the rules contradict each other he will find one) and produce it as the final argument for why the proposal won't work. >> I'm beginning to guess the dynamic aspect of python is overrated. >> > You shouldn't have to guess, and it isn't. > > Certain of its dynamic aspects do demand a certain care rather than > casual usage, however, which leads to rules of thumb like "don't use > mutables as dictionary keys". Yes, of course you can, but to a newbie > your behavior (it seems to me) is a bit like this: But I am not talking to newbees. I am talking about documentation that is in the language reference and things that I'm told. If it would just be the tutorial and like wise documents that stated to not use mutables as dictionary keys I could live with that. But if the language reference suggest the same you can no longer claim it is for the newbee's sake. > Me (to newbie): "... And, of course, you want to be careful not to shoot > yourself in the foot." > You: ":Well, actually, if you use a .22 and aim very carefully between > the big toe and its neighbor there's a 96% chance that you will only > suffer serious burns". > > So, please understand, I'm not trying to say that (most of) your > utterances are untrue, or question your knowledge of the Python > environment. I'm just trying to bring the day closer when you will be > able to watch me write something that's only 99% true and happily walk > away without writing a thousand-word essay on the remaining 1% case. Well the problem may be I don't consider the person you are talking to as a newbee. Just the fact that he asks a question that marks him as a newbee in python doesn't mean he is a newbee programmer. But you do have a point that I have a tendency to put salt on any snail. I'll try to restrain myself a bit more in the future. -- Antoon Pardon From john at grulic.org.ar Tue Jan 11 00:12:26 2005 From: john at grulic.org.ar (John Lenton) Date: Tue, 11 Jan 2005 02:12:26 -0300 Subject: fetching method names from a class, and the parameter list from a method In-Reply-To: <1105385380.10721.6.camel@localhost> References: <1105385380.10721.6.camel@localhost> Message-ID: <20050111051225.GA29014@grulic.org.ar> On Mon, Jan 10, 2005 at 08:29:40PM +0100, Philippe C. Martin wrote: > Is this possible ? > > I am trying to have auto-completion working in a shell I wrote but I > currently have the method lists done by hand (ie; if I add/subtract a > method from that class, then my auto-completion is out of date). > > Same issue with method parameters. > > I have parsed through many of the attributes (ex: I use method.__doc__) > but have not yet found a way to achieve the above goal. > > Is there a way? something like the following would be great: > 1) list = Class.__methods__ > 2) dict (because of default values: "param = None") = > Class.__method__[0].__params__ >>> import inspect >>> help(inspect) HTH -- John Lenton (john at grulic.org.ar) -- Random fortune: In Greene, New York, it is illegal to eat peanuts and walk backwards on the sidewalks when a concert is on. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From simon.brunning at gmail.com Thu Jan 13 07:57:53 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Thu, 13 Jan 2005 12:57:53 +0000 Subject: module on files & directories In-Reply-To: <20050113125122.43539.qmail@web50504.mail.yahoo.com> References: <20050113125122.43539.qmail@web50504.mail.yahoo.com> Message-ID: <8c7f10c6050113045756e5135c@mail.gmail.com> On Thu, 13 Jan 2005 04:51:22 -0800 (PST), Sara Fwd wrote: > Hi all > > Can anybody help me find a module or a function that > looks in a directory and defines whether the objects > in there are files or directories? See os.path.isfile() and os.path.isdir() - . -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From ncoghlan at iinet.net.au Thu Jan 6 07:26:22 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 06 Jan 2005 22:26:22 +1000 Subject: Python evolution: Unease In-Reply-To: References: Message-ID: <41DD2E6E.9090505@iinet.net.au> > [Daniel Bowett] > > #- Contribute to where on Sourceforge??? Which domentation are > #- we talking > #- about in general? Speaking of docs. . . I think it would help a great deal if the python.org version-specific documentation pages used the standard documentation front page that actually includes the "About the Python Documentation" link that explains how to do this. Compare: http://www.python.org/doc/2.4/ To: http://www.python.org/dev/doc/devel/ Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From dayzman at hotmail.com Tue Jan 4 18:12:46 2005 From: dayzman at hotmail.com (dayzman at hotmail.com) Date: 4 Jan 2005 15:12:46 -0800 Subject: Compiling C99 extensions Message-ID: <1104880366.091309.195540@z14g2000cwz.googlegroups.com> Hi, I'm running Windows and Python 2.4 (binary). I've been trying to compile this module with extensions that incorporate some C99 extensions (e.g. designated initialisers). I haven't had much luck with MSVC++ Toolkit 2003, because it doesn't support C99. Is there any other way I can get the module installed and the extension compiled without the need to compile Python? I heard that Intel C++ has the same ABI as VS7.1, can I use it to comple the extension separately? If so, could someone briefly explain how, because I keep getting the error "python24.lib cannot be open" or similar error. Any help will be much appreciated. Cheers, Michael From ncoghlan at iinet.net.au Fri Jan 28 20:09:00 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 29 Jan 2005 11:09:00 +1000 Subject: a sequence question In-Reply-To: References: Message-ID: <41FAE22C.8020205@iinet.net.au> Duncan Booth wrote: > Try this: > > l = [1, 2, 3, 4] > for a, b in zip(*[iter(l)]*2): > print a, b > > zip(*[iter(seq)]*N) will group by N (but if there are any odd items at the > end it will ignore them). > > map(None, *[iter(seq)]*N) will group by N padding the last item with None > if it needs to. For anyone else who was as bemused as I was that Duncan's and F. Petitjean's suggestions actually *work*, this was what I had to do to figure out *why* they work: Py> l = [1, 2, 3, 4] Py> itr = iter(l) Py> zip(itr) # Put all items from iterator in position 1 [(1,), (2,), (3,), (4,)] Py> itr = iter(l) Py> zip(itr, itr) # Put every second item in position 2 [(1, 2), (3, 4)] Using zip(*[iter(l)]*N) or zip(*(iter(l),)*N) simply extends the above to the general case. I'd definitely recommend hiding this trick inside a function. Perhaps something like (using Michael's function name): from itertools import izip, repeat, chain def partition(seq, part_len): return izip(*((iter(seq),) * part_len)) def padded_partition(seq, part_len, pad_val=None): itr = iter(seq) if (len(seq) % part_len != 0): padding = repeat(pad_val, part_len) itr = chain(itr, padding) return izip(*((itr,) * part_len)) Py> list(partition(range(10), 2)) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] Py> list(partition(range(10), 3)) [(0, 1, 2), (3, 4, 5), (6, 7, 8)] Py> list(padded_partition(range(10), 2)) [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] Py> list(padded_partition(range(10), 3)) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)] Py> list(padded_partition(range(10), 3, False)) [(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, False, False)] Py> zip(*padded_partition(range(10), 3)) [(0, 3, 6, 9), (1, 4, 7, None), (2, 5, 8, None)] Not sure how useful that last example is, but I thought it was cute :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From judi-keplar at charter.net Wed Jan 26 10:55:28 2005 From: judi-keplar at charter.net (Judi Keplar) Date: Wed, 26 Jan 2005 15:55:28 -0000 Subject: Help With Python Message-ID: I am currently taking a course to learn Python and was looking for some help. I need to write a Python statement to print a comma- separated repetition of the word, "Spam", written 511 times ("Spam, Spam, Spam"). Can anybody help me get started? I am completely new to programming! Thanks in advance! From tjreedy at udel.edu Mon Jan 24 20:24:52 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Jan 2005 20:24:52 -0500 Subject: Help with saving and restoring program state References: <85b54e91.0501241556.d281f90@posting.google.com> Message-ID: "Jacob H" wrote in message news:85b54e91.0501241556.d281f90 at posting.google.com... > I'm developing an adventure game in Python Since you are not the first, have you looked at what others have done to save/restore? The Pygame site has code you can look at for adventure (I believe) and other game types (I know). Terry J. Reedy From remi at cherrypy.org Mon Jan 3 12:46:12 2005 From: remi at cherrypy.org (remi at cherrypy.org) Date: 3 Jan 2005 09:46:12 -0800 Subject: Ann: CherryPy-2.0-beta released Message-ID: <1104774372.943278.302050@f14g2000cwb.googlegroups.com> Hello everyone, I am happy to announce the release of CherryPy-2.0-beta. CherryPy-2 is a pythonic, object-oriented web development framework. CherryPy-2 is a redesign of CherryPy-1 (the unpythonic features have been removed): no more compilation step, pure python source code (no more "CherryClass") Here is a sample Hello, World in CherryPy-2: # from cherrypy import cpg # class HelloWorld: # @cpg.expose # def index(self): # return "Hello world!" # cpg.root = HelloWorld() # cpg.server.start() Main properties: - this code starts a multi-threaded HTTP server that dispatches requests to methods - requests like "http://domain/dir/page?arg1=val1&arg2=val2" are mapped to "dir.page(arg1='val1', arg2='val2')" - requests are mapped to an object tree that is "mounted" on cpg.root (for instance: "cpg.root.user", "cpg.root.user.remi", ...) - method must be explicitely exposed with a decorator "@cpg.expose" (or "index.exposed = True" for Python-2.3) - methods can return a generator instead of a string (useful when generating big pages) Here is a non-exhaustive list of CherryPy-2 features: multi-threaded HTTP server, XML-RPC server, sessions, form handling, authentication, unicode support, gzip-compression, virtual hosting, WSGI adapter (experimental) The design of CherryPy-2 allows to easily write/use pluggable "filters" or "modules": - filters perform operations on the request/response such as gzip-compression or string encoding - modules are web applications (like a blog or a web forum) than can be easily "mounted" anywhere you want in your website CherryPy-2 is already used in production by several sites and is supported by an active community. Remi. http://www.cherrypy.org From bokr at oz.net Tue Jan 11 02:36:49 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 11 Jan 2005 07:36:49 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 9) References: Message-ID: <41e381f2.551356108@news.oz.net> On Tue, 11 Jan 2005 07:27:42 +1100, Tim Churches wrote: >Josiah Carlson wrote: >> QOTW: Jim Fulton: "[What's] duck typing?" >> Andrew Koenig: "That's the Australian pronunciation of 'duct taping'." > >I must protest. >1) No (true-blue) Australian has every uttered the words 'duct taping', >because Aussies (and Pommies) know that the universe is held together >with gaffer tape, not duct tape. See http://www.exposure.co.uk/eejit/gaffer/ >b) If an Australian were ever induced to utter the words 'duct typing', >the typical Strine (see >http://www.geocities.com/jendi2_2000/strine1.html ) pronunciation would >be more like 'duh toypn' - the underlying principle being one of >elimination of all unnecessary syllables, vowels and consonants, thus >eliminating the need to move the lips (which reduces effort and stops >flies getting in). > >Tim C >Sydney, Australia LOL. Thanks, needed that ;-) Regards, Bengt Richter From philippe at philippecmartin.com Wed Jan 19 12:58:23 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Wed, 19 Jan 2005 17:58:23 GMT Subject: [OT] Good C++ book for a Python programmer References: <1106136496.719185.87850@c13g2000cwb.googlegroups.com> Message-ID: I suggest you google 'C++ tutorial' Regards, Philippe On Wed, 19 Jan 2005 04:08:16 -0800, rick_muller at yahoo.com wrote: > I'm picking up C++ again after years of using almost nothing but > Python. I'm frankly enjoying the experience, and it's certainly > deepening my appreciation of Python (which you can read however you > like). > > I was wondering whether anyone could recommend a good C++ book, with > "good" being defined from the perspective of a Python programmer. I > realize that there isn't a book titled "C++ for Python Programmers", > but has anyone found one that they think goes particularly well with > the Python way? > > I'm asking this because evidently the C++ standard has changed a bit > since 1994, when I bought my books. Who knew that fstream was > deprecated? > > Thanks in advance... From JoshuaACohen at gmail.com Thu Jan 6 10:29:01 2005 From: JoshuaACohen at gmail.com (Josh) Date: 6 Jan 2005 07:29:01 -0800 Subject: File Handling Problems Python I/O Message-ID: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> Hi, I am having a problem with Python. I am new to Python as a programming language, but I do have experience in other languages. I am experiencing strange problems with File handling and wonder if anyone else has seen this or knows what I am doing wrong. I am simply trying to open a file for read and iterate through until the end of file. I am able to do so without a problem, but here's the catch: The open statement is only working on certain files. I open a simple text file say file1.txt without any issues, but I change the open statement to another text file and it error's out stating the file doesn't exist. I know the code is correct because it worked for the other file. I have tried both binary and ascii modes to no avail. Any idea why this is happening? I am running Python 2.3.4 wxPython 2.5.3.1 and SPE as the IDE on Win2k. Thanks Josh From itsme at yahoo.com Wed Jan 12 12:50:36 2005 From: itsme at yahoo.com (It's me) Date: Wed, 12 Jan 2005 17:50:36 GMT Subject: Iteration over two sequences References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> <34kvs0F4bqiviU1@individual.net> Message-ID: I tried this and I got: [(1, 'a'), (2, 'b'), (3, 'c')] But if I change: a=[1,2] I got: [(1, 'c')] Why is that? I thought I should be getting: [(1, 'a'),(2,'b')] ????? "Diez B. Roggisch" wrote in message news:34kvs0F4bqiviU1 at individual.net... > zip or izip is your friend: > > import itertools > > a = [1,2,3] > b = ['a', 'b', 'c'] > > for a,b in itertools.izip(a, b): > print a, b > > -- > Regards, > > Diez B. Roggisch From duncan.booth at invalid.invalid Mon Jan 17 05:51:33 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jan 2005 10:51:33 GMT Subject: OCAMl a more natural extension language for python? References: Message-ID: Jelle Feringa // EZCT / Paris wrote: > After reading about extending python with C/Fortran in the excellent > Python Scripting for Computational Science book by Hans Langtangen, > I'm wondering whether there's not a more pythonic way of extending > python. And frankly I think there is: OCAML > There is an even more pythonic way to extend (or embed) python. Have you looked at Pyrex? http://nz.cosc.canterbury.ac.nz/~greg/python/Pyrex/ From aleaxit at yahoo.com Fri Jan 7 04:25:08 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 10:25:08 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <10trej2fl8dip65@corp.supernews.com> Message-ID: <1gq0k74.1epsxog1dgcgbsN%aleaxit@yahoo.com> Jeff Shannon wrote: > Note that the so-called 'viral' nature of GPL code only applies to > *modifications you make* to the GPL software. The *only* way in which > your code can be 'infected' by the GPL is if you copy GPL source. ... > (Problems may come if someone licenses a library under the GPL; that's > what the LGPL was invented for. But the issue here is not that the > GPL is bad, it's that the author used the wrong form of it.) Stallman now says that you should use GPL, not Lesser GPL. http://www.gnu.org/licenses/why-not-lgpl.html Specifically, he wants library authors to use GPL to impose the viral nature of GPL on other programs just USING the library -- the very opposite of what you say about "only applies ... if you copy"! Quoting RMS from that URL (about Readline, a GPL library): ''' Releasing it under the GPL and limiting its use to free programs gives our community a real boost. At least one application program is free software today specifically because that was necessary for using Readline. ''' Until some judge passes some judgment, the intent and effect of GPL must remain a matter of opinion. But RMS's opinion is probably more meaningful than mine or yours -- certainly regarding intent, given his role in designing that license. If he's badly erred, and one day a judge endorses your opinion and says that a program which copies no GPL source cannot be infected by GPL, ah well -- then I guess GPL is badly designed as to putting its intents into practice. But until there is some strong basis to think otherwise, I believe it's prudent to assume RMS is probably right, and your statement therefore badly wrong. Alex From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Thu Jan 6 18:03:02 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Fri, 7 Jan 2005 00:03:02 +0100 Subject: Pb encodage & import References: <41ddaaef$0$2749$8fcfb975@news.wanadoo.fr> Message-ID: <41ddc3ce$0$2744$8fcfb975@news.wanadoo.fr> Hi ! Wilk had give me a solution pour UnicodeDecode Error. But no ideas for other problems. From jbru at comml.net Sun Jan 2 10:48:25 2005 From: jbru at comml.net (Jabaru) Date: Sun, 2 Jan 2005 15:48:25 -0000 Subject: What can I do with Python ?? References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> <33oir1F40vpumU2@individual.net> Message-ID: <33qk47F41507nU1@individual.net> > BTW, I don't know of > a way to write fullscreen games in C#... > Directx, Opengl, Gdi+, win32api, SDL... the list goes on From dbickett at gmail.com Sun Jan 23 13:53:52 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 23 Jan 2005 13:53:52 -0500 Subject: OT: problems mirroring python-list to c.l.py? Message-ID: <1d6cdae305012310535980e82d@mail.gmail.com> I'm not sure if it's just me (or, indeed, just google groups), but my "python-list" folder (label, that is) in my gmail account looks less and less similar to Google Groups' comp.lang.python with each day. Not only that, c.l.py has been acting rather strange. Example that happened just now: Ali Polatel mailed[1] (I'm assuming) the python-list asking about pi. I responded, showing an interactive shell snippet[2], however on Google Groups' c.l.py it created the thread[3] as beginning with my post (undoubtedly causing confusion because mine was an answer not a question). Is there a reason that Google Groups isn't mirroring python-list exactly like it used to, or is it simply a conspiracy I'm not in on? perfectly-capable-of-conspiring-ly y'rs, Daniel Bickett NOTES: [1] http://mail.python.org/pipermail/python-list/2005-January/261966.html [2] http://mail.python.org/pipermail/python-list/2005-January/261968.html [3] http://tinyurl.com/6tsec From http Tue Jan 4 04:28:14 2005 From: http (Paul Rubin) Date: 04 Jan 2005 01:28:14 -0800 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1104830276.579755.133870@f14g2000cwb.googlegroups.com> Message-ID: <7x652dk0gh.fsf@ruckus.brouhaha.com> "flamesrock" writes: > Maybe you are right. If so, couldn't Python be forked into something > like you describe, while still remaining compatible at the core? (if > anyones willing) It's not an issue with the Python core (language); I read that post as mostly bemoaning the poor state of the runtime library. I feel the same concerns, however, fixing it is a lot of work. From steve at holdenweb.com Sun Jan 2 10:03:10 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 02 Jan 2005 10:03:10 -0500 Subject: Continuations Based Web Framework - Seaside. In-Reply-To: <7aTBd.11928$H%6.521997@twister1.libero.it> References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <7aTBd.11928$H%6.521997@twister1.libero.it> Message-ID: gabriele renzi wrote: > Mike Thompson ha scritto: > >> >> 'Seaside' is a Smalltalk framework for what might be called "Modal Web >> Development" or "Synchronous Web Programming", or even "Continuation >> Based Web Apps". >> >> http://www.beta4.com/seaside2/ >> >> Very sexy it looks too. And it seems to be generating a lot of >> interest - Ruby and Java variants have already sprung up: >> >> http://rubyforge.org/projects/borges/ >> http://lakeshore.sourceforge.net/ > > > actually, there are also implementations in Scheme, Common Lisp > (UnCommonWeb) and Cocoon-FLOW has similar concepts. > And somewhere (I think on the portland pattern repository) I recall > reading that Viaweb (aka "the first web app") was written in CPS. Also > notice that the Wee project in ruby is more advanced that Borges. > >> I googled for the python spin-off but didn't find one. Closest I found >> was Imposter (http://csoki.ki.iif.hu/~vitezg/impostor/) which looks >> like an earlier, partially failed attempt to do what Seaside now seems >> to be delivering. > > > I think "independent" more than earlier, it seem many people are > reinventing this from time to time. > Anyway, I just wanted to point out that IIRC something on this lines > appeared recently in the nevow svn tree, maybe you can take a look. I did actually do some sort-of-related work in this area, which I presented at PyCon DC 2004 - you can access the paper at http://www.python.org/pycon/dc2004/papers/18/Setting_A_Context.pdf An audience member mentioned the Smalltalk and Scheme-based work on web continuation frameworks, and I was sorry my answer at the time seemed unduly dismissive. There are some interesting similarities, and though my own implementation is decidedly clunky I like to think the paper explains some of the advantages of maintaining state and why the "back" button is an obnoxious anachronism :-) regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From theller at python.net Wed Jan 26 05:14:46 2005 From: theller at python.net (Thomas Heller) Date: Wed, 26 Jan 2005 11:14:46 +0100 Subject: py2exe problem References: <41f7213c$0$2343$a1866201@visi.com> Message-ID: Harald Massa writes: > Grant Edwards > >> LookupError: no codec search functions registered: can't find encoding >> Googling for the error message will find you the answer. > > http://starship.python.net/crew/theller/moin.cgi/Py2Exe > > carries within "encodings" and "encodings again" receipes to get it > working. > > A software development system which REALLY solves the encodings problem > WITHOUT creating a swarm of new ones could would challange even my > devotedness to Python :)))) AFAIK, McMillan Installer solves this by including all the encodings stuff by default, and it has a --ascii flag to override this behaviour. Would that be a solution? Thomas From aleaxit at yahoo.com Sat Jan 22 05:20:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 11:20:36 +0100 Subject: finding name of instances created References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> Message-ID: <1gqsfbi.1ifq0jv1yee7vnN%aleaxit@yahoo.com> Andr? Roberge wrote: > alex = CreateRobot() > anna = CreateRobot() > > alex.move() > anna.move() Hmmmm -- while I've long since been identified as a 'bot, I can assure you that my wife Anna isn't! Alex From snail at objmedia.demon.co.uk Tue Jan 25 06:42:35 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Tue, 25 Jan 2005 11:42:35 +0000 Subject: is there better 32 clock() timing? References: <41f61372.1768192005@news.oz.net> Message-ID: >>that time.clock() is inaccurate. The problem is that the "time.clock()" >>statement takes several hundred microseconds to execute. The statement is incorrect. clock() itself isn't slow, but it is accessing a resource, the accuracy of which is no better than 1ms. There are various timers available, documented and undocumented, all of which end up at 1ms or 1.1ms, give or take. For anything shorter you need QueryPerformanceCounter() (but that *is* a slow call), or use the RDTSC instruction which is fast but gives a count of instruction cycles executed and is thus not totally accurate (multiple execution pipelines, plus multithreading considerations). You have to choose the system that works best for you. In many cases RDTSC works OK. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From lbates at syscononline.com Sat Jan 15 17:13:47 2005 From: lbates at syscononline.com (Larry Bates) Date: Sat, 15 Jan 2005 16:13:47 -0600 Subject: python to mssql In-Reply-To: <1lmwxbtst8x8x$.10hwcoinem3cs.dlg@40tude.net> References: <1lmwxbtst8x8x$.10hwcoinem3cs.dlg@40tude.net> Message-ID: You really need to ask one/several specific questions. Python works with MSSQL. You can go through ODBC, ADO, etc. to work with data in MSSQL database. Hope info helps, Larry Bates Brane wrote: > can someone please give me some info regarding subject > please advice > regards > brane From steven.bethard at gmail.com Thu Jan 27 02:02:45 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 00:02:45 -0700 Subject: String Fomat Conversion In-Reply-To: References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> Message-ID: Stephen Thorne wrote: > f = file('input', 'r') > labels = f.readline() # consume the first line of the file. > > Easy Option: > for line in f.readlines(): > x, y = line.split() > x = float(x) > y = float(y) > > Or, more concisely: > for line in f.readlines(): > x, y = map(float, line.split()) Somewhat more memory efficient: lines_iter = iter(file('input')) labels = lines_iter.next() for line in lines_iter: x, y = [float(f) for f in line.split()] By using the iterator instead of readlines, I read only one line from the file into memory at once, instead of all of them. This may or may not matter depending on the size of your files, but using iterators is generally more scalable, though of course it's not always possible. I also opted to use a list comprehension instead of map, but this is totally a matter of personal preference -- the performance differences are probably negligible. Steve From snacktime at gmail.com Wed Jan 26 00:32:02 2005 From: snacktime at gmail.com (snacktime) Date: Tue, 25 Jan 2005 21:32:02 -0800 Subject: alternatives to mod python Message-ID: <1f060c4c0501252132678ff140@mail.gmail.com> I'm looking for a simple async ssl http server that can accept http POST requests. Performance is an issue, which is why I'm currently using mod python. I don't really want to require installing apache and mod python though if I can help it, since this is software that will be distributed to end users. Anyone have any suggestions? The only other thing I looked at was twisted, which I'm still evaluating. Chris From mirnazim at gmail.com Sat Jan 1 23:51:06 2005 From: mirnazim at gmail.com (mirnazim at gmail.com) Date: 1 Jan 2005 20:51:06 -0800 Subject: Frameworks for "Non-Content Oriented Web Apps" Message-ID: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> Hi, There are great Python Web Application Framework. But most of them are meant for content oriented web apps. Is there something that can ease the development of application that are not content oriented(I call them "NON CONTENT-ORIENTED WEB APPLICATIONS" because I don't know what else to call them). I mean the applications like, accounting, high volume data entry apps, where normally GUI clients have ruled. I know very high quality ERP and similar packages have been implemented in a web based environment. But problem is that they have been developed with the tools that were actually meant for content oriented apps like Zope, PHP, etc. But is there some sort of framework or something that is actually meant for such web apps,application that make heavy use of forms, have very high amount of user interaction etc. What I am asking here may sound off beat, but I think, in todays world where web based solutions offers such a flexibility, we really need it. I also know that I am to ambiguous, but as is the characteristic of this wonderful community, talks that start as most abigous, transform in crystal clear. PS: I am a web developer, using PHP for living. I have been playing with python for a while. I found python is really a cool language(do I need to say that ;-)) with a really, really impressive collection of modules and frameworks. While developing a school information system, I felt the need of such a framework that makes developing of "Non-Content Oriented Web-Apps" easy. I know I posted a similar message earlier, but this time I a bit more general. From wuwei23 at gmail.com Wed Jan 26 22:36:05 2005 From: wuwei23 at gmail.com (alex23) Date: 26 Jan 2005 19:36:05 -0800 Subject: 20050126 find replace strings in file In-Reply-To: References: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> Message-ID: <1106796965.765179.106820@f14g2000cwb.googlegroups.com> kosh wrote: > Nah it is daily humor. Just think of it like a joke list. :) Or a daily puzzler: how many blatantly stupid things can you find in 5 mins? From mfranklin1 at gatwick.westerngeco.slb.com Fri Jan 28 10:35:26 2005 From: mfranklin1 at gatwick.westerngeco.slb.com (Martin Franklin) Date: Fri, 28 Jan 2005 15:35:26 +0000 Subject: debugging os.spawn*() calls In-Reply-To: <16890.22749.899414.324589@montanaro.dyndns.org> References: <16890.22749.899414.324589@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > I have an os.spawnv call that's failing: > > pid = os.spawnv(os.P_NOWAIT, "ssh", > ["ssh", remote, > "PATH=%(path)s nice -20 make -C %(pwd)s" % locals()]) > > When I wait for it the status returned is 32512, indicating an exit status > of 127. Unfortunately, I see no way to collect stdout or stderr from the > spawned process, so I can't tell what's going wrong. > > The "ssh remotehost PATH=$PATH nice -20 make ..." command works fine from a > similar shell script. > > Thx, > > Skip Skip, While not a 'real' answer - I use pexpect to automate my ssh scripts these days as I had a few problems using ssh with the os.* family perhaps you may find pexpect a wee bit easier... Martin. From chris.lasher at gmail.com Wed Jan 12 17:46:07 2005 From: chris.lasher at gmail.com (Chris Lasher) Date: 12 Jan 2005 14:46:07 -0800 Subject: What strategy for random accession of records in massive FASTA file? Message-ID: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> Hello, I have a rather large (100+ MB) FASTA file from which I need to access records in a random order. The FASTA format is a standard format for storing molecular biological sequences. Each record contains a header line for describing the sequence that begins with a '>' (right-angle bracket) followed by lines that contain the actual sequence data. Three example FASTA records are below: >CW127_A01 TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA GCATTAAACAT >CW127_A02 TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA GCATTAAACATTCCGCCTGGGGAGTACGGTCGCAAGATTAAAACTCAAAGGAATAGACGG >CW127_A03 TGCAGTCGAACGAGAACGGTCCTTCGGGATGTCAGCTAAGTGGCGGACGGGTGAGTAATG TATAGTTAATCTGCCCTTTAGAGGGGGATAACAGTTGGAAACGACTGCTAATACCCCATA GCATTAAACATTCCGCCTGGG ... Since the file I'm working with contains tens of thousands of these records, I believe I need to find a way to hash this file such that I can retrieve the respective sequence more quickly than I could by parsing through the file request-by-request. However, I'm very new to Python and am still very low on the learning curve for programming and algorithms in general; while I'm certain there are ubiquitous algorithms for this type of problem, I don't know what they are or where to look for them. So I turn to the gurus and accost you for help once again. :-) If you could help me figure out how to code a solution that won't be a resource whore, I'd be _very_ grateful. (I'd prefer to keep it in Python only, even though I know interaction with a relational database would provide the fastest method--the group I'm trying to write this for does not have access to a RDBMS.) Thanks very much in advance, Chris From snail at objmedia.demon.co.uk Fri Jan 28 05:02:33 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Fri, 28 Jan 2005 10:02:33 +0000 Subject: Profiling python 2.3 References: Message-ID: In message , Kenneth Johansson writes >I wonder what would be a good way to profile a python program where the >main thread starts two worker threads that do all the work. > >I get no infomation at all from the threads. Python Performance Validator (beta) http://www.softwareverify.com/pythonPerformanceValidator/index.html Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From kbk at shore.net Sun Jan 2 15:39:13 2005 From: kbk at shore.net (Kurt B. Kaiser) Date: Sun, 02 Jan 2005 20:39:13 GMT Subject: IDLE question References: Message-ID: <87mzvro9an.fsf@hydra.bayview.thirdcreek.com> Ishwor writes: > On Sun, 26 Dec 2004 13:02:01 +0100, Rolf Wester > wrote: >> Hi, >> >> I would like to use IDLE as interactively as I can with Emacs. In Emacs >> I can send a marked region to the Python interpreter. Is there any way >> to do the same thing with IDLE? > Although i don't use anything much beside IDLE, vim for coding, AFAIK > IDLE can't do that. > IDLE opens up python shell. Within that shell you type in your script > , commands and create objects as such......The interpreter will > execute your code then. Copy. Paste at shell prompt. . I'm thinking about adding copy and paste to right click menu. Maybe paste/exec would be cool in the shell window. -- KBK From fredrik at pythonware.com Sat Jan 22 14:53:17 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 20:53:17 +0100 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> Message-ID: "rm" wrote: > 100% right on, stuff (like this)? should be easy on the users, and if possible, on the developers, > not the other way around. I guess you both stopped reading before you got to the second paragraph in my post. YAML (at least the version described in that spec) isn't easy on users; it may look that way at a first glance, and as long as you stick to a small subset, but it really isn't. that's not just bad design, that's plain evil. and trust me, when things are hard to get right for developers, users will suffer too. From max at alcyone.com Mon Jan 17 01:35:08 2005 From: max at alcyone.com (Erik Max Francis) Date: Sun, 16 Jan 2005 22:35:08 -0800 Subject: [perl-python] 20050117, filter, map In-Reply-To: References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> Message-ID: Steven Bethard wrote: > Is there any chance you could post these all as part of the same thread? > That would be really nice for those of us who aren't interested -- > then we could just ignore the thread... Or, better yet, not posting it at all. He's got his mailing list, what does he need to post it here for? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Make it come down / Like molasses rain -- Sandra St. Victor From fredrik at pythonware.com Sun Jan 23 01:54:31 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 07:54:31 +0100 Subject: list unpack trick? References: <41F3398F.9010701@iinet.net.au> Message-ID: Nick Coghlan wrote: >> I am think more in the line of string.ljust(). So if we have a list.ljust(length, filler), we >> can do something like >> >> name, value = s.split('=',1).ljust(2,'') > > Eh? > > Py> s.split('=',1).ljust(2,'') > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'list' object has no attribute 'ljust' I think the "if we have" was hypothetical. I still don't see why the OP cannot just write a small helper and be done with it, but then I don't know anything about how Python is used, so I might be wrong ;-) From foo at bar.com Sat Jan 22 13:39:01 2005 From: foo at bar.com (Steve Menard) Date: Sat, 22 Jan 2005 13:39:01 -0500 Subject: embedding jython in CPython... In-Reply-To: References: Message-ID: Jim Hargrave wrote: > I've read that it is possible to compile jython to native code using > GCJ. PyLucene uses this approach, they then use SWIG to create a Python > wrapper around the natively compiled (java) Lucene. Has this been done > before for with jython? > > Another approach would be to use JPype to call the jython jar directly. > > My goal is to be able to script Java code using Jython - but with the > twist of using Cpython as a glue layer. This would allow mixing of Java > and non-Java resources - but stil do it all in Python (Jython and Cpython). > > I'd appreciate any pointers to this topic and pros/cons of the various > methods. > > Well now that IS getting kinda complicated ... AS far a natively compiling Jython scripts ... well, if you natively compile them, it'll hard to "script" you java code afterward (I assume by scripting you mean loading scripts at runtime that were not know at compile time). As for using JPype ... well it depends on what you want to script. if you Java code is the main app, I'd eschew CPython completely and use Jython to script. If you main app is in Python, and the Java code is "simply" libraries you wish to use, then I'f go with CPython + Jpype. It is very easy to manipulate Java objects that way, even to receive callbacks. I guess it all comes down to what you mean by scripting, and exaclt what the structure of your application (as far as what is java and non-java). If you care to explain your situation a bit more, we'll be better able to help you. Steve Menard Maintainer of http://jpype.sourceforge.net From dbickett at gmail.com Sun Jan 23 11:02:12 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 23 Jan 2005 11:02:12 -0500 Subject: compile python to binary In-Reply-To: References: Message-ID: <1d6cdae3050123080242bf8994@mail.gmail.com> Fredrik Lundh wrote: > see section 6.1.2 in the tutorial: > [snip] I believe Sam was talking about "frozen" python scripts using tools such as py2exe: http://starship.python.net/crew/theller/py2exe/ As to how the actual process works, I'm not qualified to answer (having only read an article in the linux magazine,) but I hope this helps. Daniel Bickett From hancock at anansispaceworks.com Fri Jan 28 13:29:58 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 28 Jan 2005 12:29:58 -0600 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <200501241906.39865.hancock@anansispaceworks.com> Message-ID: <200501281229.58544.hancock@anansispaceworks.com> On Tuesday 25 January 2005 01:51 am, Fredrik Lundh wrote: > ah, you're the guy who flamed me and called me names because PIL didn't > fit some hypothetical GNU-inspired definition of "open source software." it's > always sad when people have to attack those who don't share their religion, > but it's not that much I can do about that. That is a complete misrepresentation of the post in question. It was in no manner of interpretation a "flame". You simply took offense out of thin air. And there's not much *I* can do about *that*. I figured that my intent to contribute to your project was sufficient to indicate my good intentions. > > So, naturally, I just dropped it. > > which means that you have no idea how easy or hard it is to install PIL today > (hint: things have changed) Oh? In which version? Are you saying that your installation procedure now honors the "--with-jpeg=" and "--with-png=" flags to configure? Because although you had these flags, in the last version I installed from source, they did not work -- it was still necessary to edit the Makefile. That was either 1.1.3 or 1.1.4, and I'm pretty sure it was the latter. Now if you've actually fixed this, I look forward to trying it out the next time I have to do a complete from-source installation. I'll say "thank you", just in case. Cheers, Terry -- -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From cam.ac.uk at mh391.invalid Sun Jan 16 15:00:30 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 16 Jan 2005 20:00:30 +0000 Subject: List problems in C code ported to Python In-Reply-To: References: Message-ID: Lucas Raab wrote: > Please see both the Python and C code at > http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py If you post a small testcase here you are much more likely to get helped. -- Michael Hoffman From aleaxit at yahoo.com Tue Jan 4 03:11:11 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 4 Jan 2005 09:11:11 +0100 Subject: Integrating Python into a C++ app References: <1104801230.728736.83970@f14g2000cwb.googlegroups.com> Message-ID: <1gpuwm5.1bi5eb21qffmx8N%aleaxit@yahoo.com> Ben Sizer wrote: > I know the conventional wisdom is to write the whole app in Python and > only extend with C++ where speed is an issue, but I already have a > large C++ app that I'd like to add Python to. Ideally I'd rewrite the > whole app in Python but I don't have time to do that and maintain the > old system at the same time. So my next thought was to perhaps > integrate the two and slowly migrate modules and classes across from > C++ to Python. If it matters, the main reason I'm interested in doing > this is because I appreciate the productivity of Python and would like > to take advantage of that as I add features to the current code, to > reduce bugs and cut development time. This seems quite a reasonable approach to me. > I've read a few good things in this group about Elmer > (http://elmer.sourceforge.net), but I'm not sure how simply that > accommodates calls in the reverse direction (from Python code back into > C++). Are there any other options that would require a minimum of > rewriting of code? Does anybody have any experience of such a project? Sorry, haven't tried elmer yet. When I did such embedding a few years ago I used Boost Python (www.boost.org) -- Boost has kept growing better with the years so today it should be even easier. OTOH, the C++ application was already well structured according to Lakos' ideas (expressed in his book about large-scale program design in C++): components communicating across interfaces, rather than a free-for-all of jumbles of dependencies. The interfaces being abstract C++ classes, and the building of concrete instances always going through Factory design patterns, Boost's abilities to wrap C++ classes as Python types and let Python classes inherit from such wrapped C++ classes so that normal virtual-method-call C++ approaches proved sufficient. (In the end, after several experiments, we ended up using COM, since the application only ran on Windows anyway; much of the COM was of course done in Python, but that's another issue). I suspect that few legacy C++ applications are well structured in terms of components and interfaces. But then, trying to do any kind of major surgery without serious rearchitecting tends to produce inferior results anyway. And the rearchitecting is quite advisable whether you do end up using any Python, or not -- you want good, clean components, cohesive and coherent, with a good graph of dependencies, unit-tests for each component, dependency inversion (a la Robert Martin) to avoid dependencies going the wrong way, etc, etc. Lakos and Martin are the two authors I would suggest reading. Lakos' book is old, and among his major concerns is using just the subset of C++ you could rely on, years ago; you can probably ignore those issues safely today (to use Boost, you need a good recent C++ compiler with impeccable template support, anyway, for example). Alex From snail at objmedia.demon.co.uk Mon Jan 24 11:54:17 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Mon, 24 Jan 2005 16:54:17 +0000 Subject: Memory Usage References: Message-ID: In message , rbt writes >That's right. I look at that column. Should I measue mem usage in some >other way? Try VM Validator, a free memory visualization tool from Software Verification. http://www.softwareverify.com http://www.softwareverify.com/vmValidator/index.html It shows paged memory usage and also Virtual Memory manager usage on separate tabs. Colour coded visual representation of each 4K page of memory. Probably more use on more memory intensive applications than yours, but may still shed some light all the same. Either launch Python from VM Validator, or inject VM Validator into your running Python.exe process. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From marc.poulhiesNO-SP4M at epfl.ch Mon Jan 31 10:48:43 2005 From: marc.poulhiesNO-SP4M at epfl.ch (=?iso-8859-1?Q?Marc_Poulhi=E8s?=) Date: Mon, 31 Jan 2005 16:48:43 +0100 Subject: Using HTTPSConnection and verifying server's CRT Message-ID: <41fe5357@epflnews.epfl.ch> Hi, I'm trying to build a system using HTTPS with python clients that have to verify the server's identity. From the Python document, it seems that the server's certificate is not veryfied, and authentication can only be in the other way (client authentication). I know usually users only click on 'yes I trust this certificate', but what if you really care (this is my case)? I tried to see if the M2Crypto has this possibility, but from my tests and from what I can find on the website, it seems not :/ Can someone confirm me this is not possible or point me to something that could help me? Thanks, Marc From michael.bierenfeld at web.de Fri Jan 14 03:39:21 2005 From: michael.bierenfeld at web.de (michael.bierenfeld at web.de) Date: 14 Jan 2005 00:39:21 -0800 Subject: dynamically inserting function into an object References: <1105634097.319563.156260@c13g2000cwb.googlegroups.com> Message-ID: <1105691961.883644.49770@z14g2000cwz.googlegroups.com> *damn* it :-) python rocks. thx michael .oO (resetting c/c++/java crap collected over the years) From mcfletch at rogers.com Mon Jan 10 22:14:56 2005 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Mon, 10 Jan 2005 22:14:56 -0500 Subject: Writing huve ge Sets() to disk In-Reply-To: <41E32E2B.3090508@ribosome.natur.cuni.cz> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> <41E2E69C.7080104@ribosome.natur.cuni.cz> <1f7befae0501101245679b26f2@mail.gmail.com> <41E2F38C.30200@ribosome.natur.cuni.cz> <1f7befae05011015362e17f610@mail.gmail.com> <41E32E2B.3090508@ribosome.natur.cuni.cz> Message-ID: <41E344B0.8020200@rogers.com> Martin MOKREJ? wrote: > Tim Peters wrote: > ... >>> I was really hoping I'll get an answer how to alter the indexes for >>> dictionaries >>> in python. >> >> >> >> Sorry, I don't have a guess for what that might mean. > > > I'm not an expert, mysql for example givs you ability to index say > first 10 characters of a text column, which are typically varchar. > Just for curiosity I'd like to know how do it in python. > > When importing data from a flatfile into mysql table, there's an > option to delay indexing to the very last moment, when all keys are > loaded (it doesn't make sense to re-create index after each new > row into table is added). I believe it's exactly same waste of cpu/io > in this case - when I create a dictionary and fill it with data, > I want to create index afterward, not after every key/value pair > is recorded. Okay, you seem to be missing this key idea: A hash-table (dict) is approximately the same level of abstraction as a btree index. Your MySQL "index" is likely implemented as a btree. A hash-table could just as readily be used to implement the index. When you insert into either of these structures (btree or hash), you are not creating an "index" separate from the structure, the structure *is* an "index" of the type you are thinking about. These structures are both efficient representations that map from a data-value to some other data-value. Hashes with a good hash function (such as Python's dicts) are basically O(1) (worst case O(n), as Tim notes), while Btrees (such as common database indices) are O(log(n)) (or something of that type, basically it grows much more slowly than n). >>> Once more, I expect to have between E4 or E5 to E8??? words >>> stored in 20 dictionaries (remember words of sizes in range 1-20? >>> Every of those 20 dictionaries should be, I believe, indexed just once. >>> The indexing method should know all entries in a given file are of same >>> size, i.e. 5 chars, 15 chars, 20 chars etc. >> >> >> >> I think you're making this more complicated than it needs to be. > > > I hope the algoritm can save some logic. For example, can turn off > locking support, > index only part of the key etc. I'd tend to agree with Tim. You're making this all far too complex in what appears to be the absence of any real need. There's a maxim in computer programming that you avoid, wherever possible, what is called "premature optimisation". You are here trying to optimise away a bottleneck that doesn't exist (indexing overhead, and locking support are basically nil for a dictionary). It is almost a certainty that these are not *real* bottlenecks in your code (what with not existing), so your time would be better spent writing a "dumb" working version of the code and profiling it to see where the *real* bottlenecks are. > For example, looking up a key with it's value only once in the whole > for loop tells me > I don't need an index. Yes, I'll do this 4 times for those 4 > languages, but > still I think it's faster to live without an index, when I can sort > records. I think I like the sorted text file approach, and the dictionary > approach without an index would be almost the same, especially if I > manage > to tell the db layout not to move the cursor randomly but just to walk > down the > pre-sorted data. Again, you don't really have a cursor with a dictionary (and since it's randomly ordered, a cursor wouldn't mean anything). A *btree* has an order, but not a dictionary. You could construct a sorted list in memory that would approximate what I *think* you're thinking of as a dictionary-without-an-index. Good luck, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From tom at dtsam.com Fri Jan 21 10:23:21 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Fri, 21 Jan 2005 09:23:21 -0600 Subject: Graph and Table implementation References: Message-ID: "Jan Rienyer Gadil" wrote in message news:mailman.994.1106299588.22381.python-list at python.org... > could anyone please help me! > > what and how is the best implementation of creating a table based on > data coming from the serial port ? and also how would i be able to > create graphs (2D) based on these data? > > opinions and suggestion are most highly welcome. thanks. > If you want to use existing tools, it is hard to beat a spreadsheet with a scatter plot graph object. If you are on the Microsoft side of the fence, Excel is perfect for this. There is an easy to use MSCOMM32.OCX object to control the serial port. This reduces your problem to moving the serial port data to an [x,y] column that is attached to a scatter plot. This is easy to do with Excel's built in VBA so I assume it would also be easy to do with Python, given that you can use Python to manipulate the Excel object model . On the Linux/Unix side. Gnumeric seems to serve very well although I don't yet have sufficient personal experience with it to know about the "gotcha's" you might encounter. I am also guessing that the Open Office spreadsheet would work too. Thomas Bartkus From db3l at fitlinxx.com Tue Jan 18 17:07:32 2005 From: db3l at fitlinxx.com (David Bolen) Date: 18 Jan 2005 17:07:32 -0500 Subject: extension module, thread safety? References: <41ecbaae$0$1046$626a14ce@news.free.fr> <41eccfe4$0$16621$636a15ce@news.free.fr> Message-ID: Nick Coghlan writes: > Pierre Barbier de Reuille wrote: > > Ok, I wondered why I didn't know these functions, but they are new > > to Python 2.4 ( and I didn't take the time to look closely at Python > > 2.4 as some modules I'm working with are still not available for > > Python 2.4). But if it really allows to call Python code outside a > > Python thread ... then I'll surely use that as soon as I can use > > Python 2.4 :) Thanks for the hint :) > > The Python 2.4 docs claim the functions were added in Python 2.3, even > though they aren't documented in the 2.3.4 docs. > > The 2.3 release PEP (PEP 283) confirms that PEP 311 (which added these > functions) went in. And even before that it was certainly possible to call into the Python interpreter from a native thread using existing functions, albeit the newer functions are more convenient (and perhaps more robust, I don't know). My earliest interaction with Python (~1999, while writing a module that extended and embedded Python 1.5.2) used PyEval_AcquireThread() and PyEval_ReleaseThread() to get access to a thread state from a native C application thread (not initiated by the Python interpreter) to allow me to call safely into an executing Python script upon asynchronous data reception by the C code. -- David From fuzzyman at gmail.com Tue Jan 25 12:17:41 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 25 Jan 2005 09:17:41 -0800 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: <10vb8cve125v0b0@corp.supernews.com> Message-ID: <1106669985.689124.43860@z14g2000cwz.googlegroups.com> Cameron Laird wrote: [snip..] > This is a serious issue. > > It's also one that brings Tcl, mentioned several > times in this thread, back into focus. Tcl presents > the notion of "safe interpreter", that is, a sub- > ordinate virtual machine which can interpret only > specific commands. It's a thrillingly powerful and > correct solution to the main problem Jeff and others > have described. A better (and of course *vastly* more powerful but unfortunately only a dream ;-) is a similarly limited python virutal machine..... It could make embedding python a lot simpler for lots of applications and even 'embedded python' a lot simpler. (Not to mention 'restricted execution' - e.g. for applets in web pages) *Perhaps* the pypy core will be a bit like this - but it's design goals are very different of course. Anyway, little point in wishing on a dream - I'm certainly not up to the job :-) Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From news at outbacklinux.com Tue Jan 11 04:09:26 2005 From: news at outbacklinux.com (Adrian Casey) Date: Tue, 11 Jan 2005 18:39:26 +0930 Subject: Command line and GUI tools : need a single threading solution References: <41e26e79@duster.adelaide.on.net> Message-ID: <41e397c6@duster.adelaide.on.net> Phil Thompson wrote: >> I have a collection of multi-threaded command line tools which I want >> wrap a >> PyQt gui around. I'm using queues to route messages from the command >> line tools to the PyQt gui. The command line tools use python threads to >> do >> their work. The gui uses a QThread object to read incoming messages. >> >> This does not work consistently - and I've since read that mixing python >> threads and QThreads is a bad idea. The command line tools work well >> using >> python threads. > > How well mixing the two threading APIs works depends on version numbers. A > PyQt generated with SIP v4.x (rather than SIP v3.x) with Python v2.4 > should be Ok. > >> I don't want to maintain two copies of the tools - one for command line >> and >> another for the PyQt version. >> >> I'm thinking it may be possible to modify the command line tools to use >> qt >> threads instead of native python threads. Is this the way to go? Are >> there other options? > > Using QThreads only should work - just tell the QApplication ctor that you > have a console application. > > Phil Phil, I'm running python 2.4, sip-4.0 and PyQt-x11-gpl-3.11 (or .13 - not sure as I'm not at work). A little more detail. My script, if invoked from the command line, creates a queue object (let's call it logQueue) which is used to take the output from each individual thread. If invoked via the gui, the script is passed a logQueue created by the gui. Each thread dumps its output using logQueue.put(). There are other queues which are used to service threaded access to a database etc. The scripts use the pexpect module to login to remote systems and do sysadmin tasks (e.g. reset passwords). This works like a charm in console mode. The gui uses a QThread to poll logQueue (logQueue.get()). When it gets something, it creates a QCustomEvent and sets the data portion using the data read from the logQueue. I have a customEvent method in my application which grabs the data from the customEvent and processes it accrodingly (writing output to a QTable). The gui locks up after an arbitrary number of rows have been inserted in the QTable. It is not consistent. Sometimes it does not lock at all. I have a non-threaded set of the command line tools which run perfectly with the gui. Adrian. From peter at engcorp.com Wed Jan 19 21:28:13 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 19 Jan 2005 21:28:13 -0500 Subject: Zen of Python In-Reply-To: <10uu3iphdr23mf4@corp.supernews.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <10uu3iphdr23mf4@corp.supernews.com> Message-ID: Jeff Shannon wrote: > Timothy Fitz wrote: >> Which I agree with, and which makes sense. However your "gist" is a >> different meaning. It's not that "Flat is better than nested" it's >> that "Too flat is bad and too flat is nested so be as nested (or as >> flat) as you have to be and no more." Perhaps Tim Peters is far too >> concise for my feeble mind > > Well, the way that the Zen is phrased, it implies a bit more than that. A Zen koan always implies more than the listener infers. From zyqnews at 163.net Sat Jan 29 20:23:30 2005 From: zyqnews at 163.net (zyqnews at 163.net) Date: 29 Jan 2005 17:23:30 -0800 Subject: cx_freeze error Message-ID: <1107048210.548048.152870@z14g2000cwz.googlegroups.com> I am new to Python. I made a script, and compiled it with cx_freeze, but I got the following message from it: [cxfreeze]$./FreezePython hello.py Traceback (most recent call last): File "initscripts/ConsoleKeepPath.py", line 15, in ? exec code in m.__dict__ File "FreezePython.py", line 1, in ? File "optparse.py", line 72, in ? File "textwrap.py", line 32, in ? File "textwrap.py", line 81, in TextWrapper AttributeError: 'module' object has no attribute 'compile' Does anyone know what I should do ? Thanks From davidf at sjsoft.com Wed Jan 19 04:52:07 2005 From: davidf at sjsoft.com (David Fraser) Date: Wed, 19 Jan 2005 11:52:07 +0200 Subject: how to find site-packages path (Michael Hoffman) - use distutils In-Reply-To: References: Message-ID: Philippe C. Martin wrote: > I actually target Unix and windows so pyexe won't cut it I'm afraid - > same issue with Inno. > > As far as the site-package target, I don't fully understand your > relunctancy. Just as my potential users might not own a compiler, they > might not be computer proficient enough to easily understand how to > change the sys.path. So until I have found a clean cross platform > solution I'm going to have to stick to site-packages. Hi Philippe You may want to have a look at https://sourceforge.net/tracker/?func=detail&atid=305470&aid=793070&group_id=5470 This was originally a patch to distutils which enabled removing the source (i.e. only distributing compiled files). I have now attached a file there which enables you to do the same thing, but without patching distutils - it just wraps functions etc from outside. Basically you call allow_distutils_remove_source in the module and it does the neccessary changes. Then you get a --remove-source options to most of the commands. You can also selectively override what gets removed if you want by changing the is_removable function I hope this is useful for what you're wanting to do David From tjreedy at udel.edu Wed Jan 26 16:48:56 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Jan 2005 16:48:56 -0500 Subject: "pickle" vs. f.write() References: Message-ID: For basic builtin objects, repr(ob) generally produces a string that when eval()ed will recreate the object. IE eval(repr(ob) == ob # sometimes For writing and reading class instances, pickle is the way to go. Terry J. Reedy From tundra at tundraware.com Wed Jan 12 01:08:27 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 12 Jan 2005 01:08:27 EST Subject: Python.org, Website of Satan In-Reply-To: References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> <1105500724.648914.213880@z14g2000cwz.googlegroups.com> Message-ID: DogWalker wrote: > "Luis M. Gonzalez" said: > > >>humblythegreat... at usa.com wrote: >> >>>python.org = 194.109.137.226 >>> >>>194 + 109 + 137 + 226 = 666 >>> >>>What is this website with such a demonic name and IP address? What >>>evils are the programmers who use this language up to? >> >>You dared to unveil our secret. >>Now we'll have to kill you... >> > > But is 194.109.137.226 the only one? What other sites are in league > with the python? Yes, it's troublesome, perhaps more than you realize. Consider: 10.255.255.146 Yikes! Potential demonic (daemonic?) worship could be practiced non-routably... -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 11:33:13 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?ISO-8859-2?Q?Martin_MOKREJ=A9?=) Date: Mon, 10 Jan 2005 17:33:13 +0100 Subject: Writing huge Sets() to disk In-Reply-To: References: Message-ID: <41E2AE49.6070905@ribosome.natur.cuni.cz> Batista, Facundo wrote: > [Martin MOKREJ?] > > #- I have sets.Set() objects having up to 20E20 items, > #- each is composed of up to 20 characters. Keeping > > Are you really sure?? Either I'll have to construct them all over again say 20-30 times, or I'll find a way to keep them on disk. > #- How can I write them efficiently to disk? To be more exact, > > I think that there's some mistake here. > > At least you'll need a disk of 34694 EXABYTES!!! Hmm, you are right. So 20E15 then? I definitely need to be in range 1-14. ;-) Anyway they are large. M. From dornseif at informatik.rwth-aachen.de Fri Jan 21 17:15:13 2005 From: dornseif at informatik.rwth-aachen.de (Maximillian Dornseif) Date: Fri, 21 Jan 2005 23:15:13 +0100 Subject: Python 2.4 on FreeBSD 5.3 and ncurses Message-ID: Hello, I just installed a new FreeBSD 5.3-RELEASE System (Base System) and the first additional Packet I wanted to install was Python. While configuring I gon an error about (n)curses.h and was asked to report this to the Python list: configure: WARNING: ncurses.h: present but cannot be compiled configure: WARNING: ncurses.h: check for missing prerequisite headers? configure: WARNING: ncurses.h: see the Autoconf documentation configure: WARNING: ncurses.h: section "Present But Cannot Be Compiled" configure: WARNING: ncurses.h: proceeding with the preprocessor's result configure: WARNING: ncurses.h: in the future, the compiler will take precedence configure: WARNING: ## --------------------------------- ## configure: WARNING: ## Report this to the python lists. ## configure: WARNING: ## --------------------------------- ## If you need further Information please reply to poster - I'm not on the list. Max Dornseif The full config run: titan# (cd /usr/ports/lang/python ; make BATCH=YES package clean) ===> Vulnerability check disabled, database not found => Python-2.4.tgz doesn't seem to exist in /usr/ports/distfiles/python. => Attempting to fetch from http://www.python.org/ftp/python/2.4/. Python-2.4.tgz 100% of 8982 kB 210 kBps 00m00s ===> Extracting for python-2.4 => Checksum OK for python/Python-2.4.tgz. /usr/bin/sed -e '1s,^.*$,#!/usr/local/bin/python2.4,' /usr/ports/lang/python/work/Python-2.4/Tools/scripts/pydoc > /usr/ports/lang/python/work/pydoc2.4 /usr/bin/sed -e '1s,^.*$,#!/usr/local/bin/python2.4,' /usr/ports/lang/python/work/Python-2.4/Tools/scripts/idle > /usr/ports/lang/python/work/idle2.4 /usr/bin/sed -e '1s,^.*$,#!/usr/local/bin/python2.4,' /usr/ports/lang/python/work/Python-2.4/Lib/smtpd.py > /usr/ports/lang/python/work/smtpd2.4.py ===> Patching for python-2.4 /usr/bin/sed -i.bak -e 's,/usr/doc/python-docs-,/usr/local/share/doc/python,g' /usr/ports/lang/python/work/Python-2.4/Lib/pydoc.py /usr/bin/sed -i.bak -e 's|^\( *prefixes = .*\)\]$|\1, "/usr/X11R6"]|g' /usr/ports/lang/python/work/Python-2.4/Lib/site.py /bin/mkdir -p /usr/ports/lang/python/work/Python-2.4/Lib/plat-freebsd6 /bin/cp /usr/ports/lang/python/work/Python-2.4/Lib/plat-freebsd5/regen /usr/ports/lang/python/work/Python-2.4/Lib/plat-freebsd6/ ===> Applying FreeBSD patches for python-2.4 ===> Configuring for python-2.4 checking MACHDEP... freebsd5 checking EXTRAPLATDIR... checking for --without-gcc... no checking for --with-cxx=... no checking for c++... c++ checking for C++ compiler default output file name... a.out checking whether the C++ compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for gcc... cc checking for C compiler default output file name... a.out checking whether the C compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether cc accepts -g... yes checking for cc option to accept ANSI C... none needed checking how to run the C preprocessor... cc -E checking for egrep... grep -E checking for AIX... no checking for --with-suffix... checking for case-insensitive build directory... no checking LIBRARY... libpython$(VERSION).a checking LINKCC... $(PURIFY) $(CXX) checking for --enable-shared... no checking for --enable-profiling... checking LDLIBRARY... libpython$(VERSION).a checking for ranlib... ranlib checking for ar... ar checking for a BSD-compatible install... /usr/bin/install -c -o root -g wheel checking for --with-pydebug... no checking whether cc accepts -fno-strict-aliasing... yes checking whether cc accepts -OPT:Olimit=0... no checking whether cc accepts -Olimit 1500... no checking whether pthreads are available without options... yes checking whether c++ also accepts flags for thread support... no checking for ANSI C header files... yes checking for sys/types.h... yes checking for sys/stat.h... yes checking for stdlib.h... yes checking for string.h... yes checking for memory.h... yes checking for strings.h... yes checking for inttypes.h... yes checking for stdint.h... yes checking for unistd.h... yes checking curses.h usability... no checking curses.h presence... yes configure: WARNING: curses.h: present but cannot be compiled configure: WARNING: curses.h: check for missing prerequisite headers? configure: WARNING: curses.h: see the Autoconf documentation configure: WARNING: curses.h: section "Present But Cannot Be Compiled" configure: WARNING: curses.h: proceeding with the preprocessor's result configure: WARNING: curses.h: in the future, the compiler will take precedence configure: WARNING: ## --------------------------------- ## configure: WARNING: ## Report this to the python lists. ## configure: WARNING: ## --------------------------------- ## checking for curses.h... yes checking dlfcn.h usability... yes checking dlfcn.h presence... yes checking for dlfcn.h... yes checking fcntl.h usability... yes checking fcntl.h presence... yes checking for fcntl.h... yes checking grp.h usability... yes checking grp.h presence... yes checking for grp.h... yes checking langinfo.h usability... yes checking langinfo.h presence... yes checking for langinfo.h... yes checking libintl.h usability... no checking libintl.h presence... no checking for libintl.h... no checking ncurses.h usability... no checking ncurses.h presence... yes configure: WARNING: ncurses.h: present but cannot be compiled configure: WARNING: ncurses.h: check for missing prerequisite headers? configure: WARNING: ncurses.h: see the Autoconf documentation configure: WARNING: ncurses.h: section "Present But Cannot Be Compiled" configure: WARNING: ncurses.h: proceeding with the preprocessor's result configure: WARNING: ncurses.h: in the future, the compiler will take precedence configure: WARNING: ## --------------------------------- ## configure: WARNING: ## Report this to the python lists. ## configure: WARNING: ## --------------------------------- ## checking for ncurses.h... yes checking poll.h usability... yes checking poll.h presence... yes checking for poll.h... yes checking pthread.h usability... yes checking pthread.h presence... yes checking for pthread.h... yes checking stropts.h usability... no checking stropts.h presence... no checking for stropts.h... no checking termios.h usability... yes checking termios.h presence... yes checking for termios.h... yes checking thread.h usability... no checking thread.h presence... no checking for thread.h... no checking for unistd.h... (cached) yes checking utime.h usability... yes checking utime.h presence... yes checking for utime.h... yes checking sys/audioio.h usability... no checking sys/audioio.h presence... no checking for sys/audioio.h... no checking sys/bsdtty.h usability... no checking sys/bsdtty.h presence... no checking for sys/bsdtty.h... no checking sys/file.h usability... yes checking sys/file.h presence... yes checking for sys/file.h... yes checking sys/loadavg.h usability... no checking sys/loadavg.h presence... no checking for sys/loadavg.h... no checking sys/lock.h usability... yes checking sys/lock.h presence... yes checking for sys/lock.h... yes checking sys/mkdev.h usability... no checking sys/mkdev.h presence... no checking for sys/mkdev.h... no checking sys/modem.h usability... no checking sys/modem.h presence... no checking for sys/modem.h... no checking sys/param.h usability... yes checking sys/param.h presence... yes checking for sys/param.h... yes checking sys/poll.h usability... yes checking sys/poll.h presence... yes checking for sys/poll.h... yes checking sys/select.h usability... yes checking sys/select.h presence... yes checking for sys/select.h... yes checking sys/socket.h usability... yes checking sys/socket.h presence... yes checking for sys/socket.h... yes checking sys/time.h usability... yes checking sys/time.h presence... yes checking for sys/time.h... yes checking sys/times.h usability... yes checking sys/times.h presence... yes checking for sys/times.h... yes checking sys/un.h usability... yes checking sys/un.h presence... yes checking for sys/un.h... yes checking sys/utsname.h usability... yes checking sys/utsname.h presence... yes checking for sys/utsname.h... yes checking sys/wait.h usability... yes checking sys/wait.h presence... yes checking for sys/wait.h... yes checking pty.h usability... no checking pty.h presence... no checking for pty.h... no checking libutil.h usability... yes checking libutil.h presence... yes checking for libutil.h... yes checking sys/resource.h usability... yes checking sys/resource.h presence... yes checking for sys/resource.h... yes checking netpacket/packet.h usability... no checking netpacket/packet.h presence... no checking for netpacket/packet.h... no checking sysexits.h usability... yes checking sysexits.h presence... yes checking for sysexits.h... yes checking bluetooth.h usability... yes checking bluetooth.h presence... yes checking for bluetooth.h... yes checking bluetooth/bluetooth.h usability... no checking bluetooth/bluetooth.h presence... no checking for bluetooth/bluetooth.h... no checking for dirent.h that defines DIR... yes checking for library containing opendir... none required checking whether sys/types.h defines makedev... yes checking for term.h... no checking for clock_t in time.h... yes checking for makedev... yes checking Solaris LFS bug... no checking for mode_t... yes checking for off_t... yes checking for pid_t... yes checking return type of signal handlers... void checking for size_t... yes checking for uid_t in sys/types.h... yes checking for int... yes checking size of int... 4 checking for long... yes checking size of long... 4 checking for void *... yes checking size of void *... 4 checking for short... yes checking size of short... 2 checking for float... yes checking size of float... 4 checking for double... yes checking size of double... 8 checking for fpos_t... yes checking size of fpos_t... 8 checking for long long support... yes checking for long long... yes checking size of long long... 8 checking for uintptr_t support... no checking size of off_t... 8 checking whether to enable large file support... yes checking size of time_t... 4 checking for pthread_t... yes checking size of pthread_t... 4 checking for --enable-toolbox-glue... no checking for --enable-framework... no checking for dyld... no checking SO... .so checking LDSHARED... cc -shared -pthread checking CCSHARED... -fPIC checking LINKFORSHARED... -Wl,--export-dynamic checking CFLAGSFORSHARED... checking SHLIBS... $(LIBS) checking for dlopen in -ldl... no checking for shl_load in -ldld... no checking for library containing sem_init... none required checking for textdomain in -lintl... no checking for t_open in -lnsl... no checking for socket in -lsocket... no checking for --with-libs... no checking for --with-signal-module... yes checking for --with-dec-threads... no checking for --with-threads... yes checking if PTHREAD_SCOPE_SYSTEM is supported... yes checking for pthread_sigmask... yes checking if --enable-ipv6 is specified... yes checking ipv6 stack type... kame using libc checking for --with-doc-strings... yes checking for --with-tsc... no checking for --with-pymalloc... yes checking for --with-wctype-functions... no checking for dlopen... yes checking DYNLOADFILE... dynload_shlib.o checking MACHDEP_OBJS... MACHDEP_OBJS checking for alarm... yes checking for bind_textdomain_codeset... no checking for chown... yes checking for clock... yes checking for confstr... yes checking for ctermid... yes checking for execv... yes checking for fork... yes checking for fpathconf... yes checking for ftime... no checking for ftruncate... yes checking for gai_strerror... yes checking for getgroups... yes checking for getlogin... yes checking for getloadavg... yes checking for getpeername... yes checking for getpgid... yes checking for getpid... yes checking for getpriority... yes checking for getpwent... yes checking for getsid... yes checking for getwd... yes checking for kill... yes checking for killpg... yes checking for lchown... yes checking for lstat... yes checking for mkfifo... yes checking for mknod... yes checking for mktime... yes checking for mremap... no checking for nice... yes checking for pathconf... yes checking for pause... yes checking for plock... no checking for poll... yes checking for pthread_init... no checking for putenv... yes checking for readlink... yes checking for realpath... yes checking for select... yes checking for setegid... yes checking for seteuid... yes checking for setgid... yes checking for setlocale... yes checking for setregid... yes checking for setreuid... yes checking for setsid... yes checking for setpgid... yes checking for setpgrp... yes checking for setuid... yes checking for setvbuf... yes checking for snprintf... yes checking for sigaction... yes checking for siginterrupt... yes checking for sigrelse... no checking for strftime... yes checking for sysconf... yes checking for tcgetpgrp... yes checking for tcsetpgrp... yes checking for tempnam... yes checking for timegm... yes checking for times... yes checking for tmpfile... yes checking for tmpnam... yes checking for tmpnam_r... no checking for truncate... yes checking for uname... yes checking for unsetenv... yes checking for utimes... yes checking for waitpid... yes checking for wcscoll... yes checking for _getpty... no checking for chroot... yes checking for link... yes checking for symlink... yes checking for fchdir... yes checking for fsync... yes checking for fdatasync... no checking for ctermid_r... yes checking for flock... yes checking for getpagesize... yes checking for true... true checking for inet_aton in -lc... yes checking for hstrerror... yes checking for inet_aton... yes checking for inet_pton... yes checking for setgroups... yes checking for openpty... no checking for openpty in -lutil... yes checking for forkpty... yes checking for fseek64... no checking for fseeko... yes checking for fstatvfs... yes checking for ftell64... no checking for ftello... yes checking for statvfs... yes checking for dup2... yes checking for getcwd... yes checking for strdup... yes checking for strerror... yes checking for memmove... yes checking for getpgrp... yes checking for setpgrp... (cached) yes checking for gettimeofday... yes checking for major... yes checking for getaddrinfo... yes checking getaddrinfo bug... good checking for getnameinfo... yes checking whether time.h and sys/time.h may both be included... yes checking whether struct tm is in sys/time.h or time.h... time.h checking for struct tm.tm_zone... yes checking for struct stat.st_rdev... yes checking for struct stat.st_blksize... yes checking for struct stat.st_blocks... yes checking for time.h that defines altzone... no checking whether sys/select.h and sys/time.h may both be included... yes checking for addrinfo... yes checking for sockaddr_storage... yes checking whether char is unsigned... no checking for an ANSI C-conforming const... yes checking for working volatile... yes checking for working signed char... yes checking for prototypes... yes checking for variable length prototypes and stdarg.h... yes checking for socketpair... yes checking if sockaddr has sa_len member... yes checking whether va_list is an array... no checking for gethostbyname_r... no checking for gethostbyname... yes checking for __fpu_control... no checking for __fpu_control in -lieee... no checking for --with-fpectl... yes checking for --with-libm=STRING... default LIBM="-lm" checking for --with-libc=STRING... default LIBC="" checking for hypot... yes checking wchar.h usability... yes checking wchar.h presence... yes checking for wchar.h... yes checking for wchar_t... yes checking size of wchar_t... 4 checking for UCS-4 tcl... no checking whether wchar_t is signed... no checking what type to use for unicode... test: no: unexpected operator unsigned long checking whether byte ordering is bigendian... no checking whether right shift extends the sign bit... yes checking for getc_unlocked() and friends... yes checking for rl_callback_handler_install in -lreadline... yes checking for rl_pre_input_hook in -lreadline... yes checking for rl_completion_matches in -lreadline... yes checking for broken nice()... yes checking for broken poll()... no checking for working tzset()... yes checking for tv_nsec in struct stat... no checking whether mvwdelch is an expression... no checking whether WINDOW has _flags... no checking for /dev/ptmx... no checking for /dev/ptc... no checking for socklen_t... yes checking for build directories... done configure: creating ./config.status config.status: creating Makefile.pre config.status: creating Modules/Setup.config config.status: creating pyconfig.h creating Setup creating Setup.local creating Makefile /bin/mkdir -p /usr/ports/lang/python/work/Python-2.4/build.shared/Modules /bin/mkdir -p /usr/ports/lang/python/work/Python-2.4/build.shared/Parser /bin/mkdir -p /usr/ports/lang/python/work/Python-2.4/build.shared/Python /bin/mkdir -p /usr/ports/lang/python/work/Python-2.4/build.shared/Objects /usr/bin/sed -e 's,^\(LDLIBRARY=\).*$,\1libpython$(VERSION).so,' -e 's,^\(BLDLIBRARY=\).*$,\1-L. -lpython$(VERSION),' -e 's,^\(CFLAGSFORSHARED=\).*$,\1$(CCSHARED),' -e 's,^\(Makefile Modules/config.c:.*\)Makefile.pre,\1,' -e 's,^\(.(BUILDPYTHON):.*\).(LIBRARY),\1,' /usr/ports/lang/python/work/Python-2.4/Makefile > /usr/ports/lang/python/work/Python-2.4/build.shared/Makefile /bin/ln -sf /usr/ports/lang/python/work/Python-2.4/pyconfig.h /usr/ports/lang/python/work/Python-2.4/Include /usr/ports/lang/python/work/Python-2.4/Grammar /usr/ports/lang/python/work/Python-2.4/build.shared/ /bin/ln -sf /usr/ports/lang/python/work/Python-2.4/Python/getplatform.c /usr/ports/lang/python/work/Python-2.4/Python/importdl.c /usr/ports/lang/python/work/Python-2.4/Python/importdl.h /usr/ports/lang/python/work/Python-2.4/build.shared/Python/ /bin/ln -sf /usr/ports/lang/python/work/Python-2.4/Modules/makesetup /usr/ports/lang/python/work/Python-2.4/Modules/Setup* /usr/ports/lang/python/work/Python-2.4/Modules/*.c /usr/ports/lang/python/work/Python-2.4/Modules/*.h /usr/ports/lang/python/work/Python-2.4/build.shared/Modules/ ===> Building for python-2.4 cc -c -fno-strict-aliasing -DNDEBUG -O -pipe -DTHREAD_STACK_SIZE=0x100000 -I. -I./Include -DPy_BUILD_CORE -o Modules/python.o /usr/ports/lang/python/work/Python-2.4/Modules/python.c -- Maximillian Dornseif, Dipl. Jur., CISSP Laboratory for Dependable Distributed Systems, RWTH Aachen University Tel. +49 241 80-21431 - http://md.hudora.de/ -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 2432 bytes Desc: not available URL: From tzot at sil-tec.gr Mon Jan 31 06:01:42 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 31 Jan 2005 13:01:42 +0200 Subject: Dynamic class methods misunderstanding References: <35v5jdF4rk3m7U1@individual.net> <1gr5b2x.1s7zqt9ufc993N%aleaxit@yahoo.com> Message-ID: <7i3sv0lk63gmnh8q3a532gon7f1gg3bab9@4ax.com> On Sat, 29 Jan 2005 10:24:27 +0100, rumours say that aleaxit at yahoo.com (Alex Martelli) might have written: >Bill Mill wrote: > ... >> > class Test: >> > def __init__(self, method): >> > self.m = new.instancemethod(method, self, Test) >> >> Beautiful! thank you very much. Looking into the "new" module in >> python 2.4, that's equivalent to: >> >> self.m = type(self.__init__)(method, self, Test) >Another approach with the same result is to exploit the fact that a >function is a descriptor: > >self.m = method.__get__(self, Test) Almost true; not all builtin functions are descriptors though. .>> import new .>> f= new.instancemethod(divmod, 7, object) .>> map(f, range(1,10,2)) [(7, 0), (2, 1), (1, 2), (1, 0), (0, 7)] .>> f= divmod.__get__(7) Traceback (most recent call last): File "", line 1, in -toplevel- f= divmod.__get__(7) AttributeError: 'builtin_function_or_method' object has no attribute '__get__' I didn't run an extensive test, but it's possible that all builtin functions are not descriptors. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From Scott.Daniels at Acm.Org Wed Jan 5 19:19:22 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 05 Jan 2005 16:19:22 -0800 Subject: Building unique comma-delimited list? In-Reply-To: References: Message-ID: <41dc814c$1@nntp0.pdx.net> How about (for 2.4 or 2.3 using "from collections import Set as set": def combine(source, special='foo'): parts = set(source) if special in parts: return ', '.join([special] + list(parts - set([special]))) return ', '.join(parts) --Scott David Daniels Scott.Daniels at Acm.Org From simon.brunning at gmail.com Wed Jan 26 07:00:58 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 26 Jan 2005 12:00:58 +0000 Subject: Question: "load"ing a shared object in python In-Reply-To: References: Message-ID: <8c7f10c60501260400893a8e7@mail.gmail.com> On Tue, 25 Jan 2005 23:19:01 +0200, Pro Grammer wrote: > Hello, all, > I am not sure if this is the right place to ask, but could you kindly > tell me how to "load" a shared object (like libx.so) into python, so > that the methods in the .so can be used? That too, given that the shared > object was written in c++, compiled with g++ ? Will ctypes do the trick? http://starship.python.net/crew/theller/ctypes/ -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From tomi.hasa at gmail.com Mon Jan 10 09:00:03 2005 From: tomi.hasa at gmail.com (=?iso-8859-1?B?VG9taSBI5HPk?=) Date: 10 Jan 2005 06:00:03 -0800 Subject: OT: spacing of code in Google Groups In-Reply-To: <1104556828.320101.74750@z14g2000cwz.googlegroups.com> References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <1104549662.978986.77480@c13g2000cwb.googlegroups.com> <1104556828.320101.74750@z14g2000cwz.googlegroups.com> Message-ID: <1105365603.300139.117440@c13g2000cwb.googlegroups.com> Dan Bishop wrote: > > And for a long time, Google groups postings *were* whitespace > significant. But the new interface broke it. > > > I made a complaint several weeks ago to Google support, > > asking them too quit stripping leading whitespace, > > and the sent me a reply saying they appreciated my feedback. > > Maybe they just need more feedback :) > > I send them some earlier today. So far, I've only received > their auto-reply. Removing and adding spaces discussed in the Google Groups Beta group also: http://groups-beta.google.com/group/google-labs-groups2/browse_thread/thread/9bc4328fd27d3ad4/80ad25b58d5dbb49?_done=%2Fgroup%2Fgoogle-labs-groups2%2Fthreads%3Fstart%3D60%26order%3Drecent%26&_doneTitle=Back&&d#80ad25b58d5dbb49 http://tinyurl.com/6oe6v http://groups-beta.google.com/group/google-labs-groups2/browse_thread/thread/73b712c45c9d89d2/bdc0544e3b08a1cd?_done=%2Fgroup%2Fgoogle-labs-groups2%2Fthreads%3Fstart%3D120%26order%3Drecent%26&_doneTitle=Back&&d#bdc0544e3b08a1cd http://tinyurl.com/5nz5u Demonstration of the problem: http://groups-beta.google.com/group/Groups-2-Test-Group/browse_thread/thread/cc5a64d2e18f0594/945fa09eea37e41c?_done=%2Fgroup%2FGroups-2-Test-Group%3F&_doneTitle=Back+to+topics&_doneTitle=Back&&d#945fa09eea37e41c http://tinyurl.com/4wem9 More problems listed here: http://groups-beta.google.com/group/google-labs-groups2/msg/b54c12517c75eb24 http://tinyurl.com/3khmj More info in the FAQ: http://www.geocities.com/googlepubsupgenfaq/#groupsproblems From edin.salkovic at gmail.com Sat Jan 1 04:25:35 2005 From: edin.salkovic at gmail.com (edin.salkovic at gmail.com) Date: 1 Jan 2005 01:25:35 -0800 Subject: Why tuples use parentheses ()'s instead of something else like <>'s? In-Reply-To: References: <1104299822.394489.161500@z14g2000cwz.googlegroups.com> <41d2ce43$0$35731$a1866201@visi.com> <10t5p4nedr06h94@news.supernews.com> <33gg57F3uh3hnU1@individual.net> <41d314c6$0$30032$a1866201@visi.com> <33gjr1F3siliuU1@individual.net> Message-ID: <1104571535.045504.266000@c13g2000cwb.googlegroups.com> Roy Smith wrote: > In article <33gjr1F3siliuU1 at individual.net>, > Reinhold Birkenfeld wrote: > > > >>+<< being an operator > > Looks more like a smiley for "guy wearing a bowtie" :)), I had a nice laugh with this one. From evan at tokenexchange.com Wed Jan 26 12:38:37 2005 From: evan at tokenexchange.com (Evan Simpson) Date: Wed, 26 Jan 2005 11:38:37 -0600 Subject: Subclassed dict as globals Message-ID: In Python 2.4 the following works: >>> class G(dict): ... def __getitem__(self, k): ... return 'K' + k ... >>> g = G() >>> exec 'print x, y, z' in g Kx Ky Kz >>> ...while in Python 2.3 it fails with NameError: name 'x' is not defined. Is this an "accidental feature", or can I count on this working in future versions of Python? For that matter, is there a way to do this (intercept global variable accesses) in Python 2.3? Cheers, Evan @ 4-am From tjreedy at udel.edu Sat Jan 29 20:40:07 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 29 Jan 2005 20:40:07 -0500 Subject: {Spam?} Re: bound vs unbound functions References: <1107040729.535936.42230@c13g2000cwb.googlegroups.com> Message-ID: "Michael Tobis" wrote in message news:1107040729.535936.42230 at c13g2000cwb.googlegroups.com... > I'd like to dynamically add a method to an instance at > instantiation time. No can do. A method is function that is an attribute of a class, even if accessed via an instance. A function added to an instance as an attribute of the instance remains a function. It is instance-specific data that methods and other code can use, just like other instance data, for instance-specific effects. Two common examples: class composer: # skip obvious init def __call__(self, x): return self.outer(self.inner(x)) sincos = composer(math.sin, math.cos) # yes, this can also be done with composer function with nested scope class memoizer: # posted several times # skip init again def __call__(self,x): # return previously computed self.memodict[x] if it exists # or calculate, store, and return self.func(x) \> PS - any idea how to get past google's stupid formatting these days? I > thought they were supposed to like python, but they just ignore leading > blanks. Don't use google to post on clp. Go to news.gmane.org instead. Terry J. Reedy From mirnazim at gmail.com Mon Jan 17 10:09:09 2005 From: mirnazim at gmail.com (Mir Nazim) Date: 17 Jan 2005 07:09:09 -0800 Subject: Employablity of python programmers Message-ID: <1105974549.835152.280590@z14g2000cwz.googlegroups.com> Hi, Here I am once again to give a bit trouble. I am at the verge of completing my graduation in computer sciences. I will be graduating within 6-8 months. Now I am faced with the problems of my career. I am in a fix what skill set I must choose to be safe as far as job openings are concerned. I understand that skill set should be that one like most but job is also important. I will try to achieve a balance in both with the help of you advice. I am currently developing in PHP as a freelance web developer. But I want to move to python(for all it all cool reasons discussed a zillion times on c.l.py) and wanted to know the job oportunites available to a python programmer(I know these have been also discussed a zillion time here but still..). I am living in India and would like to know about employability of python programmers in India (I know that a few Indians frequent c.l.py. Hello Sridhar, where are you). I would also like to know that if the knowledge of any other language will boost employability of a python programmer. As far as I see it, the following combination are desirable. 1) C/C++ and Python. 2) Java and Python. 3) Pure Python. Out of the three Java along with python seems to be straight forward choice as far as employability is concerned. But I would like to know the benifits which one is a better career choice to take out of these three choices(other suggestions are welcome). For me choice three would be better, not because I have only one language to learn. If I choose choice three I could spend more time in learning different approaches to develop the application and better master the library and frameworks avaialble for python. So what are the recomendations from your side. Please help. Thanks --- Mir Nazim. From tmohr at s.netic.de Mon Jan 17 15:43:40 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Mon, 17 Jan 2005 21:43:40 +0100 Subject: Py_Object* Py_BuildValue, Py_INCREF necessary? Message-ID: Hi, when i write an extension module in C and return a Py_Object* that i've built with Py_BuildValue, do i need to use Py_INCREF on that before i return it to python from my extension module or not? Thanks for hints, Torsten. From a at b.c Tue Jan 4 11:10:00 2005 From: a at b.c (Doug Holton) Date: Tue, 04 Jan 2005 10:10:00 -0600 Subject: Python evolution: Unease In-Reply-To: <9vqdncpnrbRTNEfcRVn-ug@giganews.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> Message-ID: Istvan Albert wrote: > But if python > were to become overly complicated I'll find something else. > Three years ago I have not not used python at all, now I'm > using it for everything. You're in luck, python 2.4 won't be significantly changing anytime soon. > PS. why can't decorators solve this optional type checking > problem? I clearly remember this as being one of the > selling points for having decorators in the first place... Because they are quite obviously an ugly and overly complicated solution. Even Guido understood this: http://mail.python.org/pipermail/python-dev/2004-September/048518.html "A warning: some people have shown examples of extreme uses of decorators. I've seen decorators proposed for argument and return type annotations, and even one that used a decorator to create an object that did a regular expression substitution. Those uses are cute, but I recommend being conservative when deciding between using a decorator or some other approach, especially in code that will see a large audience (like 3rd party library packages). Using decorators for type annotations in particular looks tedious, and this particular application is so important that I expect Python 3000 will have optional type declarations integrated into the argument list." From ed at leafe.com Mon Jan 10 20:29:19 2005 From: ed at leafe.com (Ed Leafe) Date: Mon, 10 Jan 2005 20:29:19 -0500 Subject: Port blocking In-Reply-To: References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> <34f8ovF47d783U1@individual.net> Message-ID: <36D15C54-6370-11D9-B1AE-003065B11E84@leafe.com> On Jan 10, 2005, at 8:00 PM, Steve Holden wrote: >> Ah yes, but is there really? For example, I did a search of the TOC >> of GTK+ Reference Manual: >> http://developer.gnome.org/doc/API/2.0/gtk/index.html >> for the word "data", and there's apparently no widget which is >> explicitly tied to databases. So in GTKs case, for instance, it looks >> like one has to roll one's own solution, rather than just using one >> out of the box. > > There isn't, IMHO, anything with the polish of (say) Microsoft Access, > or even Microsoft SQL Server's less brilliant interfaces. Some things > Microsoft *can* do well, it's a shame they didn't just stick to the > knitting. Though it's certainly not anywhere near the polish of Access, you should check out Dabo. It's designed from the ground up to be a database application framework, and is on its way to achieving that goal. Right now you still have to do all the UI stuff in code, but we're just starting to develop the visual UI Designer. Stay tuned! ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From srijit at yahoo.com Wed Jan 19 23:10:05 2005 From: srijit at yahoo.com (srijit at yahoo.com) Date: 19 Jan 2005 20:10:05 -0800 Subject: FTPLIB & FTPS or SFTP? In-Reply-To: <9b9tu0te197u3bmheldg2hsvkbtuivlov6@4ax.com> References: <9b9tu0te197u3bmheldg2hsvkbtuivlov6@4ax.com> Message-ID: <1106194205.312667.241410@c13g2000cwb.googlegroups.com> To the best of my knowledge ftplib does not support SFTP or FTPS. I hope Paramiko (http://www.lag.net/paramiko/) serves your purpose. Paramiko supports POSIX, Windows and MacOSX Regards, /Srijit Peter A. Schott wrote: > Does the ftplib support SFTP or FTPS? Is that part of a different module? We > have a handful of partners who use FTPS or SFTP and I need to pull/push files > to/from them. > > > Thank you for all of your help. > > -Pete Schott From jerf at jerf.org Sat Jan 15 10:14:04 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 15 Jan 2005 10:14:04 -0500 Subject: Producer/consumer Queue "trick" References: Message-ID: On Fri, 14 Jan 2005 16:26:02 -0600, Evan Simpson wrote: > WEBoggle needs a new game board every three minutes. Boards take an > unpredictable (much less than 3min, but non-trivial) amount of time to > generate. I gotta ask, why? Looking over your information about "how to play", my only guess is that you're generating all possible words that may exist in the board, at the time of board generation. But it also looks like you score once at the end (as you have to anyhow in order to cancel out words found by multiple people, according to the rules of Boggle). If both of these statements are true, the generation of all possible words is a waste of time. For each word given by a human, looking it up in the dict and verifying it is on the board at score time should be a lot faster, and not need any pre-processing. If you're generating stats about what percentage of possible words were found, that can also be done during game play without loss by handing outh the board, and *then* finding all words. You still have a threading problem, but now instead of dealing with human response times, you've got a three minute deadline which ought to be enough. (The other thing I can think of is that you are trying to verify that the board contains some minimal number of words, in which case I submit that boards with only 20-ish words is just part of the game :-) I've never sat down and really studied the Boggle dice, but I've always expected/hoped that there is at least one or two dice with all vowels; even so the odds of no vowels are small and easily algorithmically discarded. ) To be clear, I'm mostly curious what's going on, but it is possible that the fundamental problem may be algorithmic, and since I don't know what's going on it's worth checking. Also, entirely separate plug, you may be interested in my XBLinJS project: http://www.jerf.org/resources/xblinjs . (I'm expecting to release 0.2 either today or tomorrow, which will have vastly more documentation and more online examples.) It'd help pull out relevant code so that it is easily re-usable in any future gaming projects by others. From rbt at athop1.ath.vt.edu Wed Jan 26 17:11:51 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Wed, 26 Jan 2005 17:11:51 -0500 Subject: exclude binary files from os.walk Message-ID: Is there an easy way to exclude binary files (I'm working on Windows XP) from the file list returned by os.walk()? Also, when reading files and you're unsure as to whether or not they are ascii or binary, I've always thought it safer to 'rb' on the read, is this correct... and if so, what's the reasoning behind this? Again all of this pertains to files on Windows XP and Python 2.4 Many thanks! From bjourne at gmail.com Fri Jan 7 08:39:09 2005 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Fri, 7 Jan 2005 14:39:09 +0100 Subject: Getting rid of "self." Message-ID: <740c3aec05010705393048a374@mail.gmail.com> I think it would be cool if you could refer to instance variables without prefixing with "self." I know noone else thinks like me so Python will never be changed, but maybe you can already do it with Python today? .import sys . .def magic(): . s = "" . for var in sys._getframe(1).f_locals["self"].__dict__: . s += var + " = self." + var + "\n" . return s . .class A: . def __init__(self): . self.hi = "yo" . . def meth(self): . exec(magic()) . print hi . .a = A() .a.meth() It works! exec(magic()) does the needed hi = self.hi. Not so impressive in this case but much cooler when there is more instance variables around. But the solution is very ugly because you have to write exec(magic()) in every method. So I'm asking here if someone knows a better way, maybe using decorators or metaclasses or other black magic? -- mvh Bj?rn From merkosh at hadiko.de Sat Jan 15 10:28:36 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Sat, 15 Jan 2005 16:28:36 +0100 Subject: deleting from tarfile Message-ID: Hi, is it possible to delete a file from a tar-archive using the tarfile module? Thanks Uwe From roy at panix.com Sat Jan 15 10:23:20 2005 From: roy at panix.com (Roy Smith) Date: Sat, 15 Jan 2005 10:23:20 -0500 Subject: java 5 could like python? References: Message-ID: vegetax wrote: > -No naming convention. The speech of "it fits in my head" is no longer valid > when i use a lot of functionality,modules,classes in a large proyect. > > For example if i remember a function i want ie:get attribute, i dont > remember if the module implementer coded it as > getAttribute,GetAttribute,get_attribute, then i have to go and check the > doc, every time,which is a waste of time. It is indeed unfortunate that the standard library doesn't use a more consistent naming convention. Perhaps in Python-3000 this will get fixed. In the meantime, if I know what I'm looking for, but just can't remember the exact name, I usually find it's pretty quick to pop into an interactive session, create an object, and see what attributes it has with dir(): >>> l = [] >>> dir (l) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] > -Is python library half object oriented? half functional oriented? I can > understand that python allows some functional programing components when > they are necesary,but there are libraries that totaly ignore object > orientation which makes them problematic to use.for example,Whats with the > os.path module and files? why do i have to say os.path.getfilesize(f.name) > all the time? why cant i say f.size? Why does urlparse returns a tuple of 7 > items instead of an URL object? why there isnt an URL object? and so on.. Again, you are correct that things are not as consistent as they might be. The newer bits of the library tend to be more OO than the older bits, and those parts of the library which are thin wrappers around classic unix functions (like much of the os module) tend to be more procedural. Things are not perfect. I think the real message is that while you can certainly find lots of places where there are imperfections and inconsistencies, overall it's a very easy to use system. Java may be much more consistent, but I find I get bogged down in details like re-exporting exceptions, declaring (and casting) variable types. To each their own. From Serge.Orlov at gmail.com Fri Jan 14 09:18:36 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 14 Jan 2005 06:18:36 -0800 Subject: Unicode conversion in 'print' In-Reply-To: References: <1105655600.059496.70350@z14g2000cwz.googlegroups.com> Message-ID: <1105712316.904407.65490@z14g2000cwz.googlegroups.com> Ricardo Bugalho wrote: > Hi, > thanks for the information. But what I was really looking for was > informaion on when and why Python started doing it (previously, it > always used sys.getdefaultencoding())) I don't have access to any other version except 2.2 at the moment but I believe it happened between 2.2 and 2.3 for Windows and UNIX terminals. On other unsupported terminals I suspect sys.getdefaultencoding is still used. The reason for the change is proper support of unicode input/output. > and why it was done only for 'print' when > stdout is a terminal instead of always. The real question is why not *never* use sys.getdefaultencoding() for printing. If you leave sys.getdefaultencoding() at Python default value ('ascii') you won't need to worry about it sys.getdefaultencoding() is a temporary measure for big projects to use within one Python version. Serge. From ncoghlan at iinet.net.au Sat Jan 15 11:33:46 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 16 Jan 2005 02:33:46 +1000 Subject: Producer/consumer Queue "trick" In-Reply-To: <7xmzvbnigr.fsf@ruckus.brouhaha.com> References: <7xmzvbnigr.fsf@ruckus.brouhaha.com> Message-ID: <41E945EA.4040507@iinet.net.au> Paul Rubin wrote: > Evan Simpson writes: > >>wakes up the producer, which has been blocked waiting to add a board >>to the Queue. It sets about generating the next board, and the >>consumer doesn't get to run again until the producer blocks again or >>is preempted. > > > That's weird. Preemption should happen every few dozen milliseconds > unless you've purposely increased the preemption delay. To me, it smells like a call into a C extension which isn't releasing the GIL before starting a time-consuming operation. After getting bitten by this a couple of times, I now make sure to release the GIL as part of my SWIG wrapper (since the code I'm wrapping knows nothing of Python, and sure as heck doesn't need to be holding the GIL!). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jack at performancedrivers.com Wed Jan 26 14:21:32 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 26 Jan 2005 14:21:32 -0500 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> Message-ID: <20050126192132.GL1607@performancedrivers.com> On Wed, Jan 26, 2005 at 10:39:18AM -0800, aurora wrote: > >On Wed, Jan 26, 2005 at 05:18:59PM +0100, Alexander Schremmer wrote: > >>On Tue, 25 Jan 2005 22:08:01 +0100, I wrote: > >> > >>>>>> sys.safecall(func, maxcycles=1000) > >>> could enter the safe mode and call the func. > >> > >>This might be even enhanced like this: > >> > >>>>> import sys > >>>>> sys.safecall(func, maxcycles=1000, > >> allowed_domains=['file-IO', 'net-IO', 'devices', > >>'gui'], > >> allowed_modules=['_sre']) > >> > >>Any comments about this from someone who already hacked CPython? > > > >Yes, this comes up every couple months and there is only one answer: > >This is the job of the OS. > >Java largely succeeds at doing sandboxy things because it was written > >that > >way from the ground up (to behave both like a program interpreter and an > >OS). > >Python the language was not, and the CPython interpreter definitely was > >not. > > > >Search groups.google.com for previous discussions of this on c.l.py > > > It is really necessary to build a VM from the ground up that includes OS > ability? What about JavaScript? > See the past threads I reccomend in another just-posted reply. Common browser implementations of Javascript have almost no features, can't import C-based libraries, and can easilly enter endless loops or eat all available memory. You could make a fork of python that matches that feature set, but I don't know why you would want to. -Jack From martin at v.loewis.de Wed Jan 26 14:30:16 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 26 Jan 2005 20:30:16 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> Message-ID: <41f7efc2$0$11596$9b622d9e@news.freenet.de> phr at localhost.localdomain wrote: > That it's not appropriate for the > distro maintainers to look at the spec and the reference (pure Python) > implementatation and say "yes, we want this, go write the C version > and we'll include it after it's had some testing". I know that I'm not going to give a blanket promise to include some code in the future. I can give blanket promises to *review* such code. Actually, assuming I find the time, I will review *any* code that is contributed. > When the inestimable Alexbot went to O'Reilly to pitch "Python in a > Nutshell", I'm sure they didn't tell him "go write the whole book from > cover to cover, circulate it for at least a year and get it thoroughly > reviewed, and if enough people recommend it, then and only then will > we begin to think about distributing it ourselves". Sure. That is because O'Reilly is willing to take a financial risk of failure of a book product. I'm not willing to take similar risks for Python code (risk of having to redesign the interface, fix bugs in the implementation, or have the submitter run away after the contribution). > Similarly, look at how the whole PEP process works. There are lots of > times when a PEP has been accepted before any working code is > distributed. Indeed. For new language features, it is more difficult to try them out in advance than for new library API. As a result, flaws of the new feature are often only fully understood years after the new feature first gets released. For an example, consider the buffer interface. > To take your view to an extreme, no project should even have a task > list of desired features that people are invited to implement. Taking it to the extreme misses the point. I'm asking for field testing for new modules - not for all changes. > That's bizarre and abnormal as a development process. What kind of > development process in industry doesn't decide whether to include a > feature, until after the feature is completely implemented at a > production scale? Any high-quality standardization process. Standards in IETF and OMG are only accepted after implementations have been available. > You seem to have the attitude that since volunteer development effort > doesn't consume actual PSF funds, the volunteer effort is worth > nothing and can be expended arbitrarily. The volunteers may not feel > that way. The volunteers are free to work on whatever they please. If you chose not to write an AES module - that's fine with me. Still, people do contribute to Python, and they do so without asking for permission first. Typically, they develop the code because it solves their own needs - then it doesn't really matter whether it also solves the needs of others. >>In either case, the user would best use the pre-compiled binary that >>somebody else provided for the platform. > > > Who's the "somebody else"? Some user. I find that users contribute binaries for all kinds of platforms for the code I publish. This is how open source works. > Do you do that > with your own modules, and still say that it's easy? I publish or link to binaries of my code that others have created, and find no problems in doing so. > Unless your requirement is different than what you say it is, I do see > what it is, and I'm saying it's better to do what normal projects do > and what Python has done in the past. That is, it's perfectly ok to > decide to do something and then do it, rather than insisting, > bizarrely, that it always be the other way around. No, it's three steps 1. decide that you want to do it 2. do it 3. decide whether you are pleased with the result, and only use it if you are IOW, there should not be a blanket guarantee to use it after step 1. > I think that question isn't the right one. We need to ask how many > users the sha module was required to have, before Greg and Andrew > could have reasonable confidence that the sha module would go into the > core once it was tested enough and shown to be reliable. They did not have *any* guarantee until they asked. I guess when they asked it was accepted immediately. > I suspect > they were able to have that confidence long before testing was > complete, and maybe before implementation even started. I'm pretty certain that you are wrong with that assumption. Again, we would have to ask - but I would not be surprised if AMK started implementing the module without even *considering* a later inclusion in the Python core at that time. He has done so on many occasions (include PyXML, which I inherited from him). Regards, Martin From nobody at here.com Thu Jan 27 15:34:28 2005 From: nobody at here.com (fedor) Date: Thu, 27 Jan 2005 21:34:28 +0100 Subject: MySQLdb In-Reply-To: References: Message-ID: <41f95051$0$156$3a628fcd@reader2.nntp.hccnet.nl> Hi Daniel, You should probably take a look at the executemany method of the cursor. Your insert times might drop by a factor 20 . Here's an example. Cheers, Fedor import time import MySQLdb db=MySQLdb.Connect(user="me",passwd="my password",db="test") c=db.cursor() n=0 tic=time.time() for i in range(3000): n+=c.execute('INSERT INTO testtable VALUES (%s)', (i,)) toc=time.time() t1=toc-tic print 'separate sql statements: %s, inserted %s records' % (t1,n) tic=time.time() n=c.executemany('INSERT INTO testtable VALUES (%s)', [(i,) for i in range(3000)]) toc=time.time() t2=toc-tic print 'all at once %s inserted %s records' % (t2,n) OUTPUT>>> separate sql statements: 0.571248054504, inserted 3000 records all at once 0.0253219604492 inserted 3000 records From sjmachin at lexicon.net Sun Jan 16 16:51:49 2005 From: sjmachin at lexicon.net (John Machin) Date: Mon, 17 Jan 2005 08:51:49 +1100 Subject: generator expressions: performance anomaly? References: <1105854381.117059.59940@c13g2000cwb.googlegroups.com> Message-ID: On Sun, 16 Jan 2005 12:18:23 GMT, "Raymond Hettinger" wrote: >"John Machin" wrote in message >news:1105854381.117059.59940 at c13g2000cwb.googlegroups.com... >> Please consider the timings below, where a generator expression starts >> out slower than the equivalent list comprehension, and gets worse: >> >> >python -m timeit -s "orig=range(100000)" "lst=orig[:];lst[:]=(x for x >> in orig)" > . . . >> >python -m timeit -s "orig=range(200000)" "lst=orig[:];lst[:]=(x for x >> in orig)" > >This has nothing to do with genexps and everything to do with list slice >assignment. > >List slice assignment is an example of a tool with a special case optimization >for inputs that know their own length -- that enables the tool to pre-allocate >its result rather than growing and resizing in spurts. Other such tools include >tuple(), map() and zip(). > My reading of the source: if the input is not a list or tuple, a (temporary) tuple is built from the input, using PySequence_Tuple() in abstract.c. If the input cannot report its own length, then that function resorts to "growing and resizing in spurts", using the following code: if (j >= n) { if (n < 500) n += 10; else n += 100; if (_PyTuple_Resize(&result, n) != 0) { Perhaps it could be changed to use a proportional increase, like list_resize() in listobject.c, which advertises (amortised) linear time. Alternative: build a temporary list instead? From mt at 3planes.com Sat Jan 29 21:48:20 2005 From: mt at 3planes.com (Michael Tobis) Date: 29 Jan 2005 18:48:20 -0800 Subject: Coding style article with interesting section on white space In-Reply-To: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> Message-ID: <1107053300.326925.183080@z14g2000cwz.googlegroups.com> (unwisely taking the bait...) If you like your language to look like this http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html then more power to you. I prefer my languages to be portable, terse and expressive. That's why I like Python. If you want your language to be obscure, ill-defined and inconsistent across platforms, by all means go to comp.lang.fortran . There is no fundamental reason why a language with expressive power much like Python's cannot have run-time performance comparable to Fortran's. Unfortunately, Fortran's dominance of the relatively small scientific computation universe has prevented such a language from emerging. The solutions which interest me in the short run are 1) writing a code generation layer from Python to a compiled language (possibly F77 though I will try to get away with C) and 2) wrapping legacy Fortran in Python. The latter is quite regularly subverted by non-standard binary data structures across compilers and a pretty profound disinterest in interoperability by the people designing the Fortran standard that makes their interest look more like turf protection and less like an interest in the progress of science. In the long run, hopefully a high-performance language that has significant capacity for abstraction and introspection will emerge. People keep trying various ways to coax Python into that role. Maybe it will work, or maybe a fresh start is needed. Awkwardly bolting even more conetmporary concepts onto Fortran is not going to achieve bringing computational science up to date. Python fundamentally respects the programmer. Fortran started from a point of respecting only the machine, (which is why Fortrans up to F77, having a well-defined objective, were reasonable) but now it is a motley collection of half-baked and confusing compromises between runtime performance, backward compatibility, and awkward efforts at keeping up with trends in computer languages. So-called "object oriented Fortran" makes the most baroque Java look elegant and expressive. For more see http://www.fortranstatement.com Language matters. You can't really write Python in any language. mt From evan at tokenexchange.com Thu Jan 27 11:39:23 2005 From: evan at tokenexchange.com (Evan Simpson) Date: Thu, 27 Jan 2005 10:39:23 -0600 Subject: Point of Sale In-Reply-To: References: Message-ID: <41F9193B.7090801@tokenexchange.com> Andreas Pauley wrote: > If the network is down each POS station should still be able to function > without interruption. > > At the moment the current POS system uses an inhouse developed message > queing system to communicate with the ERP/Retail backend. A POS station > submits each transaction (and other relevant messages) to a local queue, > from where it is sent to the back-end system. If the network is down the > messages just stay queued until the network is back up again. > The central backend system uses the same queing technique to submit > price updates etc. to each POS station. You may want to check out the Spread Toolkit, at www.spread.org, whose Python wrapper lives at http://www.python.org/other/spread/doc.html. It's used by the Zope Replication Service, for example. Cheers, Evan @ 4-am From peter at engcorp.com Mon Jan 24 14:10:43 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jan 2005 14:10:43 -0500 Subject: how to call python code from C# In-Reply-To: References: Message-ID: <8LGdneLOysys1WjcRVn-1Q@powergate.ca> paritosh mahana wrote: > How can I call python code from my C# code. One thing is to make an > .exe file of the python program and then try to call it from my C# > code. But I don't like that idea. Is there any other way to do this. > Like making a .dll file from the python code and somehow call it from > C# program.But I couldn't find anything on this topic on the net. > Actually my GUI is in C# and rest part is in python, and i need to > call python from my C# program. Please correct me if I am wrong > anywhere. You could use ctypes or the pywin32 package to provide your Python code with an ActiveX interface. Then you could just use it via COM, like any other COM object. Lots of references available via Google if you want to learn more about this approach... -Peter From tmohr at s.netic.de Mon Jan 17 15:46:17 2005 From: tmohr at s.netic.de (Torsten Mohr) Date: Mon, 17 Jan 2005 21:46:17 +0100 Subject: supplying constants in an extension module Message-ID: Hi, i write an extension module in C at the moment. I want to define some constants (integer mainly, but maybe also some strings). How do i do that best within this extension module in C? Do i supply them as RO attributes? What's the best way for it? Thanks for hints, Torsten. From tundra at tundraware.com Mon Jan 17 16:48:24 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 17 Jan 2005 16:48:24 EST Subject: news feed problem -- anyone else? In-Reply-To: <41ec1b57.1114913110@news.oz.net> References: <41ec1b57.1114913110@news.oz.net> Message-ID: <41EC3156.80708@tundraware.com> Bengt Richter wrote: > I can see postings on google, but my news service > is having a problem since sometime during the weekend. > Can get old stuff from other n.g., but no new. > Wondering whether I'll see this via google. > > Regards, > Bengt Richter Bengt - I've had very good luck using the following *free* newsfeed: http://individual.net/ HTH, ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From theller at python.net Wed Jan 26 15:28:55 2005 From: theller at python.net (Thomas Heller) Date: Wed, 26 Jan 2005 21:28:55 +0100 Subject: py2exe problem References: <41f7213c$0$2343$a1866201@visi.com> Message-ID: Harald Massa writes: > Thomas Heller wrote in > news:zmywh4yx.fsf at python.net: > >>> >>> A software development system which REALLY solves the encodings >>> problem WITHOUT creating a swarm of new ones could would challange >>> even my devotedness to Python :)))) >> >> AFAIK, McMillan Installer solves this by including all the encodings >> stuff by default, and it has a --ascii flag to override this >> behaviour. Would that be a solution? > > Thomas, > > I solved the headaches with py2exe and encodings, again and again ... > even documented some of these steps within the wiki. Much appreciated! > But encodings still give me new pain any day: storing filenames to > databases, displaying filenames in windows-controls, sending > database-extracts to excel or word ... time on time encodings and/or > unicode errors pop up and cause me misery. > > So my cryout is for a solution for all encoding-problems like the python > for-loop or list-comprehensions: elegant, simple, robust, flexible. Easy > to use, easy to implement. Armin, Would the above (include all encodings stuff by default) be a good solution, or do you have other ideas? Thomas From apardon at forel.vub.ac.be Wed Jan 19 04:35:59 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Jan 2005 09:35:59 GMT Subject: generator expressions: performance anomaly? References: <354esdF4fouh0U1@individual.net> Message-ID: Op 2005-01-18, Jeremy Bowers schreef : > On Tue, 18 Jan 2005 14:05:15 +0000, Antoon Pardon wrote: >> I don't see how generating byte code for a = 9; when seeing the >> expression a = 3 + 6, would be a problem for non-functional >> languages. > > To answer nearly every post you've made to this thread, "because Python > doesn't have the resources to program to special cases". I was countering an argument that seemed to state doing something like that was impossible on principle in python. I was not argueing people should put any effort in this, just countering it would change python beyond recognition. > Ultimately, the use is fairly limited; I can't imagine the execution time > saved would reach the time of implementation for weeks after a release, > even aggregating across all Python use in the world, and "real time > gained" (i.e., time useful to a human) would probably never add up to the > implementation time. So why bother? That's a horrid trade off when there > are so many other real gains to be had. Well if it isn't worth the bother, so be it. I can still dream about it. -- Antoon Pardon From fredrik at pythonware.com Wed Jan 26 07:23:42 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 26 Jan 2005 13:23:42 +0100 Subject: string.atoi and string.atol broken? References: <0ttev01qgb9k6a9f34g185lhohkn2p3evq@4ax.com> Message-ID: Christos TZOTZIOY Georgiou wrote: >>the function's named "atoi", not "atoitoa". > > cool. can I have a copy of your script? reminds me that I have a few patches in the inqueue. I wonder what this one does? ;-) hmm ;-) guess I can tune that later ;-) and what about that other patch? ;-) let's see ;-) patch, checkout, reload File "effbot.py", line 29238 <<<<<<< .mine ^ IndentationError: expected an indented block From 2004b at usenet.alexanderweb.de Tue Jan 11 14:49:26 2005 From: 2004b at usenet.alexanderweb.de (Alexander Schremmer) Date: Tue, 11 Jan 2005 20:49:26 +0100 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> Message-ID: <1g4nx7m906q79$.dlg@usenet.alexanderweb.de> On 11 Jan 2005 08:49:52 -0800, Paul Rubin wrote: > Alexander Schremmer <2004b at usenet.alexanderweb.de> writes: >>> I need to set up a wiki for a small group. I've played with MoinMoin >>> a little bit and it's reasonably straightforward to set up, but >>> limited in capabilities and uses BogusMarkupConventions. >> >> At which point do you see limitations? > > It doesn't have features that MW has, like user pages, It does. > lists of incoming links to wiki pages, It does. > automatic discussion links for every wiki page, Can be easily obtained manually. Just include another page where discussion is going on. You can even protect it with different ACL config etc. > automatic update notification for specific pages of your > choice, It does. > support for managing image uploads and embedding them > into wiki pages, It does. > >> And what of the markup don't you like? > > The BogusMixedCaseLinkNames. I'd rather have ordinary words with > spaces between them, like we use in ordinary writing. Of course it does. It does not even require [[ but [" at the beginning of the link which might be more intuitive to the writer. >>> In the larger world, though, there's currently One True wiki package, >>> namely Mediawiki (used by Wikipedia). >> >> It is just very famous because of Wikipedia IMHO. > > Well, it's gotten a lot more development attention because of that > same Wikipedia. Yeah, but you know: Too many cooks spoil the broth. >> Having a DBMS backend is good in your opinion? > I didn't say that it was good, in fact I was listing it as a > disadvantage there. I think for a small wiki like I was discussing, > it's just an extra administrative hassle. For a large wiki though, > MoinMoin's approach is completely unworkable and MoinMoin's > documentation actually says so. First of all MoinMoin uses a separate > subdirectory for every page, and all those subdirs are in a flat top > level directory, so if you have 100,000 wiki pages, the top level > directory has that many subdirs. Most file systems are not built to > handle such large directories with any reasonable speed. But many other are. > (Also, every revision has its own file in the subdir. Lots of Wikipedia pages have > thousands of revisions). Yeah, same point. But if you have a working btree+ etc. implementation in your FS, then it should not a problem. Personally, I just see another problem at this point: paths might get very long if your page names are long. This might result in problems on Windows. But you have to use very long page names to hit the 256 char limit. > The DBMS can also handle stuff like replication automatically. But this is non-trivial. >>> The other one will be public and is planned grow to medium size (a few >>> thousand active users) >> >> There are even MoinMoin sites that are as big as that. Maybe you should >> rethink your kind of prejudice and re-evaluate MoinMoin. > > I don't doubt there are MoinMoin sites that size, but with that large > a user base, I want something nicer looking than those > StupidMixedCasePageNames. See above. Just because most people still work with CamelCase, they are not the only solution. ["Stupid mixed case page names"] is a completly valid link in MoinMoin and has been one for years. Kind regards, Alexander From claird at lairds.us Mon Jan 3 10:08:08 2005 From: claird at lairds.us (Cameron Laird) Date: Mon, 03 Jan 2005 15:08:08 GMT Subject: Compiler benefits (was: The Industry choice) References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <33q4plF410bo2U1@individual.net> <1104689464.828070.309990@c13g2000cwb.googlegroups.com> Message-ID: In article <1104689464.828070.309990 at c13g2000cwb.googlegroups.com>, wrote: >Roy Smith wrote: >>I think you've hit the nail on the head. In awk (and perl, and most >>shells, and IIRC, FORTRAN), using an undefined variable silently gets >>you a default value (empty string or zero). This tends to propagate >>errors and make them very difficult to track down. > >You may recall correctly, but Fortran compilers have improved. The >following Fortran 90 program > >integer, parameter :: n = 1 >real :: x,y=2.0,z(n) >print*,"dog" >print*,x >z(n+1) = 1.0 >print*,z >end > >has 3 errors, all detected at compile time by the Lahey/Fujitsu Fortran >95 compiler, with the proper options: > >2004-I: "xundef.f", line 2: 'y' is set but never used. . . . I wonder how many of Lahey/Fujitsu users ignore the 'I' diagnostics: "It's not really an error--the program still runs." I'm a bit grouchy today on the subject of engineering standards. I think your point was that the checking present in modern Fortran compilers, or PyCheckers, but absent from core Python, is a net benefit. That I grant. I'm reluctant to argue for a change in Python. I personally prefer to urge PyChecker on developers. From apardon at forel.vub.ac.be Wed Jan 12 03:33:04 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 Jan 2005 08:33:04 GMT Subject: tuples vs lists References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dfe2a6$0$22729$636a15ce@news.free.fr> <41e2e8cf$0$5744$626a14ce@news.free.fr> <34iejgF4akofdU1@individual.net> Message-ID: Op 2005-01-11, Reinhold Birkenfeld schreef : > Antoon Pardon wrote: >> Op 2005-01-10, Bruno Desthuilliers schreef : >>> Antoon Pardon a ?crit : >>>> Op 2005-01-08, Bruno Desthuilliers schreef : >>>> >>>>>worzel a ?crit : >>>>> >>>>>>I get what the difference is between a tuple and a list, but why would I >>>>>>ever care about the tuple's immuutability? >>>>> >>>>>Because, from a purely pratical POV, only an immutable object can be >>>>>used as kay in a dict. >>> >>> s/kay/key/ >>> >>>> This is not true. >>> >>> Chapter and verse, please ? >> >> I don't need chapter and verse. I have already used mutable >> objects as keys and it works just fine. >> >>>>> class hlst(list): >>>>> >>>>> def __hash__(self): >>>>> sum = 0 >>>>> for el in self: >>>>> sum += hash(el) >>>>> return sum % 0x37777777 >>>>> > > Given this hash function, how do you handle changed keys? I don't change keys. The fact that I like to use a mutable as a key doesn't imply I want to mutate a key. > And if you can't access the element when it's changed, what is the > advantage over using tuples? The debate over what the adavantage is of tuples over lists or vice versa as keys in dictionaries is IMO misguided. Whether I use a list or a tuple is not guided by whether they are going to be used as a key or not, but how in general the data is to be manipulated. If the typical manipulations are modifications of an existing object, I use a list, if the typical manipulation creates new objects out of old ones I use a tuple. If I then find that I need this object as a key, I just provide a hash so that I can use this object as a key in a straight forward manner, without the hassle of converting to and from a tuple all the time. -- Antoon Pardon From deetsNOSPAM at web.de Wed Jan 26 10:31:26 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 26 Jan 2005 16:31:26 +0100 Subject: 4suite XSLT thread safe ? References: <6lkkc2-fbd.ln1@pluto.i.infosense.no> <35pntaF4os76kU1@individual.net> <35ppqeF4nu516U1@individual.net> Message-ID: <35praqF4p8vohU2@individual.net> > While the only one how can answer this is Uche himself, I'm confident that > this is not the case - modern OO-style apis associate state usually on a > per-object base. And 4suite is heavily OO-styled. I should have added that this means that using a api like 4suite where you can get a processor for one transformation, it should be safe to get another one in another thread for another transformation, as this is the preceived use case. -- Regards, Diez B. Roggisch From bokr at oz.net Fri Jan 7 16:33:36 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 07 Jan 2005 21:33:36 GMT Subject: args (was Re: Lambda as declarative idiom (was RE: what is lambda used for in real code?)) References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> Message-ID: <41deffb5.255871764@news.oz.net> On Tue, 04 Jan 2005 14:11:51 -0800, Michael Spencer wrote: [Hm, this didn't go out for some reason. I'll just send it now.] >Roman Suzi wrote: > >> Maybe this is too outlandish, but I see lambdas as a "quote" mechanism, >> which presents a possibility to postpone (precisely control, delegate) >> evaluation. That is, an ovehead for lambda must be much lower but at the >> same time visible to the programmer: >> >> d = a + (lambda x, y: x+ y)(3, 4) >[...] > >I believe that this "possibility to postpone" divides into two related but >separate concepts: controlling the moment of evaluation, and assembling the >arguments required at that moment. They are both species of 'eval', but >managing arguments is more specialized, because it includes possibly renaming >parameters, assigning default values, processing positional and keyword >arguments, and, perhaps in the future dealing with argument types. > I imagine that you should be able to identify bytecode substrings in current code that would have to be part of an implementation of what you are proposing. But ISTM mabe there's three concepts: 1) defining the formal parameter list, which is like a template for unpacking and binding an actual arglist produced by 2) the source code for a call of some named function with expression for actual arguments, and 3) the run time excution of the code compiled from (2). AFAICS, currently there is no linkage between the called function and the calling code except that the first thing put on the stack is just the result of an expression that _should_ put a reference to a compatible callable on the stack. What follows is a sequence of argument expressions which stack the arg values, and then finally the byte code is executed to make one of several kinds of specialized function calls to use the stack contents. At that point the 'callable' could be None, or another function with the wrong signature. What I see as the deferred-args-evaluation part is the code between pushing the callable reference and making the specialized call. But that can't be what your args function is, since UIAM the 'arguments' to that are not run time calling arguments, but a particular formal parameter signature. That's a guide for unpacking and binding a call's arguments at an associated function's entry, to create a _part_ of the local bindings, which has nothing to do with deferring the evaluation of the call args. >Meanwhile, GvR wrote (about defining Interfaces in the context of Optional >Static Type Checking) >> Method declarations can be inspected to find out their signature. I propose a >> __signature__ attribute (also for methods defined in classes!) which might be an >> object whose attributes make the signature easily inspectable. This might take >> the form of a list of argument declaration objects giving the name, type and default >> (if any) for each argument, and a separate argument for the return type. For >> signatures that include *args and/or **kwds, the type of the additional arguments >> should also be given (so you can write for example a varargs method whose arguments >> are all strings). > >GvR's method.__signature__ object might be related to the args object I proposed > as part of the syntax for anonymous functions without 'lambda'. i.e., > > args(a,*b,**kw) --> an object that specifies but does not evaluate its >parameters until it is supplied to a callable, possibly with calling parameters This is the part I don't understand. To me, that expression doesn't have anything to do with evaluating parameters, it has to do with unpacking a particular call's parameters after they have been evaluated. If it could "evaluate ist parameters" it would have to have code in it to do that, but the code for evaluation of parameters is generated from the translation of the calling code. And there might be dozens of lines calling the same function. I.e., args(a,*b,**kw) specifies formal parameter names and structural information for dealing with callers' post-evaluation actual args. The only way it could have the ability to control evaluation of args is if it had a reference to a deferred-arg-eval byte code snippet. IOw, maybe the function should be called argsig instead of args and args could deal with deferred actual arg evaluation. Then the tuple argsig(x, y), args(1, 2) could conceptually be like a bound method for deferred evaluation or args _and_ binding to names in some namespace like a function's local namespace, but maybe not necessarily. Maybe it could be applied to other namspaces as well. ... just musing ;-) > >This object would contain the default values, and could contain type >annotations, explicit, or inferred, as well as more complex assertions used in >several contexts. But it has to be clear that until a particular calling-args list (deferred or not) is selected by being the "current one" of possibly many, the object doesn't have arg values to mess with. > >* Current function syntax: > def func(a,*b,**c) : pass > > creates func with func.__signature__ = args(a,*b,**c) > and when func is called, the args are evaluated using a mechanism in > args.__call__ > so, roughly, eval(func.__signature__) --> func.locals Again, see above for argsig vs argeval. Or what am I missing? > > > * Anonymous functions > Syntax alternatives at http://www.python.org/moin/AlternateLambdaSyntax > e.g., (f(a) + o(b) - o(c) for args(a, b, c)) > > args would evaluated with the calling parameters and made available in the >local scope defined by () > > * A stricter alternative to keyword arguments: > argspec = args(arg1, arg2, arg3) > def func(**argspec): pass > > is equivalent to def func(arg1, arg2, arg3): pass > > > args["arg1"] > > (i.e., only args defined in argspec are accepted) > > * Useful infrastructure for user-supplied type-based dispatch/lightweight >multimethods: > > argspec = args([(a:int, b:int),(a:str,b:str)]) > > then a framework can provide a custom args.__call__ method that does > conformance-checking, adaptation or whatever > BTW, if argseval(arg1, etc) pushes arg1 and etc when "called" sort of like (*lambda arg,etc:arg,etc) without packing/unpacking then maybe they could be added, so argseval(a,b)+argseval(c) == argseval(a,b,c). Don't know what that would be good for. Maybe in currying or such? Regards, Bengt Richter From michele.simionato at gmail.com Wed Jan 26 07:50:52 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 26 Jan 2005 04:50:52 -0800 Subject: FTP Server Message-ID: <1106743852.600769.72820@c13g2000cwb.googlegroups.com> What's the simplest way to write an FTP Server in Python? A short research on the newsgroup and on the Cookbook did not bring out anything relevant (but I hear a little voice in the back of my head saying Twisted, Twisted! ...) Michele Simionato From moma at example.net Thu Jan 27 06:43:48 2005 From: moma at example.net (moma) Date: Thu, 27 Jan 2005 12:43:48 +0100 Subject: python module in webmin In-Reply-To: References: Message-ID: sam wrote: > Hi, > > Had anyone written any python module for webmin? > Since webmin is written in perl, but I want to write a python > app/module used by webmin. If you know the detail of writing a python > module for use in perl webmin, please drop me some guideline. > > Perhaps It is better off to find/write a python version of webmin first. > > Thanks > Sam. Some tips. 0) Webmin API-spesification (search for "Python" word) http://www.webmin.com/modules.html 1) Read: http://www.cendio.se/~peter/python-webmin/ Read README and Webmin.py. It says that 25% of API is converted to Python. It's normal CGI scripting and HTML. So you can easily write a real Webmin-module in Python. Maybe you can help to make Webmin.py more complete :)? 2) Search for "Python" here http://webmin.thirdpartymodules.com/?page=Search Find any modules written in Python? // moma http://www.futuredesktop.org/OpenOffice.html http://www.futuredesktop.org/hpc_linux.html From spk00 at cox.net Sun Jan 9 06:39:09 2005 From: spk00 at cox.net (Sean P. Kane) Date: Sun, 9 Jan 2005 03:39:09 -0800 Subject: Old Paranoia Game in Python Message-ID: <2005010903390916807%spk00@coxnet> I ported the old (and long since removed) game from the bsd-game pacakge called, Paranoia, based on the old Paranoia role playing game from C to Python as a simple exercise in learning the language and pure late night boredom. Anyways, here it is for anyone looking for a few minutes of nostalgia. I may get around to posting this at http://homepage.mac.com/spkane/ or http://www.spkane.org/, but for now here it is. Improvements or corrections, welcome. Thanks, Sean ---------------------------------Cut Here--------------------------------- #!/usr/bin/env python # # # -*- encoding = 'utf-8' -*- # # # Command Line GCS Upgrade Application # ==================================== # This is a port of paranoia from the old bsd-games package. # # # HISTORY # ======= # # 1.2 - 03 Jan 2005 # + Initially started porting application # # Requires # ======== # 1) Python 2.3 '''\ usage: paranoia ''' __author__ = 'Sean P. Kane ' __copyright__ = '''This is a solo paranoia game taken from the Jan/Feb issue (No 77) of SpaceGamer/FantasyGamer magazine. Article by Sam Shirley. Originally implemented in C on Vax 11/780 under UNIX by Tim Lister Ported to Python on an Apple Powerbook G4 by Sean P. Kane This is a public domain adventure and may not be sold for profit''' __date__ = '01/03/2005' #Also change version at top of main() __version__ = '1.2' #the basics import sys #For Dice Rolling import random #new argument parsing library from optparse import OptionParser moxie = 13 agility = 15 maxkill = 7 # The maximum number of UV's you can kill clone = 1 page = 1 computer_request = 0 ultra_violet = 0 action_doll = 0 hit_points = 10 read_letter = 0 plato_clone = 3 blast_door = 0 killer_count = 0 def instructions(): print """Welcome to Paranoia! HOW TO PLAY: Just press until you are asked to make a choice. Select 'a' or 'b' or whatever for your choice, then press . You may select 'p' at any time to get a display of your statistics. Always choose the least dangerous option. Continue doing this until you win. At times you will use a skill or engage in combat and will be informed of the outcome. These sections will be self explanatory. HOW TO DIE: As Philo-R-DMD you will die at times during the adventure. When this happens you will be given an new clone at a particular location. The new Philo-R will usually have to retrace some of the old Philo-R\'s path hopefully he won\'t make the same mistake as his predecessor. HOW TO WIN: Simply complete the mission before you expend all six clones. If you make it, congratulations. If not, you can try again later. """ def character(): print """"=============================================================================== The The Character : Philo-R-DMD %s Primary Attributes Secondary Attributes =============================================================================== Strength ..................... 13 Carrying Capacity ................. 30 Endurance .................... 13 Damage Bonus ....................... 0 Agility ...................... 15 Macho Bonus ....................... -1 Manual Dexterity ............. 15 Melee Bonus ...................... +5%% Moxie ........................ 13 Aimed Weapon Bonus .............. +10%% Chutzpah ...................... 8 Comprehension Bonus .............. +4%% Mechanical Aptitude .......... 14 Believability Bonus .............. +5%% Power Index .................. 10 Repair Bonus ..................... +5%% =============================================================================== Credits: 160 Secret Society: Illuminati Secret Society Rank: 1 Service Group: Power Services Mutant Power: Precognition Weapon: laser pistol to hit, 40%% type, L Range, 50m Reload, 6r Malfnt, 00 Skills: Basics 1(20%%), Aimed Weapon Combat 2(35%%), Laser 3(40%%), Personal Development 1(20%%), Communications 2(29%%), Intimidation 3(34%%) Equipment: Red Reflec Armour, Laser Pistol, Laser Barrel (red), Notebook & Stylus, Knife, Com Unit 1, Jump suit, Secret Illuminati Eye-In-The-Pyramid(tm) Decoder ring, Utility Belt & Pouches =============================================================================== """ % clone def page1(): global page print """You wake up face down on the red and pink checked E-Z-Kleen linoleum floor. You recognise the pattern, it's the type preferred in the internal security briefing cells. When you finally look around you, you see that you are alone in a large mission briefing room. """ page = 57 more() def page2(): global page global computer_request print """\"Greetings,\" says the kindly Internal Security self incrimination expert who meets you at the door, \"How are we doing today?\" He offers you a doughnut and coffee and asks what brings you here. This doesn\'t seem so bad, so you tell him that you have come to confess some possible security lapses. He smiles knowingly, deftly catching your coffee as you slump to the floor. \"Nothing to be alarmed about it\'s just the truth serum,\" he says, dragging you back into a discussion room. The next five hours are a dim haze, but you can recall snatches of conversation about your secret society, your mutant power, and your somewhat paranoid distrust of The Computer. This should explain why you are hogtied and moving slowly down the conveyer belt towards the meat processing unit in Food Services. """ if computer_request == 1: new_clone(45) else: new_clone(32) more() def page3(): global page print """You walk to the nearest Computer terminal and request more information about Christmas. The Computer says, \"That is an A-1 ULTRAVIOLET ONLY IMMEDIATE TERMINATION classified topic. What is your clearance please, Troubleshooter?\" """ choose(4,"You give your correct clearance",5,"You lie and claim Ultraviolet clearance") def page4(): global page print """\"That is classified information, Troubleshooter, thank you for your inquiry. Please report to an Internal Security self incrimination station as soon as possible.\" """ page = 9 more() def page5(): global page print """The computer says, \"Troubleshooter, you are not wearing the correct colour uniform. You must put on an Ultraviolet uniform immediately. I have seen to your needs and ordered one already it will be here shortly. Please wait with your back to the wall until it arrives.\" In less than a minute an infrared arrives carrying a white bundle. He asks you to sign for it, then hands it to you and stands back, well outside of a fragmentation grenade\'s blast radius. """ choose(6, "You open the package and put on the uniform", 7, "You finally come to your senses and run for it") def page6(): global page global ultra_violet print """The uniform definitely makes you look snappy and pert. It really looks impressive, and even has the new lopsided lapel fashion that you admire so much. What\'s more, citizens of all ranks come to obsequious attention as you walk past. This isn\'t so bad being an Ultraviolet. You could probably come to like it, given time. The beeping computer terminal interrupts your musings. """ ultra_violet = 1 page = 8 more() def page7(): global page global ultra_violet print """The corridor lights dim and are replaced by red battle lamps as the Security Breach alarms howl all around you. You run headlong down the corridor and desperately windmill around a corner, only to collide with a squad of 12 Blue clearance Vulture squadron soldiers. \"Stop, Slime Face,\" shouts the commander, \"or there won\'t be enough of you left for a tissue sample.\" \"All right, soldiers, stuff the greasy traitor into the uniform,\" he orders, waving the business end of his blue laser scant inches from your nose. With his other hand he shakes open a white bundle to reveal a pristine new Ultraviolet citizen's uniform. One of the Vulture squadron Troubleshooters grabs you by the neck in the exotic and very painful Vulture Clamp(tm) death grip (you saw a special about it on the Teela O\'Malley show), while the rest tear off your clothes and force you into the Ultraviolet uniform. The moment you are dressed they step clear and stand at attention. \"Thank you for your cooperation, sir,\" says the steely eyed leader of the Vulture Squad. \"We will be going about our business now.\" With perfect timing the Vultures wheel smartly and goosestep down the corridor. Special Note: don\'t make the mistake of assuming that your skills have improved any because of the uniform you\'re only a Red Troubleshooter traitorously posing as an Ultraviolet, and don\'t you forget it! Suddenly, a computer terminal comes to life beside you. """ ultra_violet = 1 page = 8 more() def page8(): global page print """\"Now, about your question, citizen. Christmas was an old world marketing ploy to induce lower clearance citizens to purchase vast quantities of goods, thus accumulation a large amount of credit under the control of a single class of citizen known as Retailers. The strategy used is to imply that all good citizens give gifts during Christmas, thus if one wishes to be a valuable member of society one must also give gifts during Christmas. More valuable gifts make one a more valuable member, and thus did the Retailers come to control a disproportionate amount of the currency. In this way Christmas eventually caused the collapse of the old world. Understandably, Christmas has been declared a treasonable practice in Alpha Complex. Thank you for your inquiry.\" You continue on your way to GDH7-beta. """ page = 10 more() def page9(): global page global computer_request print """As you walk toward the tubecar that will take you to GDH7-beta, you pass one of the bright blue and orange Internal Security self incrimination stations. Inside, you can see an IS agent cheerfully greet an infrared citizen and then lead him at gunpoint into one of the rubber lined discussion rooms. """ choose(2,"You decide to stop here and chat, as ordered by The Computer",10,"You just continue blithely on past") if page == 2: computer_request = 1 else: computer_request = 0 def page10(): global page global moxie global ultra_violet print """You stroll briskly down the corridor, up a ladder, across an unrailed catwalk, under a perilously swinging blast door in urgent need of repair, and into tubecar grand central. This is the bustling hub of Alpha Complex tubecar transportation. Before you spreads a spaghetti maze of magnalift tube tracks and linear accelerators. You bravely study the specially enhanced 3-D tube route map you wouldn\'t be the first Troubleshooter to take a fast tube ride to nowhere. """ if ultra_violet == 0: choose(3,"You decide to ask The Computer about Christmas using a nearby terminal",10,"You think you have the route worked out, so you\'ll board a tube train") if page == 3: return print "You nervously select a tubecar and step aboard." if dice_roll(2,10) < moxie: print "You just caught a purple line tubecar." page = 13 else: print "You just caught a brown line tubecar." page = 48 more() def page11(): global page print """The printing on the folder says \"Experimental Self Briefing.\" You open it and begin to read the following: Step 1: Compel the briefing subject to attend the briefing. Note: See Experimental Briefing Sub Form Indigo-WY-2, \'Experimental Self Briefing Subject Acquisition Through The Use Of Neurotoxin Room Foggers.\' Step 2: Inform the briefing subject that the briefing has begun. ATTENTION: THE BRIEFING HAS BEGUN. Step 3: Present the briefing material to the briefing subject. GREETINGS TROUBLESHOOTER. YOU HAVE BEEN SPECIALLY SELECTED TO SINGLEHANDEDLY WIPE OUT A DEN OF TRAITOROUS CHRISTMAS ACTIVITY. YOUR MISSION IS TO GO TO GOODS DISTRIBUTION HALL 7-BETA AND ASSESS ANY CHRISTMAS ACTIVITY YOU FIND THERE. YOU ARE TO INFILTRATE THESE CHRISTMAS CELEBRANTS, LOCATE THEIR RINGLEADER, AN UNKNOWN MASTER RETAILER, AND BRING HIM BACK FOR EXECUTION AND TRIAL. THANK YOU. THE COMPUTER IS YOUR FRIEND. Step 4: Sign the briefing subject\'s briefing release form to indicate that the briefing subject has completed the briefing. ATTENTION: PLEASE SIGN YOUR BRIEFING RELEASE FORM. Step 5: Terminate the briefing ATTENTION: THE BRIEFING IS TERMINATED. """ more() print """You walk to the door and hold your signed briefing release form up to the plexiglass window. A guard scrutinises it for a moment and then slides back the megabolts holding the door shut. You are now free to continue the mission. """ choose(3,"You wish to ask The Computer for more information about Christmas",10,"You have decided to go directly to Goods Distribution Hall 7-beta") def page12(): global page print """You walk up to the door and push the button labelled \"push to exit.\" Within seconds a surly looking guard shoves his face into the small plexiglass window. You can see his mouth forming words but you can\'t hear any of them. You just stare at him blankly for a few moments until he points down to a speaker on your side of the door. When you put your ear to it you can barely hear him say, \"Let\'s see your briefing release form, bud. You aren\'t getting out of here without it.\" """ choose(11,"You sit down at the table and read the Orange packet",57,"You stare around the room some more") def page13(): global page print """You step into the shiny plasteel tubecar, wondering why the shape has always reminded you of bullets. The car shoots forward the instant your feet touch the slippery gray floor, pinning you immobile against the back wall as the tubecar careens toward GDH7-beta. Your only solace is the knowledge that it could be worse, much worse. Before too long the car comes to a stop. You can see signs for GDH7-beta through the window. With a little practice you discover that you can crawl to the door and pull open the latch. """ page = 14 more() def page14(): global page print """You manage to pull yourself out of the tubecar and look around. Before you is one of the most confusing things you have ever seen, a hallway that is simultaneously both red and green clearance. If this is the result of Christmas then it\'s easy to see the evils inherent in its practice. You are in the heart of a large goods distribution centre. You can see all about you evidence of traitorous secret society Christmas celebration rubber faced robots whiz back and forth selling toys to holiday shoppers, simul-plast wreaths hang from every light fixture, while ahead in the shadows is a citizen wearing a huge red synthetic flower. """ page = 22 more() def page15(): global page print """You are set upon by a runty robot with a queer looking face and two pointy rubber ears poking from beneath a tattered cap. \"Hey mister,\" it says, \"you done all your last minute Christmas shopping? I got some real neat junk here. You don\'t wanna miss the big day tommorrow, if you know what I mean.\" The robot opens its bag to show you a pile of shoddy Troubleshooter dolls. It reaches in and pulls out one of them. \"Look, these Action Troubleshooter(tm) dolls are the neatest thing. This one\'s got moveable arms and when you squeeze him, his little rifle squirts realistic looking napalm. It\'s only 50 credits. Oh yeah, Merry Christmas.\" """ while True: print """\nSelect \'a\', \'b\' or \'c\' : a - You decide to buy the doll. b - You shoot the robot. c - You ignore the robot and keep searching the hall. """ choice = raw_input("Type choice and press to continue:") if choice == "a": page = 16 break elif choice == "b": page = 17 break elif choice =="c": page = 22 break def page16(): global page global action_doll print """The doll is a good buy for fifty credits it will make a fine Christmas present for one of your friends. After the sale the robot rolls away. You can use the doll later in combat. It works just like a cone rifle firing napalm, except that occasionally it will explode and blow the user to smithereens. But don\'t let that stop you. """ action_doll = 1 page = 22 more() def page17(): global page global hit_points print """You whip out your laser and shoot the robot, but not before it squeezes the toy at you. The squeeze toy has the same effect as a cone rifle firing napalm, and the elfbot\'s armour has no effect against your laser. """ robot_hp=15 i = 0 while i < 2: if dice_roll(1,100) <= 25: print "You have been hit!" hit_points = hit_points - dice_roll(1,10) if hit_points <= 0: new_clone(45) more() return else: print "It missed you, but not by much!" if dice_roll(1,100) <= 40: print "You zapped the little bastard!" robot_hp = robot_hp - dice_roll(2,10) if robot_hp <= 0: print "You wasted it! Good shooting!" print "You will need more evidence, so you search GDH7-beta further" if hit_points < 10: print "after the GDH medbot has patched you up." hit_points=10 page = 22 more() return else: print "Damn! You missed!" i = i + 1 print "It tried to fire again, but the toy exploded and demolished it." print "You will need more evidence, so you search GDH7-beta further" if hit_points < 10: print "after the GDH medbot has patched you up." hit_points=10 page = 22 more() def page18(): global page global agility print """You walk to the centre of the hall, ogling like an infrared fresh from the clone vats. Towering before you is the most unearthly thing you have ever seen, a green multi armed mutant horror hulking 15 feet above your head. Its skeletal body is draped with hundreds of metallic strips (probably to negate the effects of some insidious mutant power), and the entire hideous creature is wrapped in a thousand blinking hazard lights. It\'s times like this when you wish you\'d had some training for this job. Luckily the creature doesn\'t take notice of you but stands unmoving, as though waiting for a summons from its dark lord, the Master Retailer. WHAM, suddenly you are struck from behind. """ if dice_roll(2,10) < agility: page = 19 else: page = 20 more() def page19(): global page global maxkill global clone global killer_count print """Quickly you regain your balance, whirl and fire your laser into the Ultraviolet citizen behind you. For a moment your heart leaps to your throat, then you realise that he is indeed dead and you will be the only one filing a report on this incident. Besides, he was participating in this traitorous Christmas shopping, as is evident from the rain of shoddy toys falling all around you. Another valorous deed done in the service of The Computer! """ killer_count = killer_count + 1 if killer_count > maxkill - clone: page = 21 more() elif read_letter==1: page = 22 more() else: choose(34,"You search the body, keeping an eye open for Internal Security",22,"You run away like the cowardly dog you are") def page20(): global page print """Oh no! you can\'t keep your balance. You\'re falling, falling head first into the Christmas beast\'s gaping maw. It\'s a valiant struggle you think you are gone when its poisonous needles dig into your flesh, but with a heroic effort you jerk a string of lights free and jam the live wires into the creature\'s spine. The Christmas beast topples to the ground and begins to burn, filling the area with a thick acrid smoke. It takes only a moment to compose yourself, and then you are ready to continue your search for the Master Retailer. """ page = 22 more() def page21(): global page print """You have been wasting the leading citizens of Alpha Complex at a prodigious rate. This has not gone unnoticed by the Internal Security squad at GDH7-beta. Suddenly, a net of laser beams spear out of the gloomy corners of the hall, chopping you into teeny, weeny bite size pieces. """ new_clone(45) more() def page22(): global page print "You are searching Goods Distribution Hall 7-beta." choice = dice_roll(1,4) if choice == 1: page = 18 elif choice == 2: page = 15 elif choice == 3: page = 18 elif choice == 4: page = 29 more() def page23(): global page print """You go to the nearest computer terminal and declare yourself a mutant. \"A mutant, he\'s a mutant,\" yells a previously unnoticed infrared who had been looking over your shoulder. You easily gun him down, but not before a dozen more citizens take notice and aim their weapons at you. """ choose(28,"You tell them that it was really only a bad joke",24,"You want to fight it out, one against twelve") def page24(): global page print """Golly, I never expected someone to pick this. I haven\'t even designed the 12 citizens who are going to make a sponge out of you. Tell you what, I\'ll give you a second chance. """ choose(28,"You change your mind and say it was only a bad joke",25,"You REALLY want to shoot it out") def page25(): global page print """Boy, you really can\'t take a hint! They\'re closing in. Their trigger fingers are twitching, they\'re about to shoot. This is your last chance. """ choose(28,"You tell them it was all just a bad joke",26,"You are going to shoot") def page26(): global page print """You can read the cold, sober hatred in their eyes (They really didn\'t think it was funny), as they tighten the circle around you. One of them shoves a blaster up your nose, but that doesn\'t hurt as much as the multi-gigawatt carbonium tipped food drill in the small of your back. You spend the remaining micro-seconds of your life wondering what you did wrong """ new_clone(32) more() def page27(): global page # doesn't exist. Can't happen with computer version. # designed to catch dice cheats print "cheat..." page = 0 more() def page28(): global page print "They don\'t think it\'s funny." page = 26 more() def page29(): global page print """\"Psst, hey citizen, come here. Pssfft,\" you hear. When you peer around you can see someone\'s dim outline in the shadows. \"I got some information on the Master Retailer. It\'ll only cost you 30 psst credits.\" """ while True: print """\nSelect \'a\', \'b\' or \'c\' : a - You pay the 30 credits for the info. b - You would rather threaten him for the information. c - You ignore him and walk away. """ choice = raw_input("Type choice and press to continue:") if choice == "a": page = 30 break elif choice == "b": page = 31 break elif choice == "c": page = 22 break def page30(): global page print """You step into the shadows and offer the man a thirty credit bill. \"Just drop it on the floor,\" he says. \"So you\'re looking for the Master Retailer, pssfft? I\'ve seen him, he\'s a fat man in a fuzzy red and white jump suit. They say he\'s a high programmer with no respect for proper security. If you want to find him then pssfft step behind me and go through the door.\" Behind the man is a reinforced plasteel blast door. The centre of it has been buckled toward you in a manner you only saw once before when you were field testing the rocket assist plasma slingshot (you found it easily portable but prone to misfire). Luckily it isn\'t buckled too far for you to make out the warning sign. WARNING!! Don\'t open this door or the same thing will happen to you. Opening this door is a capital offense. Do not do it. Not at all. This is not a joke. """ while True: print """\nSelect \'a\', \'b\' or \'c\' : a - You use your Precognition mutant power on opening the door. b - You just go through the door anyway. c - You decide it\'s too dangerous and walk away. """ choice = raw_input("Type choice and press to continue:") if choice == "a": page = 56 break elif choice == "b": page = 33 break elif choice =="c": page = 22 break def page31(): global page print """Like any good troubleshooter you make the least expensive decision and threaten him for information. With lightning like reflexes you whip out your laser and stick it up his nose. \"Talk, you traitorous Christmas celebrator, or who nose what will happen to you, yuk yuk,\" you pun menacingly, and then you notice something is very wrong. He doesn\'t have a nose. As a matter of fact he\'s made of one eighth inch cardboard and your laser is sticking through the other side of his head. \"Are you going to pay?\" says his mouth speaker, \"or are you going to pssfft go away stupid?\" """ choose(30,"You pay the 30 credits",22,"You pssfft go away stupid") def page32(): global page print """Finally it\'s your big chance to prove that you\'re as good a troubleshooter as your previous clone. You walk briskly to mission briefing and pick up your previous clone\'s personal effects and notepad. After reviewing the notes you know what has to be done. You catch the purple line to Goods Distribution Hall 7-beta and begin to search for the blast door. """ page = 22 more() def page33(): global page global ultra_violet global blast_door print """You release the megabolts on the blast door, then strain against it with your awesome strength. Slowly the door creaks open. You bravely leap through the opening and smack your head into the barrel of a 300 mm \'ultra shock\' class plasma cannon. It\'s dark in the barrel now, but just before your head got stuck you can remember seeing a group of technicians anxiously watch you leap into the room. """ blast_door = 1 if ultra_violet==1: page=35 else: page=36 more() def page34(): global page global read_letter print """You have found a sealed envelope on the body. You open it and read: \"WARNING: Ultraviolet Clearance ONLY. DO NOT READ. Memo from Chico-U-MRX4 to Harpo-U-MRX5. The planned takeover of the Troubleshooter Training Course goes well, Comrade. Once we have trained the unwitting bourgeois troubleshooters to work as communist dupes, the overthrow of Alpha Complex will be unstoppable. My survey of the complex has convinced me that no one suspects a thing soon it will be too late for them to oppose the revolution. The only thing that could possibly impede the people\'s revolution would be someone alerting The Computer to our plans (for instance, some enterprising Troubleshooter could tell The Computer that the communists have liberated the Troubleshooter Training Course and plan to use it as a jumping off point from which to undermine the stability of all Alpha Complex), but as we both know, the capitalistic Troubleshooters would never serve the interests of the proletariat above their own bourgeois desires. P.S. I\'m doing some Christmas shopping later today. Would you like me to pick you up something?\" """ more() print """When you put down the memo you are overcome by that strange deja\'vu again. You see yourself talking privately with The Computer. You are telling it all about the communists\' plan, and then the scene shifts and you see yourself showered with awards for foiling the insidious communist plot to take over the complex. """ read_letter = 1 choose(46,"You rush off to the nearest computer terminal to expose the commies",22,"You wander off to look for more evidence") def page35(): global page print """\"Oh master,\" you hear through the gun barrel, \"where have you been? It is time for the great Christmas gifting ceremony. You had better hurry and get the costume on or the trainee may begin to suspect.\" For the second time today you are forced to wear attire not of your own choosing. They zip the suit to your chin just as you hear gunfire erupt behind you. \"Oh no! Who left the door open? The commies will get in. Quick, fire the laser cannon or we\'re all doomed.\" \"Too late you capitalist swine, the people\'s revolutionary strike force claims this cannon for the proletariat\'s valiant struggle against oppression. Take that, you running dog imperialist lackey. ZAP, KAPOW\" Just when you think that things couldn\'t get worse, \"Aha, look what we have here, the Master Retailer himself with his head caught in his own cannon. His death will serve as a symbol of freedom for all Alpha Complex. Fire the cannon.\" """ new_clone(32) more() def page36(): global page print """\"Congratulations, troubleshooter, you have successfully found the lair of the Master Retailer and completed the Troubleshooter Training Course test mission,\" a muffled voice tells you through the barrel. \"Once we dislodge your head from the barrel of the \'Ultra Shock\' plasma cannon you can begin with the training seminars, the first of which will concern the 100% accurate identification and elimination of unregistered mutants. If you have any objections please voice them now.\" """ while True: print """\nSelect \'a\', \'b\' or \'c\' : a - You appreciate his courtesy and voice an objection. b - After your head is removed from the cannon, you register as a mutant. c - After your head is removed from the cannon, you go to the unregistered mutant identification and elimination seminar. """ choice = raw_input("Type choice and press to continue:") if choice == "a": new_clone(32) break elif choice == "b": page = 23 break elif choice == "c": page = 37 break def page37(): global page print """\"Come with me please, Troubleshooter,\" says the Green clearance technician after he has dislodged your head from the cannon. \"You have been participating in the Troubleshooter Training Course since you got off the tube car in GDH7-beta,\" he explains as he leads you down a corridor. \"The entire Christmas assignment was a test mission to assess your current level of training. You didn\'t do so well. We\'re going to start at the beginning with the other student. Ah, here we are, the mutant identification and elimination lecture.\" He shows you into a vast lecture hall filled with empty seats. There is only one other student here, a Troubleshooter near the front row playing with his Action Troubleshooter(tm) figure. \"Find a seat and I will begin,\" says the instructor. """ page = 38 more() def page38(): global page global plato_clone print """\"I am Plato-B-PHI%d, head of mutant propaganda here at the training course.""" % plato_clone print """If you have any questions about mutants please come to me. Today I will be talking about mutant detection. Detecting mutants is very easy. One simply watches for certain tell tale signs, such as the green scaly skin, the third arm growing from the forehead, or other similar disfigurements so common with their kind. There are, however, a few rare specimens that show no outward sign of their treason. This has been a significant problem, so our researchers have been working on a solution. I would like a volunteer to test this device,\" he says, holding up a ray gun looking thing. \"It is a mutant detection ray. This little button detects for mutants, and this big button stuns them once they are discovered. Who would like to volunteer for a test?\" The Troubleshooter down the front squirms deeper into his chair. """ choose(39,"You volunteer for the test",40,"You duck behind a chair and hope the instructor doesn\'t notice you") def page39(): global page global plato_clone print """You bravely volunteer to test the mutant detection gun. You stand up and walk down the steps to the podium, passing a very relieved Troubleshooter along the """ print """way. When you reach the podium Plato-B-PHI%d hands you the mutant detection gun""" % plato_clone print """and says, \"Here, aim the gun at that Troubleshooter and push the small button. If you see a purple light, stun him.\" Grasping the opportunity to prove your worth to The Computer, you fire the mutant detection ray at the Troubleshooter. A brilliant purple nimbus instantly surrounds his body. You slip your finger to the large stun button and he falls writhing to the floor. \"Good shot,\" says the instructor as you hand him the mutant detection gun, \"I\'ll see that you get a commendation for this. It seems you have the hang of mutant detection and elimination. You can go on to the secret society infiltration class. I\'ll see that the little mutie gets packaged for tomorrow\'s mutant dissection class.\" """ page = 41 more() def page40(): global page print """You breathe a sigh of relief as Plato-B-PHI%d picks on the other Troubleshooter.""" % plato_clone print """\"You down here in the front,\" says the instructor pointing at the other Troubleshooter, \"you\'ll make a good volunteer. Please step forward.\" The Troubleshooter looks around with a \`who me?\' expression on his face, but since he is the only one visible in the audience he figures his number is up. He walks down to the podium clutching his Action Troubleshooter(tm) doll before""" print """him like a weapon. \"Here,\" says Plato-B-PHI%d, \"take the mutant detection ray""" % plato_clone print """and point it at the audience. If there are any mutants out there we\'ll know soon enough.\" Suddenly your skin prickles with static electricity as a bright purple nimbus surrounds your body. \"Ha Ha, got one,\" says the instructor. \"Stun him before he gets away.\" """ more() while True: if dice_roll(1,100) <= 30: print "His shot hits you. You feel numb all over." page = 49 break else: print "His shot just missed." if dice_roll(1,100) <= 40: print "You just blew his head off. His lifeless hand drops the mutant detector ray." page = 50 break else: print "You burnt a hole in the podium. He sights the mutant detector ray on you." more() def page41(): global page print """You stumble down the hallway of the Troubleshooter Training Course looking for your next class. Up ahead you see one of the instructors waving to you. When you get there he shakes your hand and says, \"I am Jung-I-PSY. Welcome to the secret society infiltration seminar. I hope you ...\" You don\'t catch the rest of his greeting because you\'re paying too much attention to his handshake it is the strangest thing that has ever been done to your hand, sort of how it would feel if you put a neuro whip in a high energy palm massage unit. It doesn\'t take you long to learn what he is up to you feel him briefly shake your hand with the secret Illuminati handshake. """ choose(42,"You respond with the proper Illuminati code phrase, \"Ewige Blumenkraft\"",43,"You ignore this secret society contact") def page42(): global page print """\"Aha, so you are a member of the elitist Illuminati secret society,\" he says loudly, \"that is most interesting.\" He turns to the large class already seated in the auditorium and says, \"You see, class, by simply using the correct hand shake you can identify the member of any secret society. Please keep your weapons trained on him while I call a guard. """ choose(51,"You run for it",52,"You wait for the guard") def page43(): global page print """You sit through a long lecture on how to recognise and infiltrate secret societies, with an emphasis on mimicking secret handshakes. The basic theory, which you realise to be sound from your Iluminati training, is that with the proper handshake you can pass unnoticed in any secret society gathering. What\'s more, the proper handshake will open doors faster than an \'ultra shock\' plasma cannon. You are certain that with the information you learn here you will easily be promoted to the next level of your Illuminati secret society. The lecture continues for three hours, during which you have the opportunity to practice many different handshakes. Afterwards everyone is directed to attend the graduation ceremony. Before you must go you have a little time to talk to The Computer about, you know, certain topics. """ choose(44,"You go looking for a computer terminal",55,"You go to the graduation ceremony immediately") def page44(): global page global read_letter print """You walk down to a semi-secluded part of the training course complex and activate a computer terminal. \"AT YOUR SERVICE\" reads the computer screen. """ if read_letter==0: choose(23,"You register yourself as a mutant",55,"You change your mind and go to the graduation ceremony") return while True: print """\nSelect \'a\', \'b\' or \'c\' : a - You register yourself as a mutant. b - You want to chat about the commies. c - You change your mind and go to the graduation ceremony. """ choice = raw_input("Type choice and press to continue:") if choice == "a": page = 23 break elif choice == "b": page = 46 break elif choice == "c": page = 55 break def page45(): global page print """\"Hrank Hrank,\" snorts the alarm in your living quarters. Something is up. You look at the monitor above the bathroom mirror and see the message you have been waiting for all these years. \"ATTENTION TROUBLESHOOTER, YOU ARE BEING ACTIVATED. PLEASE REPORT IMMEDIATELY TO MISSION ASSIGNMENT ROOM A17/GAMMA/LB22. THANK YOU. THE COMPUTER IS YOUR FRIEND.\" When you arrive at mission assignment room A17-gamma/LB22 you are given your previous clone\'s remaining possessions and notebook. You puzzle through your predecessor\'s cryptic notes, managing to decipher enough to lead you to the tube station and the tube car to GDH7-beta. """ page = 10 more() def page46(): global page print """\"Why do you ask about the communists, Troubleshooter? It is not in the interest of your continued survival to be asking about such topics,\" says The Computer. """ choose(53,"You insist on talking about the communists",54,"You change the subject") def page47(): global page print """The Computer orders the entire Vulture squadron to terminate the Troubleshooter Training Course. Unfortunately you too are terminated for possessing classified information. Don\'t act so innocent, we both know that you are an Illuminatus which is in itself an act of treason. Don\'t look to me for sympathy. THE END """ page = 0 more() def page48(): global page print """The tubecar shoots forward as you enter, slamming you back into a pile of garbage. The front end rotates upward and you, the garbage and the garbage disposal car shoot straight up out of Alpha Complex. One of the last things you see is a small blue sphere slowly dwindling behind you. After you fail to report in, you will be assumed dead. """ new_clone(45) more() def page49(): global page print """The instructor drags your inert body into a specimen detainment cage. \"He\'ll make a good subject for tomorrow\'s mutant dissection class,\" you hear. """ new_clone(32) more() def page50(): global page global plato_clone print """You put down the other Troubleshooter, and then wisely decide to drill a few holes in the instructor as well the only good witness is a dead witness. You continue with the training course. """ plato_clone = plato_clone + 1 page = 41 more() def page51(): global page print """You run for it, but you don\'t run far. Three hundred strange and exotic weapons turn you into a freeze dried cloud of soot. """ new_clone(32) more() def page52(): global page print """You wisely wait until the instructor returns with a Blue Internal Security guard. The guard leads you to an Internal Security self incrimination station. """ page = 2 more() def page53(): global page print "You tell The Computer about:" choose(47,"The commies who have infiltrated the Troubleshooter Training Course\n and the impending People\'s Revolution",54,"Something less dangerous") def page54(): global page global blast_door print """\"Do not try to change the subject, Troubleshooter,\" says The Computer. \"It is a serious crime to ask about the communists. You will be terminated immediately. Thank you for your inquiry. The Computer is your friend.\" Steel bars drop to your left and right, trapping you here in the hallway. A spotlight beams from the computer console to brilliantly iiluminate you while the speaker above your head rapidly repeats \"Traitor, Traitor, Traitor.\" It doesn\'t take long for a few guards to notice your predicament and come to finish you off. """ if blast_door==0: new_clone(45) else: new_clone(32) more() def page55(): global page print """You and 300 other excited graduates are marched from the lecture hall and into a large auditorium for the graduation exercise. The auditorium is extravagantly decorated in the colours of the graduating class. Great red and green plasti-paper ribbons drape from the walls, while a huge sign reading \"Congratulations class of GDH7-beta-203.44/A\" hangs from the raised stage down front. Once everyone finds a seat the ceremony begins. Jung-I-PSY is the first to speak, \"Congratulations students, you have successfully survived the Troubleshooter Training Course. It always brings me great pride to address the graduating class, for I know, as I am sure you do too, that you are now qualified for the most perilous missions The Computer may select for you. The thanks is not owed to us of the teaching staff, but to all of you, who have persevered and graduated. Good luck and die trying.\" Then the instructor begins reading the names of the students who one by one walk to the front of the auditorium and receive their diplomas.""" more() print """Soon it is your turn, \"Philo-R-DMD, graduating a master of mutant identification and secret society infiltration.\" You walk up and receive your diploma from Plato-B-PHI%d, then return to your seat. There is another speech""" % plato_clone print """after the diplomas are handed out, but it is cut short by by rapid fire laser bursts from the high spirited graduating class. You are free to return to your barracks to wait, trained and fully qualified, for your next mission. You also get that cherished promotion from the Illuminati secret society. In a week you receive a detailed Training Course bill totalling 1,523 credits. THE END """ page = 0 more() def page56(): global page print """That familiar strange feeling of deja\'vu envelops you again. It is hard to say, but whatever is on the other side of the door does not seem to be intended for you. """ choose(33,"You open the door and step through",22,"You go looking for more information") def page57(): global page print """In the centre of the room is a table and a single chair. There is an Orange folder on the table top, but you can\'t make out the lettering on it. """ choose(11,"You sit down and read the folder",12,"You leave the room") def choose(apage,adesc,bpage,bdesc): global page while True: print "\nSelect \'a\' or \'b\' :\n" print " a - %s.\n b - %s." % (adesc, bdesc) choice = raw_input("Type choice and press to continue:") if choice == "a": page = apage break elif choice == "b": page = bpage break def dice_roll(num,sides): return reduce(lambda x,y,s=sides:x +random.randrange(s), range(num+1))+num def more(): waiting = raw_input("Press to continue:") if waiting =='p': character() more() def new_clone(resume): global page global clone global ultra_violet global action_doll global hit_points global killer_count print "\nClone %d just died." % clone clone = clone + 1 if clone > 6: print "\n*** You Lose ***\n\nAll your clones are dead. Your name has been stricken from the records.\n\n THE END\n" page = 0 else: print "Clone %d now activated." % clone ultra_violet=0 action_doll=0 hit_points=10 killer_count=0 page = resume def next_page(this_page): print "\n" if this_page == 0: page = 0 return elif this_page == 1: page1() return elif this_page == 2: page2() return elif this_page == 3: page3() return elif this_page == 4: page4() return elif this_page == 5: page5() return elif this_page == 6: page6() return elif this_page == 7: page7() return elif this_page == 8: page8() return elif this_page == 9: page9() return elif this_page == 10: page10() return elif this_page == 11: page11() return elif this_page == 12: page12() return elif this_page == 13: page13() return elif this_page == 14: page14() return elif this_page == 15: page15() return elif this_page == 16: page16() return elif this_page == 17: page17() return elif this_page == 18: page18() return elif this_page == 19: page19() return elif this_page == 20: page20() return elif this_page == 21: page21() return elif this_page == 22: page22() return elif this_page == 23: page23() return elif this_page == 24: page24() return elif this_page == 25: page25() return elif this_page == 26: page26() return elif this_page == 27: page27() return elif this_page == 28: page28() return elif this_page == 29: page29() return elif this_page == 30: page30() return elif this_page == 31: page31() return elif this_page == 32: page32() return elif this_page == 33: page33() return elif this_page == 34: page34() return elif this_page == 35: page35() return elif this_page == 36: page36() return elif this_page == 37: page37() return elif this_page == 38: page38() return elif this_page == 39: page39() return elif this_page == 40: page40() return elif this_page == 41: page41() return elif this_page == 42: page42() return elif this_page == 43: page43() return elif this_page == 44: page44() return elif this_page == 45: page45() return elif this_page == 46: page46() return elif this_page == 47: page47() return elif this_page == 48: page48() return elif this_page == 49: page49() return elif this_page == 50: page50() return elif this_page == 51: page51() return elif this_page == 52: page52() return elif this_page == 53: page53() return elif this_page == 54: page54() return elif this_page == 55: page55() return elif this_page == 56: page56() return elif this_page == 57: page57() return page = 0 def main(args): '''Main Game Execution''' usage = "usage: %prog [options]" version = "%prog 1.2" parser = OptionParser(usage=usage, version=version) (options, args) = parser.parse_args() instructions() more() character() more() while page != 0: old_page = page next_page(page) print "-"*79 if __name__ == '__main__': main(sys.argv[1:]) From claird at lairds.us Sat Jan 29 12:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Sat, 29 Jan 2005 17:08:04 GMT Subject: Coding style article with interesting section on white space References: <1107010389.441457.51350@z14g2000cwz.googlegroups.com> Message-ID: <8gssc2-dcb.ln1@lairds.us> In article <1107010389.441457.51350 at z14g2000cwz.googlegroups.com>, wrote: . . . >One ought to do a little research before publishing an article. >Apparently, many authors and editors are too lazy to do so. > ... and/or ignorant or uncultured. Also, don't forget to excoriate the publishers and editors, too cheap and/or otherwise constrained to edit/fact-check/review/... From fBechmann at web.de Wed Jan 26 09:00:57 2005 From: fBechmann at web.de (Frank Bechmann (w)) Date: Wed, 26 Jan 2005 06:00:57 -0800 Subject: python without OO In-Reply-To: <41f6f4ee$1@nntp.zianet.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <41f6f4ee$1@nntp.zianet.com> Message-ID: even if I follow the other answers above - language-wise and management-advise-wise - just for the sake of completeness - I would like to point you to Lua: http://www.lua.org/ 1. portability (interpreter runs quite a bit architectures) => yes, nearly pure ANSI-C should compile 2. good basic library (already there) => you might have to collect some additional libraries and add them to the core language, so currently not the strongest part, but typical file handling is possible (at least w/ luafilesystem module) 3. modules for structuring the application (objects unnecessary) => yes, starting w/ current in-work release 4. high-level data structures (dictionaries & lists) => just one that combines both dictionary and list 5. no strong static type checking => yes 6. very nice syntax => little bit more "classic" than Python by using 'then ..end' and the like, as long as you don't exploit the built-in flexibility of Lua it is very easy to be read and written. know what's funny: in the Lua mailing list there is currently a discussion about adding OO to Lua. From nick at craig-wood.com Mon Jan 24 01:46:18 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 24 Jan 2005 06:46:18 GMT Subject: best way to do a series of regexp checks with groups References: Message-ID: Mark Fanty wrote: > In perl, I might do (made up example just to illustrate the point): > > if(/add (\d+) (\d+)/) { > do_add($1, $2); > } elsif (/mult (\d+) (\d+)/) { > do_mult($1,$2); > } elsif(/help (\w+)/) { > show_help($1); > } There was a thread about this recently under the title "regular expression: perl ==> python" Here is a different solution... class Result: def set(self, value): self.value = value return value m = Result() if m.set(re.search(r'add (\d+) (\d+)', line)): do_add(m.value.group(1), m.value.group(2)) elif m.set(re.search(r'mult (\d+) (\d+)', line)): do_mult(m.value.group(1), m.value.group(2)) elif m.set(re.search(r'help (\w+)', line)): show_help(m.value.group(1)) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From Scott.Daniels at Acm.Org Wed Jan 12 10:13:07 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 12 Jan 2005 07:13:07 -0800 Subject: Python & unicode In-Reply-To: <41E4FB91.2000106@draigBrady.com> References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <41e41633$1@nntp0.pdx.net> <41E4FB91.2000106@draigBrady.com> Message-ID: <41e53b95$1@nntp0.pdx.net> P at draigBrady.com wrote: > Scott David Daniels wrote: >> If you allow >> non-ASCII characters in symbol names, your source code will be >> unviewable (and uneditable) for people with ASCII-only terminals, >> never mind how comprehensible it might otherwise be. > > So how does one edit non ascii string literals at the moment? Generally by using editors that leave bytes alone if they cannot be understood. For many applications where I'll work on a program, I don't need to read the strings, but rather the code that uses those strings. I am at a disadvantage if I cannot understand the derivation of the names, no doubt, but at least I know when two letters are different, and what tokens are distinct. > If one edited the whole file in the specified coding > then one wouldn't have to switch editing modes when > editing strings which is a real pain. > No question, but ASCII is available as a subset for many encodings. As you might note, my conception is that I might be helping on a program with many programmers. Python spent a lot of effort to avoid favoring a character set as much as possible, while still being a medium for sharing code. --Scott David Daniels Scott.Daniels at Acm.Org From python at hope.cz Fri Jan 28 15:14:27 2005 From: python at hope.cz (python at hope.cz) Date: 28 Jan 2005 12:14:27 -0800 Subject: How to post news articles with NNTPlib In-Reply-To: <41fa577c$0$25809$8fcfb975@news.wanadoo.fr> References: <1106911698.786860.109450@z14g2000cwz.googlegroups.com> <41fa577c$0$25809$8fcfb975@news.wanadoo.fr> Message-ID: <1106943267.844980.16190@c13g2000cwb.googlegroups.com> Do Re Mi chel La Si Do wrote: > Hi ! > > > nntplib.NNTP(newsserver,port,user,passe) > > > > -- > Michel Claveau Thank you From cwilbur at mithril.chromatico.net Thu Jan 13 18:59:30 2005 From: cwilbur at mithril.chromatico.net (Charlton Wilbur) Date: Thu, 13 Jan 2005 23:59:30 GMT Subject: [perl-python] 20050112 while statement References: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> Message-ID: <87fz14q45j.fsf@mithril.chromatico.net> >>>>> "b" == brianr writes: b> (As a matter of interest, is this sequence of posts intended to b> demonstrate ignorance of both languages, or just one?) Intentional fallacy -- there's no necessary correlation between what he *intends* to do and what he actually succeeds at doing. As noted, Xah *intends* to use his expertise in Perl to teach Python to others. All he's succeeding in doing is demonstrating his incompetence at both. As for myself, I suspect it's just a cunning approach to Let's You And Him Fight. Charlton -- cwilbur at chromatico dot net cwilbur at mac dot com From http Mon Jan 31 19:23:19 2005 From: http (Paul Rubin) Date: 31 Jan 2005 16:23:19 -0800 Subject: Java Integer.ParseInt translation to python References: Message-ID: <7xfz0hi0w8.fsf@ruckus.brouhaha.com> "jose isaias cabrera" writes: > I've looked through the internet (not long, though) but I have not > been able to find a python translation to > > buffer[0] = (byte)Integer.parseInt(string,16); > > Has anyone ported any java programs to python and has translated this? I think the Python equivalent would be: buffer[0] = chr(int(string, 16)) That is, you're trying to convert two hex digits into a single char, right? From mail at tuxipuxi.org Sun Jan 23 08:30:33 2005 From: mail at tuxipuxi.org (Michael Goettsche) Date: Sun, 23 Jan 2005 14:30:33 +0100 Subject: Alternative Ways to install Python 2.4? Message-ID: <200501231430.33849.mail@tuxipuxi.org> Hello guys, I convinced my CS teacher to use Python in school. We currently have 2.2 installed on a Windows 2000 Terminal server. I asked the system administrator to upgrade to Python 2.4, but he didn't succeed in doing it. He used the microsoft installer package, which according to him crashed when starting. So my question is if there's an alternative way to install it(must be easy). Would it be an option to remove 2.2 first and then try to install 2.4 again? Sorry for asking, but he doesn't have so much time and I've to install it tomorrow. Thanks in advance Michael From beliavsky at aol.com Fri Jan 7 16:17:48 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 7 Jan 2005 13:17:48 -0800 Subject: DOS problem (simple fix??) References: Message-ID: <1105132668.495532.256850@f14g2000cwb.googlegroups.com> When I have a Python script generating a lot of output, I either open an output file and then print to it with fp = open("results.txt","w") print>>fp,"stuff" or I redirect output to a file from the command line using ">" (also works on Unix), for example python foo.py > results.txt An alternative is to open a shell buffer within Emacs or XEmacs, two text editors with Python modes. You can run a Python script from within the shell buffer, and the results will be printed there. You can move around the shell buffer as if it were a file. From mr_chan at uclink.berkeley.edu Mon Jan 17 04:04:46 2005 From: mr_chan at uclink.berkeley.edu (Steven Chan) Date: 17 Jan 2005 01:04:46 -0800 Subject: what would you like to see in a 2nd edition Nutshell? In-Reply-To: References: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> <1gpkxzx.fu7ild1r7602uN%aleaxit@yahoo.com> <200412301319.10987.drlinux@columbus.rr.com> Message-ID: <1105952686.436008.132990@z14g2000cwz.googlegroups.com> I completely agree. I'm also waiting for an advanced Python/project management book that helps folks out with large-scale projects. And, for the 2nd edition, may I suggest: - coverage of OptionParser module, which is more advanced than the getopt module that you discuss on page 141. - better Mac OS X application building coverage. Tell us how to build double-clickable applications. I wish I could ask for wxPython coverage (the whole chapter on tkinter is useless to me), but I won't start a flame war here. :: steve :: Mariano Draghi wrote: > Alex Martelli escribi?: > > > > Yes, good point... I _do_ plan another book after I'm done with the 2nd > > ed Nutshell, though ti will mostly be about Design Patterns and > > development methods so may not meet your exact desires... > > Now I'm anxious! *that* is the book I'm waiting for :) > I think the Python community really needs such a book; you have plenty > of books and articles and papers and resources on-line with (almost) all > the bits & pieces. But I really miss a book that focuses in the > "Pythonic way" of project management, design patterns, development > cycles, QA... something targeted to the enterprise. From peter at engcorp.com Sat Jan 29 12:03:30 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 29 Jan 2005 12:03:30 -0500 Subject: future of computing languages In-Reply-To: <1107003465.707681.161950@f14g2000cwb.googlegroups.com> References: <1107003465.707681.161950@f14g2000cwb.googlegroups.com> Message-ID: jelle wrote: > Quite suprised while reading the Amazin c2.com Wiki: > > http://c2.com/cgi/wiki?FutureOfProgrammingLanguages > > Take a look, and feel incredible good about yourself & your decision to > opt for python. Did work for me. Cheers, Jelle. Sorry, but it's an annoyingly long page filled with what appear to be a random collection of wild predictions about the future, and Python is barely mentioned in any case. Perhaps you could take the time to write a little about just *what* you found so "Amazin"... -Peter From FBatista at uniFON.com.ar Mon Jan 3 10:44:36 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 3 Jan 2005 12:44:36 -0300 Subject: Compiler benefits (was: The Industry choice) Message-ID: [claird at lairds.us] #- I think your point was that the checking present in modern Fortran #- compilers, or PyCheckers, but absent from core Python, is a net #- benefit. That I grant. I'm reluctant to argue for a change in #- Python. I personally prefer to urge PyChecker on developers. Cameron, I agreed 100% percent with you. But I think that PyChecker should be distributed with Python, but in an external module, as everybody has easy access to it. This, added to an official evangelization towards it, should eliminate a big percentage of claims about not-static-Python. . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bokr at oz.net Tue Jan 4 06:46:43 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 04 Jan 2005 11:46:43 GMT Subject: Lambda as declarative idiom (was RE: what is lambda used for in real code?) References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> Message-ID: <41da41d1.1835252503@news.oz.net> On Mon, 03 Jan 2005 18:54:06 GMT, Steven Bethard wrote: >Roman Suzi wrote: >> I wish lambdas will not be deprecated in Python but the key to that is >> dropping the keyword (lambda). If anybody could think of a better syntax for >> lambdas _with_ arguments, we could develop PEP 312 further. > >Some suggestions from recent lambda threads (I only considered the ones >that keep lambda as an expression): > Just for reference, am I correct in assuming these are the equivalent uses of lambda?: lambda a, b, c:f(a) + o(b) - o(c) lambda x: x * x lambda : x lambda *a, **k: x.bar(*a, **k) (lambda : x(*a, **k)) for x, a, k in funcs_and_args_list) That last seems like it might need the default-arg-value hack: i.e., (lambda x=x, a=a, k=k: x(*a, **k)) for x, a, k in funcs_and_args_list) >***** Args Before Expression ***** > >Nick Coghlan: def-to syntax [1] >(def (a, b, c) to f(a) + o(b) - o(c)) >(def (x) to x * x) >(def () to x) >(def (*a, **k) to x.bar(*a, **k)) >((def () to x(*a, **k)) for x, a, k in funcs_and_args_list) > >Nick Coghlan: def-arrow syntax [1] >(def (a, b, c) -> f(a) + o(b) - o(c)) >(def (x) -> x * x) >(def () -> x) >(def (*a, **k) -> x.bar(*a, **k)) >((def () -> x(*a, **k)) for x, a, k in funcs_and_args_list) > >Alex Martelli: def-as syntax [2] >(def (a, b, c) as f(a) + o(b) - o(c)) >(def (x) as x * x) >(def () as x) >(def (*a, **k) as x.bar(*a, **k)) >((def () as x(*a, **k)) for x, a, k in funcs_and_args_list) > >Dave Benjamin: fun syntax [7] >(fun(a, b, c): f(a) + o(b) - o(c)) >(fun(x): x * x) >(fun(): x) >(fun(*a, **k): x.bar(*a, **k)) >((fun(): x(*a, **k)) for x, a, k in funcs_and_args_list) > > >***** Expression Before Args ***** > >Robert Brewer: for (no-parens) syntax [3] >(f(a) + o(b) - o(c) for a, b, c) >(x * x for x) >(x for ()) >(x.bar(*a, **k) for *a, **k) >((x(*a, **k) for ()) for x, a, k in funcs_and_args_list) > >Nick Coghlan: for syntax [6] >(f(a) + o(b) - o(c) for (a, b, c)) >(x * x for (x)) >(x for ()) >(x.bar(*a, **k) for (*a, **k)) >((x(*a, **k) for ()) for x, a, k in funcs_and_args_list) > >Nick Coghlan: def-from syntax [4] >(def f(a) + o(b) - o(c) from (a, b, c)) >(def x * x from (x)) >(def x from ()) >(def x.bar(*a, **k) from (*a, **k)) >((def x(*a, **k) from ()) for x, a, k in funcs_and_args_list) > >Michael Spencer: from-args syntax [5] >(f(a) + o(b) - o(c) from args(a, b, c)) >(x * x from args(x)) >(x from args()) >(x.bar(*a, **k) from args(*a, **k)) >((x(*a, **k) from args()) for x, a, k in funcs_and_args_list) > >Michael Spencer: for-args syntax [5] >(f(a) + o(b) - o(c) for args(a, b, c)) >(x * x for args(x)) >(x for args()) >(x.bar(*a, **k) for args(*a, **k)) >((x(*a, **k) for args()) for x, a, k in funcs_and_args_list) > > >So there's a bunch of ideas out there. I don't know if any of them >could be overwhelmingly preferred over lambda. Just thought of another, more concise and keywordless, expression-before-args syntax: (:expression)(formalparams) # equivalent to lambda formalparams:expression (:f(a) + o(b) - o(c))(a, b, c) (:x*x)(X) (:x)() (:x.bar(*a, **k))(*a, **k) ((:x(*a, **k)() for x, a, k in funcs_and_args_list) and with args default hack: ((:x(*a, **k)(x=x, a=a, k=k) for x, a, k in funcs_and_args_list) I would have proposed (expression)(formalparams), but that is already legal ;-) > >Personally, I lean slightly towards the def-from syntax because it uses >the 'def' keyword to bring your attention to the fact that a function is >being defined, and it gives the expression precedence over the arglist, >which makes sense to me for an anonymous function, where (IMHO) the >expression is really the most important part of the declaration. The syntax above panders to that ;-) > >OTOH, I think Michael Spencer's args() function, if implementable, could >have a lot of cool uses, like getting the arguments passed to next >within a generator. (See the thread about that[8].) > Actually, I would rather have seen the function interface itself used for that, and not have a scan for yields magically convert the normal function calling interface to a generator factory interface. But we are past that, unless we invent something new. E.g. if functions had an f.multicall() factory function that would return a generator "next" function with the same interface as f but starting code execution at the start the first time, and after yields on subsequent calls, then we could write def f(x): yield x+2 yield x*2 g = f.multicall() # not currently available [g(n) for n in (2,5)] and get (untested) [4, 10] instead of as now having to write something like >>> def f(x): ... yield x[0]+2 ... yield x[0]*2 ... >>> x = ['ignored'] >>> g = f(x).next >>> [g() for x[0] in (2,5)] [4, 10] or wrapping with something more sugary. > >Steve > >[1]http://mail.python.org/pipermail/python-list/2004-December/256859.html >[2]http://mail.python.org/pipermail/python-list/2004-December/256881.html >[3]http://mail.python.org/pipermail/python-list/2004-December/257023.html >[4]http://boredomandlaziness.skystorm.net/2004/12/anonymous-functions-in-python.html >[5]http://mail.python.org/pipermail/python-list/2004-December/257893.html >[6]http://mail.python.org/pipermail/python-list/2004-December/257977.html >[7]http://mail.python.org/pipermail/python-list/2005-January/258441.html >[8]http://mail.python.org/pipermail/python-list/2005-January/258238.html Regards, Bengt Richter From ncoghlan at iinet.net.au Mon Jan 17 06:55:00 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 17 Jan 2005 21:55:00 +1000 Subject: [perl-python] 20050117, filter, map In-Reply-To: <41EBA23A.2010005@holdenweb.com> References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> <41EBA23A.2010005@holdenweb.com> Message-ID: <41EBA794.5070706@iinet.net.au> Steve Holden wrote: > As I may have mentioned before, egotism can be the only possible reason. I'd merely figured it as a textbook case of trolling - attention seeking behaviour, most likely indicative of a lack of self-esteem, rather than the reverse. Still, he does at least keep the [perl-python] mailing list tag, so automatic filtering isn't that difficult. It is an unfortunate shame that his consideration doesn't extend to removing the general Perl and Python discussion groups from his recipients list. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From EP at zomething.com Wed Jan 5 03:36:52 2005 From: EP at zomething.com (EP) Date: Wed, 5 Jan 2005 00:36:52 -0800 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbr7.1otvj5mkq1l96N%aleaxit@yahoo.com> Message-ID: <20050105003652.46489693.EP@zomething.com> Bulba! wrote: > Frankly, I find such models to be built on over-stretched analogies > to physics - how _exactly_ is gravity supposed to be an analogy > equivalent to economic "forces"? Sure such model can be built - but > is it adequate in explaining real-world phenomenons? Analogy > tends to be the weakest form of reasoning. I'd be wary of making > such analogies. Apparently the Gravity Model is still of some interest, if recent citations are an indication. I'm not an expert, but all the economic models I was taught were also grounded in math, not just analogy. gravity models: http://faculty.washington.edu/krumme/systems/gravity.html some empirical studies: http://www.hec.unil.ch/mbrulhar/Empirtrade/#gravity > Models like this probably tend to be built by French engineers from > this joke: > > The American and French engineers work together on some > product (that would look strange nowadays but it's not impossible > in principle). > > The Americans show the French engineers a working prototype. > > The French engineers scratch their heads and ask warily: > > "OK, it works in practice; but will it work in theory?" > Yeah, I hate it when people try to understand things. cheers From FBatista at uniFON.com.ar Mon Jan 10 16:18:11 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 10 Jan 2005 18:18:11 -0300 Subject: Writing huge Sets() to disk Message-ID: [Istvan Albert] #- I think that you need to first understand how dictionaries work. #- The time needed to insert a key is independent of #- the number of values in the dictionary. Are you sure? I think that is true while the hashes don't collide. If you have collisions, time starts to depend of element quantity. But I'm not sure Tim sure can enlighten us. Asking-for-god-word--ly yours, . Facundo Bitcora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ianb at colorstudy.com Wed Jan 12 03:38:02 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Wed, 12 Jan 2005 02:38:02 -0600 Subject: The best way to do web apps with Python? In-Reply-To: <7xd5wezzmd.fsf@ruckus.brouhaha.com> References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41E02FD5.5080703@holdenweb.com> <7xd5wezzmd.fsf@ruckus.brouhaha.com> Message-ID: <41E4E1EA.4050306@colorstudy.com> Paul Rubin wrote: > Steve Holden writes: > >>You can read about it in Philip Eby's excellent PEP at >> >> http://www.python.org/peps/pep-0333.html > > > I looked at this and I have the impression that it tries to do > something worthwhile, but I can't tell precisely what. The "rationale > and goals" section explains good reasons why it doesn't do various > certain things. What's not explained is what DOES it do. The only > thing I can tell is that it connects to an abstracted web server, and > builds up what looks like traditional CGI variables from the incoming > requests. It's really meant for web framework developers (as opposed to web application developers, who use web frameworks). Of course it's a fuzzy line, and people cross back and forth, especially since most all of it is open source. So basically it is what you were thinking -- it's a way to connect a web server to a web application, for any server or application, including current servers and applications (not just ones that are developed in the future). It can be a bit more interesting when you delve into middleware, which are programs that modify the request before handing it off to another application. But while that opens up interesting possibilities (I've used that technique a fair amount in WSGIKit: http://svn.colorstudy.com/trunk/WSGIKit/ ), but it's not incredibly magical. Mostly, it's the first forward movement we've had in a very long time, even if the movement isn't huge. It provides a foundation for further standardization. WSGI compliance also has some other potential benefits, like encouraging environment decoupling, and making mock requests easier to produce and responses easier to consume. But those are somewhat vague side effects. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From bwobbones at gmail.com Sun Jan 16 09:08:13 2005 From: bwobbones at gmail.com (bwobbones) Date: Sun, 16 Jan 2005 22:08:13 +0800 Subject: Newbie inheritance question. Message-ID: <41EA754D.8020307@gmail.com> Hi all, I'm a java programmer struggling to come to terms with python - bear with me! I'm trying to subclass a class, and I want to be able to see it's attributes also. Here are my classes: one.py: ***************************** class one: def __init__(self): print "one" self.testVar = 1 def printHello(self): print "hello" ***************************** two.py ***************************** from one import one class two(one): def __init__(self): print "two" def printTestVar(self): print "testVar: " + str(self.testVar) ***************************** and the driver to make it work: ***************************** from two import two class driver: def go(self): print "driver" self.two = two() self.two.printHello() self.two.printTestVar() if __name__ == '__main__': d = driver() d.go() ***************************** the "self.two.printTestVar()" call doesn't work: shouldn't two.py have access to all of it's parents attributes? In java I would make the testVar protected so it's children could see it. How do I do this in python? Thanks, Bones From deetsNOSPAM at web.de Tue Jan 18 08:18:21 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 18 Jan 2005 14:18:21 +0100 Subject: generator expressions: performance anomaly? References: <377Hd.77904$Jk5.30235@lakeread01> Message-ID: <354gj7F4etgn8U1@individual.net> > lst = list(genexp) > tpl = tuple(genexp) > > > Since in such cases the object is build in memory any way, I don't > think it would be a problem of having them prebuilt in memory, or am > I missing something? Yes. Consider this: lst = list(time.time() for i in xrange(10)) tpl = tuple(time.time() for i in xrange(10)) -- Regards, Diez B. Roggisch From humblythegreatest at usa.com Tue Jan 11 21:06:09 2005 From: humblythegreatest at usa.com (humblythegreatest at usa.com) Date: 11 Jan 2005 18:06:09 -0800 Subject: Python.org, Website of Satan Message-ID: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> python.org = 194.109.137.226 194 + 109 + 137 + 226 = 666 What is this website with such a demonic name and IP address? What evils are the programmers who use this language up to? From fredrik at pythonware.com Thu Jan 13 18:08:42 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 14 Jan 2005 00:08:42 +0100 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com><7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Huh? Expressions are not statements except when they're "expression > statements"? What kind of expression is not an expression statement? any expression that is used in a content that is not an expression statement, of course. reading the python language reference should help you sort this one out. From http Sat Jan 29 10:23:51 2005 From: http (Paul Rubin) Date: 29 Jan 2005 07:23:51 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> Message-ID: <7xvf9gqmwo.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > And one that deals with cryptography is likely to be even more complex. No. The AES module would have about the same complexity as the SHA module. From godoy at ieee.org Fri Jan 7 07:53:29 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Fri, 07 Jan 2005 10:53:29 -0200 Subject: get the IP address of a host References: <1104941334.814311.198610@z14g2000cwz.googlegroups.com> Message-ID: <1421333.HULXvHczR4@strongwill.g2ctech> Kartic, Quarta 05 Janeiro 2005 14:08, wrote: > socket.gethostbyaddr(socket.gethostname()) > > will return a tuple containing fully qualified hostname, alternative > hostnames, ip addresses (>1 if multihomed). > > or > > socket.gethostbyname(socket.gethostname()) None of these work with computers with more than one interface... They get only one of them. It would be safer, then, to specify the desired interface or use an alternative method. -- Godoy. From beliavsky at aol.com Wed Jan 26 22:55:40 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 26 Jan 2005 19:55:40 -0800 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> Message-ID: <1106798140.896125.187850@f14g2000cwb.googlegroups.com> John Hunter wrote: > >>>>> "Davor" == Davor writes: > > Davor> not really - it was not my intention at all - but it seems > Davor> people get upset whenever this OO stuff is mentioned - and > Davor> what I did not expect at all at this forum as I believed > Davor> Python people should not be so OO hardcore (seems not all > Davor> as quite a few have indicated in their > Davor> replies)... Nevertheless, I think the discussion has > Davor> several quite good points! -- > Davor> http://mail.python.org/mailman/listinfo/python-list > > Consider the case of a list, say > > x = [1,2,3,4] > > suppose you wanted to reverse the list, so that x becomes [4,3,2,1]. > In a procedural language, one might do > > x = reverse(x) > > In an OO language such as python, one might do > > x.reverse() > > Is the OO way more obscure and complicated, etc? Not really -- it's > only a minor syntactical difference. One of the core ideas behind OO > programming is that data (the contents of the list 1,2,3,4) and > methods (sorting, reversing) are bound together into a single entity, > the object. On the face of it, this is rather sensible. I think the OO way is slightly more obscure. It's obvious what x = reverse(x) does, but it is not clear unless you have the source code whether x.reverse() reverses x or if it returns a reversed list. If x.reverse() does the former, a disadvantage relative to the procedural approach is that a function can be used in an expression. It is clearer and more concise to write z = reverse(x) + reverse(y) than x.reverse() y.reverse() z = x + y Furthermore, if in Python the algorithm for the reverse function applies to many kinds of objects, it just needs to be coded once, whereas a reverse method would have to provided for each class that uses it (perhaps through inheritance). From reinhold-birkenfeld-nospam at wolke7.net Sat Jan 15 02:39:22 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 15 Jan 2005 08:39:22 +0100 Subject: [perl-python] 20050114 if statement In-Reply-To: <1105760081.771782.140700@f14g2000cwb.googlegroups.com> References: <1105760081.771782.140700@f14g2000cwb.googlegroups.com> Message-ID: <34rvlaF4f6l70U2@individual.net> Xah Lee wrote: > . # here's an example of if statement in python. > . > . x=-1 > . if x<0: > . print 'neg' > . elif x==0: > . print 'zero' > . elif x==1: > . print 'one' > . else: > . print 'other' > . > . # the elif can be omitted. > . ------------------------------ > . # here's an example of if statement in perl > . > . $x=31; > . if ($x<0) { > . print 'neg' > . } elsif ($x==0) { > . print 'zero' > . } elsif ($x==1) { > . print 'one' > . } else { > . print 'other' > . } Note that Perl's print doesn't append a newline to the printed string. Reinhold From peter at engcorp.com Wed Jan 12 12:57:42 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 Jan 2005 12:57:42 -0500 Subject: Why would I get a TypeEror? In-Reply-To: References: Message-ID: It's me wrote: > For this code snip: > > a=3 > .... > b=(1,len(a))[isinstance(a,(list,tuple,dict))] > > Why would I get a TypeError from the len function? What did you expect the "length" of the integer 3 to be? -Peter From maneeshsingh82 at gmail.com Tue Jan 4 05:56:25 2005 From: maneeshsingh82 at gmail.com (Maneesh) Date: 4 Jan 2005 02:56:25 -0800 Subject: Problem with Python module Message-ID: <708a3735.0501040256.2111009e@posting.google.com> Hi, I want to connect to a remote MS SQL Server 2000 database through my Fedora Core 2 machine via Python scripts. I have successfully installed freetds & unixODBC and can now connect to the desired DB through tsql(freetds) & isql(unixODBC). I installed mxODBC (RPM & source) to be able to connect to the DB via Python scripts without any success. The code(db3.py) under test is as follows: ---------------------------------------------- #!/usr/bin/python2.3 import mx.ODBC.unixODBC dsn="ps0196" conn=mx.ODBC.unixODBC.Connect (dsn, "maneesh_singh", "newuser") print "Content-Type: text/plain" print cursorhandle=conn.cursor() print "MySQL Databse via mxODBC....\n" cursorhandle.execute("select * from tb_mis_team") for i in cursorhandle.fetchall(): print i print cursorhandle.fetchall() for i in cursorhandle.fetchall(): print i ---------------------------------------------- The output is as follows: ---------------------------------------------- [root at ps0778 cgi-bin]# python db3.py Traceback (most recent call last): File "db3.py", line 4, in ? import mx.ODBC.unixODBC File "/usr/lib/python2.3/site-packages/mx/ODBC/unixODBC/__init__.py", line 8, in ? from mxODBC import * ImportError: libiodbcinst.so.2: cannot open shared object file: No such file or directory ---------------------------------------------- Additional info: ---------------------------------------------- [root at ps0778 unixODBC]# pwd /usr/lib/python2.3/site-packages/mx/ODBC/unixODBC [root at ps0778 unixODBC]# ldd ./mxODBC.so linux-gate.so.1 => (0x0070b000) libodbc.so.1 => /usr/lib/libodbc.so.1 (0x00b26000) libpthread.so.0 => /lib/tls/libpthread.so.0 (0x007ca000) libc.so.6 => /lib/tls/libc.so.6 (0x00eaa000) libiodbcinst.so.2 => not found libdl.so.2 => /lib/libdl.so.2 (0x006b2000) /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x0089d000) ----------------------------------------------- I want to use unixODBC and not iODBC, why is mxODBC looking for iODBC's libraray? I had earlier tried to install iODBC, unsuccessfully, hence shifted over to unixODBC. The missing iODBC library exist in /usr/local/lib folder. Do I need to link the iODBC library to mxODBC during installation? How? Configure setup.in in the source setup? Thanks! Maneesh. From fredrik at pythonware.com Thu Jan 20 14:48:46 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jan 2005 20:48:46 +0100 Subject: building extensions: ming & python mathlink for win32 References: <20050120193521.37C7A2800129@mwinf1007.wanadoo.fr> Message-ID: Jelle Feringa wrote: > What struck me while trying to compile is that instead of the Active Python > 2.4 version I was running I downloaded and installed the python.org version > (as recommended by Fletcher), and while launching it, I stated > > ActivePython 2.4 Build 243 (ActiveState Corp.) based on Python 2.4 > > HUH! WHAT! No actual difference between the python.org & activestate > version??? the python.org version I have says: Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 From jack at performancedrivers.com Wed Jan 26 14:17:20 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 26 Jan 2005 14:17:20 -0500 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: <_IadnVdKPJhrTGrcRVn-uA@comcast.com> References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> Message-ID: <20050126191720.GK1607@performancedrivers.com> On Wed, Jan 26, 2005 at 10:23:03AM -0700, Steven Bethard wrote: > Jack Diederich wrote: > >Yes, this comes up every couple months and there is only one answer: > >This is the job of the OS. > >Java largely succeeds at doing sandboxy things because it was written that > >way from the ground up (to behave both like a program interpreter and an > >OS). > >Python the language was not, and the CPython interpreter definitely was > >not. > > > >Search groups.google.com for previous discussions of this on c.l.py > > Could you give some useful queries? Every time I do this search, I get > a few results, but never anything that really goes into the security > holes in any depth. (They're ususally something like -- "look, given > object, I can get int" not "look, given object, I can get eval, > __import__, etc.) A search on "rexec bastion" will give you most of the threads, search on "rexec bastion diederich" to see the other times I tried to stop the threads by reccomending reading the older ones *wink*. Thread subjects: Replacement for rexec/Bastion? Creating a capabilities-based restricted execution system Embedding Python in Python killing thread ? -Jack From premshree.pillai at gmail.com Sat Jan 1 07:37:42 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Sat, 1 Jan 2005 18:07:42 +0530 Subject: Complementary language? In-Reply-To: References: Message-ID: On Sat, 1 Jan 2005 09:35:32 +0000 (UTC), Alan Gauld wrote: > On Sat, 25 Dec 2004 18:40:31 -0500, HackingYodel > wrote: > > Hello all! I'm learning to program at home. I can't imagine a better > > language than Python for this. The ideal situation, for me, would be to > > study two languages at the same time. Probably sounds crazy, but it > > works out better for me. Yes, the best way to learn a new language is probably to compare it with some other language (of the same paradigm) that you are already familiar with. The best part about Python is that there really isn't much "learning" involved. Python comes closest to what you'd call "pseudocode". If you know your English, you probably know Python. :D > > Me too, thats why my web tutorial features Python, VBSCript and > Javascript. (The previous version had BASIC and Tcl with Python) > > > fascinating. C, D, Objective-C, Ocaml, C++, Lisp, how is a non-tech to > > choose? Does any single language do a better job in Python's weaker > > areas? > > C is better at low level stuff, Prolog is better at declaratie > programming and Haskell is better at functional programming. > Lisp/Scheme are good for giving a good theoretical understanding > (try the SICP and HTDP web sites). And Tcl has a really different > approach which is plain fun to grapple with :-) > > I chose VBScript and JavaScript because they have similar > structure to Python (traditional imperative programming > with OOP) but very different syntax. Plus they were free and > easily available (albeit with VBScript limited to Windows > users, who are 80+% of my visitors). Javascript is especially > useful since its an easy lead in to learning C/C++, Java, > even Perl to some extent and a lot of sample code sites > use those languages. > > Alan G. > Author of the Learn to Program website > http://www.freenetpages.co.uk/hp/alan.gauld > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From fredrik at pythonware.com Sun Jan 23 11:14:25 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 17:14:25 +0100 Subject: compile python to binary References: <1d6cdae3050123080242bf8994@mail.gmail.com> Message-ID: Daniel Bickett wrote: > I believe Sam was talking about "frozen" python scripts using tools > such as py2exe: oh, you mean that "python compiler" didn't mean "the python compiler". here are links to some more tools, btw: http://effbot.org/zone/python-compile.htm From sjmachin at lexicon.net Tue Jan 25 16:54:18 2005 From: sjmachin at lexicon.net (John Machin) Date: 25 Jan 2005 13:54:18 -0800 Subject: Browsing text ; Python the right tool? References: Message-ID: <1106690058.282403.270720@f14g2000cwb.googlegroups.com> Paul Kooistra wrote: > I need a tool to browse text files with a size of 10-20 Mb. These > files have a fixed record length of 800 bytes (CR/LF), and containt > records used to create printed pages by an external company. > > Each line (record) contains an 2-character identifier, like 'A0' or > 'C1'. The identifier identifies the record format for the line, > thereby allowing different record formats to be used in a textfile. > For example: > > An A0 record may consist of: > recordnumber [1:4] > name [5:25] > filler [26:800] 1. Python syntax calls these [0:4], [4:25], etc. One has to get into the habit of deducting 1 from the start column position given in a document. 2. So where's the "A0"? Are the records really 804 bytes wide -- "A0" plus the above plus CR LF? What is "recordnumber" -- can't be a line number (4 digits -> max 10k; 10k * 800 -> only 8Mb); looks too small to be a customer identifier; is it the key to a mapping that produces "A0", "C1", etc? > > while a C1 record consists of: > recordnumber [1:4] > phonenumber [5:15] > zipcode [16:20] > filler [21:800] > > As you see, all records have a fixed column format. I would like to > build a utility which allows me (in a windows environment) to open a > textfile and browse through the records (ideally with a search > option), where each recordtype is displayed according to its > recordformat ('Attributename: Value' format). This would mean that > browsing from a A0 to C1 record results in a different list of > attributes + values on the screen, allowing me to analyze the data > generated a lot easier then I do now, browsing in a text editor with a > stack of printed record formats at hand. > > This is of course quite a common way of encoding data in textfiles. > I've tried to find a generic text-based browser which allows me to do > just this, but cannot find anything. Enter Python; I know the language > by name, I know it handles text just fine, but I am not really > interested in learning Python just now, I just need a tool to do what > I want. > > What I would REALLY like is way to define standard record formats in a > separate definition, like: > - defining a common record length; > - defining the different record formats (attributes, position of the > line); Add in the type, number of decimal places, etc as well .. > - and defining when a specific record format is to be used, dependent > on 1 or more identifiers in the record. > > I CAN probably build something from scratch, but if I can (re)use > something that already exists it would be so much better and faster... > And a utility to do what I just described would be REALLY usefull in > LOTS of environments. > > This means I have the following questions: > > 1. Does anybody now of a generic tool (not necessarily Python based) > that does the job I've outlined? No, but please post if you hear of one. > 2. If not, is there some framework or widget in Python I can adapt to > do what I want? > 3. If not, should I consider building all this just from scratch in > Python - which would probably mean not only learning Python, but some > other GUI related modules? Approach I use is along the lines of what you suggested, but w/o the GUI. I have a Python script that takes layout info and an input file and can produce an output file in one of two formats: Format 1: something like: Rec:A0 recordnumber:0001 phonenumber:(123) 555-1234 zipcode:12345 This is usually much shorter than the fixed length record, because you leave out the fillers (after checking they are blank!), and strip trailing spaces from alphanumeric fields. Whether you leave integers, money, date etc fields as per file or translated into human-readable form depends on who will be reading it. You then use a robust text editor (preferably one which supports regular expressions in its find function) to browse the output file. Format 2: Rec:A0 recordnumber:0001 etc etc i.e. one field per line? Why, you ask? If you are a consumer of such files, so that you can take small chunks of this, drop it into Excel, testers take copy, make lots of juicy test data, run it through another script which makes a flat file out of it. > 4. Or should I forget about Python and build someting in another > environment? No way! From http Tue Jan 4 08:25:25 2005 From: http (Paul Rubin) Date: 04 Jan 2005 05:25:25 -0800 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> Message-ID: <7xpt0liawq.fsf@ruckus.brouhaha.com> Ville Vainio writes: > Also, Python is not a monolithic entity. Guido certainly isn't going > to write a better IDE for Python, so the time used on language > features isn't removed from improving the infrastructure around the > language. There aren't THAT many people working on Python. Any time spent on feature X does tend to divert resources from feature Y. I think there should be a moratorium on nontrivial language changes (as opposed to library improvements) until PyPy is fully deployed. Too much of Python as we know it today is shaped by the weirdness of CPython. We ought to be able to get away from that. From duncan.booth at invalid.invalid Mon Jan 10 04:03:02 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Jan 2005 09:03:02 GMT Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) References: <34cieoF489ejfU1@individual.net> Message-ID: Nick Coghlan wrote: > Grammar Change > -------------- > Current:: > statement ::= stmt_list NEWLINE | compound_stmt > > New:: > statement ::= (stmt_list NEWLINE | compound_stmt) [local_namespace] > local_namespace ::= "with" ":" suite > > > Semantics > --------- > The code:: > > with: > > > translates to:: > > def unique_name(): > > > unique_name() > Your proposed grammar change says that you need a newline after the statement: statement with: suite e.g. res = [ f(i) for i in objects ] with: def f(x): pass or for i in objects: f(i) with: def f(x): pass From dbickett at gmail.com Sun Jan 2 02:03:03 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 2 Jan 2005 02:03:03 -0500 Subject: screen clear question In-Reply-To: <1104646987.25948.2.camel@rasputin.localnet> References: <10teqpdvramua3@corp.supernews.com> <1104646987.25948.2.camel@rasputin.localnet> Message-ID: <1d6cdae30501012303643db3fa@mail.gmail.com> import os # windows os.system("cls") # bash ( mac, linux ) os.system("clear") That's all I can account for. Daniel Bickett From martin at v.loewis.de Tue Jan 25 15:15:48 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 25 Jan 2005 21:15:48 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> Message-ID: <41f6a8ef$0$27790$9b622d9e@news.freenet.de> phr at localhost.localdomain wrote: > I hadn't thought there was any controversy over the technical side of > this. There isn't. The interface might be beautifully designed, and you might claim it is, and I would *still* require that the module gets field testing before being incorporated into Python. If other people start attesting that the module is beatifully designed, and should be included in the Python core - *then* it is worth looking into inclusion. > I'm happy to have that kind of testing (and I requested it), given > that the goal is inclusion in the core, and the core developers have > told me (as they did) that the proposal looks good and they'd like to > have the module, so I can reasonably expect it to go into the core if > it meets its technical expectations. Not if I have a say in it. *Any* new module should see out-of-the-core distribution first (unless there is BDFL pronouncement to include it, of course). This really is a matter of development process, not of technical quality. > If the developers instead say (as they seemed to somewhat later) that > because of legal/political concerns, there's no way the module can > possibly go into the core no matter how good it is technically, then > my motivation for writing the module dries up quite a bit. I personally would not say that, although I can imagine that some people do say that, and I would also defend an inclusion, and push compliance the BXA requirements so we can legally export Python out of the U.S.A. > Evidently not always. And how would the CGI user create a binary > anyway, even given a way to install it, if the web hosting service is > using a platform that the CGI user doesn't have a compiler for? Think > of a Mac user whose web host runs Windows, or vice versa. In either case, the user would best use the pre-compiled binary that somebody else provided for the platform. Actually, the Windows user using an OS X CGI server can probably just invoke the gcc which is on the target system, anyway. >>See, this is the critical point: "commonly-used functions", not >>"functions I believe would be commonly used". You must have >>*existing* users for a function to be commonly-used. > > > You're going around in circles. No, I'm merely repeating myself, and rephrasing each time. I have to, because apparently you don't see what my requirement is. > They have few Python users because the functions aren't available in > Python. To fix that, they must be added to Python. How many users > do you think the Python sha module had before it went into Python? The original source code of the SHA-1 implementation is the NIST code (Gutmann, then Hollerbach), so I guess that had hundreds of users before the module was contributed to Python. The module itself (including the API) was written by Greg Stein and Andrew Kuchling. I believe (without being able to verify) that they distributed this module for quite some time, before contributing it to Python. We would have to ask them how many users they had until they felt confident to contribute the code. Regards, Martin Andrew Kuchling From macrocosm at fastmail.fm Fri Jan 7 21:45:08 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Fri, 07 Jan 2005 21:45:08 -0500 Subject: Python Operating System??? In-Reply-To: <7xr7kx0w4m.fsf@ruckus.brouhaha.com> References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> Message-ID: <41DF4934.1070309@fastmail.fm> Paul Rubin wrote: >mike at hobbshouse.org (Michael Hobbs) writes: > > >>The problem when using Python instead of C for OS development is that >>C was *specifically designed* to create an OS, while Python was designed >>for completely different purposes. If you want to write an OS, it would >>be wise to use a language that is suited for that purpose. If you >>dislike C so much and prefer Python so much more, your first step should >>be to design a Python dialect that is more appropriate for writing OS's. >> >> > >But I thought Python was an all-purpose language. After all, OS's >have been written in Lisp before too. > > Pure Lisp? Or a Lisp/C/Asm combo? Lisp has a compiled flavor by the way. From elephantum at dezcom.mephi.ru Mon Jan 10 15:57:42 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Mon, 10 Jan 2005 23:57:42 +0300 Subject: exceptions and items in a list In-Reply-To: References: Message-ID: <34g8i6F4ad39oU1@individual.net> rbt wrote: > If I have a Python list that I'm iterating over and one of the objects > in the list raises an exception and I have code like this: > > try: > do something to object in list > except Exception: > pass > > Does the code just skip the bad object and continue with the other > objects in the list, or does it stop? # skip bad object and continue with others for object in objects: try: #do something to object except Exception: pass # stop at first bad object try: for object in objects: #do something to object except Exception: pass From andymac at bullseye.apana.org.au Thu Jan 6 05:35:07 2005 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 6 Jan 2005 21:35:07 +1100 (EST) Subject: Python evolution: Unease In-Reply-To: <10to8qulnc3vke1@news.supernews.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> Message-ID: <20050106213020.D27090@bullseye.apana.org.au> On Wed, 5 Jan 2005, John Roth wrote: > I would like to contribute some documentation to Python. > I've got the time, I write quite a bit, etc. I've got fairly > strong opinions about some things that need to be documented, > (such as all the new style class descriptor stuff from 2.2) > and I have relatively little difficulty matching the existing style. > > However, I don't > know TEX, Latex, CVS or Sourceforge. (The latter two are > on my "learn sometime soon so I can put PyFIT where it belongs" > list.) > > I have no desire to install Perl to run the documentation toolchain. > I also have no particular desire to write up a bunch of final > format stuff and drop it on someone else to put into the latex > format so it can be included. While being able to make doc changes at the Latex level directly into CVS is the ultimate, Fred Drake and others are quite happy to take straight text (ReST markup would probably help them a bit) as bugs/patches on sourceforge. ------------------------------------------------------------------------- Andrew I MacIntyre "These thoughts are mine alone..." E-mail: andymac at bullseye.apana.org.au (pref) | Snail: PO Box 370 andymac at pcug.org.au (alt) | Belconnen ACT 2616 Web: http://www.andymac.org/ | Australia From philippe at philippecmartin.com Tue Jan 18 13:55:41 2005 From: philippe at philippecmartin.com (Philippe C. Martin) Date: Tue, 18 Jan 2005 18:55:41 GMT Subject: hex notation funtion References: Message-ID: Would that do it? for i in my_byte_string: .... = atoi(binascii.hexlify(i),16) Regards, Philippe On Tue, 18 Jan 2005 20:43:44 +0200, tertius wrote: > Hi, > > Is there a builtin function that will enable me to display the hex > notation of a given binary string? (example below) > > many thanks > Tertius > > > > 0000(0000) 02 11 00 00 46 5A 1A 82 02 11 00 39 36 39 33 39 > ....FZ.....96939 > > 0016(0010) 36 39 33 00 0A 30 33 37 34 34 39 35 38 25 DD 01 > 693..03744958%.. From ark at acm.org Wed Jan 19 11:57:38 2005 From: ark at acm.org (Andrew Koenig) Date: Wed, 19 Jan 2005 16:57:38 GMT Subject: a question References: <3YvHd.80953$Jk5.28602@lakeread01> Message-ID: <6kwHd.48934$w62.45338@bgtnsc05-news.ops.worldnet.att.net> "Steve Holden" wrote in message news:3YvHd.80953$Jk5.28602 at lakeread01... > The error you get is NOT a syntax error: > > >>> cmd = '%s format %s \ > ... over %d lines' % ('my', 'string', 2) > >>> cmd > 'my format string over 2 lines' > >>> > > The interpreter is probably complaining because it needs six values to > fill out the format and you only provided four. Also, I'm dubious about the idea of splitting a string literal across multiple lines, as it's impossible to indent such a literal nicely without putting stray spaces into its contents. So instead of writing 'this is a\ long string' and not making it clear how many spaces you intend between 'a' and 'long', how about writing this instead? ('this is a ' 'long string') in which the contents are not in doubt. This code takes advantage of two properties of Python: 1) Multiple string literals with only whitespace between them are automatically concatenated; 2) Ending a line inside unbalanced parentheses implicitly makes the next line part of the same statement. From python at hope.cz Fri Jan 28 06:28:18 2005 From: python at hope.cz (python at hope.cz) Date: 28 Jan 2005 03:28:18 -0800 Subject: How to post news articles with NNTPlib Message-ID: <1106911698.786860.109450@z14g2000cwz.googlegroups.com> Hello, How to post a news article with NNTPlib if the news server requires login. I did not find nay login command in nntplib module. Thank you lad. From http Sun Jan 2 18:57:33 2005 From: http (Paul Rubin) Date: 02 Jan 2005 15:57:33 -0800 Subject: Continuations Based Web Framework - Seaside. References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <7aTBd.11928$H%6.521997@twister1.libero.it> Message-ID: <7xhdlz8jv6.fsf@ruckus.brouhaha.com> Kendall Clark writes: > That was me, actually. I remain surprised that there isn't a move > afoot either to implement something like Seaside or Borges in Python > or to adapt one of the existing web frameworks to be > modal/continuation style. Since Python doesn't have continuations, that would be a bit tricky. From jriveramerla at yahoo.com Tue Jan 25 19:26:11 2005 From: jriveramerla at yahoo.com (Jose Rivera) Date: 25 Jan 2005 16:26:11 -0800 Subject: Where can I find Mk4py.dll for python24 ? Message-ID: <11e94203.0501251626.7988599b@posting.google.com> I installed the new release and I have not been able to make work metakit. Please give me some help to enjoy metakit and python 24. Thanks From dieter at handshake.de Sat Jan 8 14:24:33 2005 From: dieter at handshake.de (Dieter Maurer) Date: 08 Jan 2005 20:24:33 +0100 Subject: Embedding a restricted python interpreter References: Message-ID: Doug Holton writes on Thu, 06 Jan 2005 20:34:31 -0600: > ... > Hi, there is a page on this topic here: > http://www.python.org/moin/SandboxedPython > > The short answer is that it is not possible to do this with the > CPython, but you can run sandboxed code on other virtual machines, > such as Java's JVM with Jython, or .NET/Mono's CLR with Boo or > IronPython. Zope contains a "restrictedPython" implementation. It uses a specialized compiler that prevents dangerous bytecode operations to be generated and enforces a restricted builtin environment. From ncoghlan at iinet.net.au Fri Jan 28 22:50:38 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 29 Jan 2005 13:50:38 +1000 Subject: Who should security issues be reported to? In-Reply-To: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> Message-ID: <41FB080E.1070308@iinet.net.au> grahamd at dscpl.com.au wrote: > Who are the appropriate people to report security problems to > in respect of a module included with the Python distribution? > I don't feel it appropriate to be reporting it on general mailing > lists. > After my original flippant reply, I've been thinking some more about this, and whether CPython can really benefit from initial notification of a security flaw going privately to the developers first. And, due to CPython's release model, I really don't think it can. Upgrading your Python interpreter (even to a new maintenance branch release) in a production environment is usually a fairly involved exercise requiring a significant amount of testing, and the fact of the matter is, you're unlikely to do so unless there is some feature or bug-fix in a new version that you really need. (I'm still using Python 2.2.2 at work - it's entirely adequate for our needs, so there's no real pressure to upgrade on the current project. For a new project, I'd probably start with 2.4, planning to go to 2.4.1 in a couple of months time, but there aren't really any post-2.2 additions to Python that I can't handle living without). So, for CPython, the window of vulnerability is driven mainly by the time to when application developers, system administrators and end users get around to upgrading, not by the time to when a patched version is released. In that sort of environment, even if the developers were to release a new maintenance patch within an hour of being notified of the problem, the window of vulnerability is still going to be huge (there are still systems out there running Python *1.5*, fer cryin' out loud). More significantly, any security problem is likely to be with a specific function or object that has been implemented in C. This means any such security problem can be worked around by not using the affected feature, by employing appropriate safeguards against abuse, or by substituting a Python equivalent. This is something which is going to be application dependent, and relies on application developers being notified. So the most appropriate response to security issues in the CPython interpreter and standard library is to notify application developers as to what the issue is, and exactly which features it affects. Sending a private notification to the *interpreter* developers does nothing to assist in this. In accordance with the above, I would suggest that, even for security problems, Python's standard Sourceforge bug tracker is the most appropriate place to file the problem report. If the problem is significant, then it should also be brought directly to the attention of python-dev. At that point, the decision may be made to make a general announcement as to the feature which needs to be avoided or handled carefully. This would likely take the form of announcements on the www.python.org website, and on comp.lang.python.announce. Regards, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jbperez808 at wahoo.com Wed Jan 12 03:15:43 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Wed, 12 Jan 2005 16:15:43 +0800 Subject: Python.org, Website of Satan In-Reply-To: References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: <34k4lgF4b49u5U1@individual.net> This would be funny except for the fact that there are actually people out there who will take this seriously. http://rmitz.org/freebsd.daemon.html Don't forget Python == Snake == Serpent == ... ;-D humblythegreatest at usa.com wrote: > python.org = 194.109.137.226 > > 194 + 109 + 137 + 226 = 666 > > What is this website with such a demonic name and IP address? What > evils are the programmers who use this language up to? From steve at holdenweb.com Mon Jan 3 15:49:11 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Jan 2005 15:49:11 -0500 Subject: Developing Commercial Applications in Python In-Reply-To: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: <_giCd.67880$Jk5.22158@lakeread01> eeykay at gmail.com wrote: > Hello All, > I am trying to convince my client to use Python in his new product. He > is worried about the license issues. Can somebody there to point me any > good commercial applications developed using python ?. The licence > clearly says Python can be used for commercial applications. Is there > any other implications like that of GPL to make the source open ? > Thanks for any help. > eeykay > No. The Python license explicitly allows you to distribute derived works (i.e. Python applications including the standard compiler, or modified versions of the compiler) without obliging you to disclose the source code in the way that the GPL does. The only obligation the license places on you are a) You must retain the original copyright notices and b) If you *do* distribute modified versions, you must include a brief description of your modifications. I believe the Python License Version 2, as found at http://www.python.org/moin/PythonSoftwareFoundationLicenseV2Easy is about as simple as a license can get, yet still the Foundation receives inquiries from people whose lawyers are unconvinced there are no hidden problems. Of course, IANAL, so the lawyers could be right, but at least the INTENT is pretty obvious. Also beware if you plan to use "The Python License" for your own software, and read http://www.python.org/moin/PythonSoftwareFoundationLicenseFaq if you are thinking of doing so. Of course, there are many contributions which were licensed to the Foundation for inclusion in the distribution. The Foundation is currently in the process of regularizing the "license stack" thus created, by negotiating with individual contributors to ensure that a compatible license is initially granted to the PSF. Nothing is currently believed to prohibit the Foundation from licensing current releases on the terms that it does, but I should include a disclaimer that this is *not* an official statement from the Foundation, rather an explanation from one of its directors (an all-too-fallible human being) about what's lately been happening in the licensing space. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From ncoghlan at iinet.net.au Thu Jan 6 07:31:08 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 06 Jan 2005 22:31:08 +1000 Subject: Is there any way/where to subscribe for automated PEP status emails? In-Reply-To: References: <41dc24f8.68802652@news.oz.net> Message-ID: <41DD2F8C.3050409@iinet.net.au> Thomas Heller wrote: > You could probably subscribe to python-checkins, and filter it. > Or read it via gmane. Hmm - can SF be used to setup a mailing list just for checkins to a single directory in the source tree? If so, that would seem to be an easy way to provide a python-pep-updates mailing list. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From bulba at bulba.com Tue Jan 4 14:26:56 2005 From: bulba at bulba.com (Bulba!) Date: Tue, 04 Jan 2005 20:26:56 +0100 Subject: Python evolution: Unease References: Message-ID: On Tue, 4 Jan 2005 15:18:48 -0200, Carlos Ribeiro wrote: >> Let's take one by one: >I'll take only a few ;-) >> - IDE: Better than what? Than IDLE? Than Eclipse? Than SPE? Than Pythonwin? > >I would like to seee Eric3, with some polish & opensourced on Win >(which means solving the Qt licensing problem). I second that. I still haven't used Eric3 much, which means I didn't exploit it in full yet, but I like it a lot. And yes, Qt licensing is a big problem for me, because for non-technical reasons I have to work on Windows: when my eval Qt license runs out of time, no more eric3 for folks like me. -- Real world is perfectly indifferent to lies that are the foundation of leftist "thinking". From eurleif at ecritters.biz Sat Jan 22 23:00:06 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Sat, 22 Jan 2005 23:00:06 -0500 Subject: What YAML engine do you use? In-Reply-To: <41f1a3e6.1477492061@news.oz.net> References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> Message-ID: <35glltF4n4b4cU1@individual.net> Bengt Richter wrote: > I thought XML was a good idea, but IMO requiring quotes around > even integer attribute values was an unfortunate decision. I think it helps guard against incompetent authors who wouldn't understand when they're required to use quotes and when they're not. I see HTML pages all of the time where the author's done something like: Sometimes it even has spaces in it. At least with a proper XML parser, they would know where they went wrong right away. From fuzzyman at gmail.com Mon Jan 24 09:07:55 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Jan 2005 06:07:55 -0800 Subject: urllib2 and proxy question Message-ID: <1106575675.520424.155310@f14g2000cwb.googlegroups.com> urllib2 (under windows) will auto-detect your proxy settings and use those. Normally that's a good thing (I guess), except when it's not ! How do I switch off this behaviour ? I'm behind a censoring proxy and wanting to test things *locally*. IE is set to not use the proxy when fetching local adresses, but urllib2 ignores that part of the setting and uses the proxy for everything. The only way I can test are changing my IE settings back and forth every time. Most annoying. I can see how to *add* a new proxy to urllib2, but not how to force it to not use a proxy. I may well be missing something obvious though. Anyone able to help ? Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From ville at spammers.com Mon Jan 10 08:55:21 2005 From: ville at spammers.com (Ville Vainio) Date: 10 Jan 2005 15:55:21 +0200 Subject: Port blocking References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> <34f8ovF47d783U1@individual.net> <34fdf6F4a7t7uU1@individual.net> Message-ID: >>>>> "Mark" == Mark Carter writes: Mark> Mark Carter wrote: >> Paul Rubin wrote: >>> Usually you wouldn't run a public corba or pyro service over >>> the internet. You'd use something like XMLRPC over HTTP port >>> 80 partly for the precise purpose of not getting blocked by >>> firewalls. Mark> I'm not sure if we're talking at cross-purposes here, but Mark> the application isn't intended for public consumption, but Mark> for fee-paying clients. Still, if the consumption happens over the internet there is almost 100% chance of the communication being prevented by firewalls. This is exactly what "web services" are for. -- Ville Vainio http://tinyurl.com/2prnb From Serge.Orlov at gmail.com Wed Jan 12 16:31:29 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 12 Jan 2005 13:31:29 -0800 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <41e41633$1@nntp0.pdx.net> <41e458a9$0$7090$8fcfb975@news.wanadoo.fr> <1105487872.494278.128510@f14g2000cwb.googlegroups.com> <41e52dca$0$7102$8fcfb975@news.wanadoo.fr> Message-ID: <1105565489.764902.73150@c13g2000cwb.googlegroups.com> Michel Claveau - abstraction m?ta-galactique non triviale en fuite perp?tuelle. wrote: > Hi ! > > Sorry, but I think that, for russians, english is an *add-on*, > and not a common-denominator. You miss the point, programs are not English writings, they are written in computer languages using libraries with English identifiers. On the other hand comments and documentation are text. And Russian programmers do write Russian comments in programs. I've seen that a lot of times. On the other hand I've never seen any serious program written with Russian identifiers. Sure such programs may exist but my point is that they are very rare. That makes English the language of choice for Russian programmers. I'm not against the ability to write identifiers in my native Russian language, I don't mind it. I'm just trying to get the message across that Russian programmers are not dying for such feature and almost all of them don't use such feature in languages that permit Unicode identifiers. > English is the most known language, but it is not common. It is > the same difference as between co-operation and colonization. When I hear "It's the same difference as ..." it raises a red flag in my mind. Often, fine words have no connection to the subject. I can say that it's the same difference as between ability to drive a car and ability to walk. The car doesn't own you ;) Serge. From danb_83 at yahoo.com Thu Jan 6 01:12:06 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 5 Jan 2005 22:12:06 -0800 Subject: BASIC vs Python References: <1103327631.570908.321770@c13g2000cwb.googlegroups.com> <9q5jt09llq0ak9h587d2ctvq29r2ag85t9@4ax.com> Message-ID: <1104991926.560128.23050@z14g2000cwz.googlegroups.com> Christos TZOTZIOY Georgiou wrote: > On 17 Dec 2004 15:53:51 -0800, rumours say that "ladasky at my-deja.com" > might have written: > > >> The BASICs of my youth also supported graphics and sounds. > >> > >> PLAY "CGFED>CC > > >Now wait a minute, shouldn't that be... > > > >PLAY "CGFED>CC > You tell us :) > > *** > music.py -- assuming winsound exists > *** I wrote a similar program once on my Linux box. It plays notes by writing the ANSI escape sequence "\x1B[10;%d]\x1B[11;%d]\a\x1B[10]\x1B[11]" % (freq, duration) to the terminal. From philippecmartin at sbcglobal.net Fri Jan 28 15:32:55 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Fri, 28 Jan 2005 14:32:55 -0600 Subject: Yet another Python commercial application Message-ID: <1106944375.8051.44.camel@localhost> SnakeCard release SCF 1.0: a smart card simulation and Q&A platform based on Python. (I said I would :-) sorry but I'm walking on air Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From mirnazim at gmail.com Mon Jan 3 12:01:30 2005 From: mirnazim at gmail.com (mirnazim at gmail.com) Date: 3 Jan 2005 09:01:30 -0800 Subject: Frameworks for "Non-Content Oriented Web Apps" References: Message-ID: <1104771690.845547.264630@z14g2000cwz.googlegroups.com> Well, I think a we can say that a framework for "Non Content Oriented Web Apps" is something that can help in (*) creating N tier data aware web applications (*) creating data-aware controls (forms etc.). (*) managing different data sources transparently(ZODB, MySQL,PostGreSQL, etc). (*) de-coupling UI, Business Logic and Data Sources from each other. (*) provide transaction management facilities(am I asking too much). (*) etc. etc. etc. Please note that "DATA is not CONTENT" here. I agree that with a little imagination, we can accomplish that in context of the content(what most web frameworks are meant for, help in serving dynamic content), but that requires attention to the details not related to the problem. Just as another attempt to clear what I mean by "Non Content Oriented Web Apps", please consider the following example. Suppose you are hired to build an ERP system, whose user interface will be completely web based. Now let me ask you a few question(humbly). Q1) What tools would you want to use that can ease up the development in terms productivity, timeliness, quality, etc? Q2) Would you not like to think about the ERP system as an ERP system? Q3) How would it be like if you have to thinking of the ERP system in context of pages of a web site? Q4) Will It not be the waste of time in mapping the functionality of ERP in terms of content(and that is what we do when we develop such an application to run on web). Q5) Last(but not definitely the least), will it not be just ugly. Of course, we can develop the whole ERP with plain cgi and people have done it and succeeded to a good extent. Moreover, I recently saw Dabo(http://www.dabodev.com/about), a framework for developing 3 tier apps with Python and wxPython(and other supported GUI toolkits). I have not tried it but I think something similar, but for web-apps, is a close definition of "A Framework for Non-Content Oriented Web Apps". From http Sun Jan 9 22:17:00 2005 From: http (Paul Rubin) Date: 09 Jan 2005 19:17:00 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> Message-ID: <7x6526otw3.fsf@ruckus.brouhaha.com> "Roose" writes: > > I've written file systems in Python, and task schedulers in > > Javascript, and they were fine for their purposes > > Uh, not to be rude, but what are you talking about? If I'm not mistaken > Javascript is that scripting language that runs inside a browser, Correct. > an application. How are you going to save and restore CPU state in > Javascript, or even call assembly that does it in Javascript? How > do you switch into kernel mode in Javascript? We are on completely > different pages apparently. Correct. > Upon reading back in the thread I see that you mean compiled Lisp, > no? I was thinking that there would be a Lisp interpreter in a > kernel, which afaik doesn't exist. Yes, compiled Lisp. There are Python compilers too. > In any case, as I said before I don't think it is impossible, just a > poor engineering decision and I don't see the rationale behind it. I don't see a convincing case against writing an OS even in interpreted Python, though of course I'd want it to be compiled if possible. What do you think OS's do, that Python wouldn't be suitable for? Your examples of task switching and virtual memory are unconvincing. Those just require setting up some suitable tables and then calling a low-level routine to poke some CPU registers. File systems can be more performance intensive, but again, in those, much of the cpu drain can be relegated to low-level routines and the complexity can be handled in Python. From essai1 at mci.local Thu Jan 13 12:15:39 2005 From: essai1 at mci.local (News M Claveau /Hamster-P) Date: Thu, 13 Jan 2005 18:15:39 +0100 Subject: Re Wide Unicode build for Windows available somewhere? References: <5d5d851f.0501121859.56c33f0c@posting.google.com> Message-ID: <41e6bfe7$0$6372$8fcfb975@news.wanadoo.fr> Hi ! See inconvcodec wrapper, at : http://cjkpython.berlios.de/ (not for Python 2.4) From michele.simionato at gmail.com Tue Jan 4 09:33:26 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 4 Jan 2005 06:33:26 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) In-Reply-To: References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> <1104846212.355098.186400@c13g2000cwb.googlegroups.com> Message-ID: <1104849206.111461.70500@c13g2000cwb.googlegroups.com> Stephan: > I'd rather use german_ae.encode('latin1') ^^^^^^ > which returns '\xe4'. uhm ... then there is a misprint in the discussion of the recipe; BTW what's the difference between .encode and .decode ? (yes, I have been living in happy ASCII-land until now ... ;) I should probably ask for an unicode primer, I have found the one by Marc Andr? Lemburg http://www.reportlab.com/i18n/python_unicode_tutorial.html and I am reading it right now. Michele Simionato From as006d4848 at blueyonder.co.uk Tue Jan 25 04:40:31 2005 From: as006d4848 at blueyonder.co.uk (Philip Smith) Date: Tue, 25 Jan 2005 09:40:31 GMT Subject: Help with Threading References: <1106569451.677064.86620@f14g2000cwb.googlegroups.com> Message-ID: wrote in message news:1106569451.677064.86620 at f14g2000cwb.googlegroups.com... >I use threading.Thread as outlined in this recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 >Thanks From ncoghlan at iinet.net.au Sun Jan 2 14:26:39 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 03 Jan 2005 05:26:39 +1000 Subject: arbitrary number of arguments in a function declaration In-Reply-To: References: Message-ID: <41D84AEF.5090507@iinet.net.au> rbt wrote: > How do I set up a function so that it can take an arbitrary number of > arguments? For example, I have a bunch of expenses which may grow or > shrink depending on the client's circumstance and a function that sums > them up... hard coding them is tedious. How might I make this dynamic so > that it can handle any amount of expenses? > > def tot_expenses(self, e0, e1, e2, e3): > pass The Python Tutorial is a wonderful thing. . . Anyway, you can either set up your function to take a proper list, and then discover that the sum function already exists to add up the contents of a list: def tot_expenses(self, expenses): self.total_expenses = sum(expenses) Or, have the function take a variable number of arguments, and do the same thing: def tot_expenses(self, *args): self.total_expenses = sum(args) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From mike at hobbshouse.org Mon Jan 31 15:48:13 2005 From: mike at hobbshouse.org (Michael Hobbs) Date: Mon, 31 Jan 2005 20:48:13 -0000 Subject: Anyone else experience Thread.join() returning early? Message-ID: <10vt6cd5e0lfp1e@corp.supernews.com> I just wanted to see if anyone else experienced a problem with the Thread.join() method in Python 2.4. Unfortunately, I did not debug this problem fully before re-writing my code to avoid Thread.join(). My specific situation was that I called subprocess.Popen() to spawn a separate process with the stdout redirected to a pipe. I then created a Thread to process the data coming through the pipe. The thread would terminate when it encountered EOF on the pipe. When I used Thread.join(), I would encounter symptoms that lead me to believe that join() was returning before the subprocess actually terminated. After I rewrote the code to manually manipulate a lock instead of using Thread.join(), the symptoms went away. I guess that I'm just curious to see if anyone else has encountered a problem here, so that a bug can be filed if necessary. I did a quick Google search, but didn't see any other reports. Thanks, - Mike From rasdj at frontiernet.net Wed Jan 26 10:47:16 2005 From: rasdj at frontiernet.net (rasdj at frontiernet.net) Date: 26 Jan 2005 07:47:16 -0800 Subject: re.search - just skip it Message-ID: <1106754436.876675.144290@c13g2000cwb.googlegroups.com> Input is this: SET1_S_W CHAR(1) NOT NULL, SET2_S_W CHAR(1) NOT NULL, SET3_S_W CHAR(1) NOT NULL, SET4_S_W CHAR(1) NOT NULL, ; .py says: import re, string, sys s_ora = re.compile('.*S_W.*') lines = open("y.sql").readlines() for i in range(len(lines)): try: if s_ora.search(lines[i]): del lines[i] except IndexError: open("z.sql","w").writelines(lines) but output is: SET2_S_W CHAR(1) NOT NULL, SET4_S_W CHAR(1) NOT NULL, ; It should delete every, not every other! thx, RasDJ From tjreedy at udel.edu Wed Jan 12 19:10:28 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Jan 2005 19:10:28 -0500 Subject: Iteration over two sequences References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com><34kvs0F4bqiviU1@individual.net> Message-ID: "It's me" wrote in message news:MrdFd.10646$5R.6473 at newssvr21.news.prodigy.com... >I tried this and I got: > [(1, 'a'), (2, 'b'), (3, 'c')] > But if I change: > a=[1,2] > I got: > [(1, 'c')] > Why is that? I thought I should be getting: > [(1, 'a'),(2,'b')] > ????? Cut and paste the actual input and output for an interactive session with a freshly started interpreter and perhaps we can answer for sure. Terry J. Reedy From fredrik at pythonware.com Mon Jan 24 12:45:46 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 18:45:46 +0100 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> Message-ID: George Sakkis wrote: > Why does slicing a tuple returns a new tuple instead of a view of the existing one, given that > tuples are immutable ? really? >>> a = 1, 2, 3 >>> b = a[:] >>> a is b True From francis.girard at free.fr Thu Jan 27 15:47:13 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 27 Jan 2005 21:47:13 +0100 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: <200501272147.14017.francis.girard@free.fr> Le jeudi 27 Janvier 2005 21:29, Steven Bethard a ?crit?: > Francis Girard wrote: > > Le jeudi 27 Janvier 2005 20:16, Steven Bethard a ?crit : > >>flamesrock wrote: > >>>The statement (1 > None) is false (or any other value above 0). Why is > >>>this? > >> > >>What code are you executing? I don't get this behavior at all: > >> > >>py> 100 > None > >>True > >>py> 1 > None > >>True > >>py> 0 > None > >>True > >>py> -1 > None > >>True > >>py> -100 > None > >>True > > > > Wow ! What is it that are compared ? I think it's the references (i.e. > > the adresses) that are compared. The "None" reference may map to the > > physical 0x0 adress whereas 100 is internally interpreted as an object > > for which the reference (i.e. address) exists and therefore greater than > > 0x0. > > > > Am I interpreting correctly ? > > Actually, I believe None is special-cased to work like this. From > object.c: > > static int > default_3way_compare(PyObject *v, PyObject *w) > { > ... > if (v->ob_type == w->ob_type) { > ... > Py_uintptr_t vv = (Py_uintptr_t)v; > Py_uintptr_t ww = (Py_uintptr_t)w; > return (vv < ww) ? -1 : (vv > ww) ? 1 : 0; > } > ... > /* None is smaller than anything */ > if (v == Py_None) > return -1; > if (w == Py_None) > return 1; > ... > } > > So None being smaller than anything (except itself) is hard-coded into > Python's compare routine. My suspicion is that even if/when objects of > different types are no longer comparable by default (as has been > suggested for Python 3.0), None will still compare as smaller than > anything... > Well, here's python doesn't seem to confirm what you're saying : >>> a = "10" >>> b = 10 >>> a > b True >>> b > a False >>> id(a) 1077467584 >>> id(b) 134536516 It really looks like the addresses are compared when objects are of different types if there is no __cmp__ or __lt__ user made specification to compare objects of different types. If this is case then it is dreadfully dangerous. You end up never really knowing for sure if you're comparing the references or the values. What would be the use to compare references anyway in language like Python. I think the code should raise a big bad exception for such cases. Francis Girard > Steve From oren at REMOVETHIS1.hishome.net Sat Jan 8 12:07:42 2005 From: oren at REMOVETHIS1.hishome.net (oren at REMOVETHIS1.hishome.net) Date: 8 Jan 2005 09:07:42 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> Message-ID: <1105204062.148318.116710@c13g2000cwb.googlegroups.com> When I first saw this I thought: "hmmm... this seems as redundant as adding a repeat/until loop to Python; there's no chance in hell it will ever be accepted by the community or Guido, but I actually kinda like it". It's nice to see mostly positive reactions to this idea so far. I think it's a really ingenious solution to the the anonymous function problem - don't make it anonymous! A short, throwaway name with a very localized scope is as good as a truly anonymous function and feels more Pythonic to me. We thought we wanted a better syntax than lambda for anonymous functions but Andrey shows that perhaps it wasn't what we really need. What we need is a solution to quickly and cleanly generate bits of callable code without polluting the containing namespace, without having to think too hard about unique names and while making their temporary and local nature clear from the context. Anonymity isn't one of the requirements. I really liked Nick Coghlan's property example. The names 'get' and 'set' are too short and generic to be used without a proper scope but with this syntax they are just perfect. Here's another example: w = Widget(color=Red, onClick=onClick, onMouseOver=onMouseOver) where: . def onClick(event): do_this(event.x, event.y, foo) . def onMouseOver(event): someotherwidget.do_that() The "onClick=onClick" part seems a bit redundant, right? So how about this: w = Widget(**kw) where: . color = Red . def onClick(event): do_this(event.x, event.y, blabla) . def onMouseOver(event): someotherwidget.do_that() . x, y = 100, 200 . kw = locals() I'm not really sure myself how much I like this. It has a certain charm but also feels like abuse of the feature. Note that "w = Widget(**locals()) where:" would produce the wrong result as it will include all the values in the containing scope, not just those defined in the where block. Oren From martin at v.loewis.de Mon Jan 10 16:23:58 2005 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Mon, 10 Jan 2005 22:23:58 +0100 Subject: Referenz auf Variable an Funktion =?utf-8?b?w7xiZXJnZWJlbj8=?= In-Reply-To: References: Message-ID: <41e2f26c$0$3326$9b622d9e@news.freenet.de> Torsten Mohr wrote: > Geht sowas auch in Python? Nicht direkt. Es ist ?blich, dass Funktionen, die Ergebnisse (R?ckgabewerte) liefern, dies mittels return tun: def vokale(string): result = [c for c in string if c in "aeiou"] return "".join(result) x = "Hallo, Welt" x = vokale(x) Falls man mehrere Strings als ?ndern will, hat man halt mehrere R?ckgabewerte def welt_anhaengen(a, b): return a+"Hallo", b+"Welt" x = "foo" y = "bar" x,y = welt_anhaengen(x,y) > Geht sowas vielleicht mit weakref? Nein. Wenn Du unbedingt das Argument ?ndern willst, musst Du ein Objekt ?bergeben, das man ?ndern kann, etwa eine Liste, die nur einen String enth?lt. def welt_anhaengen_2(a,b): a[0] += "Hallo" b[0] += "Welt" a = ["foo"] b = ["bar"] welt_anhaengen_2(a,b) Ciao, Martin P.S. comp.lang.python ist eigentlich auf Englisch. From dmarcusanu at yahoo.com Tue Jan 25 23:10:27 2005 From: dmarcusanu at yahoo.com (Dana Marcusanu) Date: Tue, 25 Jan 2005 20:10:27 -0800 (PST) Subject: DDE syntax help Message-ID: <20050126041027.59104.qmail@web52907.mail.yahoo.com> Hello, I am trying to convert an Excel SpreadSheet to Python. The formula in Excel for one of the cells is =DDE("ser1","ser2","ser3"). The name of the server is ser1, ser2 is the topic, and ser3 is an item. I already tried using: >>> import dde >>> ddes = dde.CreateServer() >>> ddes.Create("ser1") >>> ddec = dde.CreateConversation(ddes) >>> ddec.ConnectTo("ser1","ser3") >>> ddec.Connected() 1 All is ok so far. However: >>> ddec.Request("ser2") Traceback (most recent call last): File "", line 1, in ? error: Request failed >>> ddec.Exec("ser2") Traceback (most recent call last): File "", line 1, in ? error: Exec failed >>> Does anyone know the syntax to request information from a DDE server? I could not find any useful examples in the documentation. Thank you, Dana __________________________________ Do you Yahoo!? Yahoo! Mail - 250MB free storage. Do more. Manage less. http://info.mail.yahoo.com/mail_250 From shinma6980 at netscape.net Thu Jan 13 16:23:37 2005 From: shinma6980 at netscape.net (Shin) Date: Thu, 13 Jan 2005 21:23:37 GMT Subject: win32net help Message-ID: Hi all, I'm new to the python language and I'm having trouble. I'm writing a basic chat script...real basic. It's client-server based and I'm wanting the roles to change -- client becomes server and vice versa. The problem is when I do this, the server switches to the client no problem. However, when the client tries to switch to server mode, it can't because the previous server is still bound to the socket it wants to use. I've tried using socket.closesocket and socket.DisconnectEx but nothing works. Any suggestions? Or could you point me to documentation showing supported commands for win32net? Any help is greatly appreciated. -Shin From BOOGIEMANPN at YAHOO.COM Sun Jan 2 16:29:01 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Sun, 2 Jan 2005 22:29:01 +0100 Subject: How to make executable file ? References: <33r5gcF449bt0U1@individual.net> Message-ID: <1y0ocznzfuzyw.mqrsvollejs5.dlg@40tude.net> On Sun, 02 Jan 2005 21:56:45 +0100, Gian Mario Tagliaretti wrote: > don't be scared when you see the dimension of the files... 1.9 Mb for a console application ?! And is it possible to make Windows application ? I want to display results in windows message box. From amichail at gmail.com Sat Jan 8 22:25:09 2005 From: amichail at gmail.com (Amir Michail) Date: 8 Jan 2005 19:25:09 -0800 Subject: Make predictions about Python in a New Google Game Message-ID: <1105241108.972516.53440@c13g2000cwb.googlegroups.com> Hi, I have added over 50 Python related (Query, URL) pairs into the Speculative Search Game -- a new Google game. Just search for "python" to find them when making predictions: http://www.cse.unsw.edu.au/~amichail/spec/ The Speculative Search Game allows you to predict which web pages will rank more highly on Google in the future. Your score will depend on the actual ranking of those pages in the future. The output of the game will be used to build a Speculative Search Engine that ranks those web pages more highly today. Note that such predictions can be helpful in managing a large project. See for example this article: http://www.time.com/time/insidebiz/article/0,9171,1101040712-660965-1,00.html The python (Query, URL) pairs that I added have pretty general queries such as "python" and "python bindings". Feel free to add other sorts of queries to those URLs (e.g., "gui framework", "scripting language", "programming", etc.) Of course, feel free to add other sites as well, including any of your python sites that I have missed. Amir From tjreedy at udel.edu Wed Jan 26 17:03:36 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Jan 2005 17:03:36 -0500 Subject: Subclassed dict as globals References: Message-ID: "Fredrik Lundh" wrote in message news:ct8l51$2lp$1 at sea.gmane.org... > Evan Simpson wrote: > >> In Python 2.4 the following works: >> >> >>> class G(dict): >> ... def __getitem__(self, k): >> ... return 'K' + k >> ... >> >>> g = G() >> >>> exec 'print x, y, z' in g >> Kx Ky Kz >> >>> >> >> ...while in Python 2.3 it fails with NameError: name 'x' is not defined. > I don't think he added this purely by accident, As I remember, Raymond H. was responding to a request by someone who ran into that exception. In general, functions accepting a base class should at least accept subclasses of that baseclass. tjr From jimbo at cordiner.com Sat Jan 22 17:24:51 2005 From: jimbo at cordiner.com (jimbo at cordiner.com) Date: Sat, 22 Jan 2005 17:24:51 -0500 Subject: debugging process Message-ID: <6ED3DB27-6CC4-11D9-BC08-000A95AC3812@cordiner.com> Hi, I am trying to create a separate process that will launch python and then can be used to step through a script programmatically. I have tried something like: (input, output) = os.popen2(cmd="python") Then I expected I could select over the two handles input and output, make sure they aren't going to block, and then be able to write python code to the interpreter and read it back. I intend to import a module, run it in the debugger with pdb.run() and the start passing debug commands in and read the output. I hope that makes sense, what I am finding is that whenever I try to read from the output handle it blocks. My understanding was that if it is returned by select that it is ready for reading and won't block. I think that this must have something to do with python expecting itself to by in a TTY? Can anyone give any idea of where I should be going with this? Thanks, jms. ________________________________________________ james at cordiner.com http://www.cordiner.com From vincent at visualtrans.de Sat Jan 29 14:34:23 2005 From: vincent at visualtrans.de (vincent wehren) Date: Sat, 29 Jan 2005 20:34:23 +0100 Subject: tk global bindings In-Reply-To: References: Message-ID: Gabriel B. wrote: > I'm starting to write a POS application UI's module. > > There's no mouse, just a bunch of global shortcuts. > > the problem is that TK doesn't have global shortcuts! Is there a > work-around or i will have to attach 80 or so bindings for every input > element? In Tk here are three levels of binding: instance binding, class binding, and application binding represented by the bind, bind_class, and bind_all methods. You're probably looking for the the bind_all method, as in self.bind_all("", self.onSomeKey) HTH, -- Vincent Wehren > > Thanks, > Gabriel From flupke at nonexistingdomain.com Wed Jan 12 10:48:02 2005 From: flupke at nonexistingdomain.com (flupke) Date: Wed, 12 Jan 2005 16:48:02 +0100 Subject: 2 versions of python on 1 machine Message-ID: <4446BD725249914A801A2C8ED5BFA4CADE2D59@cernne02.cern.ch> Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Lines: 15 Message-ID: Date: Thu, 06 Jan 2005 15:13:42 GMT NNTP-Posting-Host: 212.123.8.34 X-Complaints-To: abuse at telenet.be X-Trace: phobos.telenet-ops.be 1105024422 212.123.8.34 (Thu, 06 Jan 2005 16:13:42 MET) NNTP-Posting-Date: Thu, 06 Jan 2005 16:13:42 MET Organization: Telenet Internet Path: cernne01.cern.ch!news-zh.switch.ch!switch.ch!news.mailgate.org!newsfeed.stueberl.de!newsgate.cistron.nl!skynet.be!skynet.be!ossa.telenet-ops.be!phobos.telenet-ops.be.POSTED!not-for-mail Xref: cernne01.cern.ch comp.lang.python:6747 I searched with Google and on this newsgroups and i didn't find any info regarding this. If there is more info, please redirect me to that info. I have version 2.3.4 and 2.4 installed on windows and i thought that by switching the PYTHONPATH parameter to the dir of the 2.4 version that that would make python 2.4 active. However when i envoke python from the commandline, it still runs 2.3.4 Is it possible to have 2 versions installed and switching versions when you need to? How can i do that? Thanks, Benedict From maxm at mxm.dk Tue Jan 4 06:45:04 2005 From: maxm at mxm.dk (Max M) Date: Tue, 04 Jan 2005 12:45:04 +0100 Subject: csh to Python In-Reply-To: References: Message-ID: <41da8164$0$221$edfadb0f@dread12.news.tele.dk> Nader Emami wrote: > Hello, > > I am new in Python world, and would like to begin with > translate a csh file to a python script. Could somebody give > me an advise (documentation or web-site) where I can do that. You are probably interrested in the os 6 os.path modules. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From ianb at colorstudy.com Wed Jan 12 18:37:03 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Wed, 12 Jan 2005 17:37:03 -0600 Subject: OT: MoinMoin and Mediawiki? In-Reply-To: <7xpt0a4bkz.fsf@ruckus.brouhaha.com> References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> <1g4nx7m906q79$.dlg@usenet.alexanderweb.de> <7xekgr7lpy.fsf@ruckus.brouhaha.com> <7x4qhn9q3g.fsf@ruckus.brouhaha.com> <7xr7kq1rk6.fsf@ruckus.brouhaha.com> <7xvfa2toed.fsf@ruckus.brouhaha.com> <7xpt0a4bkz.fsf@ruckus.brouhaha.com> Message-ID: <41E5B49F.4070805@colorstudy.com> Paul Rubin wrote: >>If you are just trying to avoid too many files in a directory, another >>option is to put files in subdirectories like: >> >>base = struct.pack('i', hash(page_name)) >>base = base.encode('base64').strip().strip('=') >>filename = os.path.join(base, page_name) > > > Using subdirectories certainly keeps directory size down, and it's a > good idea for MoinMoin given the way MoinMoin uses the file system. > But for really big wikis, I think using the file system like that > isn't workable even with subdirectories. Plus, there's the issue of > how to find backlinks and how to do full text search. If the data has to be somewhere, and you have to have relatively random access to it (i.e., access any page; not necessarily a chunk of a page), then the filesystem does that pretty well, with lots of good features like caching and whatnot. I can't see a reason not to use the filesystem, really. For backlink indexing, that's a relatively easy index to maintain manually, simply by scanning pages whenever they are modified. The result of that indexing can be efficiently put in yet another file (well, maybe one file per page). For full text search, you'll want already-existing code to do it for you. MySQL contains such code. But there's also lots of that software that works well on the filesystem to do the same thing. A database would be important if you wanted to do arbitrary queries combining several sources of data. And that's certainly possible in a wiki, but that's not so much a scaling issue as a flexibility-in-reporting issue. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From irmen at -nospam-remove-this-xs4all.nl Sat Jan 8 12:01:23 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sat, 08 Jan 2005 18:01:23 +0100 Subject: there's a socket.sendall(), so why no socket.recvall()? Message-ID: <41e011e3$0$6207$e4fe514c@news.xs4all.nl> Subject says it all; there's a socket.sendall(), so why no socket.recvall()? I know that I can use the MSG_WAITALL flag with recv(), but this is not implemented on all platforms, most notably windows. --Iremn From lbolognini at gmail.com Wed Jan 12 06:53:50 2005 From: lbolognini at gmail.com (lbolognini at gmail.com) Date: 12 Jan 2005 03:53:50 -0800 Subject: python guy ide References: Message-ID: <1105530830.393006.312560@z14g2000cwz.googlegroups.com> This is commercial. Never tried it but it exists: http://visualwx.altervista.org/ Lorenzo From matthew.garrish at sympatico.ca Sun Jan 9 19:28:17 2005 From: matthew.garrish at sympatico.ca (Matt Garrish) Date: Sun, 9 Jan 2005 19:28:17 -0500 Subject: a new Perl/Python a day References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: "Xah Lee" wrote in message news:1105315487.389577.254460 at c13g2000cwb.googlegroups.com... > i'm starting a yahoo group for learning python. Each day, a tip of > python will be shown, with the perl equivalent. For those of you > perlers who always wanted to learn python, this is suitable. (i started > it because i always wanted to switch to python but too lazy and always > falling back to a lang i am an expert at, but frustrated constantly by > its inanities and incompetences.) > What language are you an expert at? It certainly isn't Perl. Matt From Dennis.Benzinger at gmx.net Tue Jan 25 03:28:42 2005 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Tue, 25 Jan 2005 09:28:42 +0100 Subject: Open Folder in Desktop In-Reply-To: <1106635751.661619.253930@c13g2000cwb.googlegroups.com> References: <1106635751.661619.253930@c13g2000cwb.googlegroups.com> Message-ID: <41f6033a$1@news.uni-ulm.de> Kamilche wrote: > Is there a command you can execute in Python that will open a window on > the desktop, such as 'My Documents'? Kind of like 'system', but for > folder names, not just programs. I'm running on Windows 2000. > Here are some commands you can use (tested on WinXP, so YMMV): 1. The os.system function import os os.system('explorer "c:\program files"') This has the disadvantage that a cmd.exe windows is also opened, because os.system executes the command in a subshell. But using this approach the explorer starts in front of all other windows. 2. The os.startfile function import os os.startfile("C:\program files") Using startfile doesn't open a cmd.exe window, but the folder window is not started in front of the other windows 3. The subprocess.Popen function import subprocess subprocess.Popen('explorer "C:\program files"') With subprocess.Popen no cmd.exe window is opened and the explorer starts in front of the other windows. But the subprocess module is new in Python 2.4. Bye, Dennis From tdelaney at avaya.com Mon Jan 24 21:15:52 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 25 Jan 2005 13:15:52 +1100 Subject: Distutils: blurring the file==module borders Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE025202D9@au3010avexu1.global.avaya.com> Frans Englich wrote: > in ./foo/ I have an __init__.py and a handful of files named > ClassA.py, ClassB.py, ClassC.py and so forth. > > import foo.ClassA > > var = foo.ClassA.ClassA() > > while I want to do var = foo.ClassA() > > In other words, the result I want can be achieved by putting all code > in __init__.py. The problem is that I would find it horrible to have > all code in one file. # __init__.py from foo.ClassA import ClassA That brings the class 'ClassA' into the namespace of module 'foo' (replacing module 'ClassA' as a side effect - if you don't want that, change some names). Tim Delaney From http Wed Jan 12 00:24:51 2005 From: http (Paul Rubin) Date: 11 Jan 2005 21:24:51 -0800 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> <1g4nx7m906q79$.dlg@usenet.alexanderweb.de> <7xekgr7lpy.fsf@ruckus.brouhaha.com> Message-ID: <7x4qhn9q3g.fsf@ruckus.brouhaha.com> cookedm+news at physics.mcmaster.ca (David M. Cooke) writes: > >> > lists of incoming links to wiki pages, > ... > Most Wiki implementations (MoinMoin included) have this, by using a > search. Usually, following the original Wiki (http://c2.com/cgi/wiki) > model, you get at it by clicking on the title of the page. > > Searching instead of indexing makes it very resilient :-) How does it do that? It has to scan every page in the entire wiki?! That's totally impractical for a large wiki. From dial#####$#$#NOSPAM####$$##$tone at gmail.com Sun Jan 2 10:50:34 2005 From: dial#####$#$#NOSPAM####$$##$tone at gmail.com (Valentino Volonghi aka) Date: Sun, 2 Jan 2005 16:50:34 +0100 Subject: Continuations Based Web Framework - Seaside. References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> Message-ID: <1gprtcx.7y2fb7b25id2N%dial#####$#$#NOSPAM####$$##$tone@gmail.com> Mike Thompson wrote: > I googled for the python spin-off but didn't find one. Closest I found Get Nevow with wolf (flow backwards, in the svn sandbox). http://www.divmod.org/cvs/sandbox/phunt/wolf/?root=Nevow You will need stackless or greenlet if using CPython. -- Valentino Volonghi aka Dialtone Now Running MacOSX 10.3.7 Blog: http://vvolonghi.blogspot.com http://weever.berlios.de From jeff at ccvcorp.com Fri Jan 21 17:52:54 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 21 Jan 2005 14:52:54 -0800 Subject: why am I getting a segmentation fault? In-Reply-To: References: <1106330476.419418.46920@f14g2000cwb.googlegroups.com> Message-ID: <10v31kgaeij1p2d@corp.supernews.com> Paul McGuire wrote: > 4. filename=r[7].split('/')[-1] is not terribly portable. See if there is a > standard module for parsing filespecs (I'll bet there is). Indeed there is -- os.path. In particular, os.path.basename() seems to do exactly that snippet is intending, in a much more robust (and readable) fashion. Jeff Shannon Technician/Programmer Credit International From gstoyanoff at yahoo.com Fri Jan 28 10:03:10 2005 From: gstoyanoff at yahoo.com (George) Date: Fri, 28 Jan 2005 10:03:10 -0500 Subject: MySQLdb References: <41F6AF8A.3040102@bowettsolutions.com> Message-ID: <5tydndzV27iIyWfcRVn-qQ@look.ca> Daniel Bowett wrote: > Daniel Bowett wrote: >> I have just started playing around with MySQLdb for a project I am >> planning. >> >> As a test I have written a script that executes 3000 insert statements >> on a table. The table contains 10 fields with a mix of text and numbers >> - its a product table for a website eg UPC, ProductName, Price etc. >> >> The problem I have is that it takes just over two minuted to execute the >> 3000 insert statements which seems really slow! I am running it on a >> machine with a 1.5 Ghz Pentium M Processor and Gig Of Ram. I dont think >> the machine is to blame for the speed because during execution the >> processor sits at about 10% and there is loads of free RAM. >> >> Does anyone know if this sort of speed sounds right? >> >> Cheers, >> >> Dan. >> >> > > UPDATE > ------ > > I have found the "executemany" function! It now takes around a second to > complete the 3000 inserts. > > Lesson learnt - I should have posted my code... > > Thanks for your help everyone. Hi Daniel, I was just wondering the executemany sends the insert as batch, does it? That is what I was going to suggest for speed MySQL should process this very quickly as a batch the problem was probably getting them there. Regards, George From mfuhr at fuhr.org Fri Jan 7 16:56:54 2005 From: mfuhr at fuhr.org (Michael Fuhr) Date: 7 Jan 2005 14:56:54 -0700 Subject: Tkinter: passing parameters to menu commands (looping througha list) References: Message-ID: <41df05a6$1_1@omega.dimensional.com> "Philippe C. Martin" writes: > l_dec_list = ['ATR','IN'] > > for i in l_dec_list: > l_dec.add_command(label = i, command= lambda: self.__Dec(i)) Give the lambda an argument with a default: l_dec.add_command(label=i, command=lambda x=i: self.__Dec(x)) -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From fumanchu at amor.org Fri Jan 7 18:14:48 2005 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 7 Jan 2005 15:14:48 -0800 Subject: switching an instance variable between a property and a normal value Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339813C@exchange.hqamor.amorhq.net> Steven Bethard wrote: > I'm playing around with a mapping type that uses setdefault > as suggested > in http://www.python.org/moin/Python3_2e0Suggestions. The > default value > for a missing key is either a simple value, or a value > generated from a > function. If it's generated from the function, it should be > generated > new each time so that, for example, if the default is an empty list, > d[1] and d[2] don't access the same list. This is why 'c.x is c.x' > should be False if I'm using the function. > > The best option I guess is to rewrite this with a > _getdefault() function instead of a property: > > But I was hoping to avoid having two separate attributes (self._value > and self._func) when only one should have a value at any given time. It seems to me like you were using the property as a glorified flag. Just use a flag. ftypes = ('BuiltinFunctionType', 'BuiltinMethodType', 'FunctionType', 'GeneratorType', 'LambdaType', 'MethodType', 'UnboundMethodType',) class D(dict): def __init__(self): self._default = None self._call_default = False def __getitem__(self, key): if not key in self: if self._call_default: self[key] = self._default() else: self[key] = self._default return dict.__getitem__(self, key) def setdefaultvalue(self, value): self._default = value self._call_default = isinstance(value, ftypes) ...or: def setdefaultvalue(self, value, call_callables=True): self._default = value self._call_default = callable(value) and call_callables Robert Brewer MIS Amor Ministries fumanchu at amor.org From ialbert at mailblocks.com Fri Jan 14 14:17:18 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 14 Jan 2005 14:17:18 -0500 Subject: [perl-python] 20050113 looking up syntax In-Reply-To: References: <1105699357.565028.107750@c13g2000cwb.googlegroups.com> Message-ID: <3qadneWfvaojh3XcRVn-vg@giganews.com> J?rgen Exner wrote: > Why don't you just stop posting this nonsense? He will, fairly soon. I'm suspecting that the original intent behind these posts was to stir up a perl vs python flamewar. That is unlikely to materialize since the poster does not seem to understand neither of these languages. I. From emami at knmi.nl Wed Jan 19 11:16:32 2005 From: emami at knmi.nl (Nader Emami) Date: Wed, 19 Jan 2005 16:16:32 +0000 Subject: a question Message-ID: L.S., I have a long command in Unix and I have to use os.system(cmd) statement. I do the following: cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s, chmod 644 %s' % (mosbin, jaar, filetype, filetype) status = os.system(cmd) This is not very clear, and I have to break this long line in two segment by means of the next character '\' : cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s, \ chmod 644 %s' % (mosbin, jaar, filetype, filetype) But in this case I get a syntax error! I don't know how I can solve this problem. Could somebody tell me about this? With regards, Nader (this From wittempj at hotmail.com Fri Jan 28 18:34:43 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 28 Jan 2005 15:34:43 -0800 Subject: Daylight savings and getmtime In-Reply-To: <35vvjmF4sbe8jU1@individual.net> References: <8b2d5523.0501281503.253269@posting.google.com> <35vvjmF4sbe8jU1@individual.net> Message-ID: <1106955283.482973.187550@z14g2000cwz.googlegroups.com> on my windows xp box os.path.getmtime gives back local time (I just saved the file): >>> os.path.getmtime('c:\\temp\\testset.py') 1106955016 >>> print time.mktime(time.localtime()) 1106955034.0 You can try to figure out if DST is on by comparing time.localtime() versus time.gmtime(). In the Western European Timezone there's one hour difference in winter and two hours in summer. >>> os.path.getmtime('c:\\temp\\testset.py') 1106954702 >>> g = time.mktime(time.gmtime()) >>> l = time.mktime(time.localtime()) >>> print g, l 1106951381.0 1106954987.0 >>> os.path.getmtime('c:\\temp\\testset.py') 1106955016 >>> print time.mktime(time.localtime()) 1106955034.0 >>> print l - g 3606.0 >>> From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Fri Jan 14 15:10:16 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Fri, 14 Jan 2005 21:10:16 +0100 Subject: Using Sqlite with Python under Windows References: <1105710976.907378.193400@c13g2000cwb.googlegroups.com> Message-ID: <41e82bda$0$19409$8fcfb975@news.wanadoo.fr> Thanks, for the link From dayzman at hotmail.com Sun Jan 2 22:57:59 2005 From: dayzman at hotmail.com (dayzman at hotmail.com) Date: 2 Jan 2005 19:57:59 -0800 Subject: Compiling Python 2.3 Message-ID: <1104724679.583262.312660@f14g2000cwb.googlegroups.com> Hi, I'm trying to use MSVC++ Toolkit 2003 to compile 2.3. Does anyone know which is the file to compile first? I don't have VS, so I can't load up the project file in PCbuild. I've tried compiling PC/config.c, but python23.lib isn't created so I'm sure I'm missing something. Any help will be much appreciated. Cheers, Michael From skip at pobox.com Sat Jan 8 11:03:58 2005 From: skip at pobox.com (Skip Montanaro) Date: Sat, 8 Jan 2005 10:03:58 -0600 Subject: "A Fundamental Turn Toward Concurrency in Software" In-Reply-To: <20050108154453.32125.797079096.divmod.quotient.2429@ohm> References: <20050108154453.32125.797079096.divmod.quotient.2429@ohm> Message-ID: <16864.1134.493853.63764@montanaro.dyndns.org> Jp> How often do you run 4 processes that are all bottlenecked on CPU? In scientific computing I suspect this happens rather frequently. "More is never enough." -- Bob Saltzman Skip From beowulf40 at lycos.com Fri Jan 21 10:49:31 2005 From: beowulf40 at lycos.com (Beowulf) Date: 21 Jan 2005 07:49:31 -0800 Subject: Tarfile module error Message-ID: Hello, I'm using Python to automate admin tasks on my job. We use Windoze 2000 as desktop platform. When executing this daily backup scripts I get the following error: Traceback (most recent call last): File "C:\UTILS\backup.py", line 8, in ? TarFileBackup = tarfile.open(NewBackupFilename, 'w:bz2') File "C:\Python23\lib\tarfile.py", line 875, in open return func(name, filemode, fileobj) File "C:\Python23\lib\tarfile.py", line 980, in bz2open raise ReadError, "not a bzip2 file" tarfile.ReadError: not a bzip2 file ---- Here's the code: ---- import tarfile from datetime import datetime DirBackup = r'\\skpdc01\Backups' DirOrig = r'C:\WUTemp' NewBackupFilename = DirBackup + '\\' + '%s' % (datetime.today()) + '.tar.bz2' TarFileBackup = tarfile.open(NewBackupFilename, 'w:bz2') TarFileBackup.add(DirOrig) TarFileBackup.close() ---- What am I doing wrong? From the error message I gues the library is expecting the bzip file to exists, but I am explicitly open it whit 'w:bz2' Any ideas? Thanks. From tim.peters at gmail.com Thu Jan 20 11:50:14 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 20 Jan 2005 11:50:14 -0500 Subject: why no time() + timedelta() ? In-Reply-To: References: Message-ID: <1f7befae050120085041c42f59@mail.gmail.com> [josh] > Why can't timedelta arithmetic be done on time objects? Obviously, because it's not implemented . > (e.g. datetime.time(5)-datetime.timedelta(microseconds=3) > > Nonzero "days" of the timedelta could either be ignored, or > trigger an exception. And if the result is less than 0, or >= 24 hours, it could raise OverflowError, or wrap around mod 24*60*60*1000000 microseconds, and so on. There are so many arbitrary endcases that no agreement could be reached on what they "should" do. So it's not supported at all. In contrast, it was much easier to reach consensus on what datetime arithmetic should do, so that was supported. From ncoghlan at iinet.net.au Sat Jan 29 20:43:43 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 30 Jan 2005 11:43:43 +1000 Subject: tutorial idea In-Reply-To: <20050129200412.21858.00000323@mb-m05.aol.com> References: <20050129200412.21858.00000323@mb-m05.aol.com> Message-ID: <41FC3BCF.1000203@iinet.net.au> ElctrcElctrcgtr1 wrote: > have a java applet that runs python code, with a tutorial that goes along with > it. that way you just have to go to a website to learn it, instead of > downloading and installing a few programs. (i would make it so it assumes that > you don't know how to program anything.) Something like this? http://tams-www.informatik.uni-hamburg.de/applets/jython/demo.html Well, without the assumption of not knowing how to program :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From claird at lairds.us Sat Jan 1 08:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Sat, 01 Jan 2005 13:08:03 GMT Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> Message-ID: In article , Hans Nowak wrote: >Paul Rubin wrote: > >> You should write unit tests either way, but in Python you're relying >> on the tests to find stuff that the compiler finds for you with Java. > >As I wrote on my weblog a while ago, I suspect that this effect is >largely psychological. You jump through hoops, declaring types all over >the place, checking exceptions, working around the language's >limitations, etc. So when your code compiles, it *feels* safer. Like >you're at least part of the way towards ensuring correctness. All that >work must be good for *something*, right? Never mind that when writing >unit tests for a dynamic language, you don't check for these things at >all. How often do you explicitly check types in Python unit tests? >IMHO, when using a dynamic language, you don't need most of the checks >that Java, C# and their ilk force upon you. . . . Me, too. That is, while I have a LOT of respect for Paul's programming and judgment, and question myself when I'm on the side opposite him, I ultimately value type declarations in languages such as Java as more cost than benefit. It's a funny position to hold, because I simultaneously recognize that type theory is one of computing's strongest theoretical achievements, AND I am a strong advocate of "static" syntax checkers such as PyChecker. Still, I see TDD as the right place to start. From aahz at pythoncraft.com Sat Jan 8 02:18:35 2005 From: aahz at pythoncraft.com (Aahz) Date: 8 Jan 2005 02:18:35 -0500 Subject: Software archeology (was Re: Developing Commercial Applications in Python) References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: In article , Stephen Waterbury wrote: >Aahz wrote: >> In article , >> Stephen Waterbury wrote: >>> >>>Also see Python Success Stories: http://pythonology.org/success >>> >>>A notable example is Verity's search engine -- see >>>http://python.oreilly.com/news/PythonSS.pdf >> >> Actually, your statement is slightly inaccurate. The Verity search >> engine is more than fifteen years old in its core technology; it was >> started as a LISP project at IIRC MIT. (At one point I was much amused >> to look at the C source code and find car() and cdr() functions.) As of >> my last information, Python isn't used at all in or with the Verity >> search engine. What you're referring to is the Verity Ultraseek engine, >> originally written and owned by Infoseek before getting transferred to >> Verity through a series of dot-bomb transactions. The Ultraseek engine >> doesn't use Python, but Python is used to control the engine, and I think >> much of the spider is written in Python. > >Actually, Aahz didn't add anything useful that wasn't explained better >in the article itself, pointing to which was the purpose of my post, >but he is correct: Python was *not* used to write the Verity search >engine ... how the hell do these stupid rumors get started anyhow?? ;). >Just read the article, dammit! :) You're quite correct that I added little useful information, but seeing as I used to work at Verity, I couldn't resist adding some hopefully interesting and/or amusing trivia. Especially the LISP bit. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From whereU at now.com Fri Jan 21 00:06:31 2005 From: whereU at now.com (Eric Pederson) Date: Thu, 20 Jan 2005 21:06:31 -0800 Subject: File objects? - under the hood question In-Reply-To: References: <20050119034955.75129.qmail@web50306.mail.yahoo.com> Message-ID: <20050120210631.2124408001.whereU@now.com> Jeremy responds: [kind enough not to mention I must have had only 10% of my brain cells functioning when I posted] > And note that with the possible exception of that last one, there is no > relationship between these two questions. Right, I just want there to be. > There is no argument you can pass to file() that will read > an > HTTP file. A file is a file, no matter where it resides; yes I know it's not that simple. Here the sort of thing (seek, then read) I think I want: >>> IDV2=open(("http://musicsite.com/song453.mp3","rb")[:-128]) >>> song453.tags=IDV2.read() >>> len(song453.tags) 128 But it's not a Python problem. :-( Thanks for the responses and indulgence. I'm OK now - the repair man fixed the coffee pot. Eric Pederson http://www.songzilla.blogspot.com From FBatista at uniFON.com.ar Mon Jan 24 08:16:20 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 24 Jan 2005 10:16:20 -0300 Subject: on the way to find pi! Message-ID: [Fredrik Lundh] #- what's the point of that? the math module already contains #- pi with as many #- decimals as you can put in a Python float: #- #- $ python #- >>> pi = 3.1415926535897932384 #- >>> pi #- 3.1415926535897931 #- >>> import math #- >>> math.pi #- 3.1415926535897931 #- >>> pi = math.pi #- True And if you want to go beyond that, check http://www.python.org/dev/doc/devel/lib/decimal-recipes.html >>> from decimal import * >>> getcontext().prec = 60 >>> pi() Decimal("3.14159265358979323846264338327950288419716939937510582097494") >>> . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From merkosh at hadiko.de Fri Jan 28 18:02:31 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Sat, 29 Jan 2005 00:02:31 +0100 Subject: example needed: sip + Qt References: <39688.82.68.80.137.1106920041.squirrel@82.68.80.137> Message-ID: Friday 28 January 2005 23:39 pm Uwe Mayer wrote: > Friday 28 January 2005 23:18 pm Uwe Mayer wrote: >> Traceback (most recent call last): >> File "", line 1, in ? >> ImportError: ./hello.so: undefined symbol: _ZTV5Hello >> >> $ c++filt _ZTV5Hello >> vtable for Hello >> >> The compilation did not give any warnings or error messages. Any ideas? > > $ ldd -d hello.so > libqt-mt.so.3 => /usr/lib/libqt-mt.so.3 (0x40057000) > libXext.so.6 => /usr/X11R6/lib/libXext.so.6 (0x4190c000) > libX11.so.6 => /usr/X11R6/lib/libX11.so.6 (0x4154e000) > libpthread.so.0 => /lib/tls/libpthread.so.0 (0x41173000) > libstdc++.so.5 => /usr/lib/libstdc++.so.5 (0x40743000) > libm.so.6 => /lib/tls/libm.so.6 (0x4114f000) > libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x407fd000) > libc.so.6 => /lib/tls/libc.so.6 (0x41019000) > libfontconfig.so.1 => /usr/lib/libfontconfig.so.1 (0x418d8000) > libaudio.so.2 => /usr/lib/libaudio.so.2 (0x40807000) > libXt.so.6 => /usr/X11R6/lib/libXt.so.6 (0x4191c000) > libpng12.so.0 => /usr/lib/libpng12.so.0 (0x4081c000) > libz.so.1 => /usr/lib/libz.so.1 (0x41856000) > libXrender.so.1 => /usr/lib/libXrender.so.1 (0x41749000) > libXrandr.so.2 => /usr/X11R6/lib/libXrandr.so.2 (0x40842000) > libXcursor.so.1 => /usr/lib/libXcursor.so.1 (0x41734000) > libXft.so.2 => /usr/lib/libXft.so.2 (0x416e1000) > libfreetype.so.6 => /usr/lib/libfreetype.so.6 (0x42487000) > libSM.so.6 => /usr/X11R6/lib/libSM.so.6 (0x42583000) > libICE.so.6 => /usr/X11R6/lib/libICE.so.6 (0x4256a000) > libdl.so.2 => /lib/tls/libdl.so.2 (0x41184000) > /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x80000000) > libexpat.so.1 => /usr/lib/libexpat.so.1 (0x40847000) > undefined symbol: _ZTV5Hello (./hello.so) > undefined symbol: _ZNK5Hello9classNameEv (./hello.so) > undefined symbol: _ZN5Hello7qt_castEPKc (./hello.so) > undefined symbol: _ZN5Hello9qt_invokeEiP8QUObject (./hello.so) > undefined symbol: _ZN5Hello7qt_emitEiP8QUObject (./hello.so) > undefined symbol: _ZN5Hello11qt_propertyEiiP8QVariant (./hello.so) > undefined symbol: _ZTI5Hello (./hello.so) > undefined symbol: _Py_NoneStruct (./hello.so) > undefined symbol: PyCObject_Type (./hello.so) Those last two can be removed if you link against libpython2.3.so and by appending -lpython2.3 to the libs in the Makefile. Uwe From usenet_spam at janc.invalid Mon Jan 3 13:38:55 2005 From: usenet_spam at janc.invalid (JanC) Date: Mon, 03 Jan 2005 18:38:55 GMT Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: Just schreef: > You should always save stdout instead of using __stdout__. It may not be > the same! You're right, especially when this code would execute in an (at programming time) unknown context. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From tim at pollenation.net Sat Jan 22 18:43:46 2005 From: tim at pollenation.net (Tim Parkin) Date: Sat, 22 Jan 2005 23:43:46 +0000 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> Message-ID: <1106437427.1945.53.camel@localhost.localdomain> Doug Holton wrote: > That is exactly why YAML can be improved. But XML proves that getting > it "right" for developers has little to do with getting it right for > users (or for saving bandwidth). What's right for developers is what > requires the least amount of work. The problem is, that's what is right > for end-users, too. Having spent some time with YAML and it's implementations (at least pyyaml and the ruby/python versions of syck), I thought I should comment. The only problems with syck we've encountered have been to do with the python wrapper rather than syck itself. Syck seems to be used widely without problems within the Ruby community and if anybody has evidence of issues with it I'd really like to know about them. PyYAML is a little inactive and doesn't conform to the spec in many ways and, as such, we prefer the syck implementation. In my opinion there have been some bad decisions made whilst creating YAML, but for me they are acceptable given the advantages of a data format that is simple to read and write. Perhaps judging the utility of a project on it's documentation is one of the problems, as most people who have 'just used it' seem to be happy enough. These people include non-technical clients of ours who manage some of their websites by editing YAML files directly. That said, I don't think it would be the best way to enter data for a life support machine, but I wouldn't like to do that with XML either ;-) One thing that should be pointed out is that there are no parsers available that are built directly on the YAML pseudo BNF. Such work is in progress in two different forms but don't expect anything soon. As I understand it, Syck has been built to pass tests rather than conform to a constantly changing BNF and it seems to have few warts. Tim From tjreedy at udel.edu Thu Jan 6 22:30:42 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Jan 2005 22:30:42 -0500 Subject: Securing a future for anonymous functions in Python References: Message-ID: "Alan Gauld" wrote in message news:f1frt0dvi9tt37roe91gm96sg734opn07s at 4ax.com... > On Thu, 30 Dec 2004 23:28:46 +1000, Nick Coghlan > wrote: > >> GvR has commented that he want to get rid of the lambda keyword for >> Python 3.0. >> Getting rid of lambda seems like a worthy goal, > > Can I ask what the objection to lambda is? > 1) Is it the syntax? > 2) Is it the limitation to a single expression? > 3) Is it the word itself? Depending on the person, any of the 3. Plus add 4) The constant complaints re: 2) > I can sympathise with 1 and 2 but the 3rd seems strange since a > lambda is a well defined name for an anonymous function used in > several programming languages and originating in lambda calculus > in math. And that is why 'lambda' is wrong -- in Python, it is only an abbreviation for a restricted group of def statements, which is *not* its 'well defined' usage. Hence complaints re 2. If the syntax were def x: x + 2, etc, I suspect the complaints would be far fewer. For some new programmers, 'lambda' is as meaningless as elle*. All other Python keywords are English words or obvious abbreviations thereof. > So why not retain the name lambda but extend or change the syntax > to make it more capable rather than invent a wholly new syntax > for lambdas? That you suggest this illustrates, to me, what is wrong with the name ;-) Terry J. Reedy * The Spanish name for the letter 'll', pronounced el-yea, which comes after 'l' in their alphabet. From http Wed Jan 5 10:18:25 2005 From: http (Paul Rubin) Date: 05 Jan 2005 07:18:25 -0800 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> <7x4qhw859p.fsf@ruckus.brouhaha.com> Message-ID: <7xk6qrnbum.fsf@ruckus.brouhaha.com> Ville Vainio writes: > Paul> I can't parse that. It says two contradictory things. > Paul> Sentence 2 says that if something essential is not in the > Paul> (Python) distro then the (Python) distro maintainers have > Paul> screwed up. Sentence 1 says it's the Fedora maintainer's > Paul> job to deal with it. Huh? > > By "distro" I meant the Linux distribution, not the Python > distribution. Distro is a customary term for a Linux distribution so I > didn't qualify the word at the time. Oh ok, but it's the Python distribution that's missing components that are essential to Python. Fedora and other Linux distros are collections of subsystems like Python. Linux distro maintainers get asked to include a subsystem, they check that the subsystem has a reasonable reputation (Python does), they install it in the distro and run some basic tests, and they ship it. They can't be expected to immerse themselves in its intricacies and hang out on the user forums to identify all the missing components that they should also hunt down and ship. So the Python needs to take care of that stuff. I realize that in the old days, people used to write big applications without makefiles, and later when they started using makefiles, they didn't use configure scripts. So to install a package, you had to do a bunch of hand configuration for your particular environment before you could compile it, and maybe you even had to say cc -O -Dthisflag=thatnumber xyz.c pqr.c frob.c -o frob on the command line instead of typing "make" to build the program. That kind of thing really doesn't fly any more. The standards for what constitutes a properly engineered release of something have gotten higher. You really need automatic configuration and build and installation. Likewise, if you're trying to market something as a complete drop-in system ("batteries included", to use the Python terminology), it should not be missing any essential pieces that the user has to hunt down separately. From baza at themauvezone.fsnet.co.uk Tue Jan 11 13:32:50 2005 From: baza at themauvezone.fsnet.co.uk (Baza) Date: Tue, 11 Jan 2005 18:32:50 +0000 Subject: Game programming in Python Message-ID: I'm looking for any books or on-line resources on game programming using Python. Does anyone have any advice? -- Computer says, 'no' From fredrik at pythonware.com Fri Jan 28 10:09:02 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 28 Jan 2005 16:09:02 +0100 Subject: python: can't open file 'timeit.py' References: <1106921858.598528.77300@f14g2000cwb.googlegroups.com> Message-ID: Aggelos I. Orfanakos wrote: > Under Gentoo Linux, I issue: > > $ python timeit.py > python: can't open file 'timeit.py' > $ ls -al /usr/lib/python2.3/timeit.py > -rw-r--r-- 1 root root 9833 Oct 19 02:17 /usr/lib/python2.3/timeit.py > > But if I specify the full path, it works: > > $ python /usr/lib/python2.3/timeit.py -n 1 "pass" > 1 loops, best of 3: 3.1 usec per loop > > Any ideas how can I fix this? I think it may have to do with where > Python looks for modules, but I am not sure. if you pass a filename to the python interpreter, python uses that file as a script. it doesn't search for files. in Python 2.4, you can use "python -m timeit" to make it search for a module, and use it as a script. in earlier versions, create a symlink from your personal bin directory, or use a small shell script to run the python script. From wendell at zephyrsyndicate.com Fri Jan 14 20:37:19 2005 From: wendell at zephyrsyndicate.com (Wendell III) Date: Fri, 14 Jan 2005 19:37:19 -0600 Subject: Looking for a few badass Python coders (Chicago). Message-ID: <2005011419371980102%wendell@zephyrsyndicatecom> Hello everyone, I am currently involved with a project involving instant messengers and social networks. We really need some talented individuals to help our team out with some Python code. Your work would be open sourced, and you would be credited in the application itself. Compensation is negotiable. Feel free to send a CV, but (to be fair) I am primarily interested/most enthralled in/by the idea of taking a look at your best work. Individuals in the Chicagoland area greatly preferred. ;-) Looking forward, -Wendell -- ph: 773.880.1282 fx: 866.805.2744 icq: 12107743 aim: zephyrwendell gg: 7116285 y!: zephyrwendell web: http://www.zephyrsyndicate.com From pythongnome at hotmail.com Sun Jan 16 14:41:15 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Sun, 16 Jan 2005 19:41:15 GMT Subject: List problems in C code ported to Python Message-ID: I'm done porting the C code, but now when running the script I continually run into problems with lists. I tried appending and extending the lists, but with no avail. Any help is much appreciated Please see both the Python and C code at http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py TIA From skip at pobox.com Fri Jan 28 15:52:14 2005 From: skip at pobox.com (Skip Montanaro) Date: Fri, 28 Jan 2005 14:52:14 -0600 Subject: [perl-python] 20050127 traverse a dir In-Reply-To: References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> <1106875259.426213.252030@z14g2000cwz.googlegroups.com> Message-ID: <16890.42494.204788.452485@montanaro.dyndns.org> abigail> @@ No. Second, learn Python. Third, learn Perl (optional). :) abigail> Just leave the third option out. Let him learn Python. We don't abigail> want him. ;-) We don't want him either. Perhaps we can persuade him to learn INTERCAL... Skip From fredrik at pythonware.com Sat Jan 22 08:45:12 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 14:45:12 +0100 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com><797fe3d405011911465ab59acd@mail.gmail.com><1106177050.630141.33090@c13g2000cwb.googlegroups.com><972ec5bd0501191641166972b0@mail.gmail.com><7xis5szpdj.fsf@ruckus.brouhaha.com><7xekggbrns.fsf@ruckus.brouhaha.com><7x651rwbib.fsf@ruckus.brouhaha.com><7xfz0uqe1d.fsf@ruckus.brouhaha.com><7xu0p9lk4h.fsf@ruckus.brouhaha.com> <1gqsn7o.qyazai1nh7smmN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: >> I do remember seeing some cute tricks (i.e. capable of becoming >> idioms) that depend on the leakage. > > Sure, ``if [mo for mo in [myre.search(line)] if mo]: use(mo)`` and the > like, used to simulate assign-and-test. here's an old favourite: lambda x: ([d for d in [{}]], [d.setdefault(k.text or "", unmarshal(v)) for (k, v) in x], d)[2] which, when all keys are unique, is a 2.1-compatible version of lambda x: dict([(k.text or "", unmarshal(v)) for k, v in x]) which illustrates why some lambdas are better written as functions. From ncoghlan at iinet.net.au Sun Jan 2 11:15:23 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 03 Jan 2005 02:15:23 +1000 Subject: screen clear question In-Reply-To: <8ucft0tf456g07iuuavgu31m6dhrgjbmh3@4ax.com> References: <10teqpdvramua3@corp.supernews.com> <8ucft0tf456g07iuuavgu31m6dhrgjbmh3@4ax.com> Message-ID: <41D81E1B.5060703@iinet.net.au> Alan Gauld wrote: > But the bottom line is that there is no builtin command > because the mechanism is different on each platform. I'd have said it was because the inpreter is line-oriented rather than screen-oriented, but YMMV. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jerf at jerf.org Sat Jan 29 14:26:56 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 29 Jan 2005 14:26:56 -0500 Subject: [perl-python] 20050127 traverse a dir References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> Message-ID: On Thu, 27 Jan 2005 15:01:12 -0500, Chris Mattern wrote: > Is it just me, or is the disappointing lack of flamewars > slowly ratcheting up the level of vitriol in his posts? What flabbergasts me is the stunning failure in trolling that XL is. I've accidentally trolled (if you can extend the trolling definition that way) through ignorance of both subject matter and local culture, accidentally trolled through typo, and accidentally trolled through poorly chosen incendiary example that had little to do with my point. This poor guy trolls across five newsgroups and is now one of the few things that they absolutely all absolutely agree on. Now *that* is some truly breathtaking failure right there. I'm not sure I could fail that hard if I tried. (I'll shut up about Xah now.) From bokr at oz.net Sat Jan 15 19:22:50 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 16 Jan 2005 00:22:50 GMT Subject: What strategy for random accession of records in massive FASTA file? References: <1105569967.129284.85470@c13g2000cwb.googlegroups.com> <1105734450.961150.32980@z14g2000cwz.googlegroups.com> <7xfz13zrb2.fsf@ruckus.brouhaha.com> <41E97C18.305@holdenweb.com> Message-ID: <41e9a33f.953097411@news.oz.net> On Sat, 15 Jan 2005 15:24:56 -0500, Steve Holden wrote: >Bulba! wrote: > >> On 14 Jan 2005 12:30:57 -0800, Paul Rubin >> wrote: >> >> >>>Mmap lets you treat a disk file as an array, so you can randomly >>>access the bytes in the file without having to do seek operations >> >> >> Cool! >> >> >>>Just say a[234]='x' and you've changed byte 234 of the file to the >>>letter x. >> >> >> However.. however.. suppose this element located more or less >> in the middle of an array occupies more space after changing it, >> say 2 bytes instead of 1. Will flush() need to rewrite the half of >> mmaped file just to add that one byte? >> I would wonder what mm.find('pattern') in the middle of a huge file would do to the working set vs sequential reads as in my little toy (which BTW is also happy to expand or contract old vs new replacement string as it streams buffers file to file). >Nope. If you try a[234] = 'banana' you'll get an error message. The mmap >protocol doesn't support insertion and deletion, only overwriting. > >Of course, it's far too complicated to actually *try* this stuff before >pontificating [not]: > > >>> import mmap > >>> f = file("/tmp/Xout.txt", "r+") > >>> mm = mmap.mmap(f.fileno(), 200) > >>> mm[1:10] >'elcome to' > >>> mm[1] = "banana" >Traceback (most recent call last): > File "", line 1, in ? >IndexError: mmap assignment must be single-character string > >>> mm[1:10] = 'ishing ::' > >>> mm[1:10] >'ishing ::' > >>> mm[1:10] = 'a' >Traceback (most recent call last): > File "", line 1, in ? >IndexError: mmap slice assignment is wrong size > >>> > >> flush() definitely makes updating less of an issue, I'm just >> curious about the cost of writing small changes scattered all >> over the place back to the large file. >> >Some of this depends on whether the mmap is shared or private, of >course, but generally speaking you can ignore the overhead, and the >flush() calls will be automatic as long as you don't mix file and string >operations. The programming convenience is amazing. That part does look good, but will scanning a large file with find cause massive swapouts, or is there some smart prioritization or hidden sequential windowing that limits mmap's impact? > >> -- >> I have come to kick ass, chew bubble gum and do the following: >> >> from __future__ import py3k >> >> And it doesn't work. > >So make it work :-) > Regards, Bengt Richter From steve at holdenweb.com Wed Jan 19 11:27:14 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 19 Jan 2005 11:27:14 -0500 Subject: a question In-Reply-To: References: Message-ID: <3YvHd.80953$Jk5.28602@lakeread01> Nader Emami wrote: > L.S., > > I have a long command in Unix and I have to use os.system(cmd) > statement. I do the following: > > cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s, chmod 644 > %s' % (mosbin, jaar, filetype, filetype) > status = os.system(cmd) > > > This is not very clear, and I have to break this long line in two > segment by means of the next character '\' : > cmd = '%s/mos user wmarch, cd /fa/wm/%s/%s, mkdir %s, put %s, \ > chmod 644 %s' % (mosbin, jaar, filetype, filetype) > > But in this case I get a syntax error! I don't know how I can solve this > problem. Could somebody tell me about this? > The error you get is NOT a syntax error: >>> cmd = '%s format %s \ ... over %d lines' % ('my', 'string', 2) >>> cmd 'my format string over 2 lines' >>> The interpreter is probably complaining because it needs six values to fill out the format and you only provided four. In future, by the way, always include the error message in such posts! regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From elephantum at dezcom.mephi.ru Thu Jan 13 04:25:00 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Thu, 13 Jan 2005 12:25:00 +0300 Subject: else condition in list comprehension In-Reply-To: References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: <34mt3dF4ejn17U1@individual.net> Steve Holden wrote: > Nick Coghlan wrote: > >> Luis M. Gonzalez wrote: >> >>> Hi there, >>> >>> I'd like to know if there is a way to add and else condition into a >>> list comprehension. I'm sure that I read somewhere an easy way to do >>> it, but I forgot it and now I can't find it... >>> >>> for example: >>> z=[i+2 for i in range(10) if i%2==0] >>> what if I want i to be "i-2" if i%2 is not equal to 0? >>> >> >> Hmm: >> >> z = [newval(i) for i in range(10)] using: >> def newval(x): >> if x % 2: >> return x - 2 >> else: >> return x + 2 >> >> Just some more mental twiddling relating to the thread on statement >> local namespaces. >> > I presume the point of this is to avoid polluting the local namespace > with "newval". I further presume you also have plans to do something > about "i"? ;-) no, the point is in grouping definition of newval() with place where it is used. From tim.peters at gmail.com Mon Jan 10 15:45:22 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 10 Jan 2005 15:45:22 -0500 Subject: Writing huge Sets() to disk In-Reply-To: <41E2E69C.7080104@ribosome.natur.cuni.cz> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> <41E2E69C.7080104@ribosome.natur.cuni.cz> Message-ID: <1f7befae0501101245679b26f2@mail.gmail.com> [Martin MOKREJ?] > ... > > I gave up the theoretical approach. Practically, I might need up > to store maybe those 1E15 keys. We should work on our multiplication skills here . You don't have enough disk space to store 1E15 keys. If your keys were just one byte each, you would need to have 4 thousand disks of 250GB each to store 1E15 keys. How much disk space do you actually have? I'm betting you have no more than one 250GB disk. ... [Istvan Albert] >> On my system storing 1 million words of length 15 >> as keys of a python dictionary is around 75MB. > Fine, that's what I wanted to hear. How do you improve the algorithm? > Do you delay indexing to the very latest moment or do you let your > computer index 999 999 times just for fun? It remains wholly unclear to me what "the algorithm" you want might be. As I mentioned before, if you store keys in sorted text files, you can do intersection and difference very efficiently just by using the Unix `comm` utiltity. From xah at xahlee.org Thu Jan 13 20:33:26 2005 From: xah at xahlee.org (Xah Lee) Date: 13 Jan 2005 17:33:26 -0800 Subject: how to stop google from messing Python code References: <1105620098.878376.110250@z14g2000cwz.googlegroups.com> Message-ID: <1105666406.272397.170730@c13g2000cwb.googlegroups.com> gmane is great! its renaming of newsgroups is quite a headache. i found that comp.lang.python corresponds to gmane.comp.python.general. do you know which one corresponds to comp.lang.perl.misc? there's no .misc or .general... -- i thought there a strick like preceding a line by -- or something that prevents google from reformating the post. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From timr at probo.com Thu Jan 13 03:02:40 2005 From: timr at probo.com (Tim Roberts) Date: Thu, 13 Jan 2005 00:02:40 -0800 Subject: why are people still using classic classes? References: Message-ID: Simon Wittber wrote: >I've noticed that a few ASPN cookbook recipes, which are recent >additions, use classic classes. > >I've also noticed classic classes are used in many places in the >standard library. > >I've been using new-style classes since Python 2.2, and am suprised >people are still using the classic classes. > >Is there a legitimate use for classic classes that I am not aware of? >Is there a project to specifically migrate standard library classes to >new-style classes? Probably because there is still no compelling reason to break the old habits and type those 6 extra characters. Once a person has a case where the new classes make a difference, I suspect they catch the new habit and never look back. I haven't crossed that threshhold yet. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From cam.ac.uk at mh391.invalid Fri Jan 14 06:03:41 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 14 Jan 2005 11:03:41 +0000 Subject: query python env In-Reply-To: References: Message-ID: David Bear wrote: > How does one query the python environment, ie pythonhome sys.prefix > pythonpath sys.path > etc. sys.etc > also, are there any HOWTO's on keeping multiple versions of python > happy? I think it is sufficiently trivial that none is needed. Just make sure the distributions are installed in different directories. What problems are you having? -- Michael Hoffman From abigail at abigail.nl Mon Jan 17 15:31:05 2005 From: abigail at abigail.nl (Abigail) Date: 17 Jan 2005 20:31:05 GMT Subject: [perl-python] 20050117, filter, map References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> Message-ID: Steven Bethard (steven.bethard at gmail.com) wrote on MMMMCLVII September MCMXCIII in : $$ Xah Lee wrote: $$ > ? Note: this post is from the Perl-Python $$ > ? a-day mailing list at $$ > ? http://groups.yahoo.com/group/perl-python/ $$ $$ Is there any chance you could post these all as part of the same thread? Just killfile him, and stop replying. Remember, don't feed the trolls. Abigail -- my $qr = qr/^.+?(;).+?\1|;Just another Perl Hacker;|;.+$/; $qr =~ s/$qr//g; print $qr, "\n"; From ville at spammers.com Tue Jan 4 07:36:43 2005 From: ville at spammers.com (Ville Vainio) Date: 04 Jan 2005 14:36:43 +0200 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> Message-ID: >>>>> "Iwan" == Iwan van der Kleyn writes: Iwan> And then I read the following sentence by Van Rossum: Iwan> "In order to make type inferencing a little more useful, I'd Iwan> like to restrict certain forms of extreme dynamic behavior Iwan> in Python" Iwan> In the end, it's mindset which counts. And I think that Iwan> mindset is going to be determine the way foreward for Iwan> Python: more features, increased complexity, less Iwan> dynamism. Lots of syntax crud, without addressing the need Iwan> to improve the infrastructure around the language. What form of extreme dynamic behaviour have you been using lately? Do you really think it's more worthwhile than the benefits provided by type inference, least of which isn't the ability by IDEs to provide you accurate code completion. Also, Python is not a monolithic entity. Guido certainly isn't going to write a better IDE for Python, so the time used on language features isn't removed from improving the infrastructure around the language. -- Ville Vainio http://tinyurl.com/2prnb From philippecmartin at sbcglobal.net Mon Jan 31 18:59:42 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 31 Jan 2005 17:59:42 -0600 Subject: serializing data structures (Martin v. L?wis) Message-ID: <1107215982.8008.26.camel@localhost> Thanks a lot. Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From marklists at mceahern.com Mon Jan 10 07:41:06 2005 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 10 Jan 2005 06:41:06 -0600 Subject: Datetime module In-Reply-To: <1105335972.454019.46450@c13g2000cwb.googlegroups.com> References: <1105335972.454019.46450@c13g2000cwb.googlegroups.com> Message-ID: <41E277E2.4080503@mceahern.com> rublind at gmail.com wrote: >I am writing a script that acts as an AIM bot [using twisted.IM's base >scripts] and I want to add a logging feature. I got it to log who sends >what to whom, but what I want to add is the date and time that the >message was sent (or recieved by the bot), I tried to look at datetime >on my own, and I couldn't get anything to work. >Anyone know a simple way to get the current date and/or time? > >>> import datetime >>> datetime.datetime.now() datetime.datetime(2005, 1, 10, 6, 39, 56, 64000) >>> print datetime.datetime.now() 2005-01-10 06:40:03.705000 >>> You may also want to consider using the logging module. // m From reinhold-birkenfeld-nospam at wolke7.net Sat Jan 1 16:24:40 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sat, 01 Jan 2005 22:24:40 +0100 Subject: Looping using iterators with fractional values In-Reply-To: <86is6gripu.fsf@guru.mired.org> References: <1104609929.888351.8870@c13g2000cwb.googlegroups.com> <86is6gripu.fsf@guru.mired.org> Message-ID: <33oiopF40vpumU1@individual.net> Mike Meyer wrote: > Or - and much safer when dealing with floating point numbers - iterate > over integers and generate your float values: > > for j in range(1, 9): > i = j * .25 > print "%9.2f" % i There's a glitch there, though - should be range(1, 10). Reinhold PS: I'm wondering whether my genexp approach or this one is preferable. Readability is equal, I would say, but how about speed? Brought up a few timeits: Python 2.3 ---------- for i in [x/4.0 for x in range(1, 10)]: 36,9 sec for j in range(1, 10): i = j * 0.25: 33,7 sec Python 2.4 ---------- for i in (x/4.0 for x in range(1, 10)): 32,5 sec for j in range(1, 10): i = j * 0.25: 28,4 sec So what does that tell us? (a) don't use genexps where there is a simpler approach (b) Py2.4 rocks! Reinhold From cam.ac.uk at mh391.invalid Sun Jan 23 13:04:27 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 23 Jan 2005 18:04:27 +0000 Subject: What is print? A function? In-Reply-To: References: Message-ID: Frans Englich wrote: > Nah, I don't think it's a function, but rather a builtin "statement". But it's > possible to invoke it as an function; print( "test" ) works fine. That is not invoking it as a function. The parentheses are only for ordering the expression on the right You can do this too: >>> print("abc"),("def"),("ghi") abc def ghi > So I wonder, what _is_ exactly the print statement? Uh, a statement. > The reason I thinks about this is I need to implement a debug print for my > program; very simple, a function/print statement that conditionally prints > its message whether a bool is true. Not overly complex. > > I tried this by overshadowing the print keyword, but that obviously didn't > work.. Is defining a two-liner function the right way to go, or is there > better ways to approach it? In the long run, you might want to look into the logging module. In the short run: def _debug_true(text): print >>sys.stderr, text def _debug_false(text): pass if command_line_debug_option: debug = _debug_true else debug = _debug_false That way you only have to check whether the option is true once in the entire run of your program, not every time you call the debug() function (which is presumably many times). -- Michael Hoffman From snail at objmedia.demon.co.uk Wed Jan 26 12:25:10 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Wed, 26 Jan 2005 17:25:10 +0000 Subject: is there better 32 clock() timing? References: <41f61372.1768192005@news.oz.net> Message-ID: In message , Peter Hansen writes >(I've read the five or so following messages you and Bengt >have posted, but not in detail so I'm not sure where you're >going with all this, but... ) We've gone off at a tangent about Windows timing etc. Pretty much over now. >According to the docs for time.clock(), "On Windows, this function returns >wall-clock seconds elapsed since the first call to this function, as a floating > point number, based on the Win32 function QueryPerformanceCounter(). The >resolution is typically better than one microsecond." > >Depending on whether you really meant "accuracy" above, and >on other things, this is either irrelevant, or contradicts >your first statement... No contradiction. Python (from what you write above) implements time.clock() differently from the CRT clock() (which I had assumed Python would call for simplicity). Hence the differing results. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From lcatalin at siadv.com Wed Jan 5 11:18:30 2005 From: lcatalin at siadv.com (Catalin Lungu) Date: Wed, 5 Jan 2005 17:18:30 +0100 Subject: How to make executable file ? References: <10to3sve2nburaf@corp.supernews.com> Message-ID: Also, you can try with py2exe. It's very easy. Catalin. "Andrew Robert" escribi? en el mensaje news:10to3sve2nburaf at corp.supernews.com... > BOOGIEMAN wrote: >> Just how to make *.exe file from python code ?? >> I typed this : >> >> a, b = 0, 1 >> while b < 1000: >> print b, >> a, b = b, a+b >> >> and saved it as pyt.txt >> >> Now, how do I make pyt.exe file ??? >> I want to run it on windows where isn't installed python. > > You may want to try cx_freeze. > > Details on it can be found at > http://starship.python.net/crew/atuining/cx_Freeze/ > > Binaries are available for Linux and Windows. > > Alternately, source code is available if you need to compile it for a > different platform. > > > -- > Thank you, > Andrew Robert > > E-mail: arobert at townisp.com > Ur: http://shardservant.no-ip.info From cookedm+news at physics.mcmaster.ca Tue Jan 18 16:38:07 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Tue, 18 Jan 2005 16:38:07 -0500 Subject: pickling extension class References: Message-ID: harold fellermann writes: > Hi all, > > I have a problem pickling an extension class. As written in the > Extending/Embedding Manual, I > provided a function __reduce__ that returns the appropreate tuple. > This seams to work fine, > but I still cannot pickle because of the following error: > > >>> from model import hyper > >>> g = hyper.PeriodicGrid(4,4,1) > >>> g.__reduce__() > (,(4.,4.,1.)) > >>> import pickle > >>> pickle.dump(g,file("test","w")) > Traceback (most recent call last): > File "pickle_test.py", line 5, in ? > pickle.dump(g,file("test","w")) > File "/sw/lib/python2.4/pickle.py", line 1382, in dump > Pickler(file, protocol, bin).dump(obj) > File "/sw/lib/python2.4/pickle.py", line 231, in dump > self.save(obj) > File "/sw/lib/python2.4/pickle.py", line 338, in save > self.save_reduce(obj=obj, *rv) > File "/sw/lib/python2.4/pickle.py", line 414, in save_reduce > save(func) > File "/sw/lib/python2.4/pickle.py", line 293, in save > f(self, obj) # Call unbound method with explicit self > File "/sw/lib/python2.4/pickle.py", line 760, in save_global > raise PicklingError( > pickle.PicklingError: Can't pickle : it's > not found as hyper.PeriodicGrid > >>> dir(hyper) > ['Dir', 'Neighbors', 'PeriodicGrid', 'PeriodicPos', '__doc__', > '__file__', '__name__', 'refcount'] > >>> hyper.PeriodicGrid > ^^^^^ I think that's your error. The extension type is declared to be hyper.PeriodicGrid, where it actually is model.hyper.PeriodicGrid (because hyper is in the model package). Pickle stores g.__class__.__module__ (which is "hyper") and g.__class__.__name__ (="PeriodicGrid") to find the class object for reimporting, and on unpickling, tries to do __import__("hyper"), which fails. The tp_name slot of your extension type should be "model.hyper.PeriodicGrid". -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From Scott.Daniels at Acm.Org Sun Jan 2 17:52:41 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 02 Jan 2005 14:52:41 -0800 Subject: mertz@gnosis.cx Message-ID: <41d87891$1@nntp0.pdx.net> I was pointed to appendix A by a comp.lang.py post. In the "except statements" section (which might better be called the "try" statement and include a try: ... finally: ...), you say: The 'except' statement can optionally bind a name to an exception argument: >>> try: ... raise "ThisError", "some message" ... except "ThisError", x: # Bind 'x' to exception argument ... print x ... some message String exceptions should not be encouraged (nor do I think they work). Better code would be: >>> class MyError(Exception): pass >>> try: ... raise MyError, "some message" ... except MyError, x: # Bind 'x' to exception instance ... print x ... some message or, if you don't want two statements: >>> try: ... raise ValueError, "some message" ... except ValueError, x: # Bind 'x' to exception instance ... print x ... some message The x, by the way, is bound to an instance of the class of the exception, and it has a field "args" which will reflect the arguments with which the exception was created. So in these cases, x.args is ('some message',) and if the code were: >>> try: ... raise ValueError("some message", 42) ... except ValueError, x: # Bind 'x' to exception instance ... print x ... ('some message', 42) and x.args would be: ("some message", 42) --Scott David Daniels Scott.Daniels at Acm.Org From jurgenex at hotmail.com Thu Jan 27 22:15:47 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Fri, 28 Jan 2005 03:15:47 GMT Subject: [perl-python] 20050127 traverse a dir References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> Message-ID: Xah Lee wrote: [...] > [long rant about Perl modules snipped] > > # And because the way it is > # written, Yeah, indeed, you correctly identified the root of the problems. If you would have written your Perl program in a normal way instead of in your cryptic wretched style then you would not have had any of the issues that you listed. Even the best programming language in the world cannot stop a bad programmer from writing poor code. But like my old professor always used to say: No program is useless. It can always be used as an example for how not to do things. jue From apardon at forel.vub.ac.be Fri Jan 21 03:15:52 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 21 Jan 2005 08:15:52 GMT Subject: Freezing a mutable (was Re: lambda) References: <41EBA021.5060903@holdenweb.com> <41ed8c13.1209309354@news.oz.net> <41f04937.1388801641@news.oz.net> Message-ID: Op 2005-01-21, Bengt Richter schreef : > On 20 Jan 2005 14:07:57 GMT, Antoon Pardon wrote: > > Would you like a dictionary that acts as you want and takes care of all > problems internally, and accepts keys and values of any type without wrapping > or other modification -- or do you want a wrapper that can make any object > suitable for use as key or value in python's curent definition of dict? > > Just DYFR please. You still haven't you know ;-) My feeling is that I'm hungry and would like to eat and you ask whether my requirements are a sandwhich or a bowl of soup. :-) The real requirement IMO is that any attempt to mutate an object wont result in a mutated key. Both proposals seem to solve that. The second is at the moment for me the most interesting to discuss, since it is a new approach to me, and most likely to learn me something new. -- Antoon Pardon From crap1234 at hotmail.com Thu Jan 6 06:20:35 2005 From: crap1234 at hotmail.com (Stefan Axelsson) Date: Thu, 06 Jan 2005 12:20:35 +0100 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: <344l83F45rstqU1@individual.net> Bulba! wrote: > Nope. IMHO, GPL attempts to achieve the vendor lock-in. For different > purposes than another well-known vendor, but it still does. > > It's actually even worse: the only thing you can't share on a > well-known vendor's platform is the software written by that > well-known vendor -- you can choose to share or choose not to > share whatever you or other people write on this platform. > > If GPL folks had their way, it would not be possible not to "share" > _anything_ you create. It is widely acknowledged that GPL > license has the "viral" aspect of extending itself on your > software - can you point to closed-source licenses that would > have this aspect? None of the licenses I've read except GPL has > this aspect. Then you haven't read very many source code licenses, many (perhaps most?) that state that if you've as much as looked at the code you're not even allowed to write somethings similar twenty years down the line, or anything that remotely resembles something similar. (Most do in fact go a bit further than that, but the legality would be in question. Still it would take you lawyers to get off the hook). Where do you think the 'clean-room approach' came from in the first place? Furthermore, you're most often not allowed to change, disseminate, compile, discuss, etc the code but in fact just look at it. (And when it comes to Microsoft's binary licenses it's not as rosy as you would like to put it, read through them sometime there's a lot more you're not allowed to do than just 'share' it with others.) Can you say NDA? Knew you could. Now, Stallman might or might not want to achieve world domination, not by sharks with lasers on their heads, but by aiming for all software to be free software, but the GPL is actually a lot less ambitious than that. All the GPL says is that: if you received a binary, the person who provided you with it, must provide you with the source code that built it. *All* the source code, not just what he happened to receive, on the off chance that he's modified it. And as having the source code without being able to modify it would be rather pointless, you're allowed to do that too, it's a given. If you don't want to distribute binaries, that's fine, and all of the GPL falls. The GPL doesn't *force* you to share anything. It only says what must happen if you do. And I'm rather tired of the GPL's so called 'viral' nature. Look, if you're using my code, you play by my rules, that's called copyright. If you don't want to play by my rules, fine, don't use my code. So far I'm no better than Microsoft, or Sun (though that might change) or IBM for that matter. With the GPL I'm actually not as bad as that, I'll even let you look at the code, modify it, and distribute copies willy nilly (though you I'm not forcing you to), in fact, I'll even *forbid* others from taking that right away from you. If you use it, however, as a small token of your appreciation, you'll have to also agree to not take the same rights you had away from others. Finally, what *you* do with *your* code is of no concern to the GPL. As long as you don't use *my* code you can do whatever you please. But, and that's a big 'BUT', it really irks me when people release code under e.g. the BSD (or as has happened to me in the past, public domain), and then bitch and moan when I incorporate parts of it in *my* software and release the whole under the GPL. As if that was somehow 'unfair'. Look, (and I'm obviously not saying this to the parent poster as he never expressed any such sentiment, I'm just venting) that's what *you* wanted when you released the code under that license. If you don't want me to do that, then don't use those licenses, mkay. Stefan, -- Stefan Axelsson (email at http://www.cs.chalmers.se/~sax) From jacek.generowicz at cern.ch Mon Jan 10 04:02:46 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 10 Jan 2005 10:02:46 +0100 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> Message-ID: Nick Coghlan writes: > > Usually one or two have trouble grasping that "int" would be perfectly > > adequate in this situation. > > The ability to pass around functions at run-time was probably the > hardest thing to get my head around when I started with Python, And I suspect that this particular case is further complicated by the fact that int is not a function ... it's a type! I can imagine it might make a newbie's brain melt. Still, most of them survive and thoroughly enjoy the course :-) From jeff at ccvcorp.com Tue Jan 4 14:33:13 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 04 Jan 2005 11:33:13 -0800 Subject: Help clean up clumsy code In-Reply-To: <41dabf3d$1@nntp0.pdx.net> References: <41dabf3d$1@nntp0.pdx.net> Message-ID: <10tlrj8h7ffpv42@corp.supernews.com> Scott David Daniels wrote: > Nick Coghlan wrote: > >> A custom generator will do nicely: >> >> Py> def flatten(seq): >> ... for x in seq: >> ... if hasattr(x, "__iter__"): >> ... for y in flatten(x): >> ... yield y >> ... else: >> ... yield x > > > Avoiding LBYL gives you: > def flatten(seq): > for x in seq: > try: > for y in flatten(x): > yield y > except TypeError: > yield x If I'm not mistaken, this will result in infinite recursion on strings. 'for x in aString' will iterate over the characters in the string, even if the string is only a single character, so "for y in flatten('a'):" will not give a type error. You'd need to add special-case tests to watch for this condition (and try not to be too special-case and allow unicode objects to pass). Nick's version works on strings (and unicode objects) because they lack an __iter__() method, even though they follow the (older) sequence protocol. Jeff Shannon Technician/Programmer Credit International From jacek.generowicz at cern.ch Wed Jan 12 03:29:32 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 12 Jan 2005 09:29:32 +0100 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <10u5fu3o7v4h9e3@corp.supernews.com> <10u8e65lju3atbd@corp.supernews.com> Message-ID: Donn Cave writes: > List incomprehensions do not parse well in my eyes. Are you familiar with the Haskell syntax for list comprehensions? For example: http://www.zvon.org/other/haskell/Outputsyntax/listQcomprehension_reference.html Does their striking similarity to mathematical set notation help at all ? From jerf at jerf.org Sun Jan 9 19:12:20 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 09 Jan 2005 19:12:20 -0500 Subject: Long strings as function parameters References: <1105288564.441842.13060@c13g2000cwb.googlegroups.com> Message-ID: On Sun, 09 Jan 2005 08:36:04 -0800, onlyonemc wrote: > I would like to have functions that operate on long strings, 10-100 MB. In > C I would of course pass a pointer to the string for a quick function > call. What is an efficient way to do this in python? Cheers, > -mark Others have pointed out that there is no particular inefficient way to pass a string. However that only solves the immediate problem of passing. Once inside the function you should be aware that all string operations that change the string will create a new string, including slicing and such. This may not be a problem if you are examining it in small chunks, but if you routinely taking distinct multi-megabyte hunks out of it with slices, you will be constructing and destructing a lot of strings. I had thought there was an obvious class in the standard library to assist with this, but I must have been wrong. I think you can load it as an array from the array module (as long as it is an array of bytes and not an encoding like UTF-8 or something), or you might be able to use the mmap module if the string comes from a file. Both of those techniques can also load the info directly from a file so there is only one copy needed. (Wasn't there a "buffer" kind of class at one point, that you could slice into and get something back that didn't make any copies of strings?) Again, this is only an issue depending on usage, and you should probably prototype it while ignoring these issues and see if it is fast enough. But if it isn't, there are options. From francis.girard at free.fr Thu Jan 20 14:00:36 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 20 Jan 2005 20:00:36 +0100 Subject: Overloading ctor doesn't work? In-Reply-To: <35ab8oF4idc25U1@individual.net> References: <35ab8oF4idc25U1@individual.net> Message-ID: <200501202000.36727.francis.girard@free.fr> Hi, It looks like the assertEquals use the != operator which had not been defined to compare instances of your time class and instances of the datetime class. In such a case, the operator ends up in comparing the references to instances, i.e. the "id" of the objects, i.e. their physical memory addresses, which of course can't be the same. And that is why your test fails. Consider defining the __cmp__ method (see 2.3.3 Comparisons of the library reference). Sess also the operator module. Francis Girard LANNILIS Breizh FRANCE Le jeudi 20 Janvier 2005 19:23, Martin H?cker a ?crit?: > Hi there, > > I just tried to run this code and failed miserably - though I dunno why. > Could any of you please enlighten me why this doesn't work? > > Thanks a bunch. > > --- snip --- > import unittest > from datetime import datetime > > class time (datetime): > def __init__(self, hours=0, minutes=0, seconds=0, microseconds=0): > print "blah" > datetime.__init__(self, 1, 1, 1, hours, \ > minutes, seconds, microseconds) > > > class Test (unittest.TestCase): > def testSmoke(self): > # print time() # bombs, and complains that > # the time ctor needs at least 3 arguments > self.assertEquals(datetime(1,1,1,1,2,3,4),time(1,2,3,4)) > > > if __name__ == '__main__': > unittest.main() > --- snap --- > > The reason I want to do this is that I want to work with times but I > want to do arithmetic with them. Therefore I cannot use the provided > time directly. > > Now I thought, just overide the ctor of datetime so that year, month and > day are static and everything should work as far as I need it. > > That is, it could work - though I seem to be unable to overide the ctor. :( > > Why is that? > > cu Martin > > -- > Reach me at spamfaenger (at) gmx (dot) net From wuwei23 at gmail.com Mon Jan 24 01:51:28 2005 From: wuwei23 at gmail.com (alex23) Date: 23 Jan 2005 22:51:28 -0800 Subject: how to write a tutorial In-Reply-To: References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106531824.833549.28720@c13g2000cwb.googlegroups.com> Message-ID: <1106549488.550837.222480@c13g2000cwb.googlegroups.com> Daniel Bickett wrote: > Chris Mattern wrote: > > alex23 wrote: > > > > > Having read your comments on women, > > > > I hadn't looked at that part of his site until now. I can only say: > > gah. Haven't seen something like that since Dave Sim's infamous > > "Tangent" essay. > > It's painfully obvious that it is all for the sole purpose of negative > attention. > You guys are just begging for a YHBT ;-) > > Daniel Bickett From ncoghlan at iinet.net.au Sat Jan 8 03:22:53 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 18:22:53 +1000 Subject: Other notes In-Reply-To: <41def1ea.252340977@news.oz.net> References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> <41DD40F1.5030301@holdenweb.com> <41dda7c5.167823026@news.oz.net> <41def1ea.252340977@news.oz.net> Message-ID: <41DF985D.60902@iinet.net.au> Bengt Richter wrote: > IOW, I think there is a fix: keep tokenizing greedily and tokenize floating point as > a sequence of integers and operators, and let be translated by > the compiler to floating point, and be translated to the > appropriate generator expression implementation. That would be: -> float( + "." + ) -> getattr(int(), ) -> xrange(, ) However, the problem comes when you realise that 1e3 is also a floating point literal, as is 1.1e3. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From evgeni_sergeev at hotmail.com Mon Jan 3 20:47:02 2005 From: evgeni_sergeev at hotmail.com (Evgeni Sergeev) Date: 3 Jan 2005 17:47:02 -0800 Subject: Controlling newlines when writing to stdout (no \r\n). Message-ID: While I can make a verbatim copy of a file like this: file1 = file('ready.pdf', 'rb') file2 = file('out.pdf', 'wb') buffer = file1.read(256) while buffer: file2.write(buffer) buffer = file1.read(256) file1.close() file2.close() I cannot send a verbatim copy to stdout. Python replaces \n with \r\n due to its universal newline support. (This is on Windows). My aim is to send a binary file from a CGI python script. I do this: file1 = file('ready.pdf', 'rb') sys.stdout.write( \ 'Content-type: application/pdf\n' + \ 'Content-disposition: inline; filename=ready.pdf\n\n' + \ file1.read()) file1.close() Checking the traffic with my proxy server reveals that inside the PDF file, all the \n chars have been replaced with \r\n. Is there a way to avoid this intervention? (I avoided the whole problem by sending a HTTP redirect 'Location: ready.pdf\n\n', but I still want to know the answer). Evgeni Sergeev From ncoghlan at iinet.net.au Thu Jan 6 08:51:23 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 06 Jan 2005 23:51:23 +1000 Subject: get the IP address of a host In-Reply-To: References: Message-ID: <41DD425B.7080703@iinet.net.au> J Berends wrote: > Lee Harr wrote: >> Basically, it scrapes the output from ifconfig for the >> actual address assigned to the interface. Works perfectly >> on FreeBSD and Linux (given the correct configuration). > > > Nice way, have to device something for windows than. Use the same approach, but scrape the output of ipconfig instead. Use subprocess to run the command in Python 2.4, or work something out with one of the popen variants for earlier versions. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From invalidemail at aerojockey.com Mon Jan 10 08:48:45 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 10 Jan 2005 05:48:45 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> <7xllb2f3z4.fsf@ruckus.brouhaha.com> <1105355380.040837.189270@c13g2000cwb.googlegroups.com> <7xis65a5w6.fsf@ruckus.brouhaha.com> <1105357839.696387.309900@c13g2000cwb.googlegroups.com> <7xr7kt314a.fsf@ruckus.brouhaha.com> Message-ID: <1105364925.848973.73080@c13g2000cwb.googlegroups.com> Paul Rubin wrote: > > The Zen of Python, by Tim Peters > > Beautiful is better than ugly. => +1 macros > Explicit is better than implicit. => +1 macros > Simple is better than complex. => +1 macros > Complex is better than complicated. => I don't understand this, +0 > Flat is better than nested. => not sure, +0 > Sparse is better than dense. => +1 macros > Readability counts. => +1 macros > Special cases aren't special enough to break the rules. => +1 macros > Although practicality beats purity. => +1 macros > Errors should never pass silently. => +1 macros > Unless explicitly silenced. => +1 macros > In the face of ambiguity, refuse the temptation to guess. => +1 macros > There should be one-- and preferably only one --obvious way to do it. => -1 > Although that way may not be obvious at first unless you're Dutch. => ??? > Now is better than never. => +1 macros, let's do it > Although never is often better than *right* now. => +1 > If the implementation is hard to explain, it's a bad idea. => unknown, +0 > If the implementation is easy to explain, it may be a good idea. => +0 > Namespaces are one honking great idea -- let's do more of those! => +1 > > I'm -1 on doing stuff by received dogma, but in this particular case > it looks to me like the dogma is +12 for macros. What are your thoughts? Paul, When I asked you to do this, it was just a rhetorical way to tell you that I didn't intend to play this game. It's plain as day you're trying to get me to admit something. I'm not falling for it. If you have a point to make, why don't you just make it? -- CARL BANKS From aleaxit at yahoo.com Tue Jan 18 16:41:39 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 18 Jan 2005 22:41:39 +0100 Subject: Contributor's List References: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> <1105006211.527899.318740@c13g2000cwb.googlegroups.com> Message-ID: <1gqlvf0.1pklxn99wa5amN%aleaxit@yahoo.com> wrote: ... > Is this mean't to only cover additional entries which were added in > the 2nd edition, or is it also mean't to encompass entries which were > carried over from the 1st edition as well. The latter: it covers all entries. > If it is both, then the editing must have been quite cut throat as I It was indeed. Fewer than half of the recipes in the 2nd edition are "carried over" (with heavy edits in all cases) from the first. > dropped from 3 entries in the 1st edition to 0 in the 2nd edition. True, alas: your three recipes in the Distributed Processing chapter were dropped. Not light-heartedly, believe me. > I can sort of understand if the intent was to get rid of entries which It was of course not my intent to *GET RID* of anything whatsoever: I selected all the recipes for the 1st edition, just as for the 2nd one, and would dearly have loved to keep each and every one of them (I wouldn't have selected them in the first place if I didn't like them). The INTENT was to add over a couple hundred new and (I do believe) wonderful recipes; the CONSTRAINT was that I couldn't just blithely double the book's size. So, the only way to make space for the new was to ruthlessly cut much of the old, in order to limit the book's size within reasonable boundaries. > referenced packages which weren't regarded as mainstream. I guess > it is only 14 years of work down the drain. ;-( I wish you wouldn't look on it that way. The Python Cookbook is not intended as a validation or invalidation of any particular piece of software -- just, if you will, as a reflection of how widespread the current interest on it is. Consider: _my_ own lovechild "non-mainstream" package is gmpy, OK? Well, I didn't put even ONE recipe about it in either edition nor on the online Cookbook -- nor did anybody else post recipes using it to the Cookbook, validating my belief that it's too specialized to cover in the book. I don't consider this means "years of work down the drain": gmpy scratches the itch I made it for, and occasional references to others using it are just a little extra bonus, even if they do make my heart give a little jump of joy each time I see one. I think that's the spirit in which to do open-source development... Alex From solipsis at pitrou.net Thu Jan 6 08:34:15 2005 From: solipsis at pitrou.net (Antoine Pitrou) Date: Thu, 06 Jan 2005 14:34:15 +0100 Subject: parameterized metaclass (or metametaclass) Message-ID: <1105018456.389.12.camel@p-dhcp-333-72.rd.francetelecom.fr> Hi, I've been looking at writing parameterized metaclasses and here are the two solutions I've come to: (my goal was to build a way to automatically add a hash function that would take into account a selected list of object attributes) 1. all-in-one metametaclass: class Autohash2(type): """ Metametaclass that instantiates into a metaclass creating a hash function based on the attributes passed on instantiation. """ def __new__(cls, hash_attributes): def class_new(cls, name, bases, d): print "New class", name l = hash_attributes _hash = hash _tuple = tuple c = _hash(_tuple([_hash(k) for k in l])) def object_hash(obj): g = obj.__getattribute__ return _hash(_tuple([_hash(g(k)) for k in l])) d['__hash__'] = object_hash return super(Autohash2, cls).__new__(cls, name, bases, d) name = '__private' bases = (type,) d = {'__new__': class_new} print "New metaclass", name return type.__new__(cls, name, bases, d) 2. with the metametaclass property slightly abstracted away: class Metametaclass(type): def __new__(cls, name, bases, dict_): d = { '__new__': dict_['class_new'] } def meta_new(cls, *args, **kargs): print "New metaclass" name = '__private' bases = (type,) return super(Metametaclass, cls).__new__(cls, name, bases, d) dict_['__new__'] = meta_new print "New metametaclass", name return type.__new__(cls, name, bases, dict_) class Autohash(type): __metaclass__ = Metametaclass def __init__(cls, hash_attributes): cls.hash_attributes = hash_attributes def class_new(cls, name, bases, d): print "New class", name l = cls.hash_attributes _hash = hash _tuple = tuple c = _hash(_tuple([_hash(k) for k in l])) def object_hash(obj): g = obj.__getattribute__ return _hash(_tuple([_hash(g(k)) for k in l])) d['__hash__'] = object_hash return super(Autohash, cls).__new__(cls, name, bases, d) Both of those metametaclasses can be used (successfully!) in the following way: class Address(object): __metaclass__ = Autohash3(('host', 'port')) # a = Address() a.host = 'localhost' a.port = 5555 b = copy.copy(a) hash(a) == hash(b) I was wondering if there is some simpler way of building parameterized metaclasses ? Regards Antoine. From merkosh at hadiko.de Fri Jan 28 17:22:05 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Fri, 28 Jan 2005 23:22:05 +0100 Subject: example needed: sip + Qt In-Reply-To: <1106918688.3941.51.camel@albert.localnet> References: <1106918688.3941.51.camel@albert.localnet> Message-ID: <200501282322.16402.merkosh@hadiko.de> On Friday 28 January 2005 14:24 pm, Craig Ringer wrote: > Out of curiosity, would this be for an extension module used in an > embedded Python interpreter, or for plain extension module for use with > a standalone interpreter? I am writing an application program using Python and PyQt: https://savannah.nongnu.org/projects/lmc/ At one point I am using a QListView but need my items to be sorted numerically. There is no function to set the sort-criterea and the solution to this is subclassing QListViewItem and overwrite the comparison functions. However, doing so in Python was awfully slow for a greater number of items, so I want to rewrite this in C++ and wrap it back to python. Ciao Uwe -- Kilroe hic erat! -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 492 bytes Desc: not available URL: From grahamd at dscpl.com.au Thu Jan 13 23:11:56 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 13 Jan 2005 20:11:56 -0800 Subject: a ConfigParser wtf moment In-Reply-To: References: Message-ID: <1105675916.355620.324340@f14g2000cwb.googlegroups.com> Sort of hard to explain, but if you put another: list = configuration.items("core") print list at the end of the script, you will find that the original config hasn't been changed. It is a quirk of how the items() method is implemented using 'yield' that means that you see what you do. In particular to use 'yield' it it necessary to create a temporary dictionary which contains the key/value pairs from that section of the config and then overlay it with the user supplied vars. Ie., the items() code has: . d = self._defaults.copy() . try: . d.update(self._sections[section]) . except KeyError: . if section != DEFAULTSECT: . raise NoSectionError(section) . # Update with the entry specific variables . if vars: . d.update(vars) See the last line, that will replace the value of 'xyzzy' with that passed in as argument to items(). To avoid this, you need to write something like: . list = [] . for key in configuration.options("core"): . list.append((key,configuration.get("core",substitution)) . print list This cause me problems for a different reason, ie., that user vars keys appear in what items() returns. I avoid using items() for this reason. From danperl at rogers.com Sat Jan 29 20:56:35 2005 From: danperl at rogers.com (Dan Perl) Date: Sat, 29 Jan 2005 20:56:35 -0500 Subject: [perl-python] sending email References: <1107041765.890014.112530@c13g2000cwb.googlegroups.com> Message-ID: I recommend the example in the Python Library Reference as a better example: http://www.python.org/doc/lib/SMTP-example.html. You can also find the entire description of the smtplib module in the same section (http://www.python.org/doc/lib/module-smtplib.html). Xah Lee's example is missing: - The login() call needed by SMTP hosts that require authentication. - The 'From:' and 'To:' addresses in the header of the email. They are not mandatory, but you would probably use them. From http Mon Jan 10 07:44:05 2005 From: http (Paul Rubin) Date: 10 Jan 2005 04:44:05 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> <7xllb2f3z4.fsf@ruckus.brouhaha.com> <1105355380.040837.189270@c13g2000cwb.googlegroups.com> <7xis65a5w6.fsf@ruckus.brouhaha.com> <1105357839.696387.309900@c13g2000cwb.googlegroups.com> Message-ID: <7xr7kt314a.fsf@ruckus.brouhaha.com> "Carl Banks" writes: > Paul Rubin wrote: > > "Carl Banks" writes: > > > > So do you approve of the movement to get rid of the print > statement? > > > > > > Any little incremental change in Python you could make by having or > not > > > having a print statement would be minor compared to the H-Bomb of > > > ugliness we'd get if suites of statements were to be allowed inside > > > Python expressions. Having or not having a print statement might > > > violate some small aspect of the Zen, but it won't rape the whole > list. > > > > How about macros? Some pretty horrible things have been done in C > > programs with the C preprocessor. But there's a movememnt afloat to > > add hygienic macros to Python. Got any thoughts about that? > > How about this: Why don't you go to a Python prompt, type "import > this", and read the Zen of Python. Consider each line, and whether > adding macros to the language would be going against that line or for > it. After you've done that, make an educated guess of what you think > I'd think about macros, citing various Zens to support your guess. > > Then I'll tell you what my my thoughts about it are. The Zen of Python, by Tim Peters Beautiful is better than ugly. => +1 macros Explicit is better than implicit. => +1 macros Simple is better than complex. => +1 macros Complex is better than complicated. => I don't understand this, +0 Flat is better than nested. => not sure, +0 Sparse is better than dense. => +1 macros Readability counts. => +1 macros Special cases aren't special enough to break the rules. => +1 macros Although practicality beats purity. => +1 macros Errors should never pass silently. => +1 macros Unless explicitly silenced. => +1 macros In the face of ambiguity, refuse the temptation to guess. => +1 macros There should be one-- and preferably only one --obvious way to do it. => -1 Although that way may not be obvious at first unless you're Dutch. => ??? Now is better than never. => +1 macros, let's do it Although never is often better than *right* now. => +1 If the implementation is hard to explain, it's a bad idea. => unknown, +0 If the implementation is easy to explain, it may be a good idea. => +0 Namespaces are one honking great idea -- let's do more of those! => +1 I'm -1 on doing stuff by received dogma, but in this particular case it looks to me like the dogma is +12 for macros. What are your thoughts? From forestiero at qwest.net Mon Jan 31 12:19:19 2005 From: forestiero at qwest.net (DogWalker) Date: Mon, 31 Jan 2005 09:19:19 -0800 Subject: variable declaration In-Reply-To: <20050130231913.1213891237.EP@zomething.com> References: <20050130231913.1213891237.EP@zomething.com> Message-ID: <20050131171501.18641.42639@linux.local> "EP" said: >> ------------Original Message------------ >> From: Alexander_Zatvornitskiy at p131.f3.n5025.z2.fidonet.org (Alexander Zatvornitskiy) > >> >> Hello All! >> >> I'am novice in python, and I find one very bad thing (from my point of >> view) in >> language. There is no keyword or syntax to declare variable, like 'var' >> in >> Pascal, or special syntax in C. It can cause very ugly errors,like >> this: >> >> epsilon=0 >> S=0 >> while epsilon<10: >> S=S+epsilon >> epselon=epsilon+1 >> print S >> >> It will print zero, and it is not easy to find such a bug! > > >Hmmm. I am surely an expert in writing buggy code, but I can not say I make this error in Python. Why is that? > >I'm not sure, but a couple things that may help me miss making this mistake in practice may be (somewhat informal in my case) unit testing - I test for correct results for at least a few cases. > >It may also help that with Python I can code at a somewhat higher conceptual level, or maybe it is just the syntax that helps avoid these problems: > >>>> for epsilon in range (0,10): > S=S+epsilon > >>>> for epsilon in range (0,10): > S=S+epselon > >Traceback (most recent call last): > File "", line 2, in ? > S=S+epselon >NameError: name 'epselon' is not defined > > >It may seem like jumping off a cliff, but the improvement in readability (the variable declarations being visual clutter) makes it much easier for me to see my code, and any typos in it. > >It seems it would be simple enough to have one's code, or another script, automatically print out a sorted list of the variables - which would make the error you note obvious. But I haven't needed this, yet at least. > >You might like Python and find the lack of variable declaration checking not a problem. It's worth a shot. > > class MyVars(object): __slots__ = ['epsilon', 'thud', 'foo'] mv = MyVars() mv.epselon = 42 Traceback (most recent call last) /home/dw/KirbyBase-1.7/ AttributeError: 'MyVars' object has no attribute 'epselon' mv.epsilon = 42 From craig at postnewspapers.com.au Fri Jan 7 00:56:26 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 07 Jan 2005 13:56:26 +0800 Subject: Embedding a restricted python interpreter In-Reply-To: <41DD5C0B.3030007@holdenweb.com> References: <41DD5C0B.3030007@holdenweb.com> Message-ID: <1105077385.28776.69.camel@rasputin.localnet> On Thu, 2005-01-06 at 23:40, Steve Holden wrote: > Jp Calderone wrote: > > [...] > > > > > > A Python sandbox would be useful, but the hosting provider's excuse > > for not allowing you to use mod_python is completely bogus. All the > > necessary security tools for that situation are provided by the > > platform in the form of process and user separation. > > Not sure this is strictly true: mod_python gets loaded into the server's > address space and gives the ability to add any type of handler. While > Apache might well be able to respawn failed subprocesses, it's not > something that most hosting providers would like to have to do all the > time for many hosted sites. I wonder if SCGI or a similar "persistent CGI" solution might be more practical for running CGI scripts under specific user accounts. -- Craig Ringer From johng2001 at rediffmail.com Sun Jan 23 16:52:02 2005 From: johng2001 at rediffmail.com (johng2001 at rediffmail.com) Date: 23 Jan 2005 13:52:02 -0800 Subject: JPype and classpath (Was Re: embedding jython in CPython... ) In-Reply-To: References: <1106446384.384110.25150@z14g2000cwz.googlegroups.com> Message-ID: <1106517122.552509.318400@f14g2000cwb.googlegroups.com> Thanks for the response. However, I continue to have problems. Allow me to give some more detail. For simplicity of testing, I hard coded the classpath and JVM path (BTW getDefaultJVMPath() returns None on my system) import os, os.path from jpype import * startJVM("C:/jdk1.5.0/jre/bin/client/jvm.dll", "-Djava.class.path=D:/Temp/classes") ... shutdownJVM() I have setup a classes folder in the script folder (D:/Temp) and have placed test.class in it. I run the script from the script folder (working directory is the same as script's root path in this case) Now how do I load the class test? I am afraid I cannot make that out from the docs. The simple test class is public class test { public int i = 100; } What do I have to do before I can write test().i ? Thank you for your time. From "(.removethis.)kartic.krishnamurthy" at gmail.com Sat Jan 15 10:16:02 2005 From: "(.removethis.)kartic.krishnamurthy" at gmail.com (.removethis.) Date: Sat, 15 Jan 2005 15:16:02 GMT Subject: How can I get the names of the files in a directory? In-Reply-To: References: Message-ID: Sara Fwd said the following on 1/15/2005 8:10 AM: > Can you guys also help me find a module that looks in > a directory and print out the names of the files in there? You can use glob: >>> import glob >>> from os.path import isfile >>> print filter(isfile, glob.glob('/tmp/*')) # can use patterns (will print a list of all files in the given directory, matching the given pattern) If you want to traverse a directory tree recursively, please take a look at this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/200131 Thanks, --Kartic From martin at v.loewis.de Thu Jan 20 12:34:00 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 20 Jan 2005 18:34:00 +0100 Subject: rotor replacement In-Reply-To: <7x1xchlpqv.fsf@ruckus.brouhaha.com> References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> Message-ID: <41efeb82$0$27807$9b622d9e@news.freenet.de> Paul Rubin wrote: > Some countries have laws about cryptography software (against some > combination of export, import, or use). The Python maintainers didn't > want to deal with imagined legal hassles that might develop from > including good crypto functions in the distribution. Then it became > obvious that the same imagined hassles could also befall the rotor > module, so that was removed. Do you know this for a fact? The PSF does comply with the U.S. American export procedures for crypto code, and reports the crypto code in Python appropriately to BXA. Regards, Martin From andre.roberge at gmail.com Fri Jan 21 16:56:11 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Fri, 21 Jan 2005 17:56:11 -0400 Subject: Simple (newbie) regular expression question In-Reply-To: <1106340047.788392.74130@f14g2000cwb.googlegroups.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <1106340047.788392.74130@f14g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > Andr? Roberge wrote: > >>Sorry for the simple question, but I find regular >>expressions rather intimidating. And I've never >>needed them before ... >> >>How would I go about to 'define' a regular expression that >>would identify strings like >>__alphanumerical__ as in __init__ >>(Just to spell things out, as I have seen underscores disappear >>from messages before, that's 2 underscores immediately >>followed by an alphanumerical string immediately followed >>by 2 underscore; in other words, a python 'private' method). >> >>Simple one-liner would be good. >>One-liner with explanation would be better. >> >>One-liner with explanation, and pointer to 'great tutorial' >>(for future reference) would probably be ideal. >>(I know, google is my friend for that last part. :-) >> >>Andre > > > Firstly, some corrections: (1) google is your friend for _all_ parts of > your question (2) Python has an initial P and doesn't have private > methods. > > Read this: > > >>>>pat1 = r'__[A-Za-z0-9_]*__' >>>>pat2 = r'__\w*__' >>>>import re >>>>tests = ['x', '__', '____', '_____', '__!__', '__a__', '__Z__', > > '__8__', '__xyzzy__', '__plugh'] > >>>>[x for x in tests if re.search(pat1, x)] > > ['____', '_____', '__a__', '__Z__', '__8__', '__xyzzy__'] > >>>>[x for x in tests if re.search(pat2, x)] > > ['____', '_____', '__a__', '__Z__', '__8__', '__xyzzy__'] > > > I've interpreted your question as meaning "valid Python identifier that > starts and ends with two [implicitly, or more] underscores". > > In the two alternative patterns, the part in the middle says "zero or > more instances of a character that can appear in the middle of a Python > identifier". The first pattern spells this out as "capital letters, > small letters, digits, and underscore". The second pattern uses the \w > shorthand to give the same effect. > You should be able to follow that from the Python documentation. > Now, read this: http://www.amk.ca/python/howto/regex/ > > HTH, > > John > Thanks for it all. It does help! Andr? From b at b.b Sun Jan 9 01:24:20 2005 From: b at b.b (Roose) Date: Sun, 09 Jan 2005 06:24:20 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7xr7kv8bmt.fsf at ruckus.brouhaha.com... > "Roose" writes: > > My point was that you can't do a lot of hardware interface programming in > > pure Python -- there would be so much non-trivial code in C that it would be > > hard to call it a Python OS. > > Why do you say that? Is the same thing not true of C, where you need > some assembly code at the lowest levels? Because Linux has some > assembly code, would you say that it's not written in C? It's a difference of degree, but an important difference. I haven't looked at Linux or Windows NT source, but my guess is the assembly used is just small functions for accessing special CPU instructions for atomicity, context switching, and the like. I KNOW they don't have huge amounts of assembly simply because they run on different architectures. But are you really going to write a virtual memory system in Python? Are you going to write a file system, and a task scheduler in Python? Are you going to have people write device drivers in Python? I'm not saying it can't be done, but it would be a poor engineering decision, and the rationale thus far seems to be "Python is cool, I like OSes, let's write a whole OS in Python". If that's not the case then let me know what your rationale is. The right tool for the right job. I love Python probably more than any other language. But it's not the right tool for every job. I don't know why people would think it is, just as C is not the right tool for every job (which is one of the reasons I learned Python, being a C programmer first). > > > So this basically proves my point -- that you need different hardware > > altogether in order to make an OS in a high level language like Lisp or > > Python. > > It doesn't prove anything of the sort. The Lisp hardware was needed > for performance reasons, back in the day. OK, then give me an example of Lisp OS that runs on a PC. I would like to install it on my PC tomorrow. Or maybe my Mac. That was your whole point, originally, that since it could be done in Lisp, why not Python? From xah at xahlee.org Tue Jan 18 00:49:20 2005 From: xah at xahlee.org (Xah Lee) Date: 17 Jan 2005 21:49:20 -0800 Subject: [perl-python] 20050118 keyed list Message-ID: <1106027360.920787.321590@z14g2000cwz.googlegroups.com> ? # -*- coding: utf-8 -*- ? ? # in Python, there's a special type of ? # data structure called keyed list. it ? # is a unordered list of pairs, each ? # consists of a key and a value. It is ? # also known as dictionary. ? ? # define a keyed list ? aa = {'john':3, 'mary':4, 'jane':5, 'vicky':7} ? print aa ? ? # getting value from a key ? print 'mary is', aa['mary'] ? ? # delete an entry ? del aa['vicky'] ? print aa ? ? # get just the keys ? print aa.keys() ? ? # check if a key exists ? print aa.has_key('mary') ? ? # to learn more, ? # type help() and DICTIONARIES ? # or see ? # http://python.org/doc/2.3.4/tut/node7.html ? ? ------------------------------------------- ? # in perl, keyed-list is done like this: ? ? %a = ('john',3, 'mary', 4, 'jane', 5, 'vicky',7); ? use Data::Dumper qw(Dumper); ? print Dumper \%a; ? ? # the syntax of keyed list in Perl is too complex ? # to be covered in a short message. ? # see "perldoc perldata" for an unix-styled course. ? ? Xah ? xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html From mefjr75 at hotmail.com Tue Jan 25 18:16:32 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 25 Jan 2005 15:16:32 -0800 Subject: Help with saving and restoring program state References: <85b54e91.0501241556.d281f90@posting.google.com> Message-ID: <1106694992.609209.305270@f14g2000cwb.googlegroups.com> Jacob H wrote: > Hello list... > > I'm developing an adventure game in Python (which of course is lots of > fun). I am glad you are having fun , after all life is so short, isn't that what it is all about ;) > One of the features is the ability to save games and restore the > saves later. I'm using the pickle module to implement this. Capturing > current program state and neatly replacing it later is proving to be > trickier than I first imagined, so I'm here to ask for a little > direction from wiser minds than mine! > > When my program initializes, each game object is stored in two places > -- the defining module, and in a list in another module. The following > example is not from my actual code, but what happens is the same. > > (code contained in "globalstate" module) > all_fruit = [] > > (code contained in "world" module) > class Apple(object): # the class hierarchy goes back to object, anyway > def __init__(self): > self.foo = 23 > self.bar = "something" > globalstate.all_fruit.append(self) > apple = Apple() [snip] Ok here is a guess. (I recently did something similar, maybe this will help) If you already knew about this stuff then just ignore me :) You have defined a class for your objects, which is a nifty 'container'. The apple class can also keep track of the total amount of apple instances handed out. Sometimes it is better to let the objects handle there own state. Py> class Apple(object): ... total = 0 # this is a 'class variable' shared by all instances ... def __init__(self): ... self.__class__.total += 1 ... self.foo = 23 # this is an 'instance variable/name' ... self.bar = "something" ... apple = Apple() ... apple_two = Apple() ... print apple_two.total ... 2 ... apple_three = Apple() ... print apple.total ... 3 ... print apple_three.total ... 3 Now you can just pickle them and when you unpickle them as usual. Also another idea is to use a class instead of a global. I'll admit it I have a personal distaste for them, but classes work so well I never miss them. Py>class Store(object): ... pass Now just create an instance and add your attributes. Py>store = Store() ...store.color = 'red' ...store.height = 5.7 ...store.secret = 42 And get them back when needed. Py>self.SetHieght(store.hieght) Hth M.E.Farmer From aleaxit at yahoo.com Fri Jan 21 17:58:47 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 21 Jan 2005 23:58:47 +0100 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> Message-ID: <1gqrjqz.h87lff1yps8tvN%aleaxit@yahoo.com> Timothy Fitz wrote: ... > Perhaps Tim Peters is far too > concise for my feeble mind It's Zen, it's beyond Mind. Let it speak to your True Self! Alex From b at b.b Sun Jan 9 23:46:24 2005 From: b at b.b (Roose) Date: Mon, 10 Jan 2005 04:46:24 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" wrote in message news:7x6526otw3.fsf at ruckus.brouhaha.com... > "Roose" writes: > > > I've written file systems in Python, and task schedulers in > > > Javascript, and they were fine for their purposes > > > > Uh, not to be rude, but what are you talking about? If I'm not mistaken > > Javascript is that scripting language that runs inside a browser, > > Correct. > > > an application. How are you going to save and restore CPU state in > > Javascript, or even call assembly that does it in Javascript? How > > do you switch into kernel mode in Javascript? We are on completely > > different pages apparently. > > Correct. Are you actually going to answer any of my questions? Let's see this "JavaScript task scheduler" you have written! I'm calling bullshit on that, seeing as you declined to say anything useful about it. But I'm open to learn anything. Let's see it. Until then I'm not sure I want to spend a lot of energy arguing with you, because you're either pulling my leg or just profoundly mistaken. From grig.gheorghiu at gmail.com Fri Jan 28 01:09:32 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 27 Jan 2005 22:09:32 -0800 Subject: python under java References: <41f98cba$0$129$5fc30a8@news.tiscali.it> Message-ID: <1106892572.277763.116520@f14g2000cwb.googlegroups.com> At a command prompt, do "which python" to see where the python binary lives. Then specify the full path to python in your exec() call, instead of just "python". What probably happens is that you don't have the python binary in your PATH when you run exec() from your Java code. Grig From claird at lairds.us Tue Jan 25 18:08:14 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 25 Jan 2005 23:08:14 GMT Subject: Another scripting language implemented into Python itself? References: Message-ID: In article , Quest Master wrote: . . . >I know C/C++ might be better suited for a task of this kind, but most >of the modules in my application which need speed have already been >coded in C++. I want to use Python as the "glue" for this project; . . . I've lost track of what "this kind" means here; why do you think C/C++ is a better language for writing a language interpreter? Is it because, for example, Python's interpre- ter has traditionally been written in C? From lkirsh at cs.ubc.ca Sun Jan 30 16:54:38 2005 From: lkirsh at cs.ubc.ca (Lowell Kirsh) Date: Sun, 30 Jan 2005 13:54:38 -0800 Subject: how do i create such a thing? Message-ID: I want to create a class called DefaultAttr which returns a default value for all attributes which haven't been given values yet. It will work like this: >> x = DefaultAttr(99) >> print x.foo 99 >> print x.bar 99 >> x.foo = 7 >> print x.foo 7 I already have a similar class called DefaultDict which works similarly which I assume would be a good thing to use. Lowell From grante at visi.com Thu Jan 6 10:56:48 2005 From: grante at visi.com (Grant Edwards) Date: 06 Jan 2005 15:56:48 GMT Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> <41DD5C6B.2070708@holdenweb.com> Message-ID: <41dd5fc0$0$45187$a1866201@visi.com> On 2005-01-06, Steve Holden wrote: > Peter Hansen wrote: > > [...] >> >> But the whole argument is fairly moot... I've needed a rectangle >> operation only once in the last ten years, and if I hadn't known at >> the time that my editor could do it (and spent about half an hour >> figuring out how it worked), I could have written a utility to >> do the job faster if I'd been using Python at the time... > > Or even used cut(1) from the command line. IIRC, that was the first thing suggested. Using rectangular operations in an editor was a ways down the list of alternatives. -- Grant Edwards grante Yow! Is this ANYWHERE, at USA? visi.com From bob_smith_17280 at hotmail.com Tue Jan 18 19:41:16 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Tue, 18 Jan 2005 19:41:16 -0500 Subject: file copy portability Message-ID: Is shutil.copyfile(src,dst) the *most* portable way to copy files with Python? I'm dealing with plain text files on Windows, Linux and Mac OSX. Thanks! From jeff at ccvcorp.com Wed Jan 5 17:02:10 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 05 Jan 2005 14:02:10 -0800 Subject: What could 'f(this:that=other):' mean? In-Reply-To: <41DC52CA.5070104@pytex.org> References: <41DC52CA.5070104@pytex.org> Message-ID: <10toomjdjcs5v21@corp.supernews.com> Jonathan Fine wrote: > Giudo has suggested adding optional static typing to Python. > (I hope suggested is the correct word.) > http://www.artima.com/weblogs/viewpost.jsp?thread=85551 > > An example of the syntax he proposes is: > > def f(this:that=other): > > print this > > This means that f() has a 'this' parameter, of type 'that'. > And 'other' is the default value. Hm; so for a slightly more concrete example, one might have def fib_sequence(length:int=9): ... > I'm going to suggest a different use for a similar syntax. > > In XML the syntax > > > is used for name spaces. > > Name spaces allow independent attributes to be applied to an > element. For example, 'fo' attributes for fonts and layout. > XSLT is of course a big user of namespaces in XML. > > Namespaces seems to be a key idea in allow independent > applications to apply attributes to the same element. > [...] > Here's an example of how it might work. With f as above: > > f(this:that='value') > {'that': 'value'} I fail to see how this is a significant advantage over simply using **kwargs. It allows you to have multiple dictionaries instead of just one, that's all. And as you point out, it's trivial to construct your own nested dicts. Besides, Python already uses the concept of namespaces by mapping them to object attributes. Module references are a namespace, exposed via the attribute-lookup mechanism. This (IMO) fails the "there should be one (and preferably only one) obvious way to do things" test. The functionality already exists, so having yet-another way to spell it will only result in more confusion. (The fact that we're borrowing the spelling from XML does little to mollify that confusion.) > 3. Granted (2), perhaps function calls are first in the > queue for syntactic sugar. Huh? How much simpler of syntax do you want for calling a function? I'm not sure what you'd want as "sugar" instead of funcname(). Jeff Shannon Technician/Programmer Credit International From ehenriqu at gmail.com Thu Jan 27 08:38:14 2005 From: ehenriqu at gmail.com (Eduardo Henriquez A.) Date: Thu, 27 Jan 2005 09:38:14 -0400 Subject: Python-list Digest, Vol 16, Issue 457 In-Reply-To: <20050127132025.C9F281E400B@bag.python.org> References: <20050127132025.C9F281E400B@bag.python.org> Message-ID: <810c6a580501270538319d8e88@mail.gmail.com> On Thu, 27 Jan 2005 14:20:25 +0100 (CET), python-list-request at python.org wrote: > Send Python-list mailing list submissions to > python-list at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to > python-list-request at python.org > > You can reach the person managing the list at > python-list-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Python-list digest..." > > > Today's Topics: > > 1. how to pass attribute name via sys.argv (Felix Hebeler) > 2. Re: how to pass attribute name via sys.argv (Wolfram Kraus) > 3. Re: how to pass attribute name via sys.argv (Gilles Lenfant) > 4. Re: Please suggest on the book to follow (Satchidanand Haridas) > 5. Re: redirect of standard output of jython to JTextArea > (Jan Gregor) > 6. Point of Sale (Andreas Pauley) > 7. Re: Please suggest on the book to follow (Ola Natvig) > 8. a question about boost.python (Li Daobing) > 9. Re: What's so funny? WAS Re: rotor replacement (Lucas Raab) > 10. Re: exclude binary files from os.walk (Mark McEahern) > 11. Re: import hook, overwrite import? (Steve Holden) > > > > ---------- Forwarded message ---------- > From: Felix Hebeler > To: python-list at python.org > Date: Thu, 27 Jan 2005 13:48:28 +0100 > Subject: how to pass attribute name via sys.argv > Hi all, > I am doing some Python scripting for a while, but I'm not too deep into > it yet. So I have a problem I can't solve. > > I need to call an object attribute: > > value = object.attrName[0] > > the problem is, that the attribute name can only be specified at runtime. > > So what I have is something like > > >>> attrName = sys.argv[1] > >>> attrName > 'cellsize' > > and I need to pass it on so I can call > > value = object.cellsize[0] > > Can this be done using Python? > > Thanks for any hints > > Cheers > Felix > > > > ---------- Forwarded message ---------- > From: Wolfram Kraus > To: python-list at python.org > Date: Thu, 27 Jan 2005 13:53:26 +0100 > Subject: Re: how to pass attribute name via sys.argv > Felix Hebeler wrote: > > Hi all, I am doing some Python scripting for a while, but I'm not too > > deep into it yet. So I have a problem I can't solve. > > > > I need to call an object attribute: > > > > value = object.attrName[0] > > > > the problem is, that the attribute name can only be specified at > > runtime. > > > > So what I have is something like > > > >>>> attrName = sys.argv[1] attrName > > 'cellsize' > > > > and I need to pass it on so I can call > > > > value = object.cellsize[0] > Use getattr: > value = getattr(object, attrName)[0] > > > > > Can this be done using Python? > > > > Thanks for any hints > > > > Cheers Felix > > HTH, > Wolfram > > > > ---------- Forwarded message ---------- > From: Gilles Lenfant > To: python-list at python.org > Date: Thu, 27 Jan 2005 13:57:02 +0100 > Subject: Re: how to pass attribute name via sys.argv > Felix Hebeler a ?crit : > > Hi all, > > I am doing some Python scripting for a while, but I'm not too deep into > > it yet. So I have a problem I can't solve. > > > > I need to call an object attribute: > > > > value = object.attrName[0] > > > > the problem is, that the attribute name can only be specified at runtime. > > > > So what I have is something like > > > > >>> attrName = sys.argv[1] > > >>> attrName > > 'cellsize' > > > > and I need to pass it on so I can call > > > > value = object.cellsize[0] > > > > > > Can this be done using Python? > > > > Thanks for any hints > > > > Cheers > > Felix > > The builtin "setattr" is your friend. > "object" is now a reserved (builtin) name, use "objekt" instead. > > class Foo(object): > pass > objekt = Foo() > attrName = sys.argv[1] > values = ['foo', 'bar', 'whatever'] > setattr(objekt, attrName, values) > > HTH > > -- > Gilles > > > > ---------- Forwarded message ---------- > From: Satchidanand Haridas > To: santanu > Date: Thu, 27 Jan 2005 18:34:17 +0530 > Subject: Re: Please suggest on the book to follow > Hi, > > Probably the best resources for learning Python are available online. > Here are a few sites that you might find helpful: > > 1. http://byteofpython.info/ > > 2. http://www.diveintopython.org/ -- Writted by Mark Pilgrim, covers > many advanced material. The site says /"Dive into Python"/ is a "Python > book for experienced programmers." > > 3. http://gnosis.cx/TPiP/ -- "Site for Text Processing in Python", a > book by David mertz. You will find many other very good Python related > material on his website. > > regards, > Satchit > > ---- > Satchidanand Haridas (sharidas at zeomega dot com) > > ZeOmega (www.zeomega.com) > Open Minds' Open Solutions > > #20,Rajalakshmi Plaza, > South End Road, > Basavanagudi, > Bangalore-560 004, India > > santanu wrote: > > >Hi all, > > > >I know a little python (not the OOP part) learnt by studying the online > > > >tutorial. Now I would like to learn it more thoroughly. > > > >I have access to 'Programming Python' which I liked (on flipping > >through the > >pages), but the problem is it deals only with version 2.0 of Phython. > > > >So, I would be glad if you could suggest me whether it would be really > >a good > >idea to learn from this book. In other words, will I have to unlearn > >too much > >after I complete this book (by the time I am done with this book, I > >believe > >we will be having Python 2.6 or so). > > > >Please suggest. > > > >Regards, > >Santanu > > > > > > > > > > ---------- Forwarded message ---------- > From: Jan Gregor > To: python-list at python.org > Date: Thu, 27 Jan 2005 13:53:45 +0100 > Subject: Re: redirect of standard output of jython to JTextArea > problem solved. > > in class: > > sys.stdout = StdOutRedirector(self) > > class StdOutRedirector: > def __init__(self, console): > self.console = console > > def write(self, data): > #print >> sys.stderr, ">>%s<<" % data > if data != '\n': > # This is a sucky hack. Fix printResult > self.console.textArea.append(data) > > Jan > > Jan Gregor wrote: > > Hello > > > > I want to redirect output of jython's functions print and println to > > JTextArea component. Is it possible ? > > > > I tried this (swingConsole.textArea is instance): > > > > In my class > > > > self.printStream= MyPrintStream(System.out) > > System.setOut(self.printStream) > > > > ---------------------------------------------------- > > class MyPrintStream (PrintStream): > > > > def println (str): > > swingConsole.textArea.append(str) > > > > def print (str): > > swingConsole.textArea.append(str) > > > > > > Output is still directed to standard output. > > > > > > Thanks for help, > > Jan > > > > ---------- Forwarded message ---------- > From: Andreas Pauley > To: python-list at python.org > Date: Thu, 27 Jan 2005 15:07:47 +0200 (SAST) > Subject: Point of Sale > Hi, > > My company has given me a rather cool project: > I have to provide them with an open-source python-based point-of-sale / > cash register system that can integrate with their existing ERP backend. > > The project will include development to ensure that the features they > require are included in the open-source POS system. > > Can you recommend anything that I can use? > > Regards, > Andreas > > > > ---------- Forwarded message ---------- > From: Ola Natvig > To: python-list at python.org > Date: Thu, 27 Jan 2005 14:02:19 +0100 > Subject: Re: Please suggest on the book to follow > santanu wrote: > > Hi all, > > > > I know a little python (not the OOP part) learnt by studying the online > > > > tutorial. Now I would like to learn it more thoroughly. > > > > I have access to 'Programming Python' which I liked (on flipping > > through the > > pages), but the problem is it deals only with version 2.0 of Phython. > > > > So, I would be glad if you could suggest me whether it would be really > > a good > > idea to learn from this book. In other words, will I have to unlearn > > too much > > after I complete this book (by the time I am done with this book, I > > believe > > we will be having Python 2.6 or so). > > > > Please suggest. > > > > Regards, > > Santanu > > > > I realy would recomend Practival Python it's a wery good book which I > think it's written for 2.2 or 2.3, but it's got all the basic modern > python aspects like new style classes. > > http://www.amazon.com/exec/obidos/tg/detail/-/1590590066/qid=1106830797/sr=8-1/ref=sr_8_xs_ap_i1_xgl14/104-9460635-7128701?v=glance&s=books&n=507846 > > -- > -------------------------------------- > Ola Natvig > infoSense AS / development > > > > ---------- Forwarded message ---------- > From: "Li Daobing" > To: python-list at python.org > Date: 27 Jan 2005 05:05:44 -0800 > Subject: a question about boost.python > I can't use .def(str(self)) > I write a simple example, without `str', I can build it well, but with > this one, I can't build > > //Rational.cpp > #include > #include > > using namespace std; > using namespace boost::python; > > class Rational > {}; > > ostream& operator<<(ostream& os, Rational r){ > return os; > } > BOOST_PYTHON_MODULE(Rational) > { > class_("Rational") > .def(str(self)) // __str__ > ; > } > // end. > > I don't know how to write Jamfile, so I write a Makefile, it works if i > don't use .def(str(self)) > > # Makefile > CC = g++ > > CFLAGS = -Wall -W -fPIC -I/usr/include/boost \ > -I/usr/include/python2.3 -DBOOST_PYTHON_DYNAMIC_LIB \ > -O2 > > LDFLAGS = -L/usr/local/lib -lboost_python -L/usr/lib/python2.3 \ > -Wl,-rpath-link,. -fPIC > > CXXFLAGS = $(CFLAGS) > > SLIB = hello.so Rational.so > > all: $(SLIB) > > %.so : %.o > /usr/bin/objcopy --set-section-flags .debug_str=contents,debug > $^ > $(CC) $(LDFLAGS) $^ -shared -o $@ > > clean : > rm -f $(WORLD) $(OBJS) > # end. > > or a simple setup.py, it also works if I don't use `str' > > # setup.py > from distutils.core import setup, Extension > > ext_modules = [Extension('Rational', ['Rational.cpp'], > define_macros=[('BOOST_PYTHON_DYNAMIC_LIB', > None)], > libraries=['boost_python'])] > > setup(name="itcc", > version="0.2.2", > author='Li Daobing', > author_email='lidaobing at gmail.com', > ext_modules = ext_modules > ) > # end. > > This is the error message: > $ make > g++ -Wall -W -fPIC -I/usr/include/boost -I/usr/include/python2.3 > -DBOOST_PYTHON_DYNAMIC_LIB -O2 -c -o Rational.o Rational.cpp > Rational.cpp: In function `std::ostream& operator<<(std::ostream&, > Rational)': > Rational.cpp:10: warning: unused parameter `Rational r' > /usr/include/boost/python/def_visitor.hpp: In static member function > `static > void boost::python::def_visitor_access::visit(const V&, classT&) > [with V = > boost::python::def_visitor, classT = > boost::python::class_ boost::python::detail::not_specified, > boost::python::detail::not_specified, > boost::python::detail::not_specified>] > ': > /usr/include/boost/python/def_visitor.hpp:67: instantiated from `void > boost::python::def_visitor::visit(classT&) const [with > classT = boost::python::class_ boost::python::detail::not_specified, > boost::python::detail::not_specified, > boost::python::detail::not_specified>, DerivedVisitor = > boost::python::api::object]' > /usr/include/boost/python/class.hpp:225: instantiated from > `boost::python::class_& boost::python::class_ X3>::def(const boost::python::def_visitor&) [with Derived = > boost::python::api::object, W = Rational, X1 = > boost::python::detail::not_specified, X2 = > boost::python::detail::not_specified, X3 = > boost::python::detail::not_specified]' > Rational.cpp:15: instantiated from here > /usr/include/boost/python/def_visitor.hpp:31: error: no matching > function for > call to > `boost::python::api::object::visit(boost::python::class_ boost::python::detail::not_specified, > boost::python::detail::not_specified, > boost::python::detail::not_specified>&) const' > make: *** [Rational.o] Error 1 > > > > ---------- Forwarded message ---------- > From: Lucas Raab > To: python-list at python.org > Date: Thu, 27 Jan 2005 13:12:07 GMT > Subject: Re: What's so funny? WAS Re: rotor replacement > > > > > > As long as we are discussing cryptography, what's wrong with m2crypto? > > > > http://sandbox.rulemaker.net/ngps/m2/ > > > > Why not incorporate it into the standard distribution? > > > > Or, what about Andrew Kuchling's crypto toolkit? > > > > http://www.amk.ca/python/code/crypto.html > > > > > > Umm, is it just me or did we just discuss the legal issues of that?? > > > > ---------- Forwarded message ---------- > From: Mark McEahern > To: python-list at python.org > Date: Thu, 27 Jan 2005 07:18:14 -0600 > Subject: Re: exclude binary files from os.walk > The OP wrote: > > > Is there an easy way to exclude binary files (I'm working on Windows > XP) from the file list returned by os.walk()? > > Sure, piece of cake: > > #!/usr/bin/env python > > import os > > def textfiles(path): > include = ('.txt', '.csv',) > for root, dirs, files in os.walk(path): > for name in files: > prefix, ext = os.path.splitext(name) > if ext.lower() not in include: > continue > filename = os.path.join(root, name) > yield filename > > path = os.getcwd() > for name in textfiles(path): > print name > > ;-) > > // m > > > > ---------- Forwarded message ---------- > From: Steve Holden > To: python-list at python.org > Date: Thu, 27 Jan 2005 08:14:02 -0500 > Subject: Re: import hook, overwrite import? > Kartic wrote: > > > Hi Torsten, > > > > If you want to use other methods to import (other than good ole file > > system), yes, you can create an importer class and register it as an > > importer module, that import will use to search and import. > > > > For example, it is possible to use zip imports (this functionality is > > already builtin) to import from a zip archive. > > py>>> import zlib # required > > py>>> import sys > > py>>> sys.path.append('/location/to/zippedmodules.zip') > > py>>> import testzip > > py>>> testzip.__file__ > > '/location/to/zippedmodules.zip/testzip,py' > > > > To generally do it, you have to: > > 1. Create a class that provides a load_module method that returns a > > module type. > > 2. Install your class as a hook using > > sys.path_hooks.append(your_importer_class) > > > > Please take a look at the imp module : > > http://docs.python.org/lib/module-imp.html for a complete description > > on accessing the import internals. There is also a simple example in > > this section. > > > > Is this is what you are looking for? > > > > Thanks, > > --Kartic > > PS: This about how much I know...the more I find out, I will share :-) > > > I will just chime in to say I too am looking for information in this > area. I hope to put some sort of BoF or Open Space event together for > people wishing to learn about (and teach about) the import system from > PEP 302 at PyCon this year. > > Early bird registration rates are still available today and tomorrow! > > regards > Steve > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Atte, Eduardo Henr?quez A. 9-6975236 From http Fri Jan 7 05:14:20 2005 From: http (Paul Rubin) Date: 07 Jan 2005 02:14:20 -0800 Subject: Excluded and other middles in licensing References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <1gpz4ot.1hugdikn2ddctN%aleaxit@yahoo.com> <71dDd.21829$En7.1635461@phobos.telenet-ops.be> <1gpz9qx.vmv8hav17z8qN%aleaxit@yahoo.com> <75r0b2-ohg.ln1@lairds.us> <1gq0jpn.1es49j7jrk3k5N%aleaxit@yahoo.com> Message-ID: <7x3bxd5ywz.fsf@ruckus.brouhaha.com> Robert Kern writes: > > http://en.wikipedia.org/wiki/Closed_source > > "any program whose licensing terms do not qualify as open source". > > A definition with a nice big "This article may need to be reworded to > conform to a neutral point of view" warning at the top. ;-) > ... > There seems to be such an edit on the way: > http://en.wikipedia.org/wiki/Talk:Closed_source After they're done defining closed source, maybe they can work on "compact source" (a bounded closed-source program, i.e. one that, unlike Windows, doesn't try to take over every computer in the world). Note also from the Heine-Borel theorem that every closed source program can be covered by some finite collection of open source programs. From sjmachin at lexicon.net Sun Jan 23 04:18:01 2005 From: sjmachin at lexicon.net (John Machin) Date: 23 Jan 2005 01:18:01 -0800 Subject: getting file size In-Reply-To: <6qc6v0hhfedf0uncp9gieahj38srh46khk@4ax.com> References: <6qc6v0hhfedf0uncp9gieahj38srh46khk@4ax.com> Message-ID: <1106461450.952864.54770@z14g2000cwz.googlegroups.com> Tim Roberts wrote: > Bob Smith wrote: > > >Are these the same: > > > >1. f_size = os.path.getsize(file_name) > > > >2. fp1 = file(file_name, 'r') > > data = fp1.readlines() > > last_byte = fp1.tell() > > > >I always get the same value when doing 1. or 2. Is there a reason I > >should do both? When reading to the end of a file, won't tell() be just > >as accurate as os.path.getsize()? > > On Windows, those two are not equivalent. Besides the newline conversion > done by reading text files, Doesn't appear to me to go wrong due to newline conversion: Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 >>> import os.path >>> txt = 'qwertyuiop\nasdfghjkl\nzxcvbnm\n' >>> file('bob', 'w').write(txt) >>> len(txt) 29 >>> os.path.getsize('bob') 32L ##### as expected >>> f = file('bob', 'r') >>> lines = f.readlines() >>> lines ['qwertyuiop\n', 'asdfghjkl\n', 'zxcvbnm\n'] >>> f.tell() 32L ##### as expected > the solution in 2. will stop as soon as it sees > a ctrl-Z. ... and the value returned by f.tell() is not the position of the ctrl-Z but more likely the position of the end of the current block -- which could be thousands/millions of bytes before the physical end of the file. Good ol' CP/M. > > If you used 'rb', you'd be much closer. And be much less hassled when that ctrl-Z wasn't meant to mean EOF, it just happened to appear in an unvalidated data field part way down a critical file :-( From dave at pythonapocrypha.com Tue Jan 4 17:16:15 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 04 Jan 2005 15:16:15 -0700 Subject: Python evolution: Unease In-Reply-To: References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> Message-ID: <41DB15AF.6020503@pythonapocrypha.com> Roman Suzi wrote: >>The term "generic programming" is too... er... generic. :) > > > Nope. It is not generic. It has it's definition made by the co-author > of STL - A.Stepanov. And the Boost C++ library (many of us know it as > Boost Python) standardise on the approach, AFAIK. Ok, "too broad" then; Python already supports at least some aspects of generic programming (at least, in the sense that I think you mean it), so it'd be good to spell out what specific features you're referring to. > Python could have honest support of concepts. Everything else will be > available with them. "Concepts" is a pretty generic term too! ;-) Do you mean concepts as defined here: http://www.boost.org/more/generic_programming.html ? > And BTW, are we really disputing? No, not at all - I'm just trying to better understand what you mean. Words like "generic" and "concepts" don't yet have a widely recognized, strict definition in the context of programming. If somebody has assigned some specific definition to them, that's great, it's just not universal yet so references and additional explanations are helpful. -Dave From anthony.briggs at gmail.com Tue Jan 11 10:28:36 2005 From: anthony.briggs at gmail.com (Anthony) Date: Tue, 11 Jan 2005 10:28:36 -0500 Subject: else condition in list comprehension In-Reply-To: References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> <1105305000.052714.188980@c13g2000cwb.googlegroups.com> <1105372193.185270.279290@c13g2000cwb.googlegroups.com> Message-ID: <53271620050111072841df3974@mail.gmail.com> On Mon, 10 Jan 2005 09:13:17 -0700, Steven Bethard wrote: > Luis M. Gonzalez wrote: > > It's me wrote: > >>> z = [i + (2, -2)[i % 2] for i in range(10)] > >> > >> But then why would you want to use such feature? Wouldn't that make > >> the code much harder to understand ... > >> Or are we trying to write a book on "Puzzles in Python"? > > > > Once you get used to list comprehensions (and it doesn't take long), > > they are a more concise and compact way to express these operations. > > After looking the two suggestions over a couple of times, I'm still > undecided as to which one is more readable for me. The problem is not > the list comprehensions (which I love and use extensively). The problem > is the odd syntax that has to be used for an if/then/else expression in > Python. They're both pretty unreadable, IMHO. Why not just factor out the if/then/else function like this: .def plusMinusTwo(i): . if i%2 == 0: . return i-2 . else: . return i+2 . .z = [plusMinusTwo(i) for i in range(10)] Then you can add whatever you like into the function. Anthony -- ----------------------------------------------------- HyPEraCtiVE? HeY, WhO aRE YoU cALliNg HypERaCtIve?! aNthONy.BrIGgS at gmAiL.CoM ----------------------------------------------------- From steven.bethard at gmail.com Thu Jan 13 19:59:37 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 13 Jan 2005 17:59:37 -0700 Subject: porting C code In-Reply-To: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> References: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> Message-ID: Lucas Raab wrote: > I am currently in the process of porting some C code into Python and am > stuck. I don't claim to be the greatest C/C++ programmer; in fact, my > skills at C are rudimentary at best. My question is I have the > statement: "typedef unsigned long int word32" and later on: "word32 > b[3]" referencing the third bit of the integer. How do I do the same in > Python?? py> for x in range(16): ... print x, (x >> 2) & 1 ... 0 0 1 0 2 0 3 0 4 1 5 1 6 1 7 1 8 0 9 0 10 0 11 0 12 1 13 1 14 1 15 1 Basically, I use a right-shift by 2 to put the 3rd bit as the last bit, and then mask off everything but the last bit by and-ing with 1. Does that work? Steve From farcepest at gmail.com Fri Jan 28 10:00:49 2005 From: farcepest at gmail.com (Andy Dustman) Date: 28 Jan 2005 07:00:49 -0800 Subject: Mac OS and MySQLdb References: <41f95b17$0$3331$9b622d9e@news.freenet.de> Message-ID: <1106924449.079269.65810@z14g2000cwz.googlegroups.com> The source is for all platforms. Use the Source, Luke. If 1.1.9 does not compile on Mac OS X, file a bug. From kartic.krishnamurthy at gmail.com Sat Jan 1 01:17:25 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 31 Dec 2004 22:17:25 -0800 Subject: Any Python XML Data Binding Utilities Avaiable? In-Reply-To: References: Message-ID: <1104560245.235697.324180@z14g2000cwz.googlegroups.com> Hi, I have heard about and played with pyRXP (from reportlab.org) that parses XML to pythonic objects. If you want a validating parser pyRXPu (Unicode pyRXP, part of same distro) is recommended on xml forums. There is another parser by 4suite.org. Never tried it. Also check out 1. http://aspn.activestate.com/ASPN/Cookbook/Python?kwd=XML for Python XML recipes 2. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/149368 - for an XML to Object recipe. 3. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/298721 - an update to the above recipe by some other pythonista. Item #2 above did not handle multiple occurances of elements well (or may be it was me!), for example for multiple accounts in a download XML config file I created, only got one account instance instead of 3. Hope this helps. Thanks, --Kartic From roccomoretti at hotpop.com Tue Jan 25 14:44:15 2005 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Tue, 25 Jan 2005 13:44:15 -0600 Subject: Another scripting language implemented into Python itself? In-Reply-To: References: <10vb8cve125v0b0@corp.supernews.com> Message-ID: Orlando Vazquez wrote: > Jeff Shannon wrote: > >> Because you cannot make Python secure against a malicious (or >> ignorant) user -- there's too much flexibility to be able to guard >> against every possible way in which user-code could harm the system. >> Parsing your own (limited) scripting language allows much better >> control over what user-code is capable of doing, and therefore allows >> (at least some measure of) security against malicious code. > > I don't see how that would equate to something that the original > programmer should be concerned about. You could include a bit in your > licensing scheme that voids all support on code that has been modified > in any way. You shouldn't be obligated and no one expects you to support > something the end-user has mucked with. > > You could trivially enforce this by keeping checksums of all the system > files. You're thinking of two different situations. My guess is that Jeff Shannon is not referring to situations where the end user makes modifications to existing code, but rather, where the end user write *completely new* scripts in your new scripting language. As such, you can't enforce checksums - the code hasn't been written yet. The use cases probably are also different. You're thinking of delivering a completed application to an end-user's machine, but given the OP's user name ("Quest Master"), my guess is that he's looking for a server-side deployment like in an on-line game, where users script the game environment. Not only do you have a problem with a malicious user potentially crashing the game machine, but you also have issues where the user may be able to grab his "character object" and give himself infinite money or life, or whatever. Since it's a shared server, you can't just say "I'm not supporting it" when someone mucks with the server. > In any case, there's nothing you can really do to "secure" your code. > This is true of any language, C, C++, and especially scripting languages > like Python. Anyone who has the determination get at and modify the code > probably will. Well, if you don't provide mechanisms for disk access, there is no way to overwrite files, short of a bug in the interpreter (or some extension interface to a general purpose programing language). Python is just to flexible to work like that. Even if you don't provide an open function to user code, and eliminate questionable modules, you can still get a file object, even if all you are provided with is an integer object. That's why restricted execution was eliminated from the standard library. From ncoghlan at iinet.net.au Sun Jan 23 01:38:16 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 23 Jan 2005 16:38:16 +1000 Subject: Unbinding multiple variables In-Reply-To: <41f232b8.1514053864@news.oz.net> References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> <35bnkeF4jpeetU1@individual.net> <1106334800.868412.27650@f14g2000cwb.googlegroups.com> <41f232b8.1514053864@news.oz.net> Message-ID: <41F34658.9080004@iinet.net.au> Bengt Richter wrote: > (OTOH, deletions of actual local bindings do seem to propagate back into a previously > bound value of locals on exit, and a new call to locals() seems to return the same identical > object as before, so I'm not sure I believe the , unless it has a special slot > and it is automatically updated at exit. But a local bare name assignment or deletion doesn't > immediately propagate. But it does on exit. So the returned by locals() has > a special relationship to the function it reflects, if it is otherwise a normal dict: CPython frames keep two copies of their locals around - the "fast" locals, which are actually used by the code (and stored in an array for fast access, hence the name), and a Python-readable copy in a dictionary (this is the dictionary returned by locals()). Various things trigger updates from the fast locals to the locals dictionary. Updates in the other direction are far less common (exec without an 'in' clause, star imports, and monkeying with the frame via the C API are the only cases I am aware of). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ncoghlan at iinet.net.au Sun Jan 9 00:45:13 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 15:45:13 +1000 Subject: mysterious buggy behavior In-Reply-To: References: Message-ID: <41E0C4E9.2090600@iinet.net.au> Sean McIlroy wrote: > While fiddling with a little script I ran into a problem that baffles > me completely. Maybe I'm missing something completely obvious, and > somebody out there can diagnose the problem at a glance. Anyway, > that's the hope. Here's the code (it plays tic tac toe): You need to be a little more explicit than simply saying "something goes wrong". Exception? Wrong move? What? Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steven.bethard at gmail.com Mon Jan 17 23:09:31 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 17 Jan 2005 21:09:31 -0700 Subject: dynamic data types In-Reply-To: <1106016177.518013.138980@c13g2000cwb.googlegroups.com> References: <1105969253.296411.301760@f14g2000cwb.googlegroups.com> <1106016177.518013.138980@c13g2000cwb.googlegroups.com> Message-ID: Paul Simmonds wrote: > I would assume that they're refering to the fact that even the basic > data types such as int are derived from object, and hence have methods: > >>>>int.__class__.__base__ > > > > Java, for example, has both an Integer object and a basic int data > type. One word. Yuck. Heh heh. Yeah, I can remember that annoyance well. I believe Java 1.5's supposed to have auto-boxing and -unboxing though, which should make this less of a pain... Steve From pobrien at orbtech.com Wed Jan 19 15:00:04 2005 From: pobrien at orbtech.com (Pat) Date: 19 Jan 2005 12:00:04 -0800 Subject: Solutions for data storage? References: <356c7tF4g3f64U1@individual.net> Message-ID: <1106164804.410201.100550@c13g2000cwb.googlegroups.com> Leif K-Brooks wrote: > I'm writing a relatively simple multi-user public Web application with > Python. It's a rewrite of a similar application which used PHP+MySQL > (not particularly clean code, either). My opinions on various Web > frameworks tends to vary with the phase of the moon, but currently, I'm > planning to use Quixote. > > Needless to say, my application will need some kind of persistent data > storage. The previous PHP+MySQL application uses around 1.1GB of > storage, so something like PyPerSyst where everything is kept in memory > is out. You might want to look at Schevo (http://schevo.org), an ODBMS and application development framework. Schevo builds on some of the concepts introduced in Pypersyst, and can use Pypersyst as its backend storage, but it can also use ZODB and Durus (and it is easy to switch between backends). Schevo provides schema evolution and migration features, enforces referential integrity and field constraints, enforces unique indexes (whether single field or multiple field keys), etc. All you have to do is describe your objects using a simple syntax such as this snippet from a weblog application that we are putting together as an example: class Author: """Authors write posts.""" name = f.string() password = f.hashedValue() email = f.string() _key(name) _icon('.apps.kuser') def __str__(self): return self.name class Post: """Posts contain content posted to the weblog.""" slug = f.string(doc='The short name that appears in the URL.') title = f.string() published = f.datetime() author = f.entity(allow=Author) excerpt = f.memo() content = f.memo() _key(slug) _icon('.filesystems.desktop') def __str__(self): return self.slug Schevo might not be quite ready for your particular needs, but the situation you describe is the target for Schevo. While most of our UI work has been with Qt, our next focus is on Nevow, which we have used in the past on a predecessor to what is now Schevo. I've used Quixote in the past, but I'm not sure how easy it would be to use it as the UI for a Schevo app. Most of our short-term efforts are going to be concentrated on Nevow and Plone for web applications, and Qt for GUI apps (and hopefully wxPython at some point). Matthew Scott and I will be giving a Schevo presentation at PyCon on the subject of "Developing Database Applications With Schevo". You can read our outline at http://schevo.org/doc/pycon2005/proposal. Good luck with your project. -- Patrick K. O'Brien Orbtech http://www.orbtech.com Schevo http://www.schevo.org Pypersyst http://www.pypersyst.org From jeff at ccvcorp.com Tue Jan 11 16:29:36 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 11 Jan 2005 13:29:36 -0800 Subject: reference or pointer to some object? In-Reply-To: References: Message-ID: <10u8gvso8dvdkd5@corp.supernews.com> Torsten Mohr wrote: > Hi, > > i'd like to pass a reference or a pointer to an object > to a function. The function should then change the > object and the changes should be visible in the calling > function. There are two possible meanings of "change the object" in Python. One of them will "just work" for your purposes, the other won't work at all. Python can re-bind a name, or it can mutate an object. Remember, names are just convenient labels that are attached to an object in memory. You can easily move the label from one object to another, and the label isn't affected if the object it's attached to undergoes some sort of change. Passing a parameter to a function just creates a new label on that object, which can only be seen within that function. The object is the same, though. You can't change what the caller's original label is bound to, but you *can* modify (mutate) the object in place. >>> def mutate(somedict): ... somedict['foo'] = 'bar' ... >>> def rebind(somedict): ... somedict = {'foo':'bar'} ... >>> d = {'a':1, 'b':2} >>> rebind(d) >>> d {'a': 1, 'b': 2} >>> mutate(d) >>> d {'a': 1, 'b': 2, 'foo': 'bar'} >>> In mutate(), we take the object (which is d in the caller, and somedict in the function) and mutate it. Since it's the same object, it doesn't matter where the mutation happened. But in rebind(), we're moving the somedict label to a *new* dict object. Now d and somedict no longer point to the same object, and when the function ends the object pointed to by somedict is garbage-collected, while the object pointed to by d has never changed. So, to do what you want to do, you simply need to arrange things so that your parameter is an object that can be mutated in-place. Jeff Shannon Technician/Programmer Credit International From spiffy at att.net Wed Jan 19 22:12:32 2005 From: spiffy at att.net (spiffy at att.net) Date: Thu, 20 Jan 2005 03:12:32 GMT Subject: Pyzine #6 MIDI article Message-ID: Would anyone here who has the Python and MIDI article from Pyzine #6 be willing to share it with me? From steve at holdenweb.com Mon Jan 31 14:09:10 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 14:09:10 -0500 Subject: Q: quoting string without escapes In-Reply-To: <1107198137.141990.246880@c13g2000cwb.googlegroups.com> References: <1107198137.141990.246880@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > in Python, is there a way to quote a string as to avoid escaping ' or " > inside the string? > > i.e. like Perl's q or qq. > thanks. > > Xah > xah at xahlee.org > http://xahlee.org/PageTwo_dir/more.html > Aren't you the guy who's telling the whole world how to write Python and Perl? Unusual to find arrogance and humility in such close proximity. Please stop cross-posting your ill-informed and inflammatory stuff to c.l.py and c.l.perl.m. And now I have your attention, the answer to your question is ... Use triple-quoting. followups-set'ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From francis.girard at free.fr Thu Jan 27 13:54:46 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 27 Jan 2005 19:54:46 +0100 Subject: Classical FP problem in python : Hamming problem In-Reply-To: References: <63b5e209.0501210558.686f5c10@posting.google.com> Message-ID: <200501271954.47811.francis.girard@free.fr> Le jeudi 27 Janvier 2005 10:30, Nick Craig-Wood a ?crit?: > Francis Girard wrote: > > Thank you Nick and Steven for the idea of a more generic imerge. > > You are welcome :-) [It came to me while walking the children to school!] > Sometimes fresh air and children purity is all what it takes. Much better than coffee, cigarrette and flat screen. > [snip] > > > class IteratorDeiterator: > > def __init__(self, iterator): > > self._iterator = iterator.__iter__() > > self._firstVal = None ## Avoid consuming if not requested from > > outside ## Works only if iterator itself can't return None > > You can use a sentinel here if you want to avoid the "can't return > None" limitation. For a sentinel you need an object your iterator > couldn't possibly return. You can make one up, eg > Great idea. I'll use it. > self._sentinel = object() > self._firstVal = self._sentinel > > Or you could use self (but I'm not 100% sure that your recursive > functions wouldn't return it!) > > > def __iter__(self): return self > > > > def next(self): > > valReturn = self._firstVal > > if valReturn is None: > > and > > if valReturn is self._sentinel: > > valReturn = self._iterator.next() > > self._firstVal = None > > self._firstVal = self._sentinel > > etc.. > > [snip more code] > > Thanks for some more examples of fp-style code. I find it hard to get > my head round so its been good exercise! Introduction to functional programming Richard Bird and Philip Wadler Prentice Hall 1988 This is the very best intro I ever read. The book is without hype, doesn't show its age and is language neutral. Authors are world leaders in the field today. Only really strong guys have the kindness to do understandable introductions without trying to hide the difficulties (because they are strong enough to face them with simplicity). It's been a real pleasure. Regards, Francis Girard FRANCE > -- > Nick Craig-Wood -- http://www.craig-wood.com/nick From cjw at sympatico.ca Fri Jan 28 21:36:51 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 28 Jan 2005 21:36:51 -0500 Subject: PythonWin (build 203) for Python 2.3 causes Windows 2000 to grind to a halt? In-Reply-To: <3f233389.0501280813.6be97b74@posting.google.com> References: <3f233389.0501271147.43572416@posting.google.com> <41f9e4a9$1_1@127.0.0.1> <3f233389.0501280813.6be97b74@posting.google.com> Message-ID: <41FAF6C3.8000905@sympatico.ca> Chris P. wrote: > AWESOME - my life just got THAT much better. > > The bug you suggested is exactly the problem that I was having... I > had looked through the bugs being tracked, but the title of that one > didn't jump out at me as something that would help. Thanks! > > - Chris > > P.S. For anyone reading this group who wants to know exactly what I > did: > 1) Uninstall Pywin32 > 2) Open the registry editor ('regedit' at the command prompt) > 3) Go to HKEY_CURRENT_USER\Software\Python[version]\Python for Win32 > You will likely find many many many keys that have the format > "ToolbarDefault-Bar#". These keys filling up your registry cause > Windows 2000 to become extremely slow/unstable when Python is running > (especially if your debugger is running.) > 4) Delete the keys... I just deleted it at the "Python[version]" root > 5) Reinstall Pywin32 > This is a great workaround but I've found that, with build 203, it needs to be repeated from time to time. Colin W. > "Roger Upole" wrote in message news:<41f9e4a9$1_1 at 127.0.0.1>... > >>These look like symptoms of sf bug #1017504 >>http://sourceforge.net/tracker/index.php?func=detail&aid=1017504&group_id=78018&atid=551954 >> >>What version of Pywin32 are you running ? >>There's a (semi) fix for this in the latest build. >> hth >> Roger From peter at somewhere.com Thu Jan 27 05:07:42 2005 From: peter at somewhere.com (Peter Maas) Date: Thu, 27 Jan 2005 11:07:42 +0100 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: Davor schrieb: > I browsed docs a bit today, and they also confirm what I have believed - > that OO is totally secondary in Python. OO is not secondary in Python. It's secondary for you :) And Python leaves the choice to you. > In fact, > object/classes/metaclasses are nothing but *dictionaries with identity* > in python. Eliminating "nothing but" makes this a true statement :) > Love this approach. In fact, you can very easily implement > your own *OO model* completely separate of Python's OO model... Now I > actually strongly believe that Python's author has introduced the whole > OO model just to attract and make happy OO population... I believe that your belief is wrong :) Guido van Rossum has introduced OO to Python because it's a useful concept. > and you can definitely be more productive using Python's structured > programming than Java/C++ OO programming :-)... and Python is probably > the best example why we should have skipped OO all together.. Sigh. Proceed as you like but be aware that dogmatism - OO as well as anti-OO is always a poor guide. OO wasn't invented as a marketing buzz but to support programming styles that emerged in non-OO languages to control the increasing complexity of programs. > so you get a nice program with separate data structures and functions > that operate on these data structures, with modules as containers for > both (again ideally separated). Very simple to do and maintain no matter > what OO preachers tell you... The bad thing about OO preachers is not OO but preaching. And you are preaching, too ;) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From bingham at cenix-bioscience.com Tue Jan 4 04:37:34 2005 From: bingham at cenix-bioscience.com (Aaron Bingham) Date: Tue, 04 Jan 2005 10:37:34 +0100 Subject: search backward In-Reply-To: <4c57226b.0501040126.7f0eafc2@posting.google.com> References: <4c57226b.0501040126.7f0eafc2@posting.google.com> Message-ID: <41DA63DE.7040004@cenix-bioscience.com> Robert wrote: > I need to find the location of a short string in a long string. The > problem however is that i need to search backward. > > Does anybody know how to search in reverse direction? >>> "foofoo".find("foo") 0 >>> "foofoo".rfind("foo") 3 >>> "foofoo".index("foo") 0 >>> "foofoo".rindex("foo") 3 -- -------------------------------------------------------------------- Aaron Bingham Application Developer Cenix BioScience GmbH -------------------------------------------------------------------- From bokr at oz.net Thu Jan 6 15:31:17 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 06 Jan 2005 20:31:17 GMT Subject: Embedding a restricted python interpreter References: <7xbrc2a7zq.fsf@ruckus.brouhaha.com> Message-ID: <41dd9eb5.165503371@news.oz.net> On Thu, 6 Jan 2005 16:53:23 +0100, Gerhard Haering wrote: > >--rwEMma7ioTxnRzrJ >Content-Type: text/plain; charset=us-ascii >Content-Disposition: inline >Content-Transfer-Encoding: quoted-printable > >On Thu, Jan 06, 2005 at 07:32:25AM -0800, Paul Rubin wrote: >> Jp Calderone writes: >> > A Python sandbox would be useful, but the hosting provider's excuse >> > for not allowing you to use mod_python is completely bogus. All the=20 >> > necessary security tools for that situation are provided by the=20 >> > platform in the form of process and user separation. >>=20 >> But mod_python is an apache module and runs in the same apache process >> with other users' scripts. > >Which is why it's a good idea for each customer to have it's own system user >and their virtual hosts running under this uid. Which was the idea for the >perchild MPM for Apache 2 - which is abandoned now :-( muxmpm is a replacem= >ent >project in beta. Note to self. Another thing to catch up on ;-/ > >This really sucks when you use Apache2. I myself did make the switch some t= >ime >ago, then noticed that this (for me) important feature was missing. It now >works, somehow, but to make it work properly I'd need to either: > >- go back to Apache 1.3.x, missing some nice improvements And maybe have to recompile to enable the setuid stuff. But IIRC after that you can run cgi with everything private and serve only generated stuff to the world if you want. >- use different webservers per user, put them together with mod_proxy (yuck= >!) Regards, Bengt Richter From grante at visi.com Mon Jan 31 21:49:12 2005 From: grante at visi.com (Grant Edwards) Date: 01 Feb 2005 02:49:12 GMT Subject: getting data from a port in use References: Message-ID: <41feee28$0$15852$a1866201@visi.com> On 2005-02-01, Dana Marcusanu wrote: > I am trying to use Python to get the data received at a specific port (in > use) on my computer. What do you mean "in use"? You mean you want to evesdropt on data that's being sent to an existing connection? If so, you'll need to use something like the pcap library. > I already tried below code which seems to hang at the > statement accepting connections. I don't know what else I can try. Any > suggestions will be welcome. > > import socket, select, os > > PORT = 2005 > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > s.bind((socket.gethostname(), PORT)) > s.listen(1) > work_socket, addr = s.accept() > data = s.recv(1024) No matter what you're trying to do, this isn't right. Once the connection has been accepted, you have to read data from the socket returned by the accept() call. > print data > s.close() -- Grant Edwards grante Yow! Actually, what at I'd like is a little toy visi.com spaceship!! From jacek.generowicz at cern.ch Wed Jan 12 03:23:47 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 12 Jan 2005 09:23:47 +0100 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <1105289391.534192.74060@c13g2000cwb.googlegroups.com> <1105357625.835608.299560@c13g2000cwb.googlegroups.com> <10u5fu3o7v4h9e3@corp.supernews.com> <10u8e65lju3atbd@corp.supernews.com> Message-ID: Jeff Shannon writes: > I guess we'll have to agree to disagree Indeed :-) > I find that reading a lambda requires mentally pushing a stack frame > to parse the lambda and another to translate map() into a loop, > whereas a list comp's expression doesn't require such a shift > From the sounds of it, you may have the opposite experience with > reading map/lambda vs. reading list comps No, I'm perefectly happy with both. I'm just trying to understand the underlying reasons for people having trouble with one or the other, in order to be better armed when the didactic need might arise. One more question. Imagine that Python had something akin to Smalltalk code blocks. Would something like map([x | x+1], seq) be any better for you than map(lambda x:x+1, seq) ? From http Fri Jan 21 01:26:16 2005 From: http (Paul Rubin) Date: 20 Jan 2005 22:26:16 -0800 Subject: Print a string in binary format References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> Message-ID: <7xsm4vuwl3.fsf@ruckus.brouhaha.com> "neutrino" writes: > I have a binary file and wish to see the "raw" content of it. So I open > it in binary mode, and read one byte at a time to a variable, which > will be of the string type. Now the problem is how to print the binary > format of that charater to the standard output. It seems a common task > but I just cannot find the appropriate method from the documentation. There's not a builtin for it. There was some discussion in the bug system of adding it to the binascii module. Meanwhile you sort of have to write actual code. From mahs at telcopartners.com Sat Jan 22 12:50:21 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sat, 22 Jan 2005 09:50:21 -0800 Subject: Reload Tricks In-Reply-To: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> References: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> Message-ID: Kamilche wrote: > I want my program to be able to reload its code dynamically. I have a > large hierarchy of objects in memory. The inheritance hierarchy of > these objects are scattered over several files. > Michael Spencer wrote: > An alternative approach (with some pros and cons) is to modify the class in place, using something like: > > >>> def reclass(cls, to_cls): > ... """Updates attributes of cls to match those of to_cls""" > ... > ... DONOTCOPY = ("__name__","__bases__","__base__", > ... "__dict__", "__doc__","__weakref__") etc... Kamilche wrote: > Would it be possible to just not copy any attribute that starts and > ends with '__'? Or are there some important attributes being copied? Possible? of course, it's Python ;-) But there are many 'magic' attributes for behavior that you probably do want to copy: e.g., __getitem__, __setitem__ etc... See: http://docs.python.org/ref/specialnames.html Michael Hudson's recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 does auto-reloading "automatically", at the price of changing the type of the classes you want to manage. It's a very convenient approach for interactive development (which is the recipe's stated purpose). It works by tracking instances and automatically updating their class. If your program relies on class identity, you may run into problems. Michael From dave at pythonapocrypha.com Tue Jan 4 14:09:21 2005 From: dave at pythonapocrypha.com (Dave Brueck) Date: Tue, 04 Jan 2005 12:09:21 -0700 Subject: Python evolution: Unease In-Reply-To: <98WdnVGqi-yaUkfcRVn-tw@giganews.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> Message-ID: <41DAE9E1.5080105@pythonapocrypha.com> Istvan Albert wrote: > Doug Holton wrote: > >> application is so important that I expect Python 3000 will have >> optional type declarations integrated into the argument list." > > > I think that *optional* part of the "optional type declaration" > is a myth. > > It may be optional in the sense that the language will > accept missing declarations but as soon as the feature > is available it will become "mandatory" to use it > (peer pressure, workplace practices). That's my fear - type declarations could become one of the most abused language features because they'd get used too often. -Dave From ncoghlan at iinet.net.au Mon Jan 10 06:11:34 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 10 Jan 2005 21:11:34 +1000 Subject: python3: 'where' keyword In-Reply-To: <34cri1F47gda5U1@individual.net> References: <3480qqF46jprlU1@individual.net> <34cri1F47gda5U1@individual.net> Message-ID: <41E262E6.9030702@iinet.net.au> Andrey Tatarinov wrote: > And about examples for usage "where" keyword > > reading http://manatee.mojam.com/~skip/python/fastpython.html I > understand that almost every example should use that keyword =) I suspect polluting the outer namespace would still be faster, since Python wouldn't have to create the extra level of scoping all the time. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From dscottr at bellatlantic.net Mon Jan 31 15:12:29 2005 From: dscottr at bellatlantic.net (Scott Robinson) Date: Mon, 31 Jan 2005 20:12:29 GMT Subject: python and gpl References: <7xmzuqgmv6.fsf@ruckus.brouhaha.com> Message-ID: <804tv01vej83hm602acfoh291fobov5l4a@4ax.com> On 30 Jan 2005 21:59:25 -0800, Paul Rubin wrote: >John Hunter writes: >> The question is: does shipping a backend which imports a module that >> links with GPL code make some or all of the library GPL. > >Literally speaking, no, not automatically, any more than driving a car >makes you into a licensed driver if you weren't one already. But if >you weren't licensed, then you've broken the law by driving the car. >So your question should be: 1) is shipping that backend one of the >things you need the GPL to license you to legally do, and 2) if so, >does the GPL in fact give you that license? > >If you're asking in terms of legal enforcement, the answer is 1) maybe >and 2) almost certainly not. I think it's better to ask in terms of >the GPL's spirit. I would say that it's not in the GPL's spirit and >that GPL die-hards would consider that use objectionable, though they >might make exceptions for specific cases (so it doesn't hurt to ask). >Some authors who use the GPL are less strict about how they interpret >it, so again, the friendly thing to do is ask the author. > > * If a backend module somebackend does > > import somelib > > where somelib is a python wrapper of GPL code, is somebackend GPLd? > >It's GPL'd if you GPL it. If you don't GPL it, then distributing it >it may be a GPL violation that could get you taken to court. I >believe the FSF's view is that it is fact a violation; however, the >courts have not yet established this. The law doesn't have a >black-and-white boundary. It's more like a fractal. The only way to >find out what a court will decide is to actually try a case there. > >Rather than try to probe how closely you can dance around the >boundaries of the GPL, you might just ask the author of the GPL'd >library whether what you want to do is ok with him or her. If s/he >says no and you do it anyway, you're both inviting trouble over the >possible infringement, and also inviting people to try to use your >code in ways you don't like. Since the free software movement depends >on a spirit of cooperation, I think it's best to avoid trying to press >too hard against the boundaries of anyone's licenses. > >http://www.gnu.org/licenses/gpl-faq.html If you read the GPL, it claims everything it can (any "work" created using GPLed "work"). My guess is that anything that calls the code in a way not specifically allowed by the author is going to get you into trouble. IANAL, but from what I can remember about earlier licensing issues, any code specific for a GPLed library (especially "import") will get you into to trouble. Having a non-free library with an identical API and issuing exec("import "+sys.argv[1]) where the user can supply sys.argv as the name of the gpl'ed library will work (I think there is a free/non-free library out there that is never run, but exists for exactly this condition). Scott Robinson From aleaxit at yahoo.com Tue Jan 18 14:31:40 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 18 Jan 2005 20:31:40 +0100 Subject: pickling extension class References: Message-ID: <1gqlpxp.g66j8sl6zkutN%aleaxit@yahoo.com> harold fellermann wrote: > File "/sw/lib/python2.4/pickle.py", line 760, in save_global > raise PicklingError( > pickle.PicklingError: Can't pickle : it's > not found as hyper.PeriodicGrid > >>> dir(hyper) > ['Dir', 'Neighbors', 'PeriodicGrid', 'PeriodicPos', '__doc__', > '__file__', '__name__', 'refcount'] > >>> hyper.PeriodicGrid > > > So pickle complains about the class PeriodicGrid not being found in the > module hyper, but a dir() > proves that python can find it. Has anyone an idea what's going wrong > here? These symptomps are pretty weird -- let's try to pin things down a bit more. The relevant few lines of pickle.py are: try: __import__(module) mod = sys.modules[module] klass = getattr(mod, name) except (ImportError, KeyError, AttributeError): raise PicklingError( so, could you please edit your pickle.py to provide VASTLY more info, say: try: print 'Here it goes...:' _xx = __import__(module) print ' __import__ says: %r' % (_xx,) mod = sys.modules[module] print ' in sys.modules: %r' % (mod,) klass = getattr(mod, name) print ' klass is: %r' % (klass,) except (ImportError, KeyError, AttributeError), _xx: print ' OOPS, error (%s): %s' % (_xx.__class__, _xx) raise PicklingError( and let us know exactly what his modified pickle.py outputs...? Thanks, Alex From stewart.midwinter at gmail.com Mon Jan 24 20:01:20 2005 From: stewart.midwinter at gmail.com (stewart.midwinter at gmail.com) Date: 24 Jan 2005 17:01:20 -0800 Subject: smtplib bug with Windows XP Message-ID: <1106614880.586616.19780@f14g2000cwb.googlegroups.com> I'm having problem with a script that used to work under Win2k but is now broken after an install of WinXP Pro. I can no longer connect to a local mail server. Has anyone else seen this? If so, were you able to work around it? Here's the traceback (below). Interestingly, if I change ports to the POP port 110, I get a different error, but one that lets me know that I can reach the server. trying to connect on the SMTP port 25: >>> s = smtplib.SMTP('10.50.200.6',25) Traceback (most recent call last): File "", line 1, in ? File "C:\Programs\Python24\Lib\smtplib.py", line 241, in __init__ (code, msg) = self.connect(host, port) File "C:\Programs\Python24\Lib\smtplib.py", line 303, in connect raise socket.error, msg socket.error: (10053, 'Software caused connection abort') trying to connect on POP port 110: >>> s = smtplib.SMTP('10.50.200.6',110) Traceback (most recent call last): File "", line 1, in ? File "C:\Programs\Python24\Lib\smtplib.py", line 243, in __init__ raise SMTPConnectError(code, msg) smtplib.SMTPConnectError: (-1, 'Microsoft Exchange 2000 POP3 server version 6.0. 6249.0 (11exg01.es.int) ready.') All clues gratefully accepted! S From cam.ac.uk at mh391.invalid Sat Jan 15 07:58:22 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 15 Jan 2005 12:58:22 +0000 Subject: How to del item of a list in loop? In-Reply-To: References: Message-ID: skull wrote: > but I still have an other thing to worry about coming with this way: does > performance sucks when the list is big enough? > It makes a copy operation! > > here is a faster and 'ugly' solution: > > lst = [1, 2, 3] > i = 0 > while i < len(lst): > if lst[i] == 2: > lst.remove(i) > else: > i += 1 Actually, that is the slowest of the three methods proposed so far for large lists on my system. import timeit def method_copy(lst): for i in lst[:]: if i == 2: lst.remove(i) return lst def method_listcomp(lst): return [i for i in lst if i!=2] def method_while(lst): i = 0 while i < len(lst): if lst[i] == 2: lst.remove(i) else: i += 1 return lst lsts = dict(three=range(3), hundred=range(100), thousand=range(1000), million=range(1000000)) if __name__ == "__main__": for lst_name, lst in lsts.iteritems(): print "%s" % lst_name for method_name in ["method_copy", "method_listcomp", "method_while"]: stmt = '%s(lsts["%s"])' % (method_name, lst_name) setup = "from __main__ import %s, lsts" % method_name times = 3000000 / len(lst) # reduce the number of times you repeat for big lists print " %s: %s" % (method_name, timeit.Timer(stmt, setup).repeat(3, times)) RESULTS: Michael at MINIMOO ~ $ python -V && uname -a Python 2.4 CYGWIN_NT-5.1 MINIMOO 1.5.12(0.116/4/2) 2004-11-10 08:34 i686 unknown unknown Cygwin Michael at MINIMOO ~ $ python testlist.py thousand method_copy: [1.0479998588562012, 1.0080001354217529, 1.0119998455047607] method_listcomp: [1.5119998455047607, 1.5110001564025879, 1.503000020980835] method_while: [3.8680000305175781, 3.8680000305175781, 3.872999906539917] hundred method_copy: [1.1269998550415039, 1.127000093460083, 1.190000057220459] method_listcomp: [2.0360000133514404, 2.0480000972747803, 2.0069999694824219] method_while: [3.5299999713897705, 3.5540001392364502, 3.5130000114440918] three method_copy: [6.1210000514984131, 6.1679999828338623, 6.1239998340606689] method_listcomp: [9.7590000629425049, 9.5309998989105225, 9.5] method_while: [6.6609997749328613, 6.625, 6.6800000667572021] million method_copy: [1.3420000076293945, 1.3029999732971191, 1.3389999866485596] method_listcomp: [1.5409998893737793, 1.5500001907348633, 1.5289998054504395] method_while: [3.9619998931884766, 3.9210000038146973, 3.9590001106262207] Now your "while" method does use less memory, but it is not as fast as the copy method. If you want to get really hairy, you can compare the bytecode instructions for these three methods: $ python Python 2.4 (#1, Dec 4 2004, 20:10:33) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import testlist >>> from dis import dis >>> dis(testlist.method_while) 13 0 LOAD_CONST 1 (0) 3 STORE_FAST 1 (i) 14 6 SETUP_LOOP 68 (to 77) >> 9 LOAD_FAST 1 (i) 12 LOAD_GLOBAL 1 (len) 15 LOAD_FAST 0 (lst) 18 CALL_FUNCTION 1 21 COMPARE_OP 0 (<) 24 JUMP_IF_FALSE 48 (to 75) 27 POP_TOP 15 28 LOAD_FAST 0 (lst) 31 LOAD_FAST 1 (i) 34 BINARY_SUBSCR 35 LOAD_CONST 2 (2) 38 COMPARE_OP 2 (==) 41 JUMP_IF_FALSE 17 (to 61) 44 POP_TOP 16 45 LOAD_FAST 0 (lst) 48 LOAD_ATTR 3 (remove) 51 LOAD_FAST 1 (i) 54 CALL_FUNCTION 1 57 POP_TOP 58 JUMP_ABSOLUTE 9 >> 61 POP_TOP 18 62 LOAD_FAST 1 (i) 65 LOAD_CONST 3 (1) 68 INPLACE_ADD 69 STORE_FAST 1 (i) 72 JUMP_ABSOLUTE 9 >> 75 POP_TOP 76 POP_BLOCK 19 >> 77 LOAD_FAST 0 (lst) 80 RETURN_VALUE >>> dis(testlist.method_copy) 4 0 SETUP_LOOP 45 (to 48) 3 LOAD_FAST 0 (lst) 6 SLICE+0 7 GET_ITER >> 8 FOR_ITER 36 (to 47) 11 STORE_FAST 1 (i) 5 14 LOAD_FAST 1 (i) 17 LOAD_CONST 1 (2) 20 COMPARE_OP 2 (==) 23 JUMP_IF_FALSE 17 (to 43) 26 POP_TOP 6 27 LOAD_FAST 0 (lst) 30 LOAD_ATTR 2 (remove) 33 LOAD_FAST 1 (i) 36 CALL_FUNCTION 1 39 POP_TOP 40 JUMP_ABSOLUTE 8 >> 43 POP_TOP 44 JUMP_ABSOLUTE 8 >> 47 POP_BLOCK 7 >> 48 LOAD_FAST 0 (lst) 51 RETURN_VALUE >>> dis(testlist.method_listcomp) 10 0 BUILD_LIST 0 3 DUP_TOP 4 STORE_FAST 1 (_[1]) 7 LOAD_FAST 0 (lst) 10 GET_ITER >> 11 FOR_ITER 30 (to 44) 14 STORE_FAST 2 (i) 17 LOAD_FAST 2 (i) 20 LOAD_CONST 1 (2) 23 COMPARE_OP 3 (!=) 26 JUMP_IF_FALSE 11 (to 40) 29 POP_TOP 30 LOAD_FAST 1 (_[1]) 33 LOAD_FAST 2 (i) 36 LIST_APPEND 37 JUMP_ABSOLUTE 11 >> 40 POP_TOP 41 JUMP_ABSOLUTE 11 >> 44 DELETE_FAST 1 (_[1]) 47 RETURN_VALUE For method_while, almost all of the times the list runs through, you still have to add 1 to i, which is a lot of instructions: 18 62 LOAD_FAST 1 (i) 65 LOAD_CONST 3 (1) 68 INPLACE_ADD 69 STORE_FAST 1 (i) 72 JUMP_ABSOLUTE 9 With the other methods, when you find a false result, all you have to do is the JUMP_ABSOLUTE. That saves you some time over several million repetitions. Well, that was longer than I thought it would be. HTH. -- Michael Hoffman From davorss at gmail.com Tue Jan 25 19:13:19 2005 From: davorss at gmail.com (Davor) Date: Tue, 25 Jan 2005 19:13:19 -0500 Subject: python without OO In-Reply-To: <1106696406.515575.84540@z14g2000cwz.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> Message-ID: M.E.Farmer wrote: > Wrap your head around Python, don't wrap the Python around your head! > This is NOT Java, or C++ or C , it IS Python. that's interesting hypothesis that behavior will vary due to the use of different language - actually most python scripts that I have seen do not even use OO which is quite understandable (same with perl, php,..) and I'm not even sure why all these languages have incorporated OO at all... >>(note, I am not an experienced developer, nor the >>others I'll be working with (even though some think they are:-)) > > Don't worry we didn't get confused, it was quite clear ;) :-) > Also you are telling me you don't have an OO problem, you have a > problem with your managment and communication skills. yeah, it's really tough telling them to write code so I can understand it without having to know about all these patterns of theirs. Davor From wjiang at gmail.com Tue Jan 25 14:54:39 2005 From: wjiang at gmail.com (Wen Jiang) Date: 25 Jan 2005 11:54:39 -0800 Subject: pymat on 64bit linux Message-ID: <1106682878.997257.71390@f14g2000cwb.googlegroups.com> Hi, Has anyone been able to get pymat work on a 64bit linux system? I compiled the CVS version of pymat with python2.3/matlab7.01 on Mandrake10.1 64bit system, it can start the engine and use put/get function, but segfaults with eval function. From irmen at -nospam-remove-this-xs4all.nl Sun Jan 16 20:03:56 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 17 Jan 2005 02:03:56 +0100 Subject: List problems in C code ported to Python In-Reply-To: <3SDGd.22010$Z%.6947@fe1.texas.rr.com> References: <3SDGd.22010$Z%.6947@fe1.texas.rr.com> Message-ID: <41eb0ef9$0$6206$e4fe514c@news.xs4all.nl> Paul McGuire wrote: > So "A" == 'a' is true in Python, not true in C. It's not true in Python either. You probably meant to say: "a" == 'a' (lowercase a) --Irmen From steven.bethard at gmail.com Fri Jan 21 21:43:27 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 19:43:27 -0700 Subject: finding name of instances created In-Reply-To: References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> Message-ID: Andr? Roberge wrote: > Behind the scene, I have something like: > robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') } > and have mapped move() to correspond to > robot_dict['robot'].move() > (which does lots of stuff behind the scene.) > > I have tested robot_dict[] with more than one robot (each with > its own unique name) and am now at the point where I would like > to have the ability to interpret something like: > > alex = CreateRobot() > anna = CreateRobot() > > alex.move() > anna.move() > > etc. Since I want the user to learn Python's syntax, I don't > want to require him/her to write > alex = CreateRobot(name = 'alex') > to then be able to do > alex.move() How do you get the commands from the user? Maybe you can preprocess the user code? py> class Robot(object): ... def __init__(self, name): ... self.name = name ... def move(self): ... print "robot %r moved" % self.name ... py> user_code = """\ ... alex = Robot() ... anna = Robot() ... alex.move() ... anna.move()""" py> new_user_code = re.sub(r'(\w+)\s+=\s+Robot\(\)', ... r'\1 = Robot(name="\1")', ... user_code) py> print new_user_code alex = Robot(name="alex") anna = Robot(name="anna") alex.move() anna.move() py> exec new_user_code robot 'alex' moved robot 'anna' moved Steve From tundra at tundraware.com Sun Jan 23 13:58:21 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 23 Jan 2005 13:58:21 EST Subject: re Insanity In-Reply-To: References: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> Message-ID: Orlando Vazquez wrote: > Tim Daneliuk wrote: > >> For some reason, I am having the hardest time doing something that should >> be obvious. (Note time of posting ;) >> >> Given an arbitrary string, I want to find each individual instance of >> text in the form: "[PROMPT:optional text]" >> >> I tried this: >> >> y=re.compile(r'\[PROMPT:.*\]') >> >> Which works fine when the text is exactly "[PROMPT:whatever]" but >> does not match on: >> >> "something [PROMPT:foo] something [PROMPT:bar] something ..." >> >> The overall goal is to identify the beginning and end of each [PROMPT...] >> string in the line. >> >> Ideas anyone? > > > If I understand correctly, this is what you are trying to achieve: > > >>> import re > >>> temp = "something [PROMPT:foo] something [PROMPT:bar] something ..." > >>> prompt_re = re.compile(r"\[PROMPT:.*?\]") > >>> prompt_re.findall(temp) > ['[PROMPT:foo]', '[PROMPT:bar]'] > >>> > > HTH, > > -- > Orlando Yes - that seems to be the simplest solution to the problem. I'd forgotten entirely about non-greedy matching when I asked the question. Thanks. -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From deetsNOSPAM at web.de Thu Jan 13 18:43:26 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 14 Jan 2005 00:43:26 +0100 Subject: Pygtk: How to remove title bar from a window References: <1105653476.254139.58810@f14g2000cwb.googlegroups.com> Message-ID: Nick Atkins wrote: > Hi all, > > I am writing an application using pyGTK that has several pop-up dialogs > that show and hide in succession. I would like to prevent the user > from closing the dialog and if possible I'd like to use a "title > bar-less" window with a normal border so the X is not even available to > click. Is this possible? I have tried using > window.set_decorated(FALSE) but this also removes the border making the > window look quite strange. Draw your own border then. And don't rely on the user not beeing able to close the window - xkill is at hand, and even if the average user doesn't know about it - it _will_ be used. -- Regards, Diez B. Roggisch From reinhold-birkenfeld-nospam at wolke7.net Fri Jan 14 16:53:03 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Fri, 14 Jan 2005 22:53:03 +0100 Subject: Why would I get a TypeEror? In-Reply-To: References: <34ql1vF4dqd9pU1@individual.net> Message-ID: <34qt9vF4br3iqU1@individual.net> It's me wrote: > Say again??? > > "Reinhold Birkenfeld" wrote in > message news:34ql1vF4dqd9pU1 at individual.net... >> It's me wrote: >> > Sorry if my question was a little "lazy" and yes, I was asking about the >> > "lazy evaluation". :=) >> > >> > I am surprised about this (and this can be dangerous, I guess). >> > >> > If this is true, I would run into trouble real quick if I do a: >> > >> > (1/x,1.0e99)[x==0] >> > >> > and that's not good. >> > >> > Something to keep in mind. :-( >> >> Lazy evaluation: use the (x==0 and 1e99 or 1/x) form! >> >> Reinhold Say what again? Reinhold PS: Please do not produce top-posting! From fredrik at pythonware.com Thu Jan 13 04:58:32 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 13 Jan 2005 10:58:32 +0100 Subject: site.here on python 2.4 References: <1105609399.915874.71150@z14g2000cwz.googlegroups.com> Message-ID: "ariza" wrote: > greetings. it seems that the attribute site.here, of the site module, > has vanished in python 2.4. up until python 2.3, site.here seemed (to > me at least) a convenient way to get the complete path to the python > library on any platform. "here" was a temporary variable used to get the exact location of the LICENSE file. in Python 2.4, that code has been moved into a function, in which "here" is still a temporary variable. was it documented somewhere else? > can anyone propose a similarly effective and cross-platform solution > for easily discovering the the library path on any python installation? the library path is defined by the sys.path variable, which contains a list of library directories. sys.prefix gives you the installation root, sys.executable tells you where the interpreter is. if you need the exact behaviour of "site.here", you can do import os here = os.path.dirname(os.__file__) but I don't really see why your program should have to care about anything but the path... From ajsiegel at optonline.net Tue Jan 4 13:07:06 2005 From: ajsiegel at optonline.net (ajsiegel at optonline.net) Date: Tue, 04 Jan 2005 13:07:06 -0500 Subject: Python design strategy (was Python evolution: Unease) Message-ID: <683a9567dada.67dada683a95@optonline.net> Viile writes - >Type declarations are a feature that might benefit IronPython and >Jython more than they would CPython. How much is this part of Guido's decisionmaking process? Guido is , IMO, very much a strategist, as well as a language designer. That's good, I think. However it seems to me he is much more comfortable discussing language design with the community. then he is in discussing strategy. That, I think, is a strategic decision. Understandable, in fact. Nonetheless, I have been uncomfortable with this strategy in the past. For my own reasons. But had no good basis to question the strategy, as strategy.. With the language design issue now on the table, I think I can go further and question the strategy, as such. The question of *why* needs to be fully discussed with the community as part of this exercise, IMO. The "why" that does not give the BDFL's strategic thinking its due weight will not be a fully honest discussion. But what is the BDFL's strategic thinking. Will he stay vague? That it will help certain kinds of projects has been mentioned by Guido. Which specific projects now underway of which he is aware? Why is it important to accommodate those projects? What is Guido's motivation, at this level? Can we ask? Can he answer? In some specifics? To implictly direct the converstaion to the highly technical,. and implicitly assert community concensus should be reached strictly from a language design perspective on the merits, assures us more community damage then is necessary in sorting this one out. Because we won't be having the real conversation. IMO. Art From steve at holdenweb.com Sun Jan 30 16:19:15 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 30 Jan 2005 16:19:15 -0500 Subject: test_socket.py failure In-Reply-To: References: Message-ID: <41FD4F53.2040507@holdenweb.com> x2164 at mailcity.com wrote: > hi all, > > Linux 2.4.28 > Glibc 2.2.5 > gcc 2.95.3 > > > I'm new to Python. > > I've compiled Python 2.4 from tar file. > > When running 'make test' i'm getting a failure > in test_socket. > > Running './python Lib/test/test_socket.py' yields: > > > ====================================================================== > ERROR: testGetServBy (__main__.GeneralModuleTests) > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "Lib/test/test_socket.py", line 330, in testGetServBy > port2 = socket.getservbyname(service) > error: service/proto not found > > ---------------------------------------------------------------------- > Ran 58 tests in 3.826s > > > > The value of 'service' was "daytime". > > After much hand wringing, editing, and use of 'print' > statements i commented out line 330, > '# port2 = socket.getservbyname(service)' and replaced it > with the line 'port2 = port'. > > Running './python Lib/test/test_socket.py' now yields: > > > testGetServBy (__main__.GeneralModuleTests) ... ok > . > . > . > ---------------------------------------------------------------------- > Ran 58 tests in 5.181s > > OK > > > Located the code for 'socket_getservbyname' in > 'Modules/socketmodule.c' where the call to the glibc > function 'getservbyname' is made: > > Py_BEGIN_ALLOW_THREADS > sp = getservbyname(name, proto); > Py_END_ALLOW_THREADS > if (sp == NULL) { > PyErr_SetString(socket_error, "service/proto not found"); > return NULL; > } > > > The only call of socket.getservbyname that failed was when > it was passed the single argument. Since the error message > "service/proto not found" seems to only be generated upon > failure of gibc's 'getservbyname' could it be that > 'PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto)' > generates values for 'name' and/or 'proto' that cause the > failure? > > My search for prior reports of failure at line 330 found > a mention of problems at line 331. > > Well, at any rate, if someone could point me down the > correct path on this i would appreciate it. > Compiling from source requires you to indicate the features that you want compiled in. Without thread support, sockets din't work, so it looks like you need to configure threads in. IIRC you do this by editing the Modules.? file. regards Steve From jalil at feghhi.com Thu Jan 27 17:14:03 2005 From: jalil at feghhi.com (jalil at feghhi.com) Date: 27 Jan 2005 14:14:03 -0800 Subject: Missing _bssd in Python 2.4 Message-ID: <1106864043.734366.315660@c13g2000cwb.googlegroups.com> I compiled and installed python 2.4 on Redhat Linux using default options but don't seem to be getting _bsddb. I get an error message that _bssd cannot be imported. Does anybody know why this might happen? Do I need to do any special customization or install any other software? Thanks, -Jalil From aahz at pythoncraft.com Mon Jan 3 14:07:34 2005 From: aahz at pythoncraft.com (Aahz) Date: 3 Jan 2005 14:07:34 -0500 Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: In article <1104750017.235937.181370 at c13g2000cwb.googlegroups.com>, wrote: > >I am trying to convince my client to use Python in his new product. He >is worried about the license issues. Can somebody there to point me any >good commercial applications developed using python ?. The licence >clearly says Python can be used for commercial applications. Is there >any other implications like that of GPL to make the source open ? Are you looking to embed Python as a scripting language or to write the software in Python? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From fredrik at pythonware.com Thu Jan 27 14:10:00 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 27 Jan 2005 20:10:00 +0100 Subject: Question about 'None' References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> Message-ID: "flamesrock" wrote: > The statement (1 > None) is false (or any other value above 0). Why is > this? http://docs.python.org/ref/comparisons.html "The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily. (This unusual definition of comparison was used to simplify the definition of operations like sorting and the in and not in operators. In the future, the comparison rules for objects of different types are likely to change.)" From ncoghlan at iinet.net.au Fri Jan 21 08:47:50 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 21 Jan 2005 23:47:50 +1000 Subject: Zen of Python In-Reply-To: <7x651rwbib.fsf@ruckus.brouhaha.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> Message-ID: <41F10806.8030303@iinet.net.au> Paul Rubin wrote: > You snipped out the examples I gave, like [x*x for x in range(5)] > leaving unnecessary residue in the name space. Was it not obvious > from the beginning that that was a kludge? If it was obviously > a kludge, was it not obvious that there would be reason to want to > fix it someday? I'm saying that if some new feature is going to > need a fix later, it's better to fix it before releasing it in > the first place. The scoping problem isn't the the least bit obvious, since the equivalent for loop also happens at local scope: Py> lst = [] Py> for x in range(5): ... lst.append(x*x) ... Py> print x 4 Py> lst2 = [y*y for y in range(5)] Py> print y 4 However experience has shown that while having the iteration variable visible after a for loop is useful (due to the existence of the break and raise statements), with a list comprehension the identical behaviour is nothing more than namespace pollution (since you can't use list comprehensions for alternate control flow based searches). So Python 2.4's generator expressions are quite happily evaluated in a separate frame, and the fact that the iteration variable is hidden from the containing scope is viewed as a feature. But knowing a priori that copying the for loop semantics exactly would turn out to be a misfeature? I'll go with Steve's assessment of psychic powers ;) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From google at vertigrated.com Tue Jan 25 14:11:02 2005 From: google at vertigrated.com (fuzzylollipop) Date: 25 Jan 2005 11:11:02 -0800 Subject: Help! Host is reluctant to install Python In-Reply-To: References: Message-ID: <1106680262.810231.169630@z14g2000cwz.googlegroups.com> find a new host, if they can't handle simple tasks like this or simple security tasks like limiting permissions, how can you be sure anything else they do is secure or correct? From grante at visi.com Mon Jan 10 08:33:02 2005 From: grante at visi.com (Grant Edwards) Date: 10 Jan 2005 13:33:02 GMT Subject: Port blocking References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> <34fabdF49gjh1U1@individual.net> Message-ID: <41e2840e$0$71994$a1866201@visi.com> On 2005-01-10, Diez B. Roggisch wrote: >> Usually you wouldn't run a public corba or pyro service over >> the internet. You'd use something like XMLRPC over HTTP port >> 80 partly for the precise purpose of not getting blocked by >> firewalls. > > What exactly makes sending bytes over port 80 more secure than > over any other port? Nothing. When has reality had anything to do with the way corporate IT types configure firewalls? ;) > It has always been my impression that this was to create less > administrative troubles for firewall admins. It's to give corporate IT types the _illusion_ of security and relieve them of the need to learn how to configure firewalls. > But its not inherently more secure. That's a property of the > application running. -- Grant Edwards grante Yow! HAIR TONICS, please!! at visi.com From rbt at athop1.ath.vt.edu Sat Jan 29 19:28:23 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Sat, 29 Jan 2005 19:28:23 -0500 Subject: Description Field in WinXP Services In-Reply-To: <41fc0646$1_1@127.0.0.1> References: <41fc0646$1_1@127.0.0.1> Message-ID: Roger Upole wrote: > ChangeServiceConfig2 is the api functions that sets the description, > but it's not in the win32service module (yet). > > Roger OK, I can use _winreg to add the 'Description' field under the appropriate registry key. From fredrik at pythonware.com Mon Jan 17 14:14:36 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Jan 2005 20:14:36 +0100 Subject: How to prevent the script from stopping before it should References: <1105981979.853318.269300@c13g2000cwb.googlegroups.com><1105982387.852448.298900@c13g2000cwb.googlegroups.com> Message-ID: Steve Holden wrote: > You will need to import the socket module and then call socket.setdefaulttimeout() to ensure that > communication with non-responsive servers results in a socket exception that you can trap. or you can use asynchronous sockets, so your program can keep processing the sites that do respond at once while it's waiting for the ones that don't. for one way to do that, see "Using HTTP to Download Files" here: http://effbot.org/zone/effnews-1.htm (make sure you read the second and third article as well) From uche at ogbuji.net Thu Jan 27 23:01:44 2005 From: uche at ogbuji.net (Uche Ogbuji) Date: 27 Jan 2005 20:01:44 -0800 Subject: parsing WSDL In-Reply-To: <87oefa7rer.fsf@ronaldann.demon.co.uk> References: <6bc0c3c.0501270529.5b9d8e00@posting.google.com> <87oefa7rer.fsf@ronaldann.demon.co.uk> Message-ID: <1106884904.692345.237580@f14g2000cwb.googlegroups.com> Just for completeness I wanted to mention that yes, you can use 4Suite to parse WSDL and get method signature information, but I do agree that it's better to do this at a higher level, if you can. WHy reinvent that wheel? SOAPpy has a decent WSDL class. -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.net http://4Suite.org http://fourthought.com Use CSS to display XML - http://www.ibm.com/developerworks/edu/x-dw-x-xmlcss-i.html Introducing the Amara XML Toolkit - http://www.xml.com/pub/a/2005/01/19/amara.html Be humble, not imperial (in design) - http://www.adtmag.com/article.asp?id=10286UBL 1.0 - http://www-106.ibm.com/developerworks/xml/library/x-think28.html Manage XML collections with XAPI - http://www-106.ibm.com/developerworks/xml/library/x-xapi.html Default and error handling in XSLT lookup tables - http://www.ibm.com/developerworks/xml/library/x-tiplook.html Packaging XSLT lookup tables as EXSLT functions - http://www.ibm.com/developerworks/xml/library/x-tiplook2.html From ncoghlan at iinet.net.au Tue Jan 18 04:31:28 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 18 Jan 2005 19:31:28 +1000 Subject: extension module, thread safety? In-Reply-To: <41eccfe4$0$16621$636a15ce@news.free.fr> References: <41ecbaae$0$1046$626a14ce@news.free.fr> <41eccfe4$0$16621$636a15ce@news.free.fr> Message-ID: <41ECD770.5090107@iinet.net.au> Pierre Barbier de Reuille wrote: > Ok, I wondered why I didn't know these functions, but they are new to > Python 2.4 ( and I didn't take the time to look closely at Python 2.4 as > some modules I'm working with are still not available for Python 2.4). > But if it really allows to call Python code outside a Python thread ... > then I'll surely use that as soon as I can use Python 2.4 :) Thanks for > the hint :) The Python 2.4 docs claim the functions were added in Python 2.3, even though they aren't documented in the 2.3.4 docs. The 2.3 release PEP (PEP 283) confirms that PEP 311 (which added these functions) went in. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ne-nospam7 at post.cybercity.dk Sun Jan 23 15:55:11 2005 From: ne-nospam7 at post.cybercity.dk (Nils Emil P. Larsen) Date: Sun, 23 Jan 2005 21:55:11 +0100 Subject: Keyboard problems with Python shell over SSH Message-ID: <8h38v0h322qokr7cgmen17805kbldhi87o@4ax.com> Hello I'm not sure this is Python-related but it might be since Bash and vim works perfectly. I connect to my server using SSH and then run 'python' to enter the shell. I can't use the arrow buttons (up, down, left and right). Instead I get this ^[[A , ^[[B, ^[[C or ^[[D. How do I get my arrow buttons to work? Sorry if this is offtopic. Nils Emil P. Larsen -- My reply-address is valid. www.bios-flash.dk Min svar-adresse er gyldig. Redning af d?de BIOS'er From cam.ac.uk at mh391.invalid Thu Jan 13 06:06:44 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 13 Jan 2005 11:06:44 +0000 Subject: [perl-python] 20050112 while statement In-Reply-To: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> References: <1105611506.106440.135670@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > # here's a while statement in python. > > [...] > > # here's the same code in perl > > [...] So? -- Michael Hoffman From usenet1 at datahedron.com Thu Jan 20 21:30:48 2005 From: usenet1 at datahedron.com (Peter Rowell) Date: Fri, 21 Jan 2005 02:30:48 GMT Subject: Is there a library to parse Mozilla "mork" documents? In-Reply-To: References: Message-ID: <41F06957.10707@datahedron.com> John Reese wrote: > Mozilla, Firefox, Thunderbird, and so forth use this awful format > called MORK to store all kinds of things: which messages you've read [ snip ] I was searching on a similar question (about accessing the history) when I came across a nifty little bookmarklet. It dumps FF history in RDF format to the file of your choice. This temporarily solved my problem, although in the long run I want to have direct read access to the info. Perhaps you can get a few ideas and go from there. The bookmarlet was attached to Bugzilla item 241438. https://bugzilla.mozilla.org/show_bug.cgi?id=241438 HTH, Peter From mahs at telcopartners.com Sat Jan 22 00:24:47 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Fri, 21 Jan 2005 21:24:47 -0800 Subject: Reload Tricks In-Reply-To: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> References: <1106368177.530867.313610@c13g2000cwb.googlegroups.com> Message-ID: Kamilche wrote: > I want my program to be able to reload its code dynamically. I have a > large hierarchy of objects in memory. The inheritance hierarchy of > these objects are scattered over several files. > > I find that after reloading the appropriate files, and overwriting the > __class__ of object instances, one more thing is necessary: reloading > the __bases__ of each reloaded class. If I don't do this, the modules > reloaded first point to old versions of the classes from later modules, > and when the later module is reloaded, it doesn't update the > inheritance hierarchy of classes already loaded. > > This appears to be working... but now I'm wondering, what else did it > not change? Can I expect more toes to be blown off? > > --Kamilche > There are some cases when re-assigning __class__ isn't possible, for example: >>> class A(object): ... pass ... >>> class B(dict): ... pass ... >>> class C: ... pass ... >>> a = A() >>> a.__class__ = B Traceback (most recent call last): File "", line 1, in ? TypeError: __class__ assignment: 'A' object layout differs from 'B' >>> a.__class__ = C Traceback (most recent call last): File "", line 1, in ? TypeError: __class__ must be set to new-style class, not 'classobj' object >>> An alternative approach (with some pros and cons) is to modify the class in place, using something like: >>> def reclass(cls, to_cls): ... """Updates attributes of cls to match those of to_cls""" ... ... DONOTCOPY = ("__name__","__bases__","__base__", ... "__dict__", "__doc__","__weakref__") ... ... fromdict = cls.__dict__ ... todict = to_cls.__dict__ ... ... # Delete any attribute present in the new class ... [delattr(cls,attr) for attr in fromdict.keys() ... if not((attr in todict) or (attr in DONOTCOPY)) ] ... ... for to_attr, to_obj in todict.iteritems(): ... ... if to_attr in DONOTCOPY: ... continue ... ... # This overwrites all functions, even if they haven't changed. ... if type(to_obj) is types.MethodType: ... func = to_obj.im_func ... to_obj = types.MethodType(func,None, cls) ... ... setattr(cls, to_attr,to_obj) ... >>> class A(object): ... attr = "A" ... >>> class B(object): ... attr = "B" ... >>> a = A() >>> reclass(A,B) >>> a.attr 'B' >>> This copies attributes of old and new-style classes (in fact anything with a __dict__ so probably a module would work too) You still run into problems trying to re-assigning __bases__ to incompatible objects, but this one-attribute-at-a-time approach gives you the potential to intercept problem cases. In the example above, problems are avoided by not copying __bases__. An additional advantage of this aprpoach is that you don't need to keep track of class instances, in order to change their __class__. Instances automatically acquire the new behavior One wart is that class docstrings are not writeable, so cannot be copied. Why? Michael From golux at comcast.net Sat Jan 22 19:14:46 2005 From: golux at comcast.net (Stephen Waterbury) Date: Sat, 22 Jan 2005 19:14:46 -0500 Subject: [OT] XML design intent [was Re: What YAML engine do you use?] In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> <41F2C840.2050304@comcast.net> Message-ID: <41F2EC76.5020101@comcast.net> Fredrik Lundh wrote: > Stephen Waterbury wrote: >>The premise that XML had a coherent design intent >>stetches my credulity beyond its elastic limit. > > the design goals are listed in section 1.1 of the specification. > > see tim bray's annotated spec for additional comments by one > of the team members: > > http://www.xml.com/axml/testaxml.htm > > (make sure to click on all (H)'s and (U)'s in that section for the > full story). Thanks, Fredrik, I hadn't seen that. My credulity has been restored to its original shape. Whatever that was. :) However, now that I have direct access to the documented design goals (intent) of XML, it's interesting to note that the intent Steve Holden imputed to it earlier is not explicitly among them: Steve Holden wrote: > It seems to me the misunderstanding here is that XML was ever intended > to be generated directly by typing in a text editor. It was rather > intended (unless I'm mistaken) as a process-to-process data interchange > metalanguage that would be *human_readable*. Not unless you interpret "XML shall support a wide variety of applications" as "XML shall provide a process-to-process data interchange metalanguage". It might have been a hidden agenda, but it certainly was not an explicit design goal. (The "human-readable" part is definitely there: "6. XML documents should be human-legible and reasonably clear", and Steve was also correct that generating XML directly by typing in a text editor was definitely *not* a design intent. ;) > if you think that the XML 1.0 team didn't know what they were > doing, you're seriously mistaken. it's the post-1.0 standards that > are problematic... Agreed. And many XML-based standards. - Steve From lbates at syscononline.com Fri Jan 21 18:41:07 2005 From: lbates at syscononline.com (Larry Bates) Date: Fri, 21 Jan 2005 17:41:07 -0600 Subject: default value in a list In-Reply-To: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: What do you want put into the "missing" variables? I'll assume None. Something like following works: values=line.split(':') try: a=values.pop(0) except IndexError: a=None try: b=values.pop(0) except IndexError: b=None try: c=values.pop(0) except IndexError: c=None Larry Bates TB wrote: > Hi, > > Is there an elegant way to assign to a list from a list of unknown > size? For example, how could you do something like: > > >>>> a, b, c = (line.split(':')) > > if line could have less than three fields? > > Thanks, > TB > From oglycans at yahoo.com Thu Jan 13 17:16:33 2005 From: oglycans at yahoo.com (oglycans at yahoo.com) Date: 13 Jan 2005 14:16:33 -0800 Subject: how to control the mouse pointer with python? References: <1105650438.311153.167410@f14g2000cwb.googlegroups.com> <34o9npF4et4hiU1@individual.net> Message-ID: <1105654593.637145.321290@z14g2000cwz.googlegroups.com> Sorry, I should have mentioned it's linux (debian). Thanks. > It depends on your operating system. From tjreedy at udel.edu Sun Jan 2 17:44:06 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Jan 2005 17:44:06 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: "Bulba!" wrote in message news:qcagt0l3u4aou1le4phu257n6embo98kv0 at 4ax.com... > On Sat, 01 Jan 2005 15:08:01 -0500, Steve Holden > >>whereas when a company goes >>bust there's no guarantee the software IP will ever be extricated from >>the resulting mess. > > There is a good _chance_ here: money. Somebody has poured a lot > of money into this thing. It's not going to get dropped bc of that. >From what I have read, the amount of proprietary code which *did* get effectively shredded after the dot-com bust is enough to make one cry. There were a few companies that would buy code at bankruptcy sales for maybe 1% of its development cost, but even then, with the original programmers long gone, it could be hard to make anything from it. Terry J. Reedy From craig at postnewspapers.com.au Thu Jan 27 00:19:23 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Thu, 27 Jan 2005 13:19:23 +0800 Subject: how to write a tutorial In-Reply-To: References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106723545.429728.308620@f14g2000cwb.googlegroups.com> Message-ID: <1106803163.8583.4.camel@bucket.localnet> On Wed, 2005-01-26 at 09:35 +0000, Keith Thompson wrote: > "Xah Lee" writes: > [snip] > > Following is a tutorial on Python's classes. > [snip] > > Please stop posting this to comp.lang.c. I'm sure the folks in most > of the other newsgroup aren't interested either -- or if they are, > they can find it in comp.lang.python. Going by the general reaction on c.l.py, I think it'd be more accurate if you left that at "Please stop posting". Sorry for the cross-post, and for this "perl-python" moron who appears to have nothing to do with either, or any knowledge of them. -- Craig Ringer From nav+posts at bandersnatch.org Thu Jan 6 23:57:54 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: Thu, 06 Jan 2005 23:57:54 -0500 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <0WlDd.8830$5R.1182@newssvr21.news.prodigy.com> Message-ID: <87d5whesz1.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Arich Chanachai writes: > He should just build around a linux core or use OS kit (if he is > serious/determined). There's Ubuntu Linux, a Debian-based distro with commercial backing and a regular release schedule. One of the neat things about Ubuntu is that Python use is encouraged. "Python scripting everywhere" is a stated goal, and they have a number of bounties that concentrate on deepening the use of Python in the OS: http://www.ubuntulinux.org/community/bounties I've been using it on a couple of desktops, and I've been impressed by the overall quality of the distro. One thing I especially like is that the root account is disabled by default, administrative tasks are performed with sudo by users in the appropriate group (much like it is in Mac OS X 10.3). Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From jdhunter at ace.bsd.uchicago.edu Fri Jan 28 12:16:17 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 28 Jan 2005 11:16:17 -0600 Subject: Installing Numeric with ATLAS and LAPACK In-Reply-To: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> ("drife"'s message of "28 Jan 2005 08:11:56 -0800") References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> Message-ID: >>>>> "drife" == drife writes: drife> Hello, Could someone please provide instructions for drife> install Numeric with ATLAS and LAPACK? Locate libcblas.a and add that dir to the setup.py library_dirs_list. Eg on my system, /usr/local/lib/ATLAS/lib/Linux_P4SSE2_2/libcblas.a setup.py: library_dirs_list = ['/usr/local/lib/ATLAS/lib/Linux_P4SSE2_2'] Do the same for cblas.h and add it to the include_dirs var in setup.py, on my system it is /usr/local/lib/ATLAS/include/cblas.h, so in setup.py include_dirs = ['/usr/local/lib/ATLAS/include/', '/usr/include/atlas'] Then python setup.py install *should* work. JDH From phr at localhost.localdomain Mon Jan 24 21:10:57 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Tue, 25 Jan 2005 02:10:57 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <1106615822.2400.122.camel@lipscomb.mbi.ucla.edu> Message-ID: James Stroud writes: > Applications that lack features force users to accept a limited feature > set or they use an alternative program with other limitations. Putting > the possibility for cryptographic storage increases the utility of any > application that stores data, and it could be done without much work if > it were properly included in the core distribution. I have found it > amazing how few programs include encryption as an option. I believe this > is because its hard for programmers to include it and/or they falsely > reason that "if I don't need it, the user doesn't", which is up there > with "if I can't see them, then they can't see me" in terms of bad logic. The likely-best-known Python application in the world (probably more people have heard of it than have heard of Python) originally had crypto (an AES module distributed as a C extension with the beta test versions of the app) but the crypto was brutally ripped out of the application for the final release (you can still see scar tissue in the code where the crypto was, i.e., there's still a function called something like "encrypt_packet" which no longer actually encrypts the packet). I haven't found out exactly why the crypto was removed so I can't be certain that it's because of cross-platform installation headaches. I do know that its author wanted an AES module in the core to use for that application, in order to not have to distribute a C extension, and he did some of the early work with me on writing such a module to submit for that purpose. The module I ended up proposing is an offshoot of that effort. From robin at reportlab.com Fri Jan 14 12:46:07 2005 From: robin at reportlab.com (Robin Becker) Date: Fri, 14 Jan 2005 17:46:07 +0000 Subject: Free python server. In-Reply-To: <1105722100.306305.107950@z14g2000cwz.googlegroups.com> References: <002301c4f99a$cb4dcd50$55a01d53@unqku4k1fl8nea7> <1105722100.306305.107950@z14g2000cwz.googlegroups.com> Message-ID: <41E8055F.1030509@chamonix.reportlab.co.uk> rootshell at gazeta.pl wrote: >>Your file probably need to (a) be in the cgi-bin, not public_html, > > (b) > >>be flagged executable ("chmod a+x file.py"), and (c) begin with the >>line: '#!/usr/bin/env python' >> >>If the server doesn't provide you with CGI (or, strongly preferable, >>SCGI or mod_python), you're probably out of luck. > > > You're probably right, this machine doesn't provide with CGI, I'll send > an e-mail to administrator of arbornet.org and make sure. > > So, I ask once again: does anyone know where I can put my *.py files? > Greetings. > Rootshell. > Hi, I just made a cgi script on rht earbornet machine. Process as follows mkdir public_html chmod 0755 public_html cd public_html mkdir cgi-bin chmod 0755 cgi-bin echo hello world > index.html cd cgi-bin echo '#!/bin/sh > echo content-type: text/html > echo > echo "

          Hello World!

          " > ' > hw.cgi chmod a+x hw.cgi then http://m-net.arbornet.org/~rgbecker/cgi-bin/hw.cgi gives a nice red hello world ie acts as a cgi script I also created the standard echo script pytestcgi.cgi as #!/usr/local/bin/python import cgi cgi.test() chmodded as before. See http://m-net.arbornet.org/~rgbecker/cgi-bin/pytestcgi.cgi Please don't misuse it's free and I'm no longer an American :) -- Robin Becker From gandalf at geochemsource.com Fri Jan 28 04:20:01 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Fri, 28 Jan 2005 10:20:01 +0100 Subject: unicode and data strings Message-ID: <41FA03C1.50404@geochemsource.com> Hello I have a program where I would like to calculate a checksum. Looks like this: n = self.__calc_n(seed1,seed2,pwd) This is required for an OTP (One Time Password) algorithm. My code was working before without problems. Now I installed Python 2.3.4 and wxPython 2.5.3 (with unicode support). I'm getting this exception: exceptions.UnicodeDecodeError:'ascii' codec can't decode byte 0x91 in position 0: ordinal not in range(128) The I tried this: >>>'\x91'.decode('utf8') UnicodeDecodeError: 'utf8' codec can't decode byte 0x91 in position 0: unexpected code byte Here is the question: I would like to use simple binary data strings (like an array of bytes). I do not care about encodings. How do I do that? Thanks, Laci 2.0 From phr at localhost.localdomain Wed Jan 26 21:36:51 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Thu, 27 Jan 2005 02:36:51 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" writes: > > That it's not appropriate for the > > distro maintainers to look at the spec and the reference (pure Python) > > implementatation and say "yes, we want this, go write the C version > > and we'll include it after it's had some testing". > > I know that I'm not going to give a blanket promise to include some > code in the future. I can give blanket promises to *review* such > code. Actually, assuming I find the time, I will review *any* > code that is contributed. I don't see why you can't make up your mind enough to issue simple statements like "the Python lib should have a module that does so-and-so, and it should meet such-and-such requirements, so if someone submits one that meets the requirements and passes code review and testing and doesn't have unexpected issues or otherwise fail to meet reasonable expectations, we'll use it". > Sure. That is because O'Reilly is willing to take a financial risk > of failure of a book product. I'm not willing to take similar risks > for Python code (risk of having to redesign the interface, Again, we're talking about straightforward modules whose basic interface needs are obvious. And interfaces in stdlib do get extended from version to version all the time, if users turn out to need additional features beyond the obvious basics. > fix bugs in the implementation, Obviously there must be testing and review before inclusion. Acceptance is contingent on the module passing tests and review. > or have the submitter run away after the contribution). There is no way to know in advance whether that's going to happen. A lot of work on the ANSI X9 crypto standards came to a screeching halt a few years ago when one of the more prolific contributors tripped over his vacuum cleaner cord, fell down the stairs, and was killed. So if you have to be absolutely sure that the submitter will always be around, you can never accept anything. I think you mostly have to go by how maintainable the code looks and how much maintainance you think it will actually need and how many people you think are around who can take care of it when needed. And I do believe that experienced programmers are capable of making reasonable judgements about those questions, so they should not refuse to ever make such judgements. > > Similarly, look at how the whole PEP process works. There are lots of > > times when a PEP has been accepted before any working code is > > distributed. > > Indeed. For new language features, it is more difficult to try them out > in advance than for new library API. I don't see why that should be. Nothing stops anyone from implementing and testing a language feature before standardizing it. It will get even easier with PyPy, which is perhaps a reason to ban further language changes until PyPy is deployed. > Taking it to the extreme misses the point. I'm asking for field > testing for new modules - not for all changes. "Field testing" to most people means testing that a specific implementation is reliable enough for inclusion. It is the final step in a normal process of declaring a feature ready for deployment, not the initial step: 1) think about whether you want the feature 2) decide you want it 3) implement 4) field test (this naturally recognizes the possibility of reversing step 2, if something unexpectedly goes wrong in testing that's not easily repaired, but step 2 declares the basic intention for what should happen after a successful test). 5) deploy You wanted much more than for step 4 to always happen before step 5, which is reasonable. You claimed step 4 should always happen before step 1, which is silly. > > That's bizarre and abnormal as a development process. What kind of > > development process in industry doesn't decide whether to include a > > feature, until after the feature is completely implemented at a > > production scale? > > Any high-quality standardization process. Standards in IETF and OMG > are only accepted after implementations have been available. I don't know what OMG is, but there is no IETF requirement that any implementations be available in any particular language. There are also plenty of instances where the IETF decides that it wants something to be standardized (e.g. IPSEC) so it invites a working group to develop a specification. The WG members then spend a lot of time in meetings and discussions reaching a consensus on what the spec should say. They are willing to spend that time because the IETF has already given them reasonable expectation that their end result will actually be used. The IETF doesn't say "go develop a complete standard and implementation and put it in the field for a year before we [the IETF] will even think about whether we want to standardize it". They are capable of announcing in advance that they want to standardize something. I don't see why the Python folks have to be incapable of ever doing the same. For the module we're discussing, there is already a published working implementation, written in Python. It implements every feature of the API and has been integrated into various applications/demos and tested with them. And, there was reasonable consensus on clpy and on the python-crypto list that the API did the right things. That is all that the IETF normally requires ("rough consensus and working code"). The Python implementation is unsuitable for the stdlib because it's too slow to use in serious production apps and so it needs to be rewritten in C, not because anything is missing or untested about it. (There's also an unpublished hybrid Python/C implementation that's tolerably fast, but unsuitable for contribution because it depends on external packages that can't go in the Python distro). But the IETF would not care about that. All they care is that useable implementations exist. Finally, the IETF generally only specifies protocols and doesn't care about either the implementation specifics or the API (they require implementations to exist only in order to prove that the protocol is usable). The protocols here would be the FIPS operating modes (ECB, CBC, CFB, etc). Those are already standardized as FIPS and have test vectors published by NIST. The Python implementation computes all the published test vectors correctly and interoperates with various non-Python programs that use those same modes. So again, there is already enough available to satisfy an IETF-like standardization process. Your IETF example does not support your stance. > The volunteers are free to work on whatever they please. If you chose > not to write an AES module - that's fine with me. However, the result of my not writing an AES module is that Python doesn't have an AES module. Because as far as I can tell, while numerous people want to use such a module, nobody except me has expressed willingness to write and contribute one. If someone else did it, I would be overjoyed, and I'd happily use whatever they wrote, if it was useable at all, dropping any plans to write my own. (And frankly, the only feature such a module absolutely needs to provide is simple ECB mode block encryption and decryption. The other modes are helpful for good performance and convenience but can be done as pure Python functions that call the ECB mode primitive, with tolerable speed for lots of useful apps. It's just the block cipher primitive that's painfully slow in Python). > Still, people do contribute to Python, and they do so without asking > for permission first. They have not done that for an AES module. That is a fact on the ground. I don't have any burning desire to be the author of a Python AES module. I just think Python should have one that I and other app writers can rely on, so I've been willing to volunteer to write and contribute it, since I'm qualified and nobody else has stepped forward. But there appears to currently be a policy in force saying "there will be no crypto module in the Python stdlib regardless of its technical quality". Under that policy, there's no point in my writing one to contribute it. > Typically, they develop the code because it solves their own needs - > then it doesn't really matter whether it also solves the needs of others. In fact that's been done with AES and DES numerous times, and the resulting modules do meet my needs for my own end-use (I'm currently using a C library wrapped with SWIG). What's missing is a module in the stdlib that lets me ship pure-Python crypto apps that other end users can run without installing C code. And, as we discussed already, the modules people have written for their own needs (at least so far) aren't really technically suitable for the stdlib, because a good general purpose stdlib module has somewhat different characteristics than a module written to support a specific application, which is what people write to solve their own needs. Note that the same thing is true for most other types of library modules besides crypto (i.e. a general purpose module suitable for the stdlib tends to be different from what someone writes to solve their own needs). So either most stdlib modules were either not written purely to solve the author's needs and then submitted as an afterthought as you describe, or else the modules in the stdlib typically don't have good general-purpose designs. (In fact the latter is often true, which suggests that the practice of contributing modules originally written only to solve an individual need often results in lousy stdlib modules, and a policy change towards encouraging designing intentionally for the stdlib is probably a good thing. To paraphrase RMS, a good stdlib needs to come from a vision and a plan, not just from scratching a bunch of different itches). > >>In either case, the user would best use the pre-compiled binary that > >> somebody else provided for the platform. > > Who's the "somebody else"? > > Some user. I find that users contribute binaries for all kinds of > platforms for the code I publish. This is how open source works. > > > Do you do that > > with your own modules, and still say that it's easy? > > I publish or link to binaries of my code that others have created, > and find no problems in doing so. And you seriously believe that the result is as painless for end users as having a module in the stdlib that apps can just import and call without the end-user having to first locate, download and install a 3rd party module? Do you think the Python philosophy of "batteries included" really is a) meaningless, b) worthwhile in the past but now obsolete, c) a mistake to begin with, d) sort of worthwhile but not really important, e) something else? That's not a rhetorical question, I'm really having a hard time figuring out what you think "batteries included" is supposed to mean. I personally consider it meaningful and extremely important, or else I'd be using Scheme instead of Python. > No, it's three steps > 1. decide that you want to do it > 2. do it > 3. decide whether you are pleased with the result, and only > use it if you are > > IOW, there should not be a blanket guarantee to use it after step 1. But, it's completely normal to say before step 1 that "if the result of step 2 does so-and-so, then I'll be pleased in step 3", stating some clear requirements and sticking to them. People do that in real life all the time, including in standardization processes, and often with ironclad guarantees (called "contracts"). It's pathetic if the Python maintainers are so indecisive as to be incapable to ever saying (even -without- making ironclad guarantees), that "yeah, we really ought to have an XYZ module and we'll use one if someone submits it and it does so-and-so", giving an informal assurance to someone thinking of doing an implementation that they're probably not wasting their time. That's often what allows step 1 to happen. > > I think that question isn't the right one. We need to ask how > > many users the sha module was required to have, before Greg and > > Andrew could have reasonable confidence that the sha module would > > go into the core once it was tested enough and shown to be > > reliable. > > They did not have *any* guarantee until they asked. I guess when they > asked it was accepted immediately. And who do you think they asked, hmm? When I asked Guido about submitting a crypto module, he told me that he defers all technical crypto issues to Andrew. So I think Andrew had a reasonable expectation of what would happen when he submitted it. You and Frederik seem to think there's something inappropriate or self-inflated about wanting that expectation before committing to do a pile of work that's primarily for other people's benefit. I think your stated attitude is completely bizarre, that you can't really believe anything so silly, so you're really just acting bureaucratic, looking for excuses to say no instead of yes to worthwhile proposals. > Again, we would have to ask - but I would not be surprised if > AMK started implementing the [sha] module without even *considering* > a later inclusion in the Python core at that time. He has done > so on many occasions (include PyXML, which I inherited from him). I would be surprised. That need for an sha module was completely obvious, what it needed to do was completely obvious, and the requirements and implementation have nothing like the subtlety of PyXML. From steve at holdenweb.com Sun Jan 9 16:59:52 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 09 Jan 2005 16:59:52 -0500 Subject: use a file as a database, access rights In-Reply-To: <1105287418.765236.250270@c13g2000cwb.googlegroups.com> References: <1105287418.765236.250270@c13g2000cwb.googlegroups.com> Message-ID: <41E1A958.1070803@holdenweb.com> Kartic wrote: > Steve Holden wrote: > > > >>Sounds to me like you need to add a rights layer to gadfly. > > > > Aha...I did not consider that possibility. I have not gone indepth into > Gadfly...is that a straigtforward thing to implement? > Gadfly has been a very straightforwad installation for me. Of course the complexity of the access control will depend on the complexity of your application's requirements. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From rkern at ucsd.edu Mon Jan 31 00:42:45 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sun, 30 Jan 2005 21:42:45 -0800 Subject: python and gpl In-Reply-To: References: Message-ID: John Hunter wrote: > I have a question about what it takes to trigger GPL restrictions in > python code which conditionally uses a GPL library. > > Here is the context of my question. matplotlib, which I develop, is a > plotting module which is distributed under a PSF compatible license, > and hence we avoid using GPLd code so as to not trigger the GPL > requirements. matplotlib has rigid segregation between the front end > (plotting commands, figure objects, etc) and backends (gtk, wx, ps, > svg, etc). The backend is chosen dynamically at runtime -- eg the > same python script could trigger the import gtk, wx, or ps, depending > an some rc settings or command line opts. > > The question is: does shipping a backend which imports a module that > links with GPL code make some or all of the library GPL. This > question is complicated, in my mind at least, by several factors. > > Here are some sub-questions: > > * If a backend module somebackend does > > import somelib > > where somelib is a python wrapper of GPL code, is somebackend > GPLd? If it is original code, then no. To distribute it, it must have a GPL-compatible license, and when distributing it with the GPLed library, you must observe the same restrictions with your code as well as the GPLed code. However, the license of the wrapper code itself may be, e.g. BSD. If someone wants to take a bit of that code out of the wrapper (maybe it's a generally useful bit of code), and that bit of code has nothing to do with the GPLed library, then one can take that bit of code under the BSD license and incorporate it into a proprietary project. > * Assuming the answer to the above question is yes, is matplotlib > GPLd if it distributes somebackend? I think this is a nuanced > situation because matplotlib would work just fine w/o somemodule, > and only uses somemodule's code if it is selected at runtime by > the user. Ie, no other part of the code depends on it since it is > one of many interchangeable backends. Think of the situation wrt readline and the standard Python interpreter. If you distribute binaries linked to libreadline, you also have to distribute the rest of the code and ensure that that code is under a GPL-compatible license. If you excise the GPLed code because you aren't using it, you aren't bound by the GPL terms. > * To further complicate the question, the backend in question is qt, > which is dual licensed, commercial and GPL. The qt backend code > just needs to 'import qt', and neither the backend writer nor the > matplotlib frontend knows whether the deployed qt on the system is > commercial or GPLd. To date, the only GPL-like backend is GTK, > which is LGPL. Since we're only linking and not using the src, > we're protected from the GPL requirements. With QT, which has a > pure (non L) GPL variant, the situation is less clear to me. If some matplotlib-using code specifically requires the QT backend, Trolltech may have a case for requiring you to follow the GPL terms or pay for a license. Otherwise, they're probably SOL. If you're distributing PyQT binaries along with your package, then you should probably follow the GPL's terms. IANAL. TINLA. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From jacek.generowicz at cern.ch Tue Jan 11 05:27:56 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 11 Jan 2005 11:27:56 +0100 Subject: The limitation of the Photon Hypothesis References: Message-ID: Steve Holden writes: > Steve Horsley wrote: > > > Also, I think you probably accidentally posted to the wrong > > newsgroup. > > No, he deliberately posted to the wrong newsgroup. Heh ... I initially read the subject line as "The limitation of the Python Hypothesis". From __peter__ at web.de Fri Jan 28 10:31:52 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Jan 2005 16:31:52 +0100 Subject: Hey, get this! [was: import from database] References: Message-ID: Steve Holden wrote: > This is even stranger: it makes it if I import the module a second time: [second import seems to succeed] Maybe you are experiencing some version confusion? What you describe looks much like the normal Python 2.3 behaviour (with no import hook involved) whereas you seem to operate on the 2.4 library. A partially initialized module object is left behind in sys.modules and seen by further import attempts. $ cat arbitrary.py import not_there def f(): print "you ain't gonna see that" $ python Python 2.3.3 (#1, Apr 6 2004, 01:47:39) [GCC 3.3.3 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import arbitrary Traceback (most recent call last): File "", line 1, in ? File "arbitrary.py", line 2, in ? import not_there ImportError: No module named not_there >>> import arbitrary >>> arbitrary.f() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'module' object has no attribute 'f' >>> I have no experience with import hooks, but for normal imports that has been fixed in Python 2.4: $ py24 Python 2.4 (#5, Jan 4 2005, 10:14:01) [GCC 3.3.3 (SuSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import arbitrary Traceback (most recent call last): File "", line 1, in ? File "arbitrary.py", line 2, in ? import not_there ImportError: No module named not_there >>> import arbitrary Traceback (most recent call last): File "", line 1, in ? File "arbitrary.py", line 2, in ? import not_there ImportError: No module named not_there >>> Peter From nav+posts at bandersnatch.org Wed Jan 26 15:39:07 2005 From: nav+posts at bandersnatch.org (Nick Vargish) Date: Wed, 26 Jan 2005 15:39:07 -0500 Subject: Help With Python References: Message-ID: <87ekg8c4d0.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Here's my Monty Pythonic answer: ## cut here class Viking(): def __init__(): pass def order(): return 'Spam' # this is one viking making one order repeated 511 times. if you want # 511 vikings making seperate orders, you'll have to write a loop. v = Viking() orders = [ v.order() ] * 511 print ', '.join(orders) ## cut here With no apologies to Eric Idle, Nick -- # sigmask || 0.2 || 20030107 || public domain || feed this to a python print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?') From ods at strana.ru Fri Jan 21 09:14:28 2005 From: ods at strana.ru (Denis S. Otkidach) Date: Fri, 21 Jan 2005 17:14:28 +0300 Subject: need help on generator... In-Reply-To: <63b5e209.0501210558.686f5c10@posting.google.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> Message-ID: <20050121171428.61d80e99.ods@strana.ru> On 21 Jan 2005 05:58:03 -0800 joh12005 at yahoo.fr (Joh) wrote: > i'm trying to understand how i could build following consecutive sets > from a root one using generator : > > l = [1,2,3,4] > > would like to produce : > > [1,2], [2,3], [3,4], [1,2,3], [2,3,4] >>> def consecutive_sets(l): ... for i in xrange(2, len(l)): ... for j in xrange(0, len(l)-i+1): ... yield l[j:j+i] ... >>> list(consecutive_sets([1,2,3,4])) [[1, 2], [2, 3], [3, 4], [1, 2, 3], [2, 3, 4]] -- Denis S. Otkidach http://www.python.ru/ [ru] From sjmachin at lexicon.net Sat Jan 15 22:06:30 2005 From: sjmachin at lexicon.net (John Machin) Date: 15 Jan 2005 19:06:30 -0800 Subject: How to del item of a list in loop? In-Reply-To: References: <1105838984.045727.55730@f14g2000cwb.googlegroups.com> Message-ID: <1105844790.287893.75860@c13g2000cwb.googlegroups.com> Michael Hoffman wrote: > John Machin wrote: > > > Three significant figures is plenty. Showing just the minimum of the > > results might be better. > > It might be, but how much time do you want to spend on getting your > results for a benchmark that will be run once in the "better" format? > About the same time as the "worse" format. The Mona Lisa was painted once. The Taj Mahal was built once. > Next time you can run the benchmark yourself and it will be in exactly > the format you want. I've done that already. I've taken your code and improved it along the suggested lines, added timing for first, middle, and last elements, added several more methods, and added a testing facility as well. Would you like a copy? From stephen.thorne at gmail.com Thu Jan 27 00:01:52 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 27 Jan 2005 15:01:52 +1000 Subject: String Fomat Conversion In-Reply-To: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> References: <1106801582.417862.293210@c13g2000cwb.googlegroups.com> Message-ID: <3e8ca5c805012621012d745c20@mail.gmail.com> On 26 Jan 2005 20:53:02 -0800, mcg wrote: > Investigating python day 1: > > Data in file: > x y > 1 2 > 3 4 > 5 6 > > Want to read file into an array of pairs. > > in c: scanf("%d %d",&x,&y)---store x y in array, loop. > > How do I do this in python?? > In the actual application, the pairs are floating pt i.e. -1.003 f = file('input', 'r') labels = f.readline() # consume the first line of the file. Easy Option: for line in f.readlines(): x, y = line.split() x = float(x) y = float(y) Or, more concisely: for line in f.readlines(): x, y = map(float, line.split()) Regards, Stephen Thorne From steven.bethard at gmail.com Thu Jan 27 16:15:30 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 27 Jan 2005 14:15:30 -0700 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> <41F9E081.6050008@freemail.gr> Message-ID: Francis Girard wrote: > I see. There is some rule stating that all the strings are greater than ints > and smaller than lists, etc. Yes, that rule being to compare objects of different types by their type names (falling back to the address of the type object if the type names are the same, I believe). Of course, this is arbitrary, and Python does not guarantee you this ordering -- it would not raise backwards compatibility concerns to, say, change the ordering in Python 2.5. > What was the goal behind this rule ? I believe at the time, people thought that comparison should be defined for all Python objects. Guido has since said that he wishes the decision hadn't been made this way, and has suggested that in Python 3.0, objects of unequal types will not have a default comparison. Probably this means ripping the end off of default_3way_compare and raising an exception. As Fredrik Lundh pointed out, they could, if they wanted to, also rip out the code that special-cases None too. Steve From genezhang at gmail.com Sun Jan 9 19:46:11 2005 From: genezhang at gmail.com (Gene) Date: 9 Jan 2005 16:46:11 -0800 Subject: path to python file given module In-Reply-To: <1105315923.520581.280580@c13g2000cwb.googlegroups.com> References: <1105315568.887724.260370@c13g2000cwb.googlegroups.com> <1105315923.520581.280580@c13g2000cwb.googlegroups.com> Message-ID: <1105317971.205487.82770@c13g2000cwb.googlegroups.com> that method doesn't seem to work as well on UNIX: wla apocalypse[94] ~/filegen > ls filegen.py OLDwla_csv2objects.py wlaclasses.py filegen.pyc templates/ wlaclasses.pyc gen_all_from_csv.py test.py* wla apocalypse[95] ~/filegen > python ... >>> import filegen, inspect >>> inspect.getsourcefile(filegen) 'filegen.py' >>> inspect.getsourcefile(filegen.Lecture) 'wlaclasses.py' >>> import os >>> os.chdir('..') >>> inspect.getsourcefile(filegen) >>> print inspect.getsourcefile(filegen) None >>> print inspect.getsourcefile(filegen.Lecture) None From rNOSPAMon at flownet.com Mon Jan 3 10:59:21 2005 From: rNOSPAMon at flownet.com (Ron Garret) Date: Mon, 03 Jan 2005 07:59:21 -0800 Subject: Python! Is! Truly! Amazing! References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: In article , jfj wrote: > Ron Garret wrote: > > In article <1104657461.868175.252380 at c13g2000cwb.googlegroups.com>, > > "Erik Bethke" wrote: > > > > > >>I have NEVER experienced this kind of programming joy. > > > > > > Just wait until you discover Lisp! > > > > ;-) > > > I've had it with all those lisp posts lately ;-) > > There were functional and non-functional programming languages (the > first being *much* simpler to implement). There is a *reason* people > chose C over lisp. It's not that we were all blind and didn't see the > amazingness of lisp. Procedural languages are simply better, and I'm not > replying to this flamewar. Then neither am I. Yes, there's a reason people choose C over Lisp, just as there is a reason that people choose Windows over OS X, the Ford Taurus over the Lexus SC400, and Perl over Python. But I'm pretty sure joy isn't that reason. If joy is part of your quality metric for a programming language then Lisp is worth a look. (And it costs a lot less than a Lexus.) rg From timr at probo.com Thu Jan 13 02:59:20 2005 From: timr at probo.com (Tim Roberts) Date: Wed, 12 Jan 2005 23:59:20 -0800 Subject: Octal notation: severe deprecation References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105575689.335040.174490@c13g2000cwb.googlegroups.com> Message-ID: Stephen Thorne wrote: >On 12 Jan 2005 16:21:29 -0800, PJDM wrote: >> Maybe P3K will have an integer literal like "n_b" for "the integer n in >> base b". > >I would actually like to see pychecker pick up conceptual errors like this: > >import datetime >datetime.datetime(2005, 04,04) Why is that a conceptual error? Syntactically, this could be a valid call to a function. Even if you have parsed and executed datetime, so that you know datetime.datetime is a class, it's quite possible that the creation and destruction of an object might have useful side effects. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From fredrik at pythonware.com Thu Jan 20 09:40:35 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jan 2005 15:40:35 +0100 Subject: ElementTree cannot parse UTF-8 Unicode? References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com><5861401.FEXqi8ioxF@strongwill.g2ctech> <1106230846.455765.7310@c13g2000cwb.googlegroups.com> Message-ID: Erik Bethke wrote: > layout += '\n' > layout += ' \n' what does "print repr(L1Word)" print (that is, what does wxPython return?). it should be a Unicode string, but that would give you an error when you write it out: >>> f = open("file.txt", "w") >>> f.write(u'\uc5b4\ub155\ud558\uc138\uc694!') Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128) have you hacked the default encoding in site/sitecustomize? what happens if you replace the L1Word term with L1Word.encode("utf-8") can you post the repr() (either of what's in your file or of the thing, whatever it is, that wxPython returns...) From jeff at ccvcorp.com Fri Jan 7 19:12:47 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 07 Jan 2005 16:12:47 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: <7xvfa90w6g.fsf@ruckus.brouhaha.com> References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <7xis6930ah.fsf@ruckus.brouhaha.com> <7xvfa90w6g.fsf@ruckus.brouhaha.com> Message-ID: <10tu91mhv8mn89d@corp.supernews.com> Paul Rubin wrote: > Richard Feynman told a story about being on a review committee for > some grade-school science textbooks. One of these book said something > about "counting numbers" and it took him a while to figure out that > this was a new term for what he'd been used to calling "integers". With all due respect to Richard Feynman, I'd have thought that "counting numbers" would be non-negative integers, rather than the full set of integers... which, I suppose, just goes to show how perilous it can be to make up new, "more natural" terms for things. ;) Jeff Shannon Technician/Programmer Credit International From frans.englich at telia.com Mon Jan 24 21:15:58 2005 From: frans.englich at telia.com (Frans Englich) Date: Tue, 25 Jan 2005 02:15:58 +0000 Subject: Distutils: blurring the file==module borders Message-ID: <200501250215.58729.frans.englich@telia.com> Hello all, Due to the size of my source, I want to split it up into multiple files(basically one class in each file), but then I have difficulties with the directory layout when the modules are installed with distutils. This is my file layout: in ./ I have a setup.py which has 'packages="foo"' in ./foo/ I have an __init__.py and a handful of files named ClassA.py, ClassB.py, ClassC.py and so forth. The problem is that when installed, in order to reach, say, classB, I need to do: import foo.ClassA var = foo.ClassA.ClassA() while I want to do var = foo.ClassA() In other words, the result I want can be achieved by putting all code in __init__.py. The problem is that I would find it horrible to have all code in one file. Python have this one-to-one relationship between modules and files; can what I want somehow be achieved? Cheers, Frans From steve at holdenweb.com Sun Jan 16 12:32:26 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 16 Jan 2005 12:32:26 -0500 Subject: protecting the python code. In-Reply-To: <1105893393.214111.227550@f14g2000cwb.googlegroups.com> References: <1105884196.461107.28120@z14g2000cwz.googlegroups.com> <41EA92A7.3080706@holdenweb.com> <1105893393.214111.227550@f14g2000cwb.googlegroups.com> Message-ID: <41EAA52A.3070804@holdenweb.com> nell wrote: > Hi Steve, > First the "10x in advance" means thanks in advance. > The main importance of protecting my code is to save headache of > customers that want to be smart and change it and then complain on bugs > and problems. > > 10x > I'd have understood "tnx", never seens 10x b4 :-) Your concerns are what licensing's for. ("No support on modified copies" would be a good heading for a section addressing this issue). With good enough release controls you can verify the code is unmodified using md5 checksums or similar. If a customer's good enough at Python to disassemble your .pyc files, they will probably tell you they've modified your code when the support queries come in :-) regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From ncoghlan at iinet.net.au Sun Jan 23 02:18:53 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 23 Jan 2005 17:18:53 +1000 Subject: finding name of instances created In-Reply-To: <1106397218.724722.172660@c13g2000cwb.googlegroups.com> References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> <1106397218.724722.172660@c13g2000cwb.googlegroups.com> Message-ID: <41F34FDD.3010904@iinet.net.au> Andr? wrote: > So, students will be able to write: > pete = CreateRobot(2, 3) > pete.move() > > learning about objects and methods. > > As for things like > for robot in robots: > do stuff > > that will be for my use only: drawing robots on the screen, updating > the 'world' when robots pick stuff up, etc. My intention is that the > students will use the EXACT python syntax, so that they don't know that > *I* have given a *name* to their robot(s) behind the scene. > I have to cut this short; I hope it clarifies my intentions. My (and, if I understand him correctly, Jeremy's) concern would be that error messages like "Robot 'pete' has hit a wall!" would give students the impression that the robots automatically know their name as a result of the assignment. In standard Python, that simply isn't true. If, instead, CreateRobot looked something like: def CreateRobot(street, avenue, name=None): if name is None: name = "Robot" + Robot.getNextNumber() return Robot(street, avenue, name) Then, using a simple assignment: pete = CreateRobot(2, 3) pete.move() Would give an error like: "Robot1 has hit a wall" This could then be used to point out that objects named using assignment don't know about the names they have been given, and need to be told: pete = CreateRobot(2, 3, "Pete") pete.move() "Pete has hit a wall" Instead of misleading the students ("objects know what names they have been given"), you have taught them a powerful truth - objects and the names you give them via assignment are entirely independent. It also directly addresses the question of aliasing. Think about how Steven's modified dictionary would react to this code: pete = CreateRobot(2, 3) dad = pete dad.move() pete.move() Internally, idioms like "for robot in robots" should be entirely unaffected - the registration of the robot instance with the global list of robots can be handled by the robot initialisation method. Regards, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tdelaney at avaya.com Sun Jan 9 17:13:10 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 10 Jan 2005 09:13:10 +1100 Subject: interpreter Py_Initialize/Py_Finalize mem leak? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE0252027E@au3010avexu1.global.avaya.com> Roman Suzi wrote: > In pure curiosity I tried to compile loop.c from Demo/embed > and started it with 'print 2+2'. It seems, that both 2.3 and 2.4 > pythons have memory leaks in Py_Initialize/Py_Finalize calls. > (That is, interpreter doesn't clean up well after itself). What's your evidence for this (i.e. what are the symptoms)? If you have a repeatable test case, please raise a bug report on SourceForge. Tim Delaney From maxm at mxm.dk Tue Jan 4 10:48:49 2005 From: maxm at mxm.dk (Max M) Date: Tue, 04 Jan 2005 16:48:49 +0100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) In-Reply-To: <1104849206.111461.70500@c13g2000cwb.googlegroups.com> References: <1gpoaq3.1trkc8e1bxl9h4N%aleaxit@yahoo.com> <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> Message-ID: <41daba9c$0$208$edfadb0f@dread12.news.tele.dk> michele.simionato at gmail.com wrote: > uhm ... then there is a misprint in the discussion of the recipe; > BTW what's the difference between .encode and .decode ? > (yes, I have been living in happy ASCII-land until now ... ;) # -*- coding: latin-1 -*- # here i make a unicode string unicode_file = u'Some danish characters ???' #.encode('hex') print type(unicode_file) print repr(unicode_file) print '' # I can convert this unicode string to an ordinary string. # because ??? are in the latin-1 charmap it can be understood as # a latin-1 string # the ??? characters even has the same value in both latin1_file = unicode_file.encode('latin-1') print type(latin1_file) print repr(latin1_file) print latin1_file print '' ## I can *not* convert it to ascii #ascii_file = unicode_file.encode('ascii') #print '' # I can also convert it to utf-8 utf8_file = unicode_file.encode('utf-8') print type(utf8_file) print repr(utf8_file) print utf8_file print '' #utf8_file is now an ordinary string. again it can help to think of it as a file #format. # #I can convert this file/string back to unicode again by using the decode method. #It tells python to decode this "file format" as utf-8 when it loads it onto a #unicode string. And we are back where we started unicode_file = utf8_file.decode('utf-8') print type(unicode_file) print repr(unicode_file) print '' # So basically you can encode a unicode string into a special string/file format # and you can decode a string from a special string/file format back into unicode. ################################### u'Some danish characters \xe6\xf8\xe5' 'Some danish characters \xe6\xf8\xe5' Some danish characters ??? 'Some danish characters \xc3\xa6\xc3\xb8\xc3\xa5' Some danish characters ?????? u'Some danish characters \xe6\xf8\xe5' -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From ionel.mc at gmail.com Sat Jan 15 22:30:37 2005 From: ionel.mc at gmail.com (ionel) Date: Sun, 16 Jan 2005 05:30:37 +0200 Subject: threading and sockets ? Message-ID: how to make a efficient server.. please point me to some good and clear examples -- ionel. From ml at fgranger.com Thu Jan 20 05:54:03 2005 From: ml at fgranger.com (Fran=?ISO-8859-1?B?5w==?=ois Granger) Date: Thu, 20 Jan 2005 11:54:03 +0100 Subject: [ANN] MarkupToMarkup 0.2 Message-ID: Description: http://wiki.fgranger.com/Development/MarkupToMarkup Test: http://fgranger.net1.nerim.net/mtom/ MarkupToMarkup is a project to create tools for translating from various markup to various markup. There are a lot of syntax to markup texts prior to publishing them. From HTML to Markdown, and from reStructuredText to the various wiki formats. When using a tool to publish, you are tied to the particular syntax of this tool. And transferring between them is a problem, not only at the storage level, but also at the text markup level. MarkupToMarkup is built in a modular way. It use the various existing filters to transfer the input to a almost XHTML format. It then use a parser and filters to generate the various wiki like syntax formats. As demand arise, it may be extended in number of filters, in input and output methods. Dues to the number of scripts (Python, Perl, soon some PHP) and dependencies, the current version is implemented as a web service on a web page. There are plans to make it an XML-RPC service, or package it when things evolves. From beliavsky at aol.com Wed Jan 26 12:53:03 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 26 Jan 2005 09:53:03 -0800 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <1106761983.247132.192070@f14g2000cwb.googlegroups.com> Peter Maas wrote: > Davor schrieb: > > so initially I was hoping this is all what Python is about, but when I > > started looking into it it has a huge amount of additional (mainly OO) > > stuff which makes it in my view quite bloated now. > > So you think f.write('Hello world') is bloated and file_write(f,'Hello world') > is not? This is the minimum amount of OO you will see when using Python. But > I guess you will use OO in the long run to *avoid* bloated code: > > --------------snip--------------- > > print "*** Davor's evolution towards an OO programmer ***" > > print '\n*** Step 1: OO is evil, have to use atomic variables:' > > name1 = 'Smith' > age1 = 35 > sex1 = 'male' > name2 = 'Miller' > age2 = 33 > sex2 = 'female' > > print name1, age1, sex1, name2, age2, sex2 > > print '\n*** Step 2: This is messy, put stuff in lists:' > > p1 = ['Smith', 35, 'male'] > p2 = ['Miller', 33, 'female'] > > for e in p1: > print e > > for e in p2: > print e Being a Fortranner, my "Step 2" would be to use parallel arrays: names = ['Smith','Miller'] ages = [35,33] sexes = ['male','female'] for i in range(len(names)): print names[i],ages[i],sexes[i] There are disadvantages of parallel arrays (lists) -- instead of passing one list of 'persons' to a function one must pass 3 lists, and one can unexpectedly have lists of different sizes if there is a bug in the program or data file. But there are advantages, too. Sometimes one does not need to pass the entire data set to a function, just one attribute (for examples, the ages to compute the average age). This is more convenient with parallel arrays than a list of objects (although it's easy in Fortran 90/95). I am not saying that parallel arrays are better than classes for storing data, just that they are not always worse. It is a strength of Python that like C++, it does not force you to program in an object-oriented style. Lutz and Ascher, in the 2nd edition of "Learning Python", do not mention OOP for almost the first 300 pages. They say (p297) "Python OOP is entirely optional, and you don't need to use classes just to get started. In fact, you can get plenty of work done with simpler constructs such as functions, or even simple top-level script code. But classes turn out to be one of the most useful tools Python provides ..." From steve at holdenweb.com Fri Jan 21 18:36:58 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Jan 2005 18:36:58 -0500 Subject: default value in a list In-Reply-To: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: <5rgId.85257$Jk5.25077@lakeread01> TB wrote: > Hi, > > Is there an elegant way to assign to a list from a list of unknown > size? For example, how could you do something like: > > >>>> a, b, c = (line.split(':')) > > if line could have less than three fields? > l = line.split(':') l is a list, whose length will be one more than the number of colons in the line. You can access the elements of the list using a[0], a[2], and so on. For example: >>> line = "This:is:a:sample:line" >>> l = line.split(':') >>> l ['This', 'is', 'a', 'sample', 'line'] >>> for w in l: ... print w ... This is a sample line >>> len(l) 5 >>> regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From http Fri Jan 21 23:32:46 2005 From: http (Paul Rubin) Date: 21 Jan 2005 20:32:46 -0800 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> Message-ID: <7xfz0uqe1d.fsf@ruckus.brouhaha.com> Tim Peters writes: > But at that time, Python didn't have lexical scoping, and it wasn't > clear that it ever would. So what's the bigger wart? Making > listcomps exactly equivalent to an easily-explained Python for-loop > nest, or introducing a notion of lexical scope unique to listcomps, > hard to explain in terms of the way the rest of the language worked? Oops, I'd gotten confused and thought lexical scope came first and listcomps afterwards. If lexical scope came afterwards, then implementing listcomps as a for-loop at that time makes more sense. Of course in that case, since the absence of lexical scope was a wart in its own right, fixing it had to have been on the radar. So turning the persistent listcomp loop var into a documented feature, instead of describing it in the docs as a wart that shouldn't be relied on, wasn't such a hot idea. Adding lexical scope and listcomps at the same time might have also been a good way to solve the issue. From kartic.krishnamurthy at gmail.com Wed Jan 5 15:05:11 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 5 Jan 2005 12:05:11 -0800 Subject: win32com.client problem References: Message-ID: <1104955511.276842.316210@f14g2000cwb.googlegroups.com> Hi, 1. Put your COM invokations in a try/except loop. From my experience, that helped me prevent, in most cases, Excel from "hanging" and having to restart the PC too. In the except part, release the Excel (or other COM resource) (e.g.calling workbook.Close() or excelobj.Quit(), depending on the state of your program) 2. Look at http://www.faqts.com/knowledge_base/entry/versions/index.phtml?aid=5847 to see how to get the actual error. 3. Delete instances of the COM connection, RS object or whatever win32com.client instances you create. I do this: sheetobj = None wbkbobj = None excelobj = None del sheetobj del wbkobj del excelobj 4. At the end of my scripts, I do the following during the development stage: ActiveComConn = pythoncom._GetInterfaceCount() print 'Done! Active Com Connections :',ActiveComConn # Print count of Active COM connections. Thank you, --Kartic From __peter__ at web.de Tue Jan 11 13:37:46 2005 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Jan 2005 19:37:46 +0100 Subject: how to set doc-string of new-style classes References: Message-ID: harold fellermann wrote: > programm execution and should therefore be forbidden!" But, I cannot > even find out a way to set the doc string, when I CREATE a class using > type(name,bases,dict) ... At least this should be possible, IMHO. That's what the dict parameter is for: >>> T = type("T", (object,), dict(__doc__="what you want")) >>> T.__doc__ 'what you want' Peter From fuzzyman at gmail.com Thu Jan 27 10:12:03 2005 From: fuzzyman at gmail.com (fuzzyman at gmail.com) Date: 27 Jan 2005 07:12:03 -0800 Subject: [ANN] Movable Python, linky and Techie Blog Message-ID: Minor news first : 'linky' a local link checker is available. http://www.voidspace.org.uk/python/programs.shtml#linky linky will check your website for dead links (within the website) as well as comparing it to the website on your filesystem, to check for case errors that might not be picked up if you test your website on windows. It can also report files that don't appear to be linked to - for finding redundant images etc. linky uses BeautifulSoup to do the hard work. The Voidspace Techie Blog has moved. My (mainly python related blog) now lives at : http://www.voidspace.org.uk/python/weblog/index.shtml It is created using firedrop - the excellent blog tool by Hans Nowak MOVABLE PYTHON http://www.voidspace.org.uk/python/movpy http://sourceforge.net/projects/movpy Version 0.4.5 is now available, hurrah. There are now prebuilt distributions for Python 2.2, 2.3, *and* 2.4. This is a bugifx/update release. The distributions it produces are very *similar* to version 0.4.4 distributions, but there are a couple of issues resolved. See http://www.voidspace.org.uk/python/movpy/changelog.html for details. *Most* of the changes relate to the PyDistFrreeze.py in the 'source' package. This is the code that creates the frozen distributions. There have been several simplifications and improvements. Again, see the CHANGELOG for details. Version 0.5.0 Bruno Thoorens has provided me with the code for the GUI for PyDistFreeze.py When I have integrated it with PyDistFreeze.py it will form the 0.5.0 release. This should be in the next couple of weeks time permitting. The GUI is *excellent* :-) Movable Python is a Python runtime that can run scripts without the need for Python to be installed. With the inclusion of wxPython and SPE editor it is a portable (movable) development environment. Also useful for testing scripts with several different python versions. The source version will build frozen environments (using py2exe - so Windoze only currently), this can include whichever extension modules/packages you choose. Regards, Michael Foord http://www.voidspace.org.uk/python/index.shtml From stephane.bronsart at teledisnet.be Fri Jan 28 15:54:41 2005 From: stephane.bronsart at teledisnet.be (StepH) Date: Fri, 28 Jan 2005 21:54:41 +0100 Subject: How to test that an exception is raised ? In-Reply-To: References: <41fa0da9$0$2018$6c56d894@feed0.news.be.easynet.net> <41fa400b$0$2029$6c56d894@feed0.news.be.easynet.net> Message-ID: <41faa68f$0$17406$4d4efb8e@read.news.be.uu.net> Antoon Pardon a ?crit : > Op 2005-01-28, StepH schreef : > >>Thanks for you answer. >>I'm new to Python (coming from C/C++). >> >>Do you say that it's not possible to test (using unittest) if an exception >>is well raised if the tested code catch it ? >>How to solve this paradoxe ? How to automaticaly test such code ? > > > IMO you want something unittest are not designed for. So why the assertRaises function in unittest ? My goal is to test if an exception is well raised when a bad filename is passed to the mps2xml function. > > Unittest are supposed to test for particular results, not for particular > behaviour within. If the expected behaviour is that calling code doesn't > see an exception raised, then the test passed if no exception was seen. > No (unless i don't well understand you), the expected behavior is to launch an exception if a bad filename is passed. If no exception is raised, this is not normal. > You equally can't test which branch of an if statement was taken or > which parameter was given to a helper function in order to get to > the desired result. I'm agree with out on this point, but not for the exception part... > > That you internally raise an exception and catches it, is an > implementation detail, that normally is of no concern to > the tester. > I'll conclude this thred here... In fact, I think I've to go-back to theory (at least about exception)... Thanks at all fo trying to help me. I'm new to Python, and i've not already embrass the "python way" completly. See you later. StepH. From ncoghlan at iinet.net.au Sat Jan 15 11:05:34 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 16 Jan 2005 02:05:34 +1000 Subject: Why 'r' mode anyway? In-Reply-To: <16872.37598.662485.896493@montanaro.dyndns.org> References: <1105682410.406541.317590@c13g2000cwb.googlegroups.com> <41e80785$0$6203$e4fe514c@news.xs4all.nl> <41e827df$0$6219$e4fe514c@news.xs4all.nl> <1f7befae0501141613545a30cd@mail.gmail.com> <16872.37598.662485.896493@montanaro.dyndns.org> Message-ID: <41E93F4E.2080709@iinet.net.au> Skip Montanaro wrote: > Tim> "Plays well with others" was a strong motivator for Python's > Tim> design, and that often means playing by others' rules. -- > > My vote for QOTW... Is it too late to slip it into the Zen of Python? It would certainly fit, and the existing koans don't really cover the concept. Its addition also seems fitting in light of the current PEP 246 discussion which is *all* about playing well with others :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From rff_rff at remove-yahoo.it Mon Jan 10 13:38:14 2005 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Mon, 10 Jan 2005 18:38:14 GMT Subject: a new Perl/Python a day In-Reply-To: References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> Message-ID: Bob Smith ha scritto: > Scott Bryce wrote: > >> Xah Lee wrote: >> >>> frustrated constantly by its inanities and incompetences.) >> >> >> I don't see what this has to do with Perl. > > > You're joking, right? please consider that the message you all are asking are crossposted to comp.lang.perl.misc and comp.lang.python, avoid the crossgroup flames :) From bokr at oz.net Fri Jan 14 22:55:51 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 15 Jan 2005 03:55:51 GMT Subject: finding/replacing a long binary pattern in a .bin file References: <1105598214.921103.287010@f14g2000cwb.googlegroups.com> <41e6293f.725257715@news.oz.net> <10udjc3fmnhro9d@corp.supernews.com> <41e7a190.821594009@news.oz.net> <1105746027.819673.236650@c13g2000cwb.googlegroups.com> Message-ID: <41e88c55.881695170@news.oz.net> On 14 Jan 2005 15:40:27 -0800, "yaipa" wrote: >Bengt, and all, > >Thanks for all the good input. The problems seems to be that .find() >is good for text files on Windows, but is not much use when it is >binary data. The script is for a Assy Language build tool, so I know Did you try it? Why shouldn't find work for binary data?? At the end of this, I showed an example of opening and modding a text file _in binary_. >>> s= ''.join(chr(i) for i in xrange(256)) >>> s '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\ x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`ab cdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f \x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7 \xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf \xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7 \xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef \xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' >>> for i in xrange(256): ... assert i == s.find(chr(i)) ... >>> I.e., all the finds succeded for all 256 possible bytes. Why wouldn't you think that would work fine for data from a binary file? Of course, find is case sensitive and fixed, not a regex, so it's not very flexible. It wouldn't be that hard to expand to a list of old,new pairs as a change spec though. Of course that would slow it down some. >the exact seek address of the binary data that I need to replace, so >maybe I'll just go that way. It just seemed a little more general to >do a search and replace rather than having to type in a seek address. Except you run the risk of not having a unique search result, unless you have a really guaranteed unique pattern. > >Of course I could use a Lib function to convert the binary data to >ascii and back, but seems a little over the top in this case. I think you misunderstand Python strings. There is no need to "convert" the result of open(filename, 'rb').read(chunksize). Re-read the example below ;-) [...] >> >> If you wanted to change a binary file, you'd use it something like ^^^^^^^^^^^ >(although probably let >> the default buffer size be at 4096, not 20, which is pretty silly >other than demoing. >> At least the input chunks are 512 ;-) >> >> >>> from sreplace import sreplace >> >>> fw = open('sreplace.py.txt','wb') opens a binary output file >> >>> for buf in sreplace(iter(lambda >f=open('sreplace.py','rb'):f.read(512), ''),'out','OUT',20): iter(f, sentinel) is the format above. I creates an iterator that keeps calling f() until f()==sentinel, which it doesn't return, and that ends the sequence f in this case is lambda f=open(inputfilename):f.read(inputchunksize) and the sentinel is '' -- which is what is returned at EOF. The old thing to find was 'out', to be changed to 'OUT', and the 20 was a silly small return chunks size for the sreplace(...) iterator. Alll these chunks were simply passed to >> ... fw.write(buf) >> ... >> >>> fw.close() and closing the file explicitly wrapped it up. >> >>> ^Z I just typed that in interactively to demo the file change process with the source itself, so the diff could show the changes. I guess I should have made sreplace.py runnable as a binary file updater, rather than a cute demo using command line text. The files are no worry, but what is the source of your old and new binary patterns that you want use for find and replace? You can't enter them in unescaped format on a command line, so you may want to specify them in separate binary files, or you could specify them as Python strings in a module that could be imported. E.g., ---< old2new.py >------ # example of various ways to specify binary bytes in strings from binascii import unhexlify as hex2chr old = ( 'This is plain text.' + ''.join(map(chr,[33,44,55, 0xaa])) + '<<-- arbitrary list of binary bytes specified in numerically if desired' + chr(33)+chr(44)+chr(55)+ '<<-- though this is plainer for a short sequence' + hex2chr('4142433031320001ff') + r'<<-- should be ABC012\x00\x01\xff' ) new = '\x00'*len(old) # replace with zero bytes ----------------------- BTW: Note: changing binaries can be dangerous! Do so at your own risk!! And this has not been tested worth a darn, so caveat**n. ---< binfupd.py >------ from sreplace import sreplace def main(infnam, outfnam, old, new): infile = open(infnam, 'rb') inseq = iter(lambda: infile.read(4096), '') outfile = open(outfnam, 'wb') try: try: for buf in sreplace(inseq, old, new): outfile.write(buf) finally: infile.close() outfile.close() except Exception, e: print '%s:%s' %(e.__class__.__name__, e) if __name__ == '__main__': import sys try: oldnew = __import__(sys.argv[3]) main(sys.argv[1], sys.argv[2], oldnew.old, oldnew.new) except Exception, e: print '%s:%s' %(e.__class__.__name__, e) raise SystemExit, """ Usage: [python] binfupd.py infname outfname oldnewmodulename where infname is read in binary, and outfname is written in binary, replacing instances of old binary data with new specified as python strings named old and new respectively in a module named oldnewmodulename (without .py extension). """ ----------------------- REMEMBER: NO WARRANTY FOR ANY PURPOSE! USE AT YOUR OWN RISK! And, if you know where to seek to, that seems like the best way ;-) Regards, Bengt Richter From http Sat Jan 29 10:23:19 2005 From: http (Paul Rubin) Date: 29 Jan 2005 07:23:19 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> Message-ID: <7xzmysqmxk.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > What's your point? That I have to download and perhaps install them to use > them? In that case, how are these two scenarios different: > > * I have to download and build the MySQLdb package to talk to MySQL > servers from Python code > > * I have to ensure that the readline library and include files are > installed on my system before the readline module (which is included > in the core distribution) can be built The difference is that once Python is installed on your machine and you can get a ">>>" prompt, you have readline available right away but you have to download something to use MySQLdb. Whoever took care of your Python installation, and it may not have been you, also took care of readline. The past several OS distributions I've installed have included Python and readline out of the box, so I never had to think about readline. The last time I used a Python instance that didn't come with the OS (on Windows XP at work), the IT department had installed Python on my desktop before I started using it, so I still didn't have to worry about readline. But any module that doesn't come in the distro, I have to download myself. > I and many other people happily use external packages other people have > written as well as make stuff available. My guess is that you do as well. No, I don't. I do use them sometimes but I'm unhappy about them. If I can write something using a core module instead of an external module, I prefer to use the core module. So I'll generally use dbm instead of MySQL unless I really need MySQL, which I haven't yet in Python (I've used MySQL with Perl dbi, but Perl, you know, shudder). Also, external module installation scripts often don't work properly, so I end up having to wrestle the code to get it installed. And if a geek like me has such trouble installing external modules, what hope does a normal end-user have? Maybe if you're using Windows, that stuff has been debugged better, but I've had poor results under GNU/Linux. I've had this discussion here before, maybe not with you. What I really want is zero installations of anything. I just want to go to the store and buy a new computer and have a complete OS install with full sources and a full set of applications including Python already installed when I first power it up. My practical approximation is to buy a new computer, immediately reformat the HD to remove the icky Redmond virus, and then install a GNU/Linux distro that includes Python (and readline). If Python really aims for world domination, that means it has to shoot for being preinstalled on almost every new computer the way Windows is now. And all the interesting modules should be there, maybe in a "contrib" directory that gets little or no maintenance priority from the core team. > If everyone adopted your position that it wasn't Python unless it > had been added to the core, we'd all be reinventing lots of wheels > or tackling much less challenging tasks, if we programmed in Python > at all. Here's an incomplete list of stuff not in the core I have > used happily over the past several years to do my jobs using Python: That makes no sense at all. That list is a list of programs written in the Python language. They are Python programs, where Python is an adjective. Python, the noun referring to a piece of software, generally means the stuff in the Python distro. That doesn't stop programs outside the distro from being useful. Mediawiki is a PHP program. That doesn't mean Mediawiki is part of PHP. > * MySQLdb, Sqlite, pycopg, sybase-python - all database modules These should all be in the core if Python wants to be a serious competitor to PHP, which comes with interfaces for those db's and several additional ones besides. That these modules are missing are a significant library deficiency. > * CSV, Object Craft's csv, DSV - csv modules predating csv in the core That's fixed now, csv is in the core. > * SpamBayes I have the impression this is an application and not a module, or anyway is written mainly to support one application. Should be separate. Also, it's written in Python(?) rather than C, which means the installation headaches from not being in the core aren't so bad. > * Quixote Don't know what this is. > * Docutils Should be in the core if it's what I think it is. > * MoinMoin Application, should be separate. Also, GPL'd, I think. Can't be distributed under PSF license. > * Pyrex Sort of problematic, would be interesting to have something like this in the core but maybe Pyrex as it currently stands isn't the answer. I have the impression that PyPy is going to depend on Pyrex in a fundamental way, so it will have to be in the core when we dump CPython. > * Psyco I think this isn't ready for prime time yet. Should go into the core once it is. > * PyInline Not sure what this is. > * PyGTK wxPython might be a better choice. wxpython.org quotes Guido as saying "wxPython is the best and most mature cross-platform GUI toolkit, given a number of constraints. The only reason wxPython isn't the standard Python GUI toolkit is that Tkinter was there first". I don't have direct experience with either wxPython or PyGTK, though. If I can get by with Tkinter, I'd rather do that, since Tkinter is in the core. > * xmlrpclib before it was in the core 1. Did you really need this, instead of some more reasonable rpc format? xdrlib has been in the core forever. 2. Isn't xmlrpclib written in Python? > * MAL's mx.DateTime before the core datetime module was available See, as Python improved, those things went into the core. > * timeout_socket before sockets supported timeouts Could you use sigalarm instead? > Many of those things I could never have written myself, either for > lack of time, lack of skill or both. I'm grateful they were > available when I needed them and feel no qualms about using them > even though they are not distributed with Python proper. Sure, it's fine if you have all those modules and you write a Python program that uses, say, five of them. External modules aren't so bad when the developer and the end user are the same person. What happens if you send your Python program to a nonprogrammer friend who has just a vanilla Python installation? Now he has to download and install those five modules too. You send him the url's where you got the modules a year ago. What are the chances that the 5 url's even all still work, much less the chance of him being able to install and run all 5 of the modules without needing help? What if the versions he downloads (from separate developers) have gotten out of sync with each other and can't interoperate any more? If Python's maintainers are going to recommend those modules to people as a substitute for providing those functions in the core, it would be a big help if the modules were mirrored on python.org instead of merely linked, since a lot of links turn into 404's over time. > Notice another interesting feature of several of those items: csv, > xmlrpclib, mx.DateTime, timeout_socket. They were all modules I used that > eventually wound up in the core in some fashion. They didn't go in the core > first, then demonstrate their usefulness. It was the other way around. I'm not sure about timeout_socket and it sounds like it should have just been a patch to the socket module, not a new module. csv is quite a complex module and took a lot of tweaking and PEP editing before standardization. But the need for it was obvious; the only good reason it wasn't in the core ages ago was that no one had done the work of writing it and shaking it out. xmlrpclib, not sure. How long was it in separate distribution? Also, xmlrpc is a pretty new protocol so it took a while before people wanted it. DES has been around since the 1970's and AES has about the same users as DES, so there's a known level of demand. That should be enough to say yes or no to whether there should be a core module or not. Also, your notion of trying to create a "category king" of AES modules doesn't reflect how these things work. There are at least 10 different AES modules that provide the same AES function. If somebody is using one, they have no reason to switch to another. If it takes 20 visible users for including a module to be worthwhile, and those 10 modules have 5 users each, those populations are going to stay stable until one of them goes in the core and becomes the standard. (And actually: mxCrypto is the most capable of these packages and might be the one with the most users, but it's completely unsuitable for the core because of its size). > Not everything that is useful belongs in the core distribution. I > think you are confusing "batteries included" with "everything, > including the kitchen sink". Well, if you compare the Python stdlib with the toolkits that come with competing languages, say PHP or Java, you can see that Python's lib could be enhanced with considerably more stuff without being excessive. From secun at yahoo.com Fri Jan 28 11:17:23 2005 From: secun at yahoo.com (Chris) Date: Fri, 28 Jan 2005 16:17:23 GMT Subject: Help with web dashboard References: <1106924984.507889.265070@c13g2000cwb.googlegroups.com> Message-ID: In article <1106924984.507889.265070 at c13g2000cwb.googlegroups.com>, fuzzyman at gmail.com says... > Ifd you want to use standard CGI I've written a CGI user > authentication/management module called logintools. > Would this be preferred (or easier) than using an application server (ie. Zope or Webware)? If possible, I think it would be nice if the security aspect of it was already built-in so I would not need to write/test it myself. Thanks for your help. From daniel.dittmar at sap.corp Thu Jan 13 06:57:36 2005 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Thu, 13 Jan 2005 12:57:36 +0100 Subject: lambda In-Reply-To: References: Message-ID: Egor Bolonev wrote: > why functions created with lambda forms cannot contain statements? syntax/technical answer: because lambda is an expression and it is not obvious how the syntax for 'statement inside expression' should be 'Python is perfect' answer: if a function contains more than an expression, then it's complex enough to require a name > how to get unnamed function with statements? You can't. See various threads about Smalltalk/Ruby-like blocks and the recent one about the 'where' keyword for proposals to change this Daniel From godoy at ieee.org Thu Jan 20 06:44:58 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Thu, 20 Jan 2005 09:44:58 -0200 Subject: ElementTree cannot parse UTF-8 Unicode? References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> <1106181323.553028.290370@z14g2000cwz.googlegroups.com> Message-ID: <5861401.FEXqi8ioxF@strongwill.g2ctech> Fredrik Lundh, Quinta 20 Janeiro 2005 05:17, wrote: > what does it give you on your machine? (looks like wxPython cannot handle > Unicode strings, but can that really be true?) It does support Unicode if it was built to do so... -- Godoy. From steve at holdenweb.com Sun Jan 9 10:51:34 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 09 Jan 2005 10:51:34 -0500 Subject: Python Installation In-Reply-To: References: <1105220812.579690.292260@c13g2000cwb.googlegroups.com> <1105232505.142279.85810@c13g2000cwb.googlegroups.com> Message-ID: <41E15306.7090108@holdenweb.com> Peter Hansen wrote: > Simon John wrote: > >> I would say install on one machine, then just copy the C:\Python24 >> directory, but then you'd have to deal with the missing Registry >> entries.... > > > That part is pretty trivial to automate as well. Fredrik > Lundh has a useful utility on his web site that will do much > of what is required. Google for his name and "python registry" > to find out more. > Hmm, effbot.org seems to be down just now. Sure it'll be back soon, though. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From sylvain.pasquet at gmail.com Thu Jan 27 08:47:51 2005 From: sylvain.pasquet at gmail.com (Tsubasa[Hokage]) Date: 27 Jan 2005 05:47:51 -0800 Subject: Freeze with wxpython on python 2.3 or python 2.4 on Win32 with Thread Message-ID: <549f320e.0501270547.2beea5a5@posting.google.com> Hello i have a problem with thread and wxpython on WIN32. With this script : I would like to SetValue to my gauge widget in a thread. I can GetValue without a hitch but if I SetValue it freezing. Try following script and go to AF-Tools Menu and click install Normally in the install thread, I wrote "yo" in the console and I SetValue of the gauge passed to the thread. from wxPython.wx import * from wxPython.wizard import * from os import * #import os #import win32wnet, win32netcon #import wmi #import win32api #import _winreg import time #import win32com,win32com.client import sys import shutil import dircache import struct, socket from optparse import OptionParser #import thread import threading #import Queue __auteur__="FLFRSPA" def map_drive(local, remote, username, password): ###self.map_drive("Z:", "\\\L00438\c$",r"localhost\administrator","")### return win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK,local, remote, None,username, password,0) class InstallThread(threading.Thread): ###La classe recoit login,password,workstation,checkboxdomaine,domaine,self.log,self.g1,package def __init__(self,login,password,workstation,checkboxdomaine,domaine,log,gauge,package): threading.Thread.__init__(self) self.result = None self.i=0 self.login=login self.password=password self.workstation=workstation self.package=package self.checkboxdomaine=checkboxdomaine self.domaine=domaine self.log=log self.gauge=gauge def run(self): self.result=1 print "yo" self.gauge.SetValue(10) self.result=1 return class main_PyXrunAS(wx.Frame): def __init__(self, *args, **kwds): kwds["style"] = wx.DEFAULT_FRAME_STYLE wx.Frame.__init__(self, *args, **kwds) sizer = wxBoxSizer(wxVERTICAL) self.SetSizer(sizer) menuBar = wx.MenuBar() # 1st menu from left menu1 = wx.Menu() #menu1.Append(101, "&Options", "Options de la LoFBOX") menu1.Append(102, "&Quitter", "Quitter") #self.Bind(wx.EVT_MENU, self.quit, id=102) menu1.AppendSeparator() menuBar.Append(menu1, "&Fichier") # 2st menu from left menu2 = wx.Menu() menu2.Append(201, "&Test Connection", "Effectue un test de connection sur la machine distante") #self.Bind(wx.EVT_MENU, self.aide_dialog, id=201) self.Bind(wx.EVT_MENU, self.query_freespace, id=201) menu2.Append(202, "&Reboot Distant", "Effectue le reboot d'une machine") self.Bind(wx.EVT_MENU, self.query_reboot, id=202) #self.Bind(wx.EVT_MENU, self.Apropos, id=202) menu2.Append(202, "&Wake On Lan", "Effectue le d?marrage distant d'une machine") menu2.Append(203, "&Install", "Install le package selectionn?") self.Bind(wx.EVT_MENU, self.install_thread, id=203) menu2.AppendSeparator() menuBar.Append(menu2, "&AF-Tools") self.SetMenuBar(menuBar) ###Logo Titre self.remlogo = wx.StaticBitmap(self, -1, wx.Bitmap("data/remote_logo.jpg", wx.BITMAP_TYPE_ANY),pos=(5,5)) sizer.AddWindow(self.remlogo, 0, wxALIGN_CENTRE|wxALL, 5) sizer.AddWindow(wxStaticLine(self, -1), 0, wxEXPAND|wxALL, 5) ###Creation de la liste des packages self.a=dircache.listdir('Package/') self.a=self.a[:] # Copy the return value so we can change 'a' t1=wx.Choice(self, -1, (60, 60), choices = self.a) self.tc1 = t1 self.Bind(wx.EVT_CHOICE, self.Evtpackage, t1) t1.Bind(wx.EVT_TEXT, self.Evtpackage) l1 = wx.StaticText(self, -1, "Package: ",pos=(5,60)) l1.SetBackgroundColour("white") ###Jauge d'evolution self.g1 = wx.Gauge(self, -1, 50, (220, 210), (190, 25)) self.g1.SetBezelFace(3) self.g1.SetShadowWidth(3) self.g1.SetBackgroundColour("White") ###Label progression label_pro = wx.StaticText(self, -1, "Progression: ",pos=(220,190)) label_pro.SetBackgroundColour("white") ###Multiline log label_log = wx.StaticText(self, -1, "Log: ",pos=(220,60)) label_log.SetBackgroundColour("white") self.log = wx.TextCtrl(self, -1, "", size=(250, 100),pos=(220,80), style = wx.TE_MULTILINE #| wx.TE_RICH | wx.TE_RICH2 ) ###Setmachine self.workstation = wx.TextCtrl(self, -1, "", size=(105, -1),pos=(60,100)) label_workstation = wx.StaticText(self, -1, "Poste: ",pos=(6,100)) label_workstation.SetBackgroundColour("white") #self.workstation.SetInsertionPoint(0) self.workstation.Bind(wx.EVT_TEXT, self.EvtChar) ###Bouton pour tester la connection #self.workstation_connect = wx.Button(self, -1, "Test Connection", (210,55)) #self.workstation_connect.Disable() #self.label_freespace = wx.StaticText(self, -1, "",pos=(270,102)) #self.label_freespace.SetBackgroundColour("white") #self.Bind(wx.EVT_BUTTON, self.query_freespace, self.workstation_connect) #self.Bind(wx.EVT_BUTTON, self.OnButton, b) ###Login/Password/Domain self.t2 = wx.TextCtrl(self, -1, "", size=(105, -1),pos=(60,140)) l2 = wx.StaticText(self, -1, "Login: ",pos=(6,142)) l2.SetBackgroundColour("white") self.t3 = wx.TextCtrl(self, -1, "", size=(105, -1),pos=(60,180),style=wx.TE_PASSWORD) l3 = wx.StaticText(self, -1, "Password: ",pos=(6,182)) l3.SetBackgroundColour("white") self.t5 = wx.TextCtrl(self, -1, "", size=(105, -1),pos=(60,230)) l4 = wx.StaticText(self, -1, "Domaine: ",pos=(6,230)) self.t5.Disable() l4.SetBackgroundColour("white") self.cb1 = wx.CheckBox(self, -1, "Domaine", (60, 210), (90, 20), wx.NO_BORDER) self.cb1.SetBackgroundColour("white") self.Bind(wx.EVT_CHECKBOX, self.EvtCheckBox, self.cb1) self.__set_properties() self.__do_layout() def EvtChar(self, event): pass return def Evtpackage(self, event): pass return #print self.workstation.GetValue() #event.Skip() def EvtListBox(self, event): print 'EvtListBox: %s\n' % event.GetString() def EvtCheckListBox(self, event): index = event.GetSelection() label = self.lb.GetString(index) #status = 'un' if self.lb.IsChecked(index): self.list_option.append(label) else: self.list_option.remove(label) print self.list_option self.lb.SetSelection(index) # so that (un)checking also selects (moves the highlight) return def __set_properties(self): # begin wxGlade: MyFrame1.__set_properties #user=win32api.GetUserName() #self.t4.WriteText('%s' % user) #self.t4.Disable() self.SetTitle("AF-Remote-MSI "+__version__) self.SetBackgroundColour("white") self.SetSize((490, 350)) # end wxGlade def __do_layout(self): # begin wxGlade: MyFrame1.__do_layout sizer_3 = wx.BoxSizer(wx.VERTICAL) self.SetAutoLayout(True) self.SetSizer(sizer_3) self.Layout() # end wxGlade def query_freespace(self,event): machine=self.workstation.GetValue() pi=0 try: c = wmi.WMI (machine) pi=1 except: self.log.WriteText(str(sys.exc_info()[1])+" \n") pi=0 #self.label_freespace.SetLabel("Connection OK: ") if (pi!=0): for disk in c.Win32_LogicalDisk (DriveType=3): self.log.WriteText(self.log.GetValue()+str(disk.Caption)+str(int(disk.FreeSpace)/1000000)+ "Mo Libres\n") return def query_reboot(self,event): pi=0 try: machine=self.workstation.GetValue() c = wmi.WMI (computer=str(machine), privileges=["RemoteShutdown"]) pi=1 except: self.log.WriteText(str(sys.exc_info()[1])+" \n") pi=0 if (pi!=0): os = c.Win32_OperatingSystem (Primary=1)[0] os.Reboot () self.log.WriteText("Reboot [OK]") return def SendWol(self,event): if (str(self.mac.GetValue())!="aa-bb-cc-dd-ee \n"): self.WakeOnLan(self.mac.GetValue()) else: self.log.WriteText("Erreur adresse mac") return def WakeOnLan(self,ethernet_address): pass def EvtCheckBox(self, event): #print 'EvtCheckBox: %d\n' % event.IsChecked() if (event.IsChecked()==1): self.t5.Enable() if (event.IsChecked()==0): self.t5.Disable() def OnButton(self, event): dlg = wx.DirDialog(self, "Choose a directory:", style=wx.DD_DEFAULT_STYLE|wx.DD_NEW_DIR_BUTTON) if dlg.ShowModal() == wx.ID_OK: # This returns a Python list of files that were selected. paths = dlg.GetPath() for path in paths: self.tc1.WriteText('%s' % path) dlg.Destroy() return def Ecrire_batch(self): #contenu="cscript //H:CScript //S \n" contenu="xrunas.vbs /profile /user:administrator /pwd:????? "+str(self.tc1.GetValue()) #contenu=contenu+" -pw="+input+" -language=F -client=100 -sysname=\"FP1 - Production\"" batch="AFpyxras.bat" file = open(batch, "w") file.write(contenu) file.close() return def install_thread(self,event): subThread2 = InstallThread(self.t2.GetValue(),self.t3.GetValue(),self.workstation.GetValue(),self.t5.GetValue(),self.cb1,self.log,self.g1,self.a[self.tc1.GetSelection()]) subThread2.start() subThread2.join() #result = subThread2.result #print result def install_vnc(self,name,time): pass return class GUIThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): class PyXrunAS(wx.App): def OnInit(self): wx.InitAllImageHandlers() frame_2 = main_PyXrunAS(None, -1, "") self.SetTopWindow(frame_2) frame_2.Show() return 1 self.app = PyXrunAS(0) self.app.MainLoop() if __name__ == "__main__": subThread = GUIThread() subThread.start() subThread.join() #subThread.Run() Can someone help me ? From invalidemail at aerojockey.com Sat Jan 8 00:48:22 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 7 Jan 2005 21:48:22 -0800 Subject: how to extract columns like awk $1 $5 In-Reply-To: References: <487rklcxbidr$.gwsa68us9f3a.dlg@40tude.net> Message-ID: <1105163302.044524.85110@f14g2000cwb.googlegroups.com> Roy Smith wrote: > Hmmm. There's something going on here I don't understand. The ref > manual (3.3.5 Emulating container types) says for __getitem__(), "Note: > for loops expect that an IndexError will be raised for illegal indexes > to allow proper detection of the end of the sequence." I expected my > little demo class to therefore break for loops, but they seem to work > fine: > > >>> import awk > >>> l = awk.awkList ("foo bar baz".split()) > >>> l > ['foo', 'bar', 'baz'] > >>> for i in l: > ... print i > ... > foo > bar > baz > >>> l[5] > '' > > Given that I've caught the IndexError, I'm not sure how that's working. The title of that particular section is "Emulating container types", which is not what you're doing, so it doesn't apply here. For built-in types, iterators are at work. The list iterator probably doesn't even call getitem, but accesses the items directly from the C structure. -- CARL BANKS From petite.abeille at gmail.com Thu Jan 27 17:47:27 2005 From: petite.abeille at gmail.com (PA) Date: Thu, 27 Jan 2005 23:47:27 +0100 Subject: ANN: Tao Scripting Language 0.8.5 beta released! In-Reply-To: References: <397cc8578b5e9adf0e31f18ffa556593@gmail.com> Message-ID: <20a7bea6e3332d34a1b170ffb808502f@gmail.com> On Jan 27, 2005, at 23:42, Limin Fu wrote: > at that time I didn't heard about Lua. I knew it about > 2 or 3 months after I began to implement Tao. So, compared to Lua for example, what does Tao brings to the table that you found worthwhile? Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 11:41:52 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?ISO-8859-2?Q?Martin_MOKREJ=A9?=) Date: Mon, 10 Jan 2005 17:41:52 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E339814E@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E339814E@exchange.hqamor.amorhq.net> Message-ID: <41E2B050.4050806@ribosome.natur.cuni.cz> Robert Brewer wrote: > Martin MOKREJ? wrote: > >> I have sets.Set() objects having up to 20E20 items, >>each is composed of up to 20 characters. Keeping >>them in memory on !GB machine put's me quickly into swap. >>I don't want to use dictionary approach, as I don't see a sense >>to store None as a value. The items in a set are unique. >> >> How can I write them efficiently to disk? > > > got shelve*? I know about shelve, but doesn't it work like a dictionary? Why should I use shelve for this? Then it's faster to use bsddb directly and use string as a key and None as a value, I'd guess. Even for that, note that even for data contained in _set11, the index should be(could be) optimized for keysize 11. There are no other record-sizes. Similarly, _set15 has all keys of size 15. In the bsddb or anydbm and other modules docs, I don't see how to optimize that. Without this optimization, I think it would be even slower. And shelve gives me exactly such, unoptimized, general index on dictionary. Maybe I'm wrong, I'm just a beginner here. Thanks M. From phr at localhost.localdomain Thu Jan 27 10:52:39 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Thu, 27 Jan 2005 15:52:39 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: Skip Montanaro writes: > >> As long as we are discussing cryptography, what's wrong with > >> m2crypto? Or, what about Andrew Kuchling's crypto toolkit? > > Lucas> Umm, is it just me or did we just discuss the legal issues of > Lucas> that?? > > You may have. Whether or not there are legal issues with them is of little > relevance to the point I was making. Anything Paul writes would probably > have the same legal entanglements. Andrew's toolkit does incorporate some patented algorithms, but those aren't critical and could be removed from a stdlib version. > I was simply pointing out that maybe, just maybe, there are already > suitable candidates from a technical standpoint and that he doesn't > need to write anything. There really don't appear to be any that are both technically suitable, and that the authors are willing to contribute to PSF. I'd be delighted to be wrong. Of course that still leaves the legal issue. From fredrik at pythonware.com Thu Jan 20 07:12:58 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 20 Jan 2005 13:12:58 +0100 Subject: ElementTree cannot parse UTF-8 Unicode? References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com><1106181323.553028.290370@z14g2000cwz.googlegroups.com> <5861401.FEXqi8ioxF@strongwill.g2ctech> Message-ID: Jorge Luiz Godoy Filho wrote: >> what does it give you on your machine? (looks like wxPython cannot handle >> Unicode strings, but can that really be true?) > > It does support Unicode if it was built to do so... Python has supported Unicode in release 1.6, 2.0, 2.1, 2.2, 2.3 and 2.4, so you might think that Unicode should be enabled by default in a UI toolkit for Python... From http Mon Jan 31 18:55:01 2005 From: http (Paul Rubin) Date: 31 Jan 2005 15:55:01 -0800 Subject: serializing data structures References: Message-ID: <7xu0ox9msq.fsf@ruckus.brouhaha.com> "Philippe C. Martin" writes: > I am trying to figure out the traps/issues about sending data structures > through a TCP/IP socket under the following circumstances: > > 1) there could be a different O/S on both side of the socket > 2) there could be a difference CPU architecure on both side of the > socket > 3) there could be a different major release of python (ex 2.3 and 2.4) > on both side of the socket. > > I once wrote something in C to do that, but since python usually has a > solution for me .... What do you mean by data structures? If they're limited to basic objects like strings and ints, try xdrlib. If you want longs, class instances, etc., there's really no good way in the Python stdlib that doesn't create security vulnerabilities if the source of data isn't trusted. See SF bugs 471893 and 467384 for some discussion. From jerf at jerf.org Sat Jan 15 10:24:46 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Sat, 15 Jan 2005 10:24:46 -0500 Subject: [perl-python] 20050115, for statement References: <1105783084.748174.307680@f14g2000cwb.googlegroups.com> Message-ID: On Sat, 15 Jan 2005 10:54:28 +0000, Michael Hoffman wrote: > Xah Lee wrote: > >> ? a = range(1,51) >> ? for x in a: >> ? if x % 2 == 0: >> ? print x, 'even' > > Now he's mixing tabs and spaces. Hideous. > > Are you doing things wrong on purpose? I think the most exciting thing is the breath-taking pace he has chosen. I mean, wow, we've been going for what, five days now and we're up to for loops? Woo! So far, even for his stated purpose, he's at negative value vs. just reading even the simplest tutorials for the languages. The value in Perl<->Python documentation is to help with idiom translation, syntax is truly trivial. At the rate he's going, he'll get out of Negative Value and start entering Colossal Waste Of Time in about a month. So good on you, Xah Lee. The world needs more people producing things of negative value and posting them everywhere they can. Wouldn't want The Masses (TM) to find the good resources, learn, and subsequently compete with people who know things already. (Hell, five days into Python and some people are already producing working Backgammon games (I think that was the post last week), and Xah Lee here is still on for loops! Woo! Go Xah!) From steven.bethard at gmail.com Mon Jan 17 00:39:14 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 16 Jan 2005 22:39:14 -0700 Subject: [perl-python] 20050117, filter, map In-Reply-To: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > ? Note: this post is from the Perl-Python > ? a-day mailing list at > ? http://groups.yahoo.com/group/perl-python/ Is there any chance you could post these all as part of the same thread? That would be really nice for those of us who aren't interested -- then we could just ignore the thread... Thanks in advance, Steve From franz.steinhaeusler at utanet.at Fri Jan 21 03:45:02 2005 From: franz.steinhaeusler at utanet.at (Franz Steinhaeusler) Date: Fri, 21 Jan 2005 09:45:02 +0100 Subject: What's the best python web-developer's editor References: Message-ID: On Thu, 20 Jan 2005 18:47:53 +0000, andy wrote: >Anybody like to comment on which editor they use for python web app >development - for both discrete and mixed python and html code, and why? > I use DrPython, because: It is open source, written in python and wxPython and use wx.stc. It is extensible via plugins and script, you have a python prompt, free shortcut assignments, ... It is developed heavily. I'm a member of the project :) http://sourceforge.net/projects/drpython/ >I'm comfortable with IDLE (used it for years) but of course it lacks ftp >or webDAV abilities, obviously because it's not intended for that type >of use. What do you mean with ftp abilities exactly? Saving and opening files directly over ftp? >[...] regards, -- Franz Steinhaeusler From andre.roberge at gmail.com Sat Jan 8 11:01:43 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 8 Jan 2005 08:01:43 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net><41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> Message-ID: <1105200103.921226.186930@c13g2000cwb.googlegroups.com> At the risk of generating controversy, here's another type of example: def gcd(a, b): where: a: int, b: int return c where: c: int while a: a, b = b%a, a return b More can be found at http://aroberge.blogspot.com Andre From itsme at yahoo.com Tue Jan 11 13:23:24 2005 From: itsme at yahoo.com (It's me) Date: Tue, 11 Jan 2005 18:23:24 GMT Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: Operator overloading (and function overloading) helps but not enough. You have to be aware of the complex type *everywhere* you go and that's very annoying and error prone. I've been the works with C++, and later with Modelica. I am very happy that Python included *native* complex number support. I really like Python's notion of having just one data type: the duck. "Anno Siegel" wrote in message news:cs145l$8d6 > > Like this? > > use Math::Complex; > > my $z = sqrt( -1); > print 1 + $z, "\n"; # prints "1+i" > > Operator overloading makes it possible to work with complex numbers as if > they were a native data type. > > Anno > From michele.simionato at gmail.com Tue Jan 11 09:24:48 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 11 Jan 2005 06:24:48 -0800 Subject: Python & unicode In-Reply-To: <41e3cb2a$1_2@newspeer2.tds.net> References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> <1105434532.132061.24030@f14g2000cwb.googlegroups.com> <1105434900.511862.54740@f14g2000cwb.googlegroups.com> <41e3cb2a$1_2@newspeer2.tds.net> Message-ID: <1105453488.204651.47870@f14g2000cwb.googlegroups.com> Kent: > I don't think so. You have hacked an attribute with latin-1 characters in it, but you > haven't actually created an identifier. No, I really created an identifier. For instance I can create a global name in this way: >>> globals()["?"]=1 >>> globals()["?"] 1 > According to the language reference, identifiers can only contain letters a-z and A-Z, > digits 0-9 and underscore. >http://docs.python.org/ref/identifiers.html The parser has this restriction, so it gets confused if it finds "?". But the underlying implementation just works for generic identifiers. Michele Simionato From kent3737 at yahoo.com Sat Jan 8 11:43:43 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Sat, 08 Jan 2005 11:43:43 -0500 Subject: Tkinter: passing parameters to menu commands In-Reply-To: References: Message-ID: <41e00b8d$1_3@newspeer2.tds.net> Philippe C. Martin wrote: >>>menu.add_cascade(label="File", menu=filemenu) >>>filemenu.add_command(label="New", command=lambda: callback('New')) >>>filemenu.add_command(label="Open...", command=lambda: > >>>Of course you could do this with named forwarding functions if you > > prefer > > > I'm not sure what 'named forwarding functions' Bad choice of terminology, I just mean you can explicitly define def handleNew: callback('New') etc. are but I'm actually in a > class and when applying your suggestion in the following manner, > everything works (THANKS!) > > **************************** > def __Dec(self,p_string): > for i in p_string: > self.__Insert(i) > . > . > . > #menu creation > l_dec.add_command(label = 'ATR', command=lambda: self.__Dec('ATR')) > l_dec.add_command(label = 'IN', command=lambda:self.__Dec('IN')) > . > . > . > **************************** > > Yet I have a question: > > If I replace the menu creation code as below, and since __Insert appends > the string p_string into a text widget that is created _after_ the menu > creation; the method __Dec seems to be called at the menu creation and > I get an error in __Insert because the test widget is equal to None. > > My reflexes of C programmer tell me that command=self.__Dec.... just > passes a method pointer (sorry I said it) to add_command - yet it does > not seem to be so. > > What is actually going on ? > > > #menu creation > l_dec.add_command(label = 'ATR', command=self.__Dec('ATR')) > l_dec.add_command(label = 'IN', command=self.__Dec('IN')) self.__Dec is a reference to the function. It is similar to a method pointer so you don't need to apologize ;) The name of a function without the () is a reference. When you append () it becomes a call to the referenced function. The command parameter for the menu must be a reference to a function. The function is called with no arguments when the menu is invoked. So, you need a function of no arguments to handle the command. For example, def handleMenu(): print 'Handled' filemenu.add_command(label="New", command=handleMenu) Note there is no () after handleMenu. 'command' is bound to the function object; the function is not called until later. OK, now suppose you want to pass a parameter to handleMenu? def handleMenu(menuName): print 'Handled', menuName Now what do you put in the command parameter? This won't work because you are *calling* handleMenu and assigning the result of the call (in this case the value None) to 'command': filemenu.add_command(label="New", command=handleMenu('New')) # WRONG You need a new function of zero arguments to bind to 'command'. Here is one way to do it: def handleNew(): handleMenu('New') filemenu.add_command(label="New", command=handleNew) # OK Note, again, no () after handleNew. 'command' is bound to the function object again. OK, what about lambda? lambda is a way to create a simple anonymous function. One simple use of lambda is to make a new function that binds a parameter to another function. lambda: handleMenu('New') defines a function that does the same thing as handleNew. The value of the lambda expression is the function object. So filemenu.add_command(label="New", command=lambda: handleMenu('New')) # OK is another way to get the result you want. Kent From peter at engcorp.com Mon Jan 17 19:36:40 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 17 Jan 2005 19:36:40 -0500 Subject: dynamic data types In-Reply-To: <1105969253.296411.301760@f14g2000cwb.googlegroups.com> References: <1105969253.296411.301760@f14g2000cwb.googlegroups.com> Message-ID: Charlie wrote: > The description of Python always mentions "very high level dynamic data > types". Now, I can't seem to find any examples of these (nothing > described with this term anyway). Is this simply refering to built-in > dynamic data structures such as lists and dictionaries, with a great > deal of operators defined on? Or is there something else meant by > "dynamic data types" in Python? I'd say this is "list", "dict", "set", all the similar ones, plus anything custom defined by the programmer... plus probably just about any other data type in Python, since they're all "high level", the "very" part is meaningless, and they're pretty much all more "dynamic" than most similar things in, say, a language that's, uh, "less dynamic". ;-) Really, think of it as marketing propaganda, and don't worry exactly what the original author of the words intended it to apply to. -Peter From michele.simionato at gmail.com Sat Jan 8 03:12:29 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 8 Jan 2005 00:12:29 -0800 Subject: "A Fundamental Turn Toward Concurrency in Software" In-Reply-To: References: Message-ID: <1105171949.823433.72860@f14g2000cwb.googlegroups.com> > So I've always had it in > the back of my mind that languages that can easily support massive > (especially automatic) parallelization will have their day in the sun, > at least someday. and the language of the future will be called ... FORTRAN! :-) (joking, but it is the only language I know supporting massive parallelization ...) Michele Simionato From Scott.Daniels at Acm.Org Sat Jan 22 12:50:08 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 22 Jan 2005 09:50:08 -0800 Subject: finding name of instances created In-Reply-To: References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> Message-ID: <41f28f16@nntp0.pdx.net> Andr? Roberge wrote: > Craig Ringer wrote: > >> On Fri, 2005-01-21 at 16:13 -0800, Andr? wrote: >> >>> Short version of what I am looking for: >>> >>> Given a class "public_class" which is instantiated a few times e.g. >>> >>> a = public_class() >>> b = public_class() >>> c = public_class() >>> >>> I would like to find out the name of the instances so that I could >>> create a list of them e.g. >>> ['a', 'b', 'c'] > > ... > Behind the scene, I have something like: > robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') } > and have mapped move() to correspond to robot_dict['robot'].move() > (which does lots of stuff behind the scene.) > ...[good explanation]... > Does this clarify what I am trying to do and why? Yup. Would something like this help? parts = globals().copy() parts.update(locals()) names = [name for name, value in parts.iteritems() if isinstance(value, Robot)] # actual class name here Note, however, that a = b = CreateRobot() will give two different names to the same robot. And even: Karl = CreateRobot() Freidrich = CreateRobot() for robot in (Karl, Freidrich): robot.move() Will have two names for "Freidrich" -- Freidrich and robot --Scott David Daniels Scott.Daniels at Acm.Org From steven.bethard at gmail.com Tue Jan 25 13:58:30 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Jan 2005 11:58:30 -0700 Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) In-Reply-To: <41f60485.1764371081@news.oz.net> References: <41f325b5.1576259210@news.oz.net> <6I2dnYLoXdcTmGncRVn-vw@comcast.com> <41f490e8.1669238027@news.oz.net> <41f5568c.1719834331@news.oz.net> <41f60485.1764371081@news.oz.net> Message-ID: <6PKdnVVD-4dLC2vcRVn-gQ@comcast.com> Bengt Richter wrote: > On Mon, 24 Jan 2005 20:35:09 GMT, bokr at oz.net (Bengt Richter) wrote: > >>>>>from presets import presets, curry >>>>>@presets(verbose=True, a=1, b=2, deftime=__import__('time').ctime()) >> >>... def foo(): >>... print (a, b) >>... print deftime >>... >> >>presets: -- "name(?)" means name may be unused >> a = 1 >> b = 2 >> deftime = 'Mon Jan 24 12:16:07 2005' >> >> >>>>>foo() >> >>(1, 2) >>Mon Jan 24 12:16:07 2005 > > Not much reaction Sorry, it's definitely cool -- I was just waiting for you to post the Cookbook link so I could see how you did it. ;) Steve From belovedbob at XXgreennet.net Thu Jan 27 23:30:40 2005 From: belovedbob at XXgreennet.net (Robert Kaplan) Date: Thu, 27 Jan 2005 23:30:40 -0500 Subject: win32com/makepy question In-Reply-To: References: Message-ID: <41f9f6d5$1@news.greennet.net> Hi, I've been looking at the client side com stuff in __init__.py in the client subdirectory under win32com, and some of the routines do exactly that. Certainly DispatchWithEvents tries to generate that, and I thought Dispatch does before returning a late binding object. Hope this helps, Bob Tom Willis wrote: >Just a general question. > >It seems in COM late binding is something that should be avoided if possible. > >Because python seems to be really good at doing thing dynamically I'm >wondering why no one has figured out how to make the functionality in >makepy fire automagically when you need it. > >For example, it would be nice if you are creating an object >repeatedly(ADODB.Recordset) that some logic would trigger whatever >makepy does to generate and cache the modules generated from the >typelib that's accessed. > > >It would be cool, that's all I'm saying. I'm sure the standard >response is "Why don't you write it" and maybe I will, I'm just >wondering if anyone has thought of it before and is working on it or >whatever. > > > > From elephantum at dezcom.mephi.ru Tue Jan 11 05:05:49 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Tue, 11 Jan 2005 13:05:49 +0300 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> Message-ID: <34hmnuF4cvj0uU1@individual.net> Nick Coghlan wrote: >> Semantics >> --------- >> The code:: >> >> with: >> >> >> translates to:: >> >> def unique_name(): >> >> >> unique_name() >> > > Bleh. Not only was my proposed grammar change wrong, my suggested > semantics are wrong, too. > > Raise your hand if you can see the problem with applying the above > semantics to the property descriptor example. > > So I think the semantics will need to be more along the lines of > "pollute the namespace but mangle the names so they're unique, and the > programmer can *act* like the names are statement local". > > This will be much nicer in terms of run-time performance, but getting > the locals() builtin to behave sensibly may be a challenge. afair you told yourself that var = where: translates to: def unique_name(): return var = unique_name() in this case class gets unique_name() function? is it that bad? anyway I'd prefer to change semantics deeper. adding new statement-only scope and adding our suite-definitions there. From nick at craig-wood.com Sun Jan 30 06:30:03 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 30 Jan 2005 11:30:03 GMT Subject: What's so funny? WAS Re: rotor replacement References: <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> <7xacqsbfk2.fsf@ruckus.brouhaha.com> <41fbcb11$0$12030$9b622d9e@news.freenet.de> <7xsm4j1wbe.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Martin v. L?wis" writes: > > Apparently, people disagree on what precisely the API should be. E.g. > > cryptkit has > > > > obj = aes(key) > > obj.encrypt(data) > > I don't disagree about the API. The cryptkit way is better than ECB > example I gave, but the ECB example shows it's possible to do it in > one call. There is a PEP about this... API for Block Encryption Algorithms v1.0 http://www.python.org/peps/pep-0272.html -- Nick Craig-Wood -- http://www.craig-wood.com/nick From claird at lairds.us Sat Jan 15 10:08:05 2005 From: claird at lairds.us (Cameron Laird) Date: Sat, 15 Jan 2005 15:08:05 GMT Subject: java 5 could like python? References: Message-ID: <7umnb2-rd.ln1@lairds.us> In article , vegetax wrote: . . . >For example if i remember a function i want ie:get attribute, i dont >remember if the module implementer coded it as >getAttribute,GetAttribute,get_attribute, then i have to go and check the >doc, every time,which is a waste of time. . . . Are you comfortable using the base interpreter's built-in interactive facilities, such as help()? I strongly urge you to exercise these for at least a few minutes. From steve at holdenweb.com Mon Jan 31 10:23:51 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 31 Jan 2005 10:23:51 -0500 Subject: import directory error In-Reply-To: <41fe49b5$0$2168$8fcfb975@news.wanadoo.fr> References: <41fe49b5$0$2168$8fcfb975@news.wanadoo.fr> Message-ID: Olivier Noblanc ATOUSOFT wrote: > Hello, > > > When i want to import a .py fire from another subdirectory i make > > import inc/setupxml > > > but that make me an error message. > > A man tell me to put a dot but that doesn't work. > > Can you help me ? > > Thanks. > > > If you want to import a single .py (a Python module) then the ONLY way to achieve that is to make sure it appears in a directory that is a member of the sys.path list. (This is a slight simplification, but it will do as long as you are only importing from the file store). There are various ways to affect the contents of sys.path, the best known of which include 1. Setting the PYTHONPATH environment variable 2. Creating *.pth files 3. Altering sys.path inside site-customize.py in your standard library Python does allow you to implement PACKAGES, which are directories containing a) a file called __init__.py and (optionally) b) other modules (.py files) and packages (directories containing __init__.py files). The Python interpreter looks for packages in all the same places it looks for modules, but it imports packages by running the __init__.py file (as usual, this happens on the *first* time the package is imported). So, for example, under Cygwin or Linux/Unix, I can define a package (with no Python in it, but still obeying the rules) as follows: sholden at dellboy ~ $ mkdir mp1 sholden at dellboy ~ $ touch mp1/__init__.py sholden at dellboy ~ $ touch mp1/rhubarb.py sholden at dellboy ~ $ mkdir mp1/p2 sholden at dellboy ~ $ touch mp1/p2/__init__.py sholden at dellboy ~ $ python Python 2.4 (#1, Dec 4 2004, 20:10:33) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> "" in sys.path True >>> import mp1 >>> import mp1.rhubarb >>> import mp1.p2 >>> sholden at dellboy ~ $ find mp1 mp1 mp1/p2 mp1/p2/__init__.py mp1/p2/__init__.pyc mp1/rhubarb.py mp1/rhubarb.pyc mp1/__init__.py mp1/__init__.pyc In this case mp1.rhubarb is a module from the mp1 package, mp1.p2 is a sub-package of mp1. You can see what's been compiled by the interpreter on import and when by looking at the .pyc files. Does this help any? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From skip at pobox.com Tue Jan 4 10:32:54 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 Jan 2005 09:32:54 -0600 Subject: Unicode universe (was Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)) In-Reply-To: References: <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> Message-ID: <16858.46886.472080.270031@montanaro.dyndns.org> aahz> Here's the stark simple recipe: when you use Unicode, you *MUST* aahz> switch to a Unicode-centric view of the universe. Therefore you aahz> encode *FROM* Unicode and you decode *TO* Unicode. Period. It's aahz> similar to the way floating point contaminates ints. That's what I do in my code. Why do Unicode objects have a decode method then? Skip From matternc at comcast.net Sun Jan 23 22:48:53 2005 From: matternc at comcast.net (Chris Mattern) Date: Sun, 23 Jan 2005 22:48:53 -0500 Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106531824.833549.28720@c13g2000cwb.googlegroups.com> Message-ID: alex23 wrote: > Having read your comments on women, I hadn't looked at that part of his site until now. I can only say: gah. Haven't seen something like that since Dave Sim's infamous "Tangent" essay. -- Christopher Mattern "Which one you figure tracked us?" "The ugly one, sir." "...Could you be more specific?" From steve at holdenweb.com Tue Jan 4 08:38:53 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 04 Jan 2005 08:38:53 -0500 Subject: input record sepArator (equivalent of "$|" of perl) In-Reply-To: References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> <1103657476.495700.191020@f14g2000cwb.googlegroups.com> <1103671235.093738.198680@z14g2000cwz.googlegroups.com> <86wtuup21t.fsf@guru.mired.org> Message-ID: Dennis Lee Bieber wrote: > On Mon, 03 Jan 2005 19:14:54 -0500, Steve Holden > declaimed the following in comp.lang.python: > > >>Plus the builders quite routinely ask suppliers for things like "a meter >>of two (inches) by four (inches)". They don;t care that they're getting >>the closest metric equivalent, to them a 2 x 4 is still a 2 x 4. >> > > And what do they get? A normal finished 2x4 runs about 1.5x3.5 > inches... > > A 1x4 is 0.75x3.5 > Who knows, but htey don;t complain about it. In the UK also the sizes refer to the rough cut, before finish planing. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From steve at holdenweb.com Wed Jan 12 17:46:13 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 12 Jan 2005 17:46:13 -0500 Subject: shutil.move has a mind of its own In-Reply-To: References: Message-ID: <41E5A8B5.7070908@holdenweb.com> Daniel Bickett wrote: > Hello, > > I'm writing an application in my pastime that moves files around to > achieve various ends -- the specifics aren't particularly important. > The shutil module was chosen as the means simply because that is what > google and chm searches returned most often. > > My problem has to do with shutil.move actually putting the files where > I ask it to. Citing code wouldn't serve any purpose, because I am > using the function in the most straight forward manner, ex: > > shutil.move( "C:\omg.txt" , "C:\folder\subdir" ) > > In my script, rather than a file being moved to the desired location, > it is, rather, moved to the current working directory (in this case, > my desktop -- without any exceptions, mind you). As it happens, the > desired locations are system folders (running windows xp, the folders > are as follows: C:\WINDOWS, C:\WINDOWS\SYSTEM, C:\WINDOWS\SYSTEM32). > To see if this factor was causing the problem, I tried it using the > interpreter, and found it to be flawless. > > My question boils down to this: What factors could possibly cause > shutil.move to fail to move a file to the desired location, choosing > instead to place it in the cwd (without raising any exceptions)? > > Thank you for your time, > > Daniel Bickett > > P.S. I know I said I didn't need to post code, but I will anyway. You > never know :) > > http://rafb.net/paste/results/FcwlEw86.html AS several people have already suggested, you must have an error in the calling code, which wasn't included in the pasted snippet. Also, "data" appears to be a global variable, which leaves us lacking some useful information. Does the debugMess() call show the full destination path for the file? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From xah at xahlee.org Thu Jan 20 02:27:48 2005 From: xah at xahlee.org (Xah Lee) Date: 19 Jan 2005 23:27:48 -0800 Subject: iteritems() and enumerate() Message-ID: <1106206068.867004.195010@f14g2000cwb.googlegroups.com> Python has iteritems() and enumerate() to be used in for loops. can anyone tell me what these are by themselves, if anything? are they just for idiom? thanks. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From mahs at telcopartners.com Tue Jan 4 17:11:51 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 04 Jan 2005 14:11:51 -0800 Subject: args (was Re: Lambda as declarative idiom (was RE: what is lambda used for in real code?)) In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> Message-ID: Roman Suzi wrote: > Maybe this is too outlandish, but I see lambdas as a "quote" mechanism, > which presents a possibility to postpone (precisely control, delegate) > evaluation. That is, an ovehead for lambda must be much lower but at the > same time visible to the programmer: > > d = a + (lambda x, y: x+ y)(3, 4) [...] I believe that this "possibility to postpone" divides into two related but separate concepts: controlling the moment of evaluation, and assembling the arguments required at that moment. They are both species of 'eval', but managing arguments is more specialized, because it includes possibly renaming parameters, assigning default values, processing positional and keyword arguments, and, perhaps in the future dealing with argument types. Meanwhile, GvR wrote (about defining Interfaces in the context of Optional Static Type Checking) > Method declarations can be inspected to find out their signature. I propose a > __signature__ attribute (also for methods defined in classes!) which might be an > object whose attributes make the signature easily inspectable. This might take > the form of a list of argument declaration objects giving the name, type and default > (if any) for each argument, and a separate argument for the return type. For > signatures that include *args and/or **kwds, the type of the additional arguments > should also be given (so you can write for example a varargs method whose arguments > are all strings). GvR's method.__signature__ object might be related to the args object I proposed as part of the syntax for anonymous functions without 'lambda'. i.e., args(a,*b,**kw) --> an object that specifies but does not evaluate its parameters until it is supplied to a callable, possibly with calling parameters This object would contain the default values, and could contain type annotations, explicit, or inferred, as well as more complex assertions used in several contexts. * Current function syntax: def func(a,*b,**c) : pass creates func with func.__signature__ = args(a,*b,**c) and when func is called, the args are evaluated using a mechanism in args.__call__ so, roughly, eval(func.__signature__) --> func.locals * Anonymous functions Syntax alternatives at http://www.python.org/moin/AlternateLambdaSyntax e.g., (f(a) + o(b) - o(c) for args(a, b, c)) args would evaluated with the calling parameters and made available in the local scope defined by () * A stricter alternative to keyword arguments: argspec = args(arg1, arg2, arg3) def func(**argspec): pass is equivalent to def func(arg1, arg2, arg3): pass args["arg1"] (i.e., only args defined in argspec are accepted) * Useful infrastructure for user-supplied type-based dispatch/lightweight multimethods: argspec = args([(a:int, b:int),(a:str,b:str)]) then a framework can provide a custom args.__call__ method that does conformance-checking, adaptation or whatever Michael From alan.gauld at btinternet.com Mon Jan 24 01:34:54 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Jan 2005 06:34:54 +0000 (UTC) Subject: Automatic Windows printer creation? References: Message-ID: On Wed, 19 Jan 2005 14:35:22 -0500, "GMane Python" wrote: > Anyone know if there's a module which will allow me to 'create' windows > printer definitions? Not from a Windows domain network, but just to add a > printer that sends to a jet-direct-attached printer. The easiest way by far is to use the Windows Script Host objects from winall. WSH makes creating windows resources like printers etc fairly easy. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From matt.fryer at gmail.com Sat Jan 8 02:19:16 2005 From: matt.fryer at gmail.com (Matt) Date: 7 Jan 2005 23:19:16 -0800 Subject: Raw Sockets vs. What? In-Reply-To: <1102892218.056702.71520@f14g2000cwb.googlegroups.com> References: <1102761325.189000.217480@f14g2000cwb.googlegroups.com> <1102892218.056702.71520@f14g2000cwb.googlegroups.com> Message-ID: <1105168755.978567.275620@f14g2000cwb.googlegroups.com> Just thought I'd follow up to say that I'm using XML-RPC after all. Not that I was intimidated when I finally learned that Fredrik had written the thing. No, it was more the issue that we want to write a php debugger next and XML-RPC plays well with php, too. Thanks again, --Matt From eric_brunel at despammed.com Mon Jan 3 12:12:00 2005 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 03 Jan 2005 18:12:00 +0100 Subject: Tkinter zoom box = maximize/unmaximize box/button In-Reply-To: References: Message-ID: <41d97b0d$0$12153$8fcfb975@news.wanadoo.fr> Philippe C. Martin wrote: > By zoom box I meant one of the top right button/box one uses to > maximize/unmaximize the current window. This is a known problem in tcl/tk. See http://minilien.com/?7O2BAOm9t0 There is apparently a patch available. Latest tcl/tk versions apparently include the correction. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From http Sat Jan 22 17:51:36 2005 From: http (Paul Rubin) Date: 22 Jan 2005 14:51:36 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> <7xacr4ewjk.fsf@ruckus.brouhaha.com> <41ef4a7a.1323588509@news.oz.net> <7xwtu8vb17.fsf@ruckus.brouhaha.com> <41EF72DE.5030305@jessikat.fsnet.co.uk> <7xwtu8pgr4.fsf@ruckus.brouhaha.com> Message-ID: <7x7jm5m613.fsf@ruckus.brouhaha.com> jjl at pobox.com (John J. Lee) writes: > > Building larger ones seems to > > have complexity exponential in the number of bits, which is not too > > Why? The way I understand it, that 7-qubit computer was based on embedding the qubits on atoms in a large molecule, then running the computation procedure on a bulk solution containing zillions of the molecules, then shooting RF pulses through the solution and using an NMR spectrometer to find a peak at the most likely quantum state (i.e. the state which had the most of the molecules in that state). To do it with 8 qubits instead of 7, you'd have to use twice as much solution, so that particular technique doesn't scale. What we want is a way to calculations on single molecules, not bulk solutions. But no one so far has managed to do even 7 qubits that way. > > It's not even known in theory whether quantum computing is > > possible on a significant scale. > > Discuss. The problem is maintaining enough coherence through the whole calculation that the results aren't turned into garbage. In any physically realizeable experiment, a certain amount of decoherence will creep in at every step. So you need to add additional qubits for error correction, but then those qubits complicate the calculation and add more decoherence, so you need even more error correcting qubits. So the error correction removes some of your previous decoherence trouble but adds some of its own. As I understand it, whether there's a quantum error correcting scheme that removes decoherence faster than it adds it as the calculation gets larger, is an open problem in quantum computing theory. I'm not any kind of expert in this stuff but have had some conversations with people who are into it, and the above is what they told me, as of a few years ago. I probably have it all somewhat garbled. From BOOGIEMANPN at YAHOO.COM Sat Jan 1 20:52:03 2005 From: BOOGIEMANPN at YAHOO.COM (BOOGIEMAN) Date: Sun, 2 Jan 2005 02:52:03 +0100 Subject: What can I do with Python ?? References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> Message-ID: <1bkzoh3dskuit$.ppe264krg156$.dlg@40tude.net> On Sat, 01 Jan 2005 16:03:08 -0500, Mark Nenadov wrote: > What can you do with Python? Just about anything your heart desires. Thanks everybody, I downloaded latest windows version and Python-Docs-2.4 archive. Is that enough for absolute beginner. Is there any e-book, step by step guide ... etc for download, or anything else important what I have to know before I start learning Python ? From snacktime at gmail.com Wed Jan 26 15:48:21 2005 From: snacktime at gmail.com (snacktime) Date: Wed, 26 Jan 2005 12:48:21 -0800 Subject: XOR on string Message-ID: <1f060c4c05012612487e5ce3a7@mail.gmail.com> I need to calculate the lrc of a string using an exclusive or on each byte in the string. How would I do this in python? Chris From francis.girard at free.fr Thu Jan 27 15:58:24 2005 From: francis.girard at free.fr (Francis Girard) Date: Thu, 27 Jan 2005 21:58:24 +0100 Subject: Question about 'None' In-Reply-To: <41F9E081.6050008@freemail.gr> References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> <41F9E081.6050008@freemail.gr> Message-ID: <200501272158.24182.francis.girard@free.fr> Le vendredi 28 Janvier 2005 07:49, jfj a ?crit?: > Francis Girard wrote: > > Wow ! What is it that are compared ? I think it's the references (i.e. > > the adresses) that are compared. The "None" reference may map to the > > physical 0x0 adress whereas 100 is internally interpreted as an object > > for which the reference (i.e. address) exists and therefore greater than > > 0x0. > > > > Am I interpreting correctly ? > > Not really. If objects of different types are compared (like compare a > string with a list), then no matter what, all strings but be "smaller" > than all lists. Or the oposite. > > So the fast way to accomplish this is to compare the addresses of the > object's method table. Something which is common for all objects of > the same type. > > > G. I see. There is some rule stating that all the strings are greater than ints and smaller than lists, etc. What was the goal behind this rule ? Francis Girard From sridharinfinity at gmail.com Wed Jan 26 01:15:14 2005 From: sridharinfinity at gmail.com (Sridhar) Date: 25 Jan 2005 22:15:14 -0800 Subject: alternatives to mod python In-Reply-To: References: Message-ID: <1106720114.039907.234560@c13g2000cwb.googlegroups.com> > Anyone have any suggestions? The only other thing > I looked at was twisted, which I'm still evaluating. I second that. Add Nevow too - www.nevow.com From adsr at poczta.onet.pl Sat Jan 8 05:30:57 2005 From: adsr at poczta.onet.pl (AdSR) Date: Sat, 08 Jan 2005 11:30:57 +0100 Subject: python3: 'where' keyword In-Reply-To: References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> Message-ID: Nick Coghlan wrote: > > Killer app for this keyword: > > class C(object): > > x = property(get, set) where: > def get(self): > return "Silly property" > def set(self, val): > self.x = "Told you it was silly" Hey, this is super-elegant! AdSR From ebolonev at mail.ru Thu Jan 13 05:53:09 2005 From: ebolonev at mail.ru (Egor Bolonev) Date: Thu, 13 Jan 2005 20:53:09 +1000 Subject: lambda Message-ID: why functions created with lambda forms cannot contain statements? how to get unnamed function with statements? From kent3737 at yahoo.com Sun Jan 9 20:31:58 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Sun, 09 Jan 2005 20:31:58 -0500 Subject: Speed revisited In-Reply-To: <36c3u0tpbg6f98ta6cm4fkj2kn0dkv624m@4ax.com> References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> <1105237556.402188.126980@c13g2000cwb.googlegroups.com> <1105303172.147395.63580@c13g2000cwb.googlegroups.com> <36c3u0tpbg6f98ta6cm4fkj2kn0dkv624m@4ax.com> Message-ID: <41e1d8d6$1_1@newspeer2.tds.net> Andrea Griffini wrote: > I've to admit that I also found strange that deleting the > first element from a list is not O(1) in python. My wild > guess was that the extra addition and normalization required > to have insertion in amortized O(1) and deletion in O(1) at > both ends of a random access sequence was going to have > basically a negligible cost for normal access (given the > overhead that is already present in python). This was added to Python 2.4 as collections.deque Kent From ncoghlan at iinet.net.au Mon Jan 10 08:07:45 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 10 Jan 2005 23:07:45 +1000 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: <41E26D05.5060408@iinet.net.au> References: <34cieoF489ejfU1@individual.net> <41E26D05.5060408@iinet.net.au> Message-ID: <41E27E21.6010606@iinet.net.au> Nick Coghlan wrote: > Disallowing local namespaces for statement lists would suggest something > like this: > > statement ::= (simple_stmt > (NEWLINE | ";" stmt_list NEWLINE | local_namespace) > ) | > (compound_stmt [local_namespace]) > local_namespace ::= "with" ":" suite > Corrected version of the above to avoid an unintended syntax change: statement ::= (simple_stmt (NEWLINE | ";" [stmt_list] NEWLINE | local_namespace) ) | (compound_stmt [local_namespace]) local_namespace ::= "with" ":" suite (The original version incorrectly prohibited a trailing semi-colon for a single statement) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steven.bethard at gmail.com Sun Jan 23 16:01:12 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 23 Jan 2005 14:01:12 -0700 Subject: finding name of instances created In-Reply-To: <1106513417.897059.92250@c13g2000cwb.googlegroups.com> References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106513417.897059.92250@c13g2000cwb.googlegroups.com> Message-ID: Michael Tobis wrote: > I have a similar problem. Here's what I do: > > .def new_robot_named(name,indict=globals()): > . execstr = name + " = robot('" + name + "')" > . exec(execstr,indict) > > .class robot(object): > . def __init__(self,name): > . self.name = name > > . def sayhi(self): > . print "Hi! I'm %s!" % self.name > > .if __name__=="__main__": > . new_robot_named('Bert') > . new_robot_named('Ernie') > . Ernie.sayhi() > . Bert.sayhi() > If you're changing the syntax from alex = CreateRobot() to new_robot_named('Alex') I don't see what you gain from using exec... py> class robot(object): ... def __init__(self,name): ... self.name = name ... def sayhi(self): ... print "Hi! I'm %s!" % self.name ... py> def new_robot_named(name, indict=globals()): ... indict[name] = robot(name) ... py> new_robot_named('Bert') py> new_robot_named('Ernie') py> Ernie.sayhi() Hi! I'm Ernie! py> Bert.sayhi() Hi! I'm Bert! py> import new py> temp = new.module('temp') py> new_robot_named('Alex', temp.__dict__) py> temp.Alex.sayhi() Hi! I'm Alex! That said, I do think a 'new_robot_named' function is probably a better approach than trying to change the meaning of Python's assignment statement... Steve From firstname.lastname at iki.fi-spam Mon Jan 10 17:33:42 2005 From: firstname.lastname at iki.fi-spam (Simo Melenius) Date: 11 Jan 2005 00:33:42 +0200 Subject: Writing huge Sets() to disk References: <1105390704.241316.267690@f14g2000cwb.googlegroups.com> Message-ID: <8765246hix.fsf@sme.intra.citec.fi> "John Lenton" writes: > you probably want to look into building set-like objects ontop of > tries, given the homogeneity of your language. You should see > imrpovements both in size and speed. Ternary search trees give _much_ better space-efficiency compared to tries, at the expense of only slightly slower build and search time. This is especially essential as the OP mentioned he could have huge sets of data. br, S From fredrik at pythonware.com Sun Jan 23 13:09:51 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 19:09:51 +0100 Subject: What is print? A function? References: <200501231801.50080.frans.englich@telia.com> Message-ID: >> The reason I thinks about this is I need to implement a debug print for my >> program; very simple, a function/print statement that conditionally prints >> its message whether a bool is true. Not overly complex. >> >> I tried this by overshadowing the print keyword, but that obviously didn't >> work.. Is defining a two-liner function the right way to go > > yup. something like this might be useful: > > def printif(cond, fmt, *args): > if cond: print fmt % args or, perhaps more useful in your case: if my_debug_flag: def debug(fmt, *args): print fmt % args else: def debug(*args): pass debug("hello!") debug("the value is %d", value) From guettli at thomas-guettler.de Wed Jan 5 10:52:22 2005 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Wed, 05 Jan 2005 16:52:22 +0100 Subject: date/time References: Message-ID: Am Wed, 05 Jan 2005 15:08:37 +0100 schrieb Nader Emami: > L.S., > > Could somebody help me how I can get the next format of date > from the time module? I don't understand your question. Do you want to have the next day? 20041231 --> 20050101 ? You can do it like this: - parse the string with time.strptime - timetuple[2]+=1 - mktime(timetuple) # --> secs - strftime(localtime(secs)) HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From steven.bethard at gmail.com Mon Jan 24 17:52:47 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 24 Jan 2005 15:52:47 -0700 Subject: Why I use private variables (WAS: RE:"private" variables a.k.a. name mangling?) In-Reply-To: References: Message-ID: <6dWdnSqi_sSm4WjcRVn-oQ@comcast.com> Philippe C. Martin wrote: > I used double underscore because I thought it was the correct way to name > private variables/methods - I will have to change those to single > underscore since that it the current methodology. > > A private variable to me: > 1) is internal to the processing of a class and needs not be accessed by > external or derivated objects. [snip] > 2) Must not be documented to library users as they're using it would > go againts 'law' 1). Yeah, I use single-underscores for similar reasons, and so that PythonWin doesn't show my "private" variables in the drop-down list of object attributes. I think for most uses, no name-mangling is required... Of course, I could generate an arbitrary number of "problem cases" -- I just don't think they happen often in real code... Steve From farcepest at gmail.com Sat Jan 29 10:42:35 2005 From: farcepest at gmail.com (Andy Dustman) Date: 29 Jan 2005 07:42:35 -0800 Subject: An mysql-python tutorial? References: Message-ID: <1107013355.659173.96490@c13g2000cwb.googlegroups.com> It's a pretty good tutorial, thought I would recommend you forget about the fetchone() example. The example below demonstrates three additional features that will make your life easier: MySQL option files, tuple unpacking, and cursors as iterators (fourth feature: the default host is localhost; this is rapidly turning into the Spanish Inquisition sketch): #!/usr/bin/python import MySQLdb db = MySQLdb.connect(db="db56a", read_default_file="~/.my.cnf") cursor = db.cursor() cursor.execute("SELECT name, species FROM animals") for name, species in cursor: print name, "-->", species (I also shy away from doing SELECT *; what if your schema changes?) (If the indentation is hosed, blame Google Groups.) From ptmcg at austin.rr._bogus_.com Sun Jan 16 21:50:15 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 17 Jan 2005 02:50:15 GMT Subject: List problems in C code ported to Python References: <3SDGd.22010$Z%.6947@fe1.texas.rr.com> Message-ID: "Michael Hoffman" wrote in message news:csf51g$cum$1 at gemini.csx.cam.ac.uk... > Michael Hoffman wrote: > > Paul McGuire wrote: > >> So "A" == 'a' is true in Python, not true in C. > > I think you meant: > > > > >>> "A" == "A" > > True > > Er, "A" == 'A' > -- > Michael Hoffman Yeah, that's the one I meant... :) -- Paul From segphault at sbcglobal.net Mon Jan 24 08:29:55 2005 From: segphault at sbcglobal.net (Ryan Paul) Date: Mon, 24 Jan 2005 13:29:55 GMT Subject: finding name of instances created References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> Message-ID: On Mon, 24 Jan 2005 13:19:45 +0000, Ryan Paul wrote: > > A working solution: > > class A: > pass > > a = A() > b = A() > c = A() > > [x for x,y in locals().items() if > hasattr(y,"__class__") and y.__class__ == A] > Just wanted to clarify, because I know that the intellectually deficient amongst you will say that isinstance is better than using __class__... In this case isinstance isnt desirable because it will catch instances of any objects that inherit A, not just instances of A. Observe: class A: pass class B(A): pass a = A() b = A() c = A() d = B() >>> [x for x,y in locals().items() if isinstance(y,A)] ['a', 'c', 'b', 'd'] >>> [x for x,y in locals().items() if ... hasattr(y,"__class__") and y.__class__ == A] ['a', 'c', 'b'] -- SegPhault From jacek.generowicz at cern.ch Wed Jan 5 04:55:14 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 05 Jan 2005 10:55:14 +0100 Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> Message-ID: Peter Hansen writes: > Grant Edwards wrote: > > I always rather liked line numbers (a-la 'can -n'). That also > > makes discussion of the code easier: > > That, unfortunately, is somewhat harder to remove without > using a regular expression... You mean to say that your editor does not have rectangle operations ? :-) From fredrik at pythonware.com Wed Jan 19 15:50:57 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 19 Jan 2005 21:50:57 +0100 Subject: ElementTree cannot parse UTF-8 Unicode? References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> Message-ID: Erik Bethke wrote: > I am getting an error of not well-formed at the beginning of the Korean > text in the second example. I am doing something wrong with how I am > encoding my Korean? Do I need more of a wrapper about it than simple > quotes? Is there some sort of XML syntax for indicating a Unicode > string, or does the Elementree library just not support reading of > Unicode? XML is Unicode, and ElementTree supports all common encodings just fine (including UTF-8). > this one fails: > > > > this works just fine on my machine. what's the exact error message? what does print repr(open("test2.xml").read()) print on your machine? what happens if you attempt to parse ? From fccoelho at gmail.com Wed Jan 12 17:12:02 2005 From: fccoelho at gmail.com (Flavio codeco coelho) Date: 12 Jan 2005 14:12:02 -0800 Subject: Python serial data aquisition References: <41e384d0.552090624@news.oz.net> Message-ID: fccoelho at gmail.com (Flavio codeco coelho) wrote in message news:... > struct.unpack returns a tuple of values represented by a string(the > output of the read command) packed according to the format specified > by ">BB" > In this forma string, ">" stands for big Endian representation and "B" > stands for unsigned char. > If anyone has a better suggestion, speack up! > oof! I started this thread knowing next to nothing about this stuff, > It seem that I am finally getting the idea! :)) > cheers, > Fl?vio Ok Folks, Thanks for all the help! Thanks to you and especially to Chris Liechti (pyserial), I managed to finish the Data aquisition module for the Dataq DI-151RS. you can check it out here: http://www.procc.fiocruz.br:8080/procc/Members/flavio/codepy/dataq/ It implements the basic operational functionality, fancier stuff should be added by the user. enjoy! Fl?vio Codeco Coelho P.S.: I'll be happy to support other hardware from Dataq if people give me access to other devices. From usenet_spam at janc.invalid Fri Jan 21 21:35:22 2005 From: usenet_spam at janc.invalid (JanC) Date: Sat, 22 Jan 2005 02:35:22 GMT Subject: hash patent by AltNet; Python is prior art? References: <41e96949$0$44082$5fc3050@dreader2.news.tiscali.nl> Message-ID: Tim Churches schreef: > And I agree 100% with Alex Martelli - Europe and other countries must > reject software, algorithmic and business method patents and thus create > a powerhouse of innovation. let the US and fellow-travellers stew in > their own juice - they will become powerhouses of litigation instead. > Provided other countries don't recognise software and business method > patents, the litigation will be confined within US borders, where > resources can be productivelt spent making television dramas about > attractive young patent attorneys and plodding, tram-riding patent > clerks who are really brilliant physicists if only someone would > recognise their potential. So yes, please write to your MP and MEP and > protest against the prospect of software and business method patents in > Europe. Hopefully one day within my lifetime we'll have a governemt here > in Australia which will roll back the damage done to our patent system > by trying to make just like the US system, just so we can conclude an > unbelieveably inequitable free trade agreement with the US. But that's > our problem. It's not looking really good here in Europe: If they succeed to push this through and Poland--or another country-- doesn't help us... :-( -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From Scott.Daniels at Acm.Org Sat Jan 1 16:20:16 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 01 Jan 2005 13:20:16 -0800 Subject: exposing C array to python namespace: NumPy and array module. In-Reply-To: References: Message-ID: <41d71170$1@nntp0.pdx.net> Bo Peng wrote: > Dear list, > I am writing a Python extension module that needs a way to expose pieces > of a big C array to python. Currently, I [use] NumPy.... Users ... actually > change the underlying C array. > > Python's array module is built-in, easy to use, but *without* a > FromLenAndData function! Python's array module is not built to do this well. It can re-size the array, delete elements inside the array, and other things that don't work very well with C-managed data. I wrote "blocks and views" to overcome this problem. A "View" of data can be pointed at data, and the "view" behaves much like a Python array (except that you cannot affect the array's size). You can even take "slices" of the view, which will produce a new view referring to the same base memory. There are two kinds of views available, read-only views and writable views. Have a look at: http://members.dsl-only.net/~daniels/Block.html to see if it addresses your problem. It is MIT-licensed (give credit, but feel free to use). Let me know if it works OK, could use a tweak, or is completely useless. I'll be more than happy to respond to questions. --Scott David Daniels Scott.Daniels at Acm.Org From belred at gmail.com Mon Jan 31 02:26:16 2005 From: belred at gmail.com (Bryan) Date: Sun, 30 Jan 2005 23:26:16 -0800 Subject: Regarding exception handling In-Reply-To: References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> <41FDD5F4.8030507@gmail.com> Message-ID: <41FDDD98.9070806@gmail.com> Fredrik Lundh wrote: > "Bryan" wrote > > >>the above is not the same. make the a = ... raise an exception and you'll see the difference. >> >>s = ... # >>a = 1/0 >>s.close() >> >>as you can see, s.close() will never be called. also, in this example, i intentionally didn't put >>the extra try/except around the try/finally statement. > > > file handles and sockets are closed when the objects are garbage collected. > under CPython, they're usually closed when they go out of scope. > > using try/finally on files and sockets are usually overkill. > > > > > i was trying to be generic and use the term resource. i know you are correct about file handles and sockets. there are other resources that don't behave so nicely. i'm currently using a third party module that will crash python (the entire interpreter GPF's) if you don't explicitly close the resource before your python script exits. other times, depending on a variable to go out of scope to have a resource automically close itself is not practical. or sometimes you want a resource to be closed, but still hold on to the reference. so, i don't feel as strongly as you do that try/finally on even files and socks are overkill. of course on small scripts, i don't use try/finally or close() either :) bryan From kartic.krishnamurthy at gmail.com Thu Jan 13 10:49:20 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 13 Jan 2005 07:49:20 -0800 Subject: Free python server. In-Reply-To: References: Message-ID: <1105631360.938494.286750@c13g2000cwb.googlegroups.com> You can try for a free shell access at www.arbornet.org. telnet (or better SSH) to m-net.arbornet.org and at the login prompt, type newuser, press enter and follow the on-screen instructions to register. Once you register, you get a shell account with email and web space. Since it is a free service, space is very limited but should more than serve your needs now. --Kartic From bj_666 at gmx.net Sat Jan 22 16:21:06 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 22 Jan 2005 22:21:06 +0100 Subject: getting file size References: Message-ID: In , Bob Smith wrote: > Are these the same: > > 1. f_size = os.path.getsize(file_name) > > 2. fp1 = file(file_name, 'r') > data = fp1.readlines() > last_byte = fp1.tell() > > I always get the same value when doing 1. or 2. Is there a reason I > should do both? When reading to the end of a file, won't tell() be just > as accurate as os.path.getsize()? You don't always get the same value, even on systems where `tell()` returns a byte position. You need the rights to read the file in case 2. >>> import os >>> os.path.getsize('/etc/shadow') 612L >>> f = open('/etc/shadow', 'r') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 13] Permission denied: '/etc/shadow' Ciao, Marc 'BlackJack' Rintsch From andre.roberge at gmail.com Fri Jan 21 21:33:58 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 21 Jan 2005 18:33:58 -0800 Subject: finding name of instances created In-Reply-To: References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106359068.802501.35190@z14g2000cwz.googlegroups.com> Message-ID: <1106361238.142879.222100@f14g2000cwb.googlegroups.com> Steven Bethard wrote: > Andr? wrote: > > Using the method suggested by Steven Bethard, I *almost* got it working > > the way I would like. [snip] > > It looks like you want PrivateClass.dict updated every time that > globals() is updated. yes, that is what I would like to do. >You can just use globals directly instead: > > py> class PrivateClass(object): > ... def __init__(self, globals): > ... self.globals = globals > ... def apparently_simple_method(self): > ... for name, value in self.globals.iteritems(): > ... if value is self: > ... print "instance %s called not so simple" % name > ... > py> def public_class(): > ... return PrivateClass(globals()) > ... > py> alpha = public_class() > py> alpha.apparently_simple_method() > instance alpha called not so simple > py> beta = public_class() > py> beta.apparently_simple_method() > instance beta called not so simple > That's exactly what I was looking for; thank you! > On the other hand, the iteration in > PrivateClass.apparently_simple_method has a very bad code smell... > I'm not sure what you mean... Is it because it makes use of information that is exterior to the class, which is not passed as a parameter to the method? [feel free to ignore this question if you want; you have already helped me tremendously!!!] Andr? From steve at holdenweb.com Wed Jan 5 15:01:58 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 05 Jan 2005 15:01:58 -0500 Subject: modpython, apache and windows In-Reply-To: References: Message-ID: Sam wrote: > Hi All, > > I am interested in learning python since I am hearing more and more > about python for use in web development > > I am starting out on python, with knowledge of PHP some perl > > my current hurdle is setting up either apache 1 or 2 with python 2.3.3 I > have installed modpython fine > > which informed me that I need to make some configuration changes to > httpd.conf > These changes are relatively easy, but of course making them requires access to the files, not always available unless you are managing your own server. Note, though, that it's easily possible to use Python as a CGI language on most Apache installations. > I have not had it working yet, searches on the web give conflicting > suggestions and so far has confused me > Perhaps if you could explain what it is you are failing to do, you might elicit some explicit help. > some forums mention spyce and serving .spy files > > so far I one explanation worked in that a .py file was parsed but I had > to set the name of the actual file within apache.conf > this seems strange > > thanks in advance >> SS > > Try creating a Python file (.py file, with world-executable permissions) in a cgi-bin directory: #!/usr/bin/env python print """Content-Type: text/plain Hello, world""" and see if you can call it from a web browser. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From steve at holdenweb.com Thu Jan 20 13:45:56 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 20 Jan 2005 13:45:56 -0500 Subject: Overloading ctor doesn't work? In-Reply-To: <35ab8oF4idc25U1@individual.net> References: <35ab8oF4idc25U1@individual.net> Message-ID: Martin H?cker wrote: > Hi there, > > I just tried to run this code and failed miserably - though I dunno why. > Could any of you please enlighten me why this doesn't work? > > Thanks a bunch. > > --- snip --- > import unittest > from datetime import datetime > > class time (datetime): > def __init__(self, hours=0, minutes=0, seconds=0, microseconds=0): > print "blah" > datetime.__init__(self, 1, 1, 1, hours, \ > minutes, seconds, microseconds) > > > class Test (unittest.TestCase): > def testSmoke(self): > # print time() # bombs, and complains that > # the time ctor needs at least 3 arguments > self.assertEquals(datetime(1,1,1,1,2,3,4),time(1,2,3,4)) > > > if __name__ == '__main__': > unittest.main() > --- snap --- > > The reason I want to do this is that I want to work with times but I > want to do arithmetic with them. Therefore I cannot use the provided > time directly. > > Now I thought, just overide the ctor of datetime so that year, month and > day are static and everything should work as far as I need it. > > That is, it could work - though I seem to be unable to overide the ctor. :( > > Why is that? > Perhpas the error message or output, which you don't provide, would avoid our having to use our psychic powers? ;-) In other words: what's wrong? How do you *know* you can't override it? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From daniel at bowettsolutions.com Thu Jan 20 03:48:37 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Thu, 20 Jan 2005 08:48:37 +0000 Subject: mod_python friendly isps in europe In-Reply-To: <1106134550.347891.129260@f14g2000cwb.googlegroups.com> References: <1106134550.347891.129260@f14g2000cwb.googlegroups.com> Message-ID: paulo.jpinto at gmail.com wrote: > Hello everybody > > I'm thinking about improving my web site scripts > and would like to use Python instead of PHP/Perl. > > Does anyone know of mod_python friendly ISPs in > europe? With prices around 10? ? > > Thanks in advance, > Paulo > I would doubt you will find any commercial python ISP's out there. If you do could you post them here? From rnd at onego.ru Sat Jan 8 14:33:09 2005 From: rnd at onego.ru (Roman Suzi) Date: Sat, 8 Jan 2005 22:33:09 +0300 (MSK) Subject: interpreter Py_Initialize/Py_Finalize mem leak? Message-ID: In pure curiosity I tried to compile loop.c from Demo/embed and started it with 'print 2+2'. It seems, that both 2.3 and 2.4 pythons have memory leaks in Py_Initialize/Py_Finalize calls. (That is, interpreter doesn't clean up well after itself). This is my setup: gcc -fpic loop.c -DHAVE_CONFIG_H -lm -lpython2.4 \ -lpthread -lutil -ldl \ -I/usr/local/include/python2.4 \ -L/usr/local/lib/python2.4/config \ -o looptest (It's on Linux RedHat 7.3) I do not know if this is of any importance though. Probably it is for embedded Python uses. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From chris321 at hotmail.com Mon Jan 24 00:52:51 2005 From: chris321 at hotmail.com (Chris Line) Date: Mon, 24 Jan 2005 16:52:51 +1100 Subject: Asynchronous event handling...? Message-ID: An HTML attachment was scrubbed... URL: From mc at mclaveau.com Sun Jan 23 14:45:05 2005 From: mc at mclaveau.com (Michel Claveau) Date: Sun, 23 Jan 2005 20:45:05 +0100 Subject: [python-win32] on the way to find pi! References: <20050123182847.74790.qmail@web61009.mail.yahoo.com> Message-ID: <029001c50184$0cd23220$0701a8c0@PORTABLES> Hi ! Very more simplistic, but easy for to code : def pi(nb): cpi=0 for i in xrange(1,nb,4): cpi=cpi+4./i-4./(i+2.) return(cpi) print pi(999999) @-salutations -- Michel Claveau From python-url at phaseit.net Fri Jan 28 10:08:05 2005 From: python-url at phaseit.net (Cameron Laird) Date: Fri, 28 Jan 2005 15:08:05 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 28) Message-ID: QOTW: "It might be nice if it was widely understood (in IT) that Python was a language any competent programmer could pick up in an afternoon, such that Java, C, and Perl shops would not be concerned about the need for their staff to learn a new language." -- Eric Pederson "What's kind of surprising is that it has turned out to be easier to rewire the entire world for high-bandwidth Internet than it is to make a good replication architecture so you can work disconnected!" -- Joel http://www.salon.com/tech/feature/2004/12/09/spolsky/index4.html It's the Early Bird deadline for PyCon 2005! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/5a0eef8d2f4b41c6 A wide-ranging thread on "security" yields, among other high points, a recommendation to read *Security Engineering* and examples of real security issues Python has: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a5ab5a6a91590230/ Can Python operate on a Windows "desktop"? Sure, in a variety of ways. Thanks to Dennis Benzinger, Jimmy Retzlaff, Vincent Wehren, and others for their catalogue: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/f73cc8e9cad01288/ The martellibot illustrates why Python's introspection--and __subclasses__, in particular--make correct "sandboxing" so challenging for us: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d5f4d7e2c397c2ca/ After a rest of a couple months, it's time again to urge consideration of IPython as your working shell: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/3fed261a83318a1e 4XSLT is thread-safe, but individual processor instances are not. 4Suite exploits processor-per-thread: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/c118d6ead64ca003 Thread inheritance with win32com requires Co*nitialize() management: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/3e3487f970825fc8 Gerald and the timbot speak sense on the platform-specificity that is memory management. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2bef18c56f085eeb Do NOT let your inheritance schemes complexify. One palliative tactic is to remember (lazy) "containerization" as an alternative to subclassing. And learn about decorators. And descriptors, for that matter: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/730e4e3bb3c55b28/ Do people still FTP? Well, Python people *can* ...: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/37b847a725bd8d9f ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. deli.cio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From petr at tpc.cz Tue Jan 18 19:21:33 2005 From: petr at tpc.cz (McBooCzech) Date: 18 Jan 2005 16:21:33 -0800 Subject: script to automate GUI application (newbie) In-Reply-To: <9q90c2-tou.ln1@lairds.us> References: <1106071392.908441.262500@c13g2000cwb.googlegroups.com> <9q90c2-tou.ln1@lairds.us> Message-ID: <1106094093.132587.260630@c13g2000cwb.googlegroups.com> Try following scripting language to automating Windows GUI, it simulates keystrokes (supports most keyboard layouts), simulates mouse movements and clicks and does tons of other stuff: http://www.hiddensoft.com/autoit3/ It works nicely for me. From claudio.grondi at freenet.de Wed Jan 26 05:26:08 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 26 Jan 2005 10:26:08 -0000 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: <35p61bF4og5tgU1@individual.net> I can't resist to point here to the Re: How to input one char at a time from stdin? posting in this newsgroup to demonstrate, what this thread is about. Claudio > >On Tue, 25 Jan 2005 12:38:13 -0700, Brent W. Hughes > > wrote: > >> I'd like to get a character from stdin, perform some action, get another > >> character, etc. If I just use stdin.read(1), it waits until I finish typing > >> a whole line before I can get the first character. How do I deal with this? > > > >This is exactly what you need: > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 > >Title: "getch()-like unbuffered character reading from stdin on both > >Windows and Unix" > > Nice to know how, but all those double underscores made my eyes bleed. > Three classes? What's wrong with something simple like the following > (not tested on Unix)? > > > import sys > bims = sys.builtin_module_names > if 'msvcrt' in bims: > # Windows > from msvcrt import getch > elif 'termios' in bims: > # Unix > import tty, termios > def getch(): > fd = sys.stdin.fileno() > old_settings = termios.tcgetattr(fd) > try: > tty.setraw(sys.stdin.fileno()) > ch = sys.stdin.read(1) > finally: > termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) > return ch > else: > raise NotImplementedError, '... fill in Mac Carbon code here' "Davor" schrieb im Newsbeitrag news:1106689788.676121.48490 at c13g2000cwb.googlegroups.com... > Is it possible to write purely procedural code in Python, or the OO > constructs in both language and supporting libraries have got so > embedded that it's impossible to avoid them? Also, is anyone aware of > any scripting language that could be considered as "Python minus OO > stuff"? (As you can see I'm completely new to Python and initially > believed it's a nice&simple scripting language before seeing all this > OO stuff that was added in over time) > Thanks, > Davor Here the OO "solution" (activestate recipe 134892): class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix() def __call__(self): return self.impl() class _GetchUnix: def __init__(self): import tty, sys def __call__(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ch = sys.stdin.read(1) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch class _GetchWindows: def __init__(self): import msvcrt def __call__(self): import msvcrt return msvcrt.getch() getch = _Getch() From olaf.delgado at asu.edu Thu Jan 13 04:01:37 2005 From: olaf.delgado at asu.edu (Olaf Delgado-Friedrichs) Date: Thu, 13 Jan 2005 10:01:37 +0100 Subject: java 5 could like python? In-Reply-To: References: Message-ID: <34mrlmF4e2g6dU1@individual.net> Roman Suzi wrote: >>-Realying on ides is imposible due to python dinamic nature,very litle(next >>to nothing) assistance can be espected from them. > > > Class browsing and auto-completion are probably the only features > I sometime miss. But otherwise what IDEs are for? Refactoring? You got to admit, Bicycle Repair Man is not much of a superhero. Eclipse's refactoring capabilies and the standard library was what drove me from Python to Java, although I still like Python much better as a language. Cheers, O. From peter at engcorp.com Mon Jan 24 10:58:16 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jan 2005 10:58:16 -0500 Subject: What YAML engine do you use? In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7xoefhtavd.fsf@ruckus.brouhaha.com> Message-ID: <9-adnZ2OTqeKhmjcRVn-uA@powergate.ca> Sion Arrowsmith wrote: > Paul Rubin wrote: > >>YAML looks to me to be completely insane, even compared to Python >>lists. I think it would be great if the Python library exposed an >>interface for parsing constant list and dict expressions, e.g.: >> [1, 2, 'Joe Smith', 8237972883334L, # comment >> {'Favorite fruits': ['apple', 'banana', 'pear']}, # another comment >> 'xyzzy', [3, 5, [3.14159, 2.71828, []]]] >>[ ... ] >>Note that all the values in the above have to be constant literals. >>Don't suggest using eval. That would be a huge security hole. > > > I'm probably not thinking deviously enough here, but how are you > going to exploit an eval() which has very tightly controlled > globals and locals (eg. eval(x, {"__builtins__": None}, {}) ? See, for example, Alex Martelli's post in an old thread from 2001: http://groups.google.ca/groups?selm=9db3oi01aph%40news2.newsguy.com -Peter From ncoghlan at iinet.net.au Mon Jan 10 08:33:08 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 10 Jan 2005 23:33:08 +1000 Subject: Speed revisited In-Reply-To: <1105315414.432202.249470@c13g2000cwb.googlegroups.com> References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> <1105237556.402188.126980@c13g2000cwb.googlegroups.com> <1105303172.147395.63580@c13g2000cwb.googlegroups.com> <36c3u0tpbg6f98ta6cm4fkj2kn0dkv624m@4ax.com> <1105315414.432202.249470@c13g2000cwb.googlegroups.com> Message-ID: <41E28414.4060603@iinet.net.au> John Machin wrote: > My wild guess: Not a common use case. Double-ended queue is a special > purpose structure. As Kent said, the suggestion of making index 0 insertions and deletions on lists more efficent was made, and the decision was to leave list alone and provide collections.deque instead. This let deque sacrifice some of list's flexibility in favour of increased speed. Appropriate parts of the core which needed a FIFO were then updated to use the new data type, while everything else continues to use lists. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From martyn_quick at yahoo.co.uk Mon Jan 24 10:24:40 2005 From: martyn_quick at yahoo.co.uk (Martyn Quick) Date: 24 Jan 2005 07:24:40 -0800 Subject: Configuring Python for Tk on Mac (continued) Message-ID: From: Alex Martelli (aleaxit at yahoo.com) > > No idea about any 10.2, sorry, but on 10.3 that's not the problem: Tk > support is there alright, it's Tcl/Tk which _isn't_. Get MacPython, its > PackageManager will explain where to get Tcl/Tk Aqua from, as a prereq > for Tkinter and IDLE! Ok, I've installed MacPython. It doesn't seem to work right though... for example, if I try to run the 00-HELLO-WORLD.py example then it crashes and tells me the IDE has unexpectedly crashed. I can't really see how to run things either. (I'm used to just typing "python" in a terminal on Unix but that seems to just run the version that comes pre-installed.) Sorry for not knowing much about Macs and being a bit clueless. Martyn From http Sun Jan 30 20:43:16 2005 From: http (Paul Rubin) Date: 30 Jan 2005 17:43:16 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> <7xacqsbfk2.fsf@ruckus.brouhaha.com> <41fbcb11$0$12030$9b622d9e@news.freenet.de> <7xsm4j1wbe.fsf@ruckus.brouhaha.com> <41fc9eec$0$25945$9b622d9e@news.freenet.de> Message-ID: <7xpszmgyq3.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > > Oh, ok. Earlier you said you wanted user feedback before you could > > conclude that there was reason to want an AES module at all. > > I believe I never said that. I said that I wanted user feedback to > determine whether *this* AES module (where this is either your > from-scratch implementation, or any other specific implementation > contributed) is desirable. If that's what you're saying now, I'll accept it and not bother looking for your other posts that came across much differently. > > I had thought there were insurmountable > > obstacles of a nontechnical nature, mainly caused by legal issues,.. > > These obstacles are indeed real. But I believe they are not > unsurmountable. For example, there is the valid complaint that, > in order to export the code from SF, we need to follow U.S. > export laws. 10 years ago, these would have been unsurmountable. Well, yes, 10 years ago, SF didn't exist . But there was an ftp site run by Michael Johnson that had some special server side checks that made sure the client was in the USA. That was considered good enough to comply with the export regs, and another guy and I distributed crypto code (a program that let you use your PC as an encrypted voice phone) through that site in 1995. Of course, every time my co-author and I released a new version through the controlled ftp site, within a day or so the code somehow managed to show up on another ftp site in Italy with worldwide access. We (the authors) always managed to be shocked when that happened. But we had nothing to do with it, so it wasn't our problem. > Today, it is still somewhat painful to comply with these laws, > but this is what the PSF is for, which can fill out the forms > necessary to allow exporting this code from the U.S.A. Well, complying is painful in the sense of being morally repugnant (people shouldn't have to notify the government in order to exercise their free speech rights), but the actual process is pretty easy in terms of the work required. Python should qualify for the TSU exception which means you just need to send an email to the BXA, without needing to fill out any forms. I thought that's what you had done for the rotor module. From peter at somewhere.com Thu Jan 20 03:43:38 2005 From: peter at somewhere.com (Peter Maas) Date: Thu, 20 Jan 2005 09:43:38 +0100 Subject: rotor replacement In-Reply-To: <7xwtu8vb17.fsf@ruckus.brouhaha.com> References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> <7xacr4ewjk.fsf@ruckus.brouhaha.com> <41ef4a7a.1323588509@news.oz.net> <7xwtu8vb17.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schrieb: >>Wasn't there a default 40-bit version that was ok (weak), but you had >>to declare yourself US resident to download 128-bit support? > > > That was years ago. The regulations changed since then, so they all > have 128 bits now. Perhaps the NSA has found a way to handle 128bit in the meantime. But this is unlikely because there is no export regulation to ban 512bit as far as I know :) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From ialbert at mailblocks.com Tue Jan 4 09:35:58 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Tue, 04 Jan 2005 09:35:58 -0500 Subject: Python evolution: Unease In-Reply-To: <41DA79DB.7020507@none.net> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> Message-ID: <9vqdncpnrbRTNEfcRVn-ug@giganews.com> Iwan van der Kleyn wrote: > And I do sense (reading planet python/this newsgroup) a mindset or at > least a tendency by the people who really matter in these discussion to > keep on adding features to the syntax; to add "structure" to Python. My > personal preference would be to leave the language alone for a while and > to improve its infrastructure. In all honesty this: http://www.artima.com/weblogs/viewpost.jsp?thread=86641 scares me too. Reminds me of Larry Wall's writings on Perl 6 that make me tune out fairly quickly. I don't have the kind of problems that the these features will solve so I can't relate to them at all. But others might do. Especially when using python in an environment where enforcing a strict contract is important. But if python were to become overly complicated I'll find something else. Three years ago I have not not used python at all, now I'm using it for everything. Languages should evolve with time, adapt to the needs of its users. Sometimes that means that in some areas it might feel worse. But it could also mean that the problem is with us, so it would be unfair to spend effort towards holding back this evolution just because we don't need it. Istvan. PS. why can't decorators solve this optional type checking problem? I clearly remember this as being one of the selling points for having decorators in the first place... From alan.gauld at btinternet.com Mon Jan 24 15:26:28 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 24 Jan 2005 20:26:28 +0000 (UTC) Subject: how to ncurses on win32 platform References: <3nkds3kzc9mp.18yfed1y3vo9d$.dlg@40tude.net> Message-ID: On Mon, 24 Jan 2005 17:06:52 +0100, Brane wrote: > please advice You can use ncurses via cygwin. There are DOS ports too but I couldn't get any of them to work on my XP box, YMMV... Search the Vaults of Parnassus for the DOS Stuff. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From deetsNOSPAM at web.de Wed Jan 26 10:05:37 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 26 Jan 2005 16:05:37 +0100 Subject: 4suite XSLT thread safe ? References: <6lkkc2-fbd.ln1@pluto.i.infosense.no> <35pntaF4os76kU1@individual.net> Message-ID: <35ppqeF4nu516U1@individual.net> > It is not unthinkable that some parts of the library would not be > threadsafe. They could have some internal shared global variable > that keeps track of an intermediate state. > Some C string processing functions are not thread safe either. While the only one how can answer this is Uche himself, I'm confident that this is not the case - modern OO-style apis associate state usually on a per-object base. And 4suite is heavily OO-styled. -- Regards, Diez B. Roggisch From jelleferinga at planet.nl Tue Jan 25 17:43:44 2005 From: jelleferinga at planet.nl (jelle) Date: 25 Jan 2005 14:43:44 -0800 Subject: quering the google desktop database Message-ID: <1106693024.840653.160200@f14g2000cwb.googlegroups.com> Hi, Has anyone so far been messing accessing / quering the google desktop database files? It seems it could be the best reflection of one in a couple of hundred mb, and i intent to unleash some furious queries on it, when i'd know how to access it. Any suggestion how this could be done in python? My intention is to apply data mining to the google desktop database. How about it, who's in for it? Cheers, Jelle From peter at engcorp.com Wed Jan 26 15:57:17 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 Jan 2005 15:57:17 -0500 Subject: XOR on string In-Reply-To: References: Message-ID: snacktime wrote: > I need to calculate the lrc of a string using an exclusive or on each > byte in the string. How would I do this in python? lrc == Linear Redundancy Check? or Longitudinal? Note that such terms are not precisely defined... generally just acronyms people make up and stick in their user manuals for stuff. :-) import operator lrc = reduce(operator.xor, [ord(c) for c in string]) Note that this returns an integer, so if you plan to send this as a byte or compare it to a character received, use chr(lrc) on it first. -Peter From __peter__ at web.de Wed Jan 26 02:58:45 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Jan 2005 08:58:45 +0100 Subject: string.atoi and string.atol broken? References: <1106700417.482871.45140@z14g2000cwz.googlegroups.com> Message-ID: Dan Bishop wrote: >> def itoa(n, base): >>assert?2?<=?base?<=?16 > > Why have the restriction base <= 16???int()?allows?up?to?36.??All?you > need to do is > > BASE36_DIGITS = string.digits + string.lowercase For no other reason than carelessness. I have not yet seen anything beyond base-16 in the wild. By the way, does anyone know the Greek name for 36? Peter From nightmarch at gmail.com Mon Jan 24 22:13:03 2005 From: nightmarch at gmail.com (nightmarch) Date: Tue, 25 Jan 2005 11:13:03 +0800 Subject: I want update one record using ADO,but I can't ,why? Message-ID: <31d9b15c050124191356f25daa@mail.gmail.com> I want update one record ,but I can't ,why? code like following: ##------------------------------------------------- import win32com.client as wc def main(): conn = wc.Dispatch(r'ADODB.Connection') rs = wc.Dispatch(r'ADODB.Recordset') connStr = "Provider=MSDAORA.1;Password=jmpower;User ID=jmpower;Data Source=jmgis_agps3;Persist Security Info=True" tblName = r'wjtmp' conn.Open(connStr ) rs.Open( tblName, conn, wc.constants.adOpenKeyset, wc.constants.adLockOptimistic ) if rs.Supports( wc.constants.adUpdate ): rs.Fields.Item(0).Value = 11 rs.Update() else: print "recordset can't update" rs.Close() conn.Close() if __name__ == '__main__': main() ##------------------------------------------------- thanks! From xah at xahlee.org Wed Jan 26 02:12:25 2005 From: xah at xahlee.org (Xah Lee) Date: 25 Jan 2005 23:12:25 -0800 Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> Message-ID: <1106723545.429728.308620@f14g2000cwb.googlegroups.com> in my previous two messages, i've criticized the inanity of vast majority of language documentations and tutorials in the industry. I've used the Python tutorial's chapter on class as an example. I've indicated that proper tutorial should be simple, covering just common cases, be self-contained, and be example based. Documenting or covering the language's functionalities manifest as it is. An exemplary case of this style i've indicated is Stephen Wolfram Mathematica documentation. Following is a tutorial on Python's classes. It is part of a a-Python-a-day mailing list. As an example, it shows what i mean by covering the language's functionalities as is, without needing to chalk up to rocket sciences. If expanded slightly and edited, it can supplant sections 9.0 to 9.4 of the Python tutorial. Languages Tutorials should follow this style. --------------- From: xah at xahlee.org Subject: [perl-python] 20050124 classes and objects Date: January 24, 2005 6:44:14 AM PST To: perl-python at yahoogroups.com # -*- coding: utf-8 -*- # Python # in Python, one can define a boxed set # of data and functions, which are # traditionally known as "class". # in the following, we define a set of data # and functions as a class, and name it xxx ?class xxx: ? "a class extempore! (^_^)" ? i=1 # i'm a piece of data ? def okaydokey(self): return "okaydokey" ? def square(self,a): return a**a # in the following, # we create an object, of the class xxx. # also known as "instantiate a class". x = xxx() # data or functions defined in a class # are called the class's attributes or # methods. # to use them, append a dot and # their name after the object's name. print 'value of attribute i is:', x.i print "3 squared is:", x.square(3) print "okaydokey called:", x.okaydokey() # in the definition of function inside a # class, the first parameter "self" is # necessary. (you'll know why when you need to) # the first line in the class definition # is the class's documentation. It can # be accessed thru the __doc__ # attribute. print "xxx's doc string is:", x.__doc__ # one can change data inside the class x.i = 400 # one can also add new data to the class x.j=4 print x.j # or even override a method x.square = 333 # (the following line will no longer work) # print "3 squared is:", x.square(3) # in Python, one must be careful not to # overwrite data or methods defined in a # class. #----------------------- # for a obfuscated treatment with a few # extra info, see # http://python.org/doc/2.3.4/tut/node11.html # in Python terminal, type help() then # topic CLASSES to read about existing # datatypes as classes, and classes in # Python # try to write a class with one data of # integer and two functions, one # increases it by 1, one decreases it by # 1. note: inside a class definition, # to refer to data inside itself use # self. e.g. self.i Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From FBatista at uniFON.com.ar Mon Jan 24 07:35:32 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 24 Jan 2005 09:35:32 -0300 Subject: Py2.4 .exe installer Message-ID: I'm trying to get everybody at the office to become a Python programmer. The bigger problem I'm facing is that the "official" operating system installed in the PCs is Win NT 4.0, tweaked and restricted, and it's impossible to install the Microsoft package that enables the .msi as a installer. Result: they can not install Py24.msi. There's somewhere a Py24.exe installer? Thanks! Facundo Batista Desarrollo de Red fbatista at unifon.com.ar (54 11) 5130-4643 Cel: 15 5097 5024 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From erikbethke at gmail.com Tue Jan 18 04:03:59 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 18 Jan 2005 01:03:59 -0800 Subject: wxPython and PyGame - do they play well together? In-Reply-To: References: <1106026599.092269.292170@c13g2000cwb.googlegroups.com> Message-ID: <1106039039.627729.62990@f14g2000cwb.googlegroups.com> Thank you, My apologies to all for insufficient googling.... -Erik From skip at pobox.com Tue Jan 11 09:56:33 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 11 Jan 2005 08:56:33 -0600 Subject: why not datetime.strptime() ? In-Reply-To: <20050111021152.GA20127@yucs.org> References: <20050111021152.GA20127@yucs.org> Message-ID: <16867.59681.423983.244528@montanaro.dyndns.org> Josh> OK, it was pretty straightforward. Thanks for the direction. Glad to help. Josh> To whom should I send the patch (attached)? Patches should be posted to SourceForge using this form: http://sourceforge.net/tracker/?func=add&group_id=5470&atid=305470 Note that you will have to be registered at SourceForge if you aren't already. Full details about submitting patches are here: http://www.python.org/patches/ (though I think we're just as happy to read unified diffs as context diffs these days). The patch you posted looks like a good start. I have a few quick comments: * The references returned by PySequence_GetItem() are leaking. An easy way to see is to run it in an infinite loop and watch your process's memory size: while True: x = datetime.datetime.strptime("2004-12-01", "%Y-%m-%d") If it's leaking, memory size should grow pretty quickly. A debug build will also show the memory growth: >>> x = datetime.datetime.strptime("2004-12-01", "%Y-%m-%d") [29921 refs] >>> x = datetime.datetime.strptime("2004-12-01", "%Y-%m-%d") [29928 refs] >>> x = datetime.datetime.strptime("2004-12-01", "%Y-%m-%d") [29935 refs] >>> x = datetime.datetime.strptime("2004-12-01", "%Y-%m-%d") [29942 refs] You can see the leaking references quite clearly. * The seventh item returned from time.strptime() is the day of the week. You're passing it into the microsecond arg of the datetime constructor and ignoring the timezone info (ninth item returned from time.strptime(), eighth arg to the datetime constructor). * The return values of the Py* calls must always be checked. * A documentation patch for Doc/lib/libdatetime.tex is needed. * Lib/test/test_datetime.tex should be extended to add one or more test cases for the new constructor. * It would be nice if the import happened only once and was cached: static PyObject *time_module; ... if (time_module == NULL && (time_module = PyImport_ImportModule("time")) == NULL) return NULL; obj = PyObject_CallMethod(time_module, ...); After awhile these sorts of things become second nature. They are part of the boilerplate/details required for most changes though. Skip From fredrik at pythonware.com Thu Jan 13 05:01:39 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 13 Jan 2005 11:01:39 +0100 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com><7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: Antoon Pardon wrote: > Well, it seems that Guido is wrong then. The documentation clearly > states that an expression is a statement. no, it says that an expression statement is a statement. if you don't understand the difference, please *plonk* yourself. From simon.brunning at gmail.com Thu Jan 13 09:16:43 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Thu, 13 Jan 2005 14:16:43 +0000 Subject: Unclear On Class Variables In-Reply-To: References: Message-ID: <8c7f10c6050113061629c999ed@mail.gmail.com> On Thu, 13 Jan 2005 08:56:10 -0500, Peter Hansen wrote: > Simon, it's really not about mutability at all. You've changed > the example, Err, there *wasn't* an example, not really. The OP just mentioned 'setting the values' of instance members. That *can* mean name binding, but (to my mind at least) it can also mean calling mutating methods. I just wanted to show both. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From http Wed Jan 12 18:54:07 2005 From: http (Paul Rubin) Date: 12 Jan 2005 15:54:07 -0800 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> <1g4nx7m906q79$.dlg@usenet.alexanderweb.de> <7xekgr7lpy.fsf@ruckus.brouhaha.com> <7x4qhn9q3g.fsf@ruckus.brouhaha.com> <7xr7kq1rk6.fsf@ruckus.brouhaha.com> <7xvfa2toed.fsf@ruckus.brouhaha.com> <7xpt0a4bkz.fsf@ruckus.brouhaha.com> Message-ID: <7xekgqurts.fsf@ruckus.brouhaha.com> Ian Bicking writes: > If the data has to be somewhere, and you have to have relatively > random access to it (i.e., access any page; not necessarily a chunk of > a page), then the filesystem does that pretty well, with lots of good > features like caching and whatnot. I can't see a reason not to use > the filesystem, really. For one thing you waste lots of space for small files because of partially empty blocks at the end of each page. Sure, disk space is cheap, but you similarly waste space in your ram cache, which impacts performance and isn't so cheap. For another, you need multiple seeks to get to each file (scan the directory to get the inode number, read the inode, get the list of indirect blocks from the file, read each of those, etc). With big files, the inode and indirect blocks will be cached, so you only have to seek once. Finally, you lose some control over what's in ram and what needs to be retrieved. You can do a better job of tuning your cache strategy to the precise needs of your wiki, than the file system can with its one-size-fits-all approach. > For backlink indexing, that's a relatively easy index to maintain > manually, simply by scanning pages whenever they are modified. The > result of that indexing can be efficiently put in yet another file > (well, maybe one file per page). Opening and closing the extra files imposes considerable overhead, though it would take actual benchmarking to get precise figures. > For full text search, you'll want already-existing code to do it for > you. MySQL contains such code. But there's also lots of that > software that works well on the filesystem to do the same thing. Have you ever used the MySQL fulltext search feature? It's awful. > A database would be important if you wanted to do arbitrary queries > combining several sources of data. And that's certainly possible in a > wiki, but that's not so much a scaling issue as a > flexibility-in-reporting issue. An RDBMS is a good backend for a medium sized wiki, since it takes care of so many issues for you. For a very big wiki that needs high performance, there are better approaches, though they take more work. From frans.englich at telia.com Wed Jan 26 16:02:22 2005 From: frans.englich at telia.com (Frans Englich) Date: Wed, 26 Jan 2005 21:02:22 +0000 Subject: Inherting from object. Or not. Message-ID: <200501262102.22884.frans.englich@telia.com> (Picking up a side track of the "python without OO" thread.) On Wednesday 26 January 2005 11:01, Neil Benn wrote: > I say this because you do need to be aware of the > 'mythical python wand' which will turn you from a bad programmer into a > good programmer simply by typing 'class Klass(object):'. What is the difference between inherting form object, and not doing it? E.g, what's the difference between the two following classes? class foo: pass class bar(object): pass Sometimes people inherit from it, and sometimes not. I don't see a pattern in their choices. Cheers, Frans From rmemmons at member.fsf.org Mon Jan 3 21:16:35 2005 From: rmemmons at member.fsf.org (Rob Emmons) Date: Mon, 03 Jan 2005 20:16:35 -0600 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: > Theoretically. Because even though the source code is available > and free (like in beer as well as in speech) the work of > programmers isn't cheap. > > This "free software" (not so much OSS) notion "but you can > hire programmers to fix it" doesn't really happen in practice, > at least not frequently: because this company/guy remains > ALONE with this technology, the costs are unacceptable. This certainly is the thinking, but I is the wrong thinking in many cases. If companies could some how take a larger view and realize that by working together here and there -- they enable and open development model which in the end saves them money. AHHH but that's such a hard argument because it takes vision, time, and trust. It takes a whole vision change to work in this environment -- believing in an economy of plenty rather than an economy of scarcity. > It depends on definition of "rational", on definition of your or > company's goals and on the definitions of the situations that > are the context. I work for a very large company -- there is an internal culture that defines what "rational" is: (a) Rational means outsourcing and doing less inside the company, (b) pretty much single sourcing commerical software, (c) releasing nothing outside the company unless there is a direct demonstratable significant business benifit related to our core products. I could argue these are not rational in the long run, but this is the direction of the company as far as I know. This will change -- and someone will get a big promotion for doing it -- but it will take a lot of time. And of course someone already got a big promotion for outsourcing and developing the single source stratagy -- bone headed as it is. Rob From jlenton at gmail.com Mon Jan 10 15:58:24 2005 From: jlenton at gmail.com (John Lenton) Date: 10 Jan 2005 12:58:24 -0800 Subject: Writing huge Sets() to disk In-Reply-To: References: Message-ID: <1105390704.241316.267690@f14g2000cwb.googlegroups.com> you probably want to look into building set-like objects ontop of tries, given the homogeneity of your language. You should see imrpovements both in size and speed. From fredrik at pythonware.com Mon Jan 31 13:18:57 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 31 Jan 2005 19:18:57 +0100 Subject: Relocatable binary installs.... References: <1107195180.462949.222980@z14g2000cwz.googlegroups.com> Message-ID: friedmud at gmail.com wrote: > Is there a way to make a relocateable python binary... that is... a > python installation that won't care where it is on the machine... and > won't care if it gets put somewhere else besides / ? the standard CPython interpreter is 100% "relocatable". If you think it isn't, you have to be a bit more specific. From steve at holdenweb.com Thu Jan 6 09:27:49 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Jan 2005 09:27:49 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: Bulba! wrote: > On 04 Jan 2005 19:25:12 -0800, Paul Rubin > wrote: > > >>"Rob Emmons" writes: >> >>>Me personally, I believe in free software, but always talk about open >>>source. My answer regarding forcing people to share -- I like the GPL >>>-- and I am perfectly happy to have anyone who does not like the GPL >>>not to use any GPLed software. I don't feel compelled to share. > > >>I'd go further. It's not possible to force anyone to share, but the >>GPL aims to remove software from a system that instead aims to force >>people NOT to share. > > > Nope. IMHO, GPL attempts to achieve the vendor lock-in. For different > purposes than another well-known vendor, but it still does. > Well you are entitled to your opinion. But *my* opinion is that the GPL attempts to ensure that if you re-use code by an author who so desires, then redistribution of your code is only possible by making your own extensions to it available on the same terms. This gives you a clear choice. To put it another way, it allows an author to specify that their code can't be hijacked for proprietary purposes *in distributed programs*. I will specifically point out that there is *nothing* in the GPL that requires you to reveal the source of program you write but do not distribute, even when such programs incorporate tons of GPL'd code. > It's actually even worse: the only thing you can't share on a > well-known vendor's platform is the software written by that > well-known vendor -- you can choose to share or choose not to > share whatever you or other people write on this platform. > Well that's way over-simplified. And if you mean Microsoft, *say*( Microsoft. And you certainly can't share GPL'd code on Windows without doing so under the terms required by the GPL. > If GPL folks had their way, it would not be possible not to "share" > _anything_ you create. It is widely acknowledged that GPL > license has the "viral" aspect of extending itself on your > software - can you point to closed-source licenses that would > have this aspect? None of the licenses I've read except GPL has > this aspect. LGPL is still a different story, though. > The GPL folks are quite happy to have you "share" anything that *you* create. Their simply-stated and elegantly-achieved intent is that you don't "share" anything that *they* create except on the terms they have required for their creations. So, it seems to me, you are whining because the authors of GPL'd code don't want you to release *their* code except under the GPL. What gives *you* the right to dictate to them? How would you like it if Richard Stallman insisted that you release your code under the GPL? Which, of course, he doesn't. > >> As the MPAA knows, people do want to share, and >>forcing them not to do so is impossible without turning the world into >>a police state. > Socialism is unpopular for many reasons, and many of them are indeed to do with maintaining the separation between individuals and thereby retaining the ability to treat them as separate economic units. But we aren't going to change that by insisting on particular software licenses. Realize this is a very small part of a very large debate. > > What's the cost of copying music files vs cost of combining > some programs together, even in the form of e.g. using an > external library? > > >>Maybe if Python were GPL, then Bulba wouldn't use it, >>but since it's not GPL, some people find themselves much less willing >>to contribute to it than if it were GPL. > And that is their choice. They should realize, however, that some licenses (including the more recent Python licenses) are cleared as "GPL-compatible". I believe this means that if I receive software licensed under a GPL-compatible license, I am at liberty to distribute it under the GPL. I suspect that this point is far too infrequently stressed. > > Personally, I have precisely opposite impression: the OSS licensed > with BSD/MIT/Artistic/Python-like license gets contributed to a lot > simply because people like to use it and they are not afraid of > licensing issues. > This merely goes to show that different people can form different impressions when discussing the same sets of facts, and therefore how useless impressions are as the basis for rational discussion. > When people share: > > _it is not because this or that license of software used by them says > so, but because they want to for reasons orthogonal to licensing > issues_. > Absolutely not. Some people want to share under very specific conditions, hence the proliferation of licenses in the open source world. > >>(I myself contribute bug >>reports and maybe small patches, but resist larger projects since >>there are GPL'd things that I can do instead). So catering to the >>wishes of Bulba and Microsoft may actually be impeding Python >>development. Yes, there are some people selfless enough to do long >>and difficult unpaid software tasks so that Bulba and Bill G can get >>richer by stopping people from sharing it, but others of us only want >>to do unpaid programming if we can make sure that the results stay >>available for sharing. > > > Actually, I get the impression that GPL-ed software is written by > programmers for programmers, not really for end users. > Not at all. It's written to be redistributed under specific terms, and anyone who doesn't like those terms has the option of redeveloping the functionality for themselves. You can't insist that people give you their intellectual property on *your* terms. That would be like insisting that the music industry bring down the price of their clearly-overpriced products, or that the Baltimore Orioles stop the concession stands from charging $4.50 for a one-dollar beer. If you want a vote in such situations then your feet are the appropriate instrument. Walk away, and stop whining :-). Insisting will do you no good. > GPL folks just insulate themselves in their ghetto from the rest > of the world. More and more of the successful OSS projects have > non-GPLed licenses: Apache, Postgres, Perl, Mozilla, Python. Do you > _really_ see few contributions made to those? > > More and more? Can we see some numbers to support this "impression"? > > -- > It's a man's life in a Python Programming Association. Since I'm taking issue with you, I will end by gently pointing out that there's a substantial minority (? - my impression) of people who might find your tag line (which I am sure is intended to be supportive of Python and the c.l.py ethic, such as we might agree exists), gender-biased and therefore just as unacceptable to them as the GPL appears to be to you. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From ialbert at mailblocks.com Fri Jan 14 11:05:37 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 14 Jan 2005 11:05:37 -0500 Subject: Integration with java In-Reply-To: References: Message-ID: Joachim Boomberschloss wrote: > the code is already written in Python, using the > standard libraries and several extension modules One thing to keep in mind is that Jython does not integrate CPython, instead it "understands" python code directly. So if you have a C extension that works with python it won't work with Jython. My feeling is that if you had a lot of Java code written and wanted to build on that with python Jython would be a better fit than vice versa. Istvan. From matternc at comcast.net Mon Jan 24 11:24:37 2005 From: matternc at comcast.net (Chris Mattern) Date: Mon, 24 Jan 2005 11:24:37 -0500 Subject: [perl-python] 20050124 classes & objects References: <1106578456.705117.74220@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > Perl does not support classes or > objects in the so-called "Object > Oriented" programing. Boy, the ignorance never stops, does it? > However, a > complete set of emulations of OO > style of programing have been done, > resulting in modules and books and > many documentations and tutorials. > It doesn't have OO, but it emulates in software! Better go with python, which has hardware OO. :-) -- Christopher Mattern "Which one you figure tracked us?" "The ugly one, sir." "...Could you be more specific?" From duncan.booth at invalid.invalid Mon Jan 24 04:02:27 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Jan 2005 09:02:27 GMT Subject: best way to do a series of regexp checks with groups References: Message-ID: Mark Fanty wrote: > No nesting, but the while is misleading since I'm not looping and this > is a bit awkward. I don't mind a few more key strokes, but I'd like > clarity. I wish I could do > > if m = re.search(r'add (\d+) (\d+)', $line): > do_add(m.group(1), m.group(2)) > elif m = re.search(r'mult (\d+) (\d+)', $line): > do_mult(m.group(1), m.group(2)) > else m = re.search(r'help (\w+)', $line): > show_help(m.group(1)) > > Now that's what I'm looking for, but I can't put the assignment in an > expression. Any recommendations? Less "tricky" is better. Try thinking along the following lines. It is longer, but clearer and easily extended to more commands. For more complete command processing use the 'cmd' module. import sys class Command: def do_add(self, a, b): '''add ''' return int(a)+int(b) def do_mult(self, a, b): '''mult ''' return int(a)*int(b) def do_help(self, *what): '''help [words] - give some help''' if not what: what = sorted(s[3:] for s in dir(self) if s.startswith('do_')) def error(): '''Unknown command''' for w in what: cmd = getattr(self, 'do_'+w, error) print "Help for %r:\n%s\n" % (w, cmd.__doc__) def do_exit(self): '''exit - the program''' sys.exit(0) def __call__(self, line): words = line.split() if not words: return command = words.pop(0) cmdfn = getattr(self, 'do_'+command, None) if not cmdfn: print "Unknown command %r. Use 'help' for help" % command return result = None try: result = cmdfn(*words) except TypeError, msg: print msg if result is not None: print "result is",result cmd = Command() while 1: cmd(sys.stdin.readline()) From usenet_spam at janc.invalid Mon Jan 3 04:01:07 2005 From: usenet_spam at janc.invalid (JanC) Date: Mon, 03 Jan 2005 09:01:07 GMT Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: Ron Garret schreef: > But this topic does bring up a legitimate question: I have a bunch of > code that generates HTML using PRINT statements. I need to convert all > this code to return strings rather than actually printing them (so I can > use the results to populate templates). In Lisp I could do this: > > (with-output-to-string (s) > (let ( (*standard-output* s) ) > (call-html-generating-code) > s)) > > Is there an equivalent Python trick to capture a function call's output > as a string? Something like this: py> import cStringIO py> import sys py> py> def foo(): ... print "test" ... py> f = cStringIO.StringIO() py> sys.stdout = f py> foo() py> s = f.getvalue() py> sys.stdout = sys.__stdout__ py> f.close() py> print s.capitalize() Test -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From lbates at syscononline.com Thu Jan 13 20:39:49 2005 From: lbates at syscononline.com (Larry Bates) Date: Thu, 13 Jan 2005 19:39:49 -0600 Subject: newbie ?s In-Reply-To: <1105656971.768148@sj-nntpcache-5> References: <1105656971.768148@sj-nntpcache-5> Message-ID: You should probably take a look at: http://www.amk.ca/python/code/medusa Larry Bates Syscon, Inc. Venkat B wrote: > Hi folks, > > I'm looking build a CGI-capable SSL-enabled web-server around Python 2.4 on > Linux. > It is to handle ~25 hits possibly arriving "at once". Content is non-static > and built by the execution of py cgi-scripts talking to a few backend > processes. > > 1) I was wondering if anyone has opinions on the ability of CGIHTTPServer (a > forking variant) to be able to handle this. > 2) If so, would something like pyOpenSSL be useful to make such a webserver > SSL-enabled. > > I checked out John Goerzen's book: Foundations of Python Network Programming > (ISBN 1590593715) and searched around. While I found how one can write py > scripts that could communicate with SSL-enabled webservers, tips on building > SSL-enabled webservers isn't obvious. > > I was hoping to build a cleaner solution around the CGIHTTPServer variant > instead of say something like mini-httpd/OpenSSL/Python. I'd appreciate any > pointers. > > TIA, > /venkat > > > > From theller at python.net Tue Jan 11 15:05:03 2005 From: theller at python.net (Thomas Heller) Date: Tue, 11 Jan 2005 21:05:03 +0100 Subject: appending data to an xml file Message-ID: I want to append/insert additional data to an xml file. Context: I use gccxml to parse C header files. gccxml creates an xml file containing all the definitions from the header files. The xml files may be somewhat largish, for 'windows.h' it has more than 5 MB. Since the xml does not contain #define statements, I want to run gccxml again with the --preprocess and -dM flags, which dumps out the #define'd symbols. I want this information also to be in the same file, but simply appending it to the xml smells hackish, and I don't know if the latter xml parsing stage can get this additional data with an error handler, or somehow else. Maybe I can find the end of the xml data myself, before giving it to the sax parser. Better, imo, would be to add the dumped info into a proper xml tag, and inject it into the original file. Is that (efficiently) possible? Thomas From david.tolpin at gmail.com Mon Jan 24 10:02:08 2005 From: david.tolpin at gmail.com (david.tolpin at gmail.com) Date: 24 Jan 2005 07:02:08 -0800 Subject: What is print? A function? In-Reply-To: References: Message-ID: <1106578928.307172.107910@c13g2000cwb.googlegroups.com> > Is it possible to create own statements, such that it would be possible to do: > > printDebug "test" > > ? This question is well addressed in a neighbour group comp.lang.lisp . From steve at holdenweb.com Wed Jan 12 18:06:04 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 12 Jan 2005 18:06:04 -0500 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: <7xoefuenqn.fsf@ruckus.brouhaha.com> References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <1105509379.301556.178130@z14g2000cwz.googlegroups.com> <7xoefuenqn.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > michele.simionato at gmail.com writes: > >>>I can't imagine how it could be worse than the learning curve of >>>__metaclass__, which we already have. >> >>To me, learning macros *and their subtilities* was much more difficult >>than learning metaclasses. > > > I guess I've only used Lisp macros in pretty straightforward ways, > that weren't hard to understand. That's enough for anything I've > needed. But we don't hear much about __metaclass__ because almost > nobody understands it. > Paraphrasing Tim Peters, "if you don't definitely know that you need metaclasses then you almost certainly don't". The primary reason for the existence of metaclasses is as an implementation detail that allows basic Python types to be base classes for inheritance. Python could have hidden this mechanism, but the generally introspective nature of the language makes it sensible to expose the mechanism for (ab)use by knowledgeable users. > >>Go to comp.lang.scheme and google for "macros and module system"; >>you will get everything you want to know and much more! > > > OK, I might do this. > Well I'd be interested to know what you find out, not being a Lisper myself. > >>Well, I see this as a positive fact. If a syntax is contrived (such >>as a ternary operator, for instance) it is better *not* to have it >>than to have one hundred custom made syntaxes. At the end, we are >>just talking about syntax sugar here, not about lack of >>functionality. > > > I think the idea is there would be some experimentation and then one of > the versions would make it into the standard library. > Erm, you'd put syntax into a library module? That would be in __future__, I take it? > >>>[compiling Lisp to Python bytecode] >> >>This is a bizarre idea if you want to make Python run faster. It is >>not so bizarre if what you want is to have access to Python from >>Lisp/Scheme in the same sense Jython has access to Java. > > > Why not just use a foreign function interface? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From sam.wun at authtec.com Sun Jan 9 21:11:16 2005 From: sam.wun at authtec.com (sam) Date: Mon, 10 Jan 2005 10:11:16 +0800 Subject: Powerful CGI libraries for Python? Message-ID: Hi, I m looking for a CGI libraries just like perl's CGI.pm for Python. From google, I found quite a few of CGI libraries already written for python. But I haven't had experience to try any of them in Python. Can anyone share your Python CGI experience with me? Which library is better in terms of functionality and stability? Thanks Sam From martinnitram at excite.com Wed Jan 19 21:40:13 2005 From: martinnitram at excite.com (martinnitram at excite.com) Date: 19 Jan 2005 18:40:13 -0800 Subject: safest way to kill a thread In-Reply-To: <05WdnRFlE52Z7HPcRVn-gg@powergate.ca> References: <1106106497.429643.307440@f14g2000cwb.googlegroups.com> <1106115159.200989.60870@c13g2000cwb.googlegroups.com> <1106121882.809441.12670@z14g2000cwz.googlegroups.com> <05WdnRFlE52Z7HPcRVn-gg@powergate.ca> Message-ID: <1106188813.173214.190480@c13g2000cwb.googlegroups.com> Thank for all helping and sorry that i overlooked the previous message. Peter Hansen wrote: > martinnitram at excite.com wrote: > > Should the 'daemonic' flag at setDaemon() function set to 1/TRUE or > > 0/FALSE to do such action? > > First of all, it's "True" and "False" in Python, not TRUE > and FALSE. > > Secondly, the answer to the question was in the previous > message where "limodou" told you about this in the first > place. Go back and read it again... > > -Peter From usenet_spam at janc.invalid Sat Jan 1 23:47:16 2005 From: usenet_spam at janc.invalid (JanC) Date: Sun, 02 Jan 2005 04:47:16 GMT Subject: OT: spacing of code in Google Groups References: Message-ID: Terry Reedy schreef: > "JanC" wrote in message > news:Xns95D132B172343JanC at 213.118.32.224... >> I don't know if gmane keeps formating of messages intact when >> posting? That could be an alternative too... > > Reading posts via gmane with Outlook Express preserves leading spaces > just fine. However, OE deletes tabs regardless of what newsgroup > does. OE is useless anyway (at least as a newsreader). I was talking about the gmane web interface as an alternative to Google's. They have an NNTP server but also three http-based interfaces: RSS-feed, blog-style & framed (looks more or less like a newsreader). ... Tested it in gmane.test, posting through their web interface preserves whitespace. -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From michele.simionato at gmail.com Tue Jan 25 06:32:33 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 25 Jan 2005 03:32:33 -0800 Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) In-Reply-To: References: Message-ID: <1106652753.936349.143850@z14g2000cwz.googlegroups.com> >Name mangling is there to keep you from accidentally hiding such an >attribute in a subclass, but how often is this really a danger? Can >someone give me an example of where __-mangling really solved a problem >for them, where a simple leading underscore wouldn't have solved the >same problem? Look at the "autosuper" implementation on Guido's descrintro paper; there the fact that you user __super instead of _super is essential. However I have written tens of thousands of lines of Python code and never needed __protected variables except in a few experimental scripts for learning purpose. So I agree that the need does not occur often, but it is still an useful thing to have. Michele Simionato From bhoel at despammed.com Wed Jan 5 17:30:07 2005 From: bhoel at despammed.com (=?iso-8859-15?q?Berthold_H=F6llmann?=) Date: Wed, 05 Jan 2005 23:30:07 +0100 Subject: Building unique comma-delimited list? References: Message-ID: roy at panix.com (Roy Smith) writes: > I've got a silly little problem that I'm solving in C++, but I got to > thinking about how much easier it would be in Python. Here's the > problem: > > You've got a list of words (actually, they're found by searching a > data structure on the fly, but for now let's assume you've got them as > a list). You need to create a comma-delimited list of these words. > There might be duplicates in the original list, which you want to > eliminate in the final list. You don't care what order they're in, > except that there is a distinguised word which must come first if it > appears at all. > > Some examples ("foo" is the distinguised word): > > ["foo"] => "foo" > ["foo", "bar"] => "foo, bar" > ["bar", "foo"] => "foo, bar" > ["bar", "foo", "foo", "baz", "bar"] => "foo, bar, baz" or "foo, baz, bar" > > The best I've come up with is the following. Can anybody think of a > simplier way? ... How about: .>>> words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"] .>>> ', '.join(dict( ( (w,w) for w in words ) ).keys()) 'baz, foo, bar' .>>> words = ["foo",] .>>> ', '.join(dict( ( (w,w) for w in words ) ).keys()) 'foo' or with Python 2.3 or higher: .>>> import sets .>>> words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"] .>>> ', '.join(sets.Set(words)) 'baz, foo, bar' .>>> words = ["foo",] .>>> ', '.join(sets.Set(words)) 'foo' Kind regards Berthold -- berthold at xn--hllmanns-n4a.de / bhoel at web.de / From sp1d3rx at gmail.com Tue Jan 11 16:34:52 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 11 Jan 2005 13:34:52 -0800 Subject: Time script help sought! In-Reply-To: <1105477084.525279.312970@f14g2000cwb.googlegroups.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> <1105477084.525279.312970@f14g2000cwb.googlegroups.com> Message-ID: <1105479292.689762.155510@f14g2000cwb.googlegroups.com> post your script here so we can go over it with you. From http Fri Jan 28 08:01:39 2005 From: http (Paul Rubin) Date: 28 Jan 2005 05:01:39 -0800 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> <7x3bwlsqnj.fsf@ruckus.brouhaha.com> Message-ID: <7x8y6diu6k.fsf@ruckus.brouhaha.com> Duncan Booth writes: > SF doesn't seem to know about any such bug any more. > Google finds me > http://mail.python.org/pipermail/python-bugs-list/2001-October/007669.html > which appears to be SF bug 467384, but it says nothing about security or > the Cookie module, just that you wanted better documentation. The Cookie issue is discussed some in that bug thread. But more relevant is bug 471893. Sorry. > I think its a bit borderline whether this really was a security bug in > Python rather than just a problem with the way some people used Python. If using a module the way it's documented results in a security hole, that's definitely a security bug. If using the module in an obvious and natural way that looks correct results in a security hole, I'd say it's at least an issue needing attention, even if some sufficiently hairsplitting reading of the documentation says that usage is incorrect. Principle of least astonishment. I highly recommend reading the book "Security Engineering" by Ross Anderson if you're trying to implement anything that might ever be exposed to malicious parties. That includes any application that communicates over the internet (such as web servers or clients), and it includes any application that processes data downloaded from the internet (such as jpeg viewers). Each of those classes of programs has had examples of where hostile data could take over the application. From jason.b.burke at abbott.com Thu Jan 20 11:23:03 2005 From: jason.b.burke at abbott.com (Jason B Burke) Date: Thu, 20 Jan 2005 10:23:03 -0600 Subject: sys.stdin and idle bug? Message-ID: Greetings All, I apologize if this has been brought up before, but I'm having a small issue with the handling of sys.stdin in Idle. I'm using a routine to mimic the c library function getch(), to get a single character from the keyboard. The function works in the standard python shell, but in Idle I get an error when I try to reference sys.stdin.fileno(). Within the standard shell sys.stdin is a file object with a mode of 'r'. Looks like this in the interpreter: ', mode 'r' at 0xSome_address> However, in Idle the object is quite different: and typing sys.stdin.fileno() returns an AttributeError: fileno. Is this a bug in idle, or is this normal? If it's normal is there a work around for it? Thanks for any replies and references to more info on this issue. Sincerely, Jason Burke -------------- next part -------------- An HTML attachment was scrubbed... URL: From ncoghlan at iinet.net.au Sun Jan 9 06:23:14 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 21:23:14 +1000 Subject: python3: 'where' keyword In-Reply-To: <34ch7gF45vrjoU1@individual.net> References: <3480qqF46jprlU1@individual.net> <34ch7gF45vrjoU1@individual.net> Message-ID: <41E11422.5070700@iinet.net.au> Andrey Tatarinov wrote: > sorry, I used "expression" carelessly. > > I mean that > >>> print words[3], words[5] > is a single expression > (and that would be in Python 3, when print would be subtituted with > write()/writeln()). 'statement' is the appropriate word in Python's grammar. And I don't think we'd actually have to wait for Python 3 for this, we'd just have to do the __future__ dance in order to introduce the new keyword. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tjreedy at udel.edu Sat Jan 8 05:39:41 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 8 Jan 2005 05:39:41 -0500 Subject: Getting rid of "self." References: <740c3aec05010705393048a374@mail.gmail.com> Message-ID: "BJ?rn Lindqvist" wrote in message news:740c3aec05010705393048a374 at mail.gmail.com... >I think it would be cool if you could refer to instance variables >without prefixing with "self." Others have expressed such a wish -- this comes up perhaps once a year. The bottom line is that as long as Python has separate instance and local namespaces with possibly duplicate names, then there must be a way to tell which namespace a name should be looked up in. The current system is completely consistent with Python's object.attribute system. It would be odd if instance attributes were referred to differently in module level code and function level code. Terry J. Reedy From bob_smith_17280 at hotmail.com Tue Jan 11 21:05:04 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Tue, 11 Jan 2005 21:05:04 -0500 Subject: a new Perl/Python a day In-Reply-To: <34ism6F4athpcU1@individual.net> References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> <87r7ku3pwq.fsf@mithril.chromatico.net> <34ism6F4athpcU1@individual.net> Message-ID: Peter Maas wrote: > Charlton Wilbur schrieb: > >>>>>>> "XL" == Xah Lee writes: >> >> >> >> XL> i'll cross post to comp.lang.perl.misc and comp.lang.python. >> XL> If you spot mistakes, feel free to correct or discourse here. >> >> Error #1: crossposting to those two groups. >> (Error #2 is implying that you're a Perl expert, but someone else >> already pointed that out.) > > > Xah Lee is the guy who used to fight Unixism some time ago thereby > producing an extremly long and useless thread in this group. Now > he's fighting Perl :) Please stop answering him if you don't want > to waste your time. > With terms such as "blabbering Unix donkeys" and "sloppy perl monkeys" Xah's articles are very entertaining. He has some valid points as well... he just presents them in anti-social ways. From kartic.krishnamurthy at gmail.com Fri Jan 14 08:56:16 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 14 Jan 2005 05:56:16 -0800 Subject: Using Sqlite with Python under Windows In-Reply-To: References: Message-ID: <1105710976.907378.193400@c13g2000cwb.googlegroups.com> Michael Goettsche wrote: > I succeeded in convincing my CS teacher to use Python and Sqlite instead of > Microsoft Access to get started with databases. > We are working on a windows terminal server to which I have no admin access, > so I'd like to ask you which module is best suited to use Sqlite with Python > under windows. The best would be a module which is easy to install without > further dependencies. Michael, I posted this morning but I don't know what happened to my post! In any case, PySqlite is the distribution I have used and is available at pysqlite.org. I believe there is another module called APSW (Another Python Sqlite Wrapper) available, that I stumbled upon just today, after reading your post. Home page : http://www.rogerbinns.com/apsw.html Please read the section "pysqlite differences" to see which one you want to install. As for installation, it should be as simple as downloading the win32 binaries for your Python distro and executing it. I do not have admin rights on my Win2K PC at work, but it installed and worked just fine. So, you should not have any problem. You will not have to install anything additional other the python-sqlite module itself. Good choice on selecting Sqlite..I love it and hope you will enjoy it too! Thanks, --Kartic From kartic.krishnamurthy at gmail.com Thu Jan 27 16:29:47 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 27 Jan 2005 13:29:47 -0800 Subject: Problem with win32net on Windows 2K In-Reply-To: References: Message-ID: <1106861387.838837.204910@z14g2000cwz.googlegroups.com> Thomas, I have a Win2K machine and win32net imports just fine. Here is what I did - started python shell with the -v switch and imported win32net. This is what it says: py>>> import win32net # c:\python24\lib\encodings\cp437.pyc matches c:\python24\lib\encodings\cp437.py import encodings.cp437 # precompiled from c:\python24\lib\encodings\cp437.pyc import win32net # dynamically loaded from C:\Python24\Lib\site-packages\win32\win32net.pyd I tried this on Python 2.4, pywin32 build 203 and Win2k Version 5.00.2195 SP 4. What version of Python are you using? Do you have the Python-version corresponding version of the pywin32 extensions installed? Another item you may want to check is if your PYTHONPATH is correct. Are you able to import other win32 components correctly, for example, win32com.client? Here is my Pythonpath: c:\python24;c:\python24\lib;c:\python24\scripts;C:\Python24\Lib\site-packages\wi n32;C:\Python24\Lib\site-packages\win32\lib;C:\Python24\Lib\site-packages\Python win;C:\WorkArea\Python / Thanks, --Kartic From terti at mighty.co.za Tue Jan 18 15:13:00 2005 From: terti at mighty.co.za (tertius) Date: Tue, 18 Jan 2005 22:13:00 +0200 Subject: hex notation funtion In-Reply-To: References: Message-ID: <5-qdnXvCHr1L8HDcRVn-tQ@is.co.za> tertius wrote: > Hi, > > Is there a builtin function that will enable me to display the hex > notation of a given binary string? (example below) > Thanks all. From stephen.thorne at gmail.com Sat Jan 29 09:37:09 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Sun, 30 Jan 2005 00:37:09 +1000 Subject: The next Xah-lee post contest In-Reply-To: <5a309bd305012905357e14df62@mail.gmail.com> References: <5a309bd305012905357e14df62@mail.gmail.com> Message-ID: <3e8ca5c80501290637403b9ce5@mail.gmail.com> On Sat, 29 Jan 2005 19:05:55 +0530, Steve wrote: > Hi All, > For sometime now, I have just been a passive lurker on this > list. Of late I saw an increase in the number of posts by Xah Lee, and > I have to admit, what he lacks in understanding of the various > programming languages he talks about, he makes up for in creativity. > So, I was wondering, how would it be to be Mr Lee. That got me > thinking of his next post. Well, I know through my days of lurking > around, a lot of people here love creative challenges ...so here's one > for you. Write up the next Xah Lee post ! The requirement are: > a) The post should talk about a single language, although the example > code needn't adhere to that restriction. > b) It should explain the style, structure and design of some code > snippet/program, though not necessarily of the same code > snippet/program mentioned in the post. > c) Should be written in English ... respect to English grammar is not mandatory. > d) It *must* be flammable. If you need to do more research for the posting style, I recommend the following links: http://netscan.research.microsoft.com/Static/author/authorProfile.asp?searchfor=xah%40xahlee.org http://groups-beta.google.com/groups?q=%22Xah+Lee%22 Interesting to note that xah posted as far back as '02 asking for help with python, as he was porting perl web applications. Which leads me to conclude he is not a beginner being stupid, but somone who has been around long enough to know better. Stephen. From jeremy+plusnews at jeremysanders.net Fri Jan 7 12:38:26 2005 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Fri, 07 Jan 2005 17:38:26 +0000 Subject: how to extract columns like awk $1 $5 References: Message-ID: On Fri, 07 Jan 2005 12:15:48 -0500, Anand S Bisen wrote: > Is there a simple way to extract words speerated by a space in python > the way i do it in awk '{print $4 $5}' . I am sure there should be some > but i dont know it. mystr = '1 2 3 4 5 6' parts = mystr.split() print parts[3:5] Jeremy From gstoyanoff at gmail.com Fri Jan 28 09:55:06 2005 From: gstoyanoff at gmail.com (g_xo) Date: Fri, 28 Jan 2005 09:55:06 -0500 Subject: Hello In-Reply-To: <351e887105012723467f3eb873@mail.gmail.com> References: <1106898375.3909.9.camel@albert.localnet> <351e887105012723467f3eb873@mail.gmail.com> Message-ID: Hi guys, Thank you for your help once I put my isp news server as the server I was able to get access to comp.lang.python. Thank you for your help :) George On Fri, 28 Jan 2005 13:16:48 +0530, Swaroop C H wrote: > > Most ISPs provide > > news servers, often at 'news.ispname.net' if the ISP is 'ispname.net'. > > You need to get the correct details of which news server to use from > > your ISP and configure your newsreader to use that. Once your newsread > > is talking correctly to your ISP's news server, *then* you can subscribe > > to comp.lang.python. > > If you can't find a Usenet server, try news.gmane.org > > > -- > Swaroop C H > Blog: http://www.swaroopch.info > Book: http://www.byteofpython.info > -- George +------------------------------------------------+ Linux - the future is free +------------------------------------------------+ From fredrik at pythonware.com Mon Jan 31 15:05:48 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 31 Jan 2005 21:05:48 +0100 Subject: [ANN] Spike Asset Manager release 0.13 References: <1107196878.026930.154270@c13g2000cwb.googlegroups.com> <16894.36152.345508.583247@montanaro.dyndns.org> Message-ID: Skip Montanaro wrote: > Matt> Spike Asset Manager (SAM) is an open-source cross-platform > Matt> framework written in python for probing a system for components > Matt> and reporting them. > > That's a pretty generic description. Pardon my ignorance, but what's the > advantage over, for example, "rpm -aq | grep httpd"? C:\>rpm -aq | grep httpd 'rpm' is not recognized as an internal or external command, operable program or batch file. (on the other hand, it doesn't find any Python installation on my machine, which I do find a bit strange...) From steven.bethard at gmail.com Mon Jan 10 11:47:22 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 10 Jan 2005 09:47:22 -0700 Subject: syntax error in eval() In-Reply-To: References: Message-ID: harold fellermann wrote: > Python 2.4 (#1, Dec 30 2004, 08:00:10) > [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> class X : pass > ... > >>> attrname = "attr" > >>> eval("X.%s = val" % attrname , {"X":X, "val":5}) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 1 > X.attr = val > ^ > SyntaxError: invalid syntax You may want to use exec instead of eval: py> class X(object): ... pass ... py> attrname = "attr" py> exec "X.%s = val" % attrname in dict(X=X, val=5) py> X.attr 5 But personally, I'd use setattr, since that's what it's for: py> class X(object): ... pass ... py> attrname = "attr" py> setattr(X, attrname, 5) py> X.attr 5 Steve From steve at holdenweb.com Mon Jan 3 21:19:05 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 03 Jan 2005 21:19:05 -0500 Subject: Advice request for project In-Reply-To: References: <41D957B1.3040500@holdenweb.com> Message-ID: Peter Hansen wrote: > Steve Holden wrote: > >> Look at the Pyrex package to get you started thinking about remote >> execution and client/server communications. This lets a program on one >> machine call methods on objects on another machine. > > > Steve meant to say "Pyro", not "Pyrex". The former is what > he actually described. The latter is actually a Python-like > language that lets one write code that can be compiled as > an extension module, to write performance-critical code or > interface to existing libraries more easily. > > Correct, Python Remote Objects is indeed what I meant. Thanks, Peter. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From hat at se-126.se.wtb.tue.nl Wed Jan 12 07:36:57 2005 From: hat at se-126.se.wtb.tue.nl (Albert Hofkamp) Date: Wed, 12 Jan 2005 12:36:57 +0000 (UTC) Subject: distutils linux script installation broken? References: Message-ID: On Wed, 12 Jan 2005 10:09:03 +0000, Cory Davis wrote: > command has been behaving badly. In the part where it is supposed to > adjust the first line of the script it now produces > > #!None > > instead of > > #!/whereverpythonis/python > > Has anyone else encountered this? I haven't (as I am not using 2.4 :-) ) However, there is an easy way around this, just use #!/usr/bin env python instead. Albert -- Unlike popular belief, the .doc format is not an open publically available format. From steven.bethard at gmail.com Fri Jan 14 18:17:53 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 14 Jan 2005 16:17:53 -0700 Subject: (objects as) mutable dictionary keys In-Reply-To: References: Message-ID: Peter Maas wrote: > I have summarized the discussion about the usability of lists (and > and other mutable types) as dictionary keys and put it into the > Python wiki.URL: http://www.python.org/moin/DictionaryKeys. Antoon Pardon wrote: > I had a look and I think you should correct the followingr: > > Dictionary lookup with mutable types like lists is a source of > unpleasant surprises for the programmer and therefore impossible in > Python. > > It is not impossible in Python. It may be discouraged but it is not > impossible since I have already done so. John Roth wrote: > The last piece has an incorrect conclusion. Lists are not safe > _because_ the cmp function is NOT a compare of id(list), but > is based on list contents, which can change at any time. > > It should also be emphasized that the default instance hash > and cmp functions quoted make it impossible for two different > instances to compare equal, thus there is no reason to store them > as dictionary keys: it's simpler to make the value an attribute of > the instance and bypass the additional complexity of the dictionary. Note that Peter Maas has put this up on the Python wiki, so if you find things that are wrong or inaccurate, don't hesitate to correct them yourselves. =) That said, I just made a few substantial edits that may have at least partially resolved your concerns. Steve From deetsNOSPAM at web.de Fri Jan 28 10:57:37 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 28 Jan 2005 16:57:37 +0100 Subject: Dynamic class methods misunderstanding References: Message-ID: <35v5jdF4rk3m7U1@individual.net> > > Why doesn't m get the implicit self parameter in the self.method() > call? How would I make it a proper member of the class, so that a > self.method() call would work with the above "m" function? Use new.instancemethod: import new class Test: def __init__(self, method): self.m = new.instancemethod(method, self, Test) def m(self): print self Test(m).m() -- Regards, Diez B. Roggisch From peter at somewhere.com Tue Jan 11 15:51:34 2005 From: peter at somewhere.com (Peter Maas) Date: Tue, 11 Jan 2005 21:51:34 +0100 Subject: a new Perl/Python a day In-Reply-To: <87r7ku3pwq.fsf@mithril.chromatico.net> References: <1105315487.389577.254460@c13g2000cwb.googlegroups.com> <87r7ku3pwq.fsf@mithril.chromatico.net> Message-ID: <34ism6F4athpcU1@individual.net> Charlton Wilbur schrieb: >>>>>>"XL" == Xah Lee writes: > > > XL> i'll cross post to comp.lang.perl.misc and comp.lang.python. > XL> If you spot mistakes, feel free to correct or discourse here. > > Error #1: crossposting to those two groups. > > (Error #2 is implying that you're a Perl expert, but someone else > already pointed that out.) Xah Lee is the guy who used to fight Unixism some time ago thereby producing an extremly long and useless thread in this group. Now he's fighting Perl :) Please stop answering him if you don't want to waste your time. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From grante at visi.com Mon Jan 17 11:52:08 2005 From: grante at visi.com (Grant Edwards) Date: 17 Jan 2005 16:52:08 GMT Subject: List problems in C code ported to Python References: Message-ID: <41ebed38$0$87063$a1866201@visi.com> On 2005-01-17, Lucas Raab wrote: > data[4][j] = ((int)ref_rotor[j]-'A'+26)%26; > data[4],[j] = (ref_rotor[j] - 'A'+26) % 26 ^ The comma shouldn't be there. C: data[4][j] Python: data[4][j] > Now, do I need to start boning up on lists and how to use them Sort of. I think you mostly just need to sit down and proofread your code. I would also advise building your Python app in smaller steps. Translate one function, and test it to make sure it works. Then translate the next function and test it to make sure it works. Then the next function, etc. -- Grant Edwards grante Yow! My ELBOW is a remote at FRENCH OUTPOST!! visi.com From DoubleMPi at Netscape.com Tue Jan 25 18:23:16 2005 From: DoubleMPi at Netscape.com (Mike Moum) Date: Tue, 25 Jan 2005 23:23:16 GMT Subject: string.atoi and string.atol broken? Message-ID: I think there may be a bug in string.atoi and string.atol. Here's some output from idle. > Python 2.3.4 (#2, Jan 5 2005, 08:24:51) > [GCC 3.3.5 (Debian 1:3.3.5-5)] on linux2 > Type "copyright", "credits" or "license()" for more information. > > **************************************************************** > Personal firewall software may warn about the connection IDLE > makes to its subprocess using this computer's internal loopback > interface. This connection is not visible on any external > interface and no data is sent to or received from the Internet. > **************************************************************** > > IDLE 1.0.4 >>>> import string as s >>>> s.atoi('2',3) > 2 >>>> s.atoi('4',3) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > s.atoi('4',3) > File "/usr/lib/python2.3/string.py", line 220, in atoi > return _int(s, base) > ValueError: invalid literal for int(): 4 >>>> s.atoi('12',11) > 13 >>>> s.atoi('13',4) > 7 >>>> s.atoi('12',4) > 6 >>>> s.atoi('8',4) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > s.atoi('8',4) > File "/usr/lib/python2.3/string.py", line 220, in atoi > return _int(s, base) > ValueError: invalid literal for int(): 8 >>>> s.atoi('4',3) should result in 11 s.atoi('13',4) should result in 31 s.atoi('12',4) should result in 30 s.atoi('8',4) is legitimate, but it generates an error. Is this a bug, or am I missing something obvious? TIA, Mike From Dennis.Benzinger at gmx.net Tue Jan 25 13:17:22 2005 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Tue, 25 Jan 2005 19:17:22 +0100 Subject: module for 'po' files In-Reply-To: References: Message-ID: <41f68d31$1@news.uni-ulm.de> Sara Fwd wrote: > Hi all > Is there a module for processing & handling '.po' > files in python? > [...] I don't know if there is a module for processing them, but Python comes with msgfmt.py (in Tools/i18n) which creates .mo files out of your .po files. So read the source and see if there's something in there which you can use! Bye, Dennis From ziongmail-py at yahoo.com Wed Jan 12 10:06:43 2005 From: ziongmail-py at yahoo.com (Ziong) Date: 12 Jan 2005 07:06:43 -0800 Subject: Newbie: module structure and import question Message-ID: <8fb821f9.0501120706.499dd04c@posting.google.com> hi all, i have question on how to design a module structure. for example, i have 3 files. [somewhere]/main.py [somewhere]/myLib/Base/BaseA.py [somewhere]/myLib/ClassA.py main.py ======= from myLib.ClassA import ClassA a = classA() dir(a) myLib/ClassA.py =============== from myLib.Base.BaseA import BaseA class ClassA(BaseA): def __init__(self): BaseA.__init__(self) print "classA" if (__name__ == "__main__"): print "test class A" a = ClassA() print a myLib/Base/BaseA.py =================== class BaseA: def __init__(self): print "BaseA" It's fine when i run main.py. however when i run ClassA.py individually, it would fail in import statment since the import path is incorrect. I would like to know is something wrong in my design, or something i missed. Also, in practical usage, is that one class in one py file? thx! a python newbie From newsgroups at jhrothjr.com Fri Jan 7 11:43:08 2005 From: newsgroups at jhrothjr.com (John Roth) Date: Fri, 7 Jan 2005 10:43:08 -0600 Subject: Getting rid of "self." References: <740c3aec05010705393048a374@mail.gmail.com> <1105114214.359029.152240@f14g2000cwb.googlegroups.com> Message-ID: <10ttf1slqmefi28@news.supernews.com> "Roy Smith" wrote in message news:crmdqk$jo6$1 at panix2.panix.com... > Simon Brunning wrote: >>On 7 Jan 2005 08:10:14 -0800, Luis M. Gonzalez wrote: >>> The word "self" is not mandatory. You can type anything you want >>> instead of self, as long as you supply a keyword in its place (it can >>> be "self", "s" or whatever you want). >> >>You *can*, yes, but please don't, not if there's any chance that >>anyone other than you are going to have to look at your code. >>'self.whatever' is clearly an instance attribute. 's.whatever' isn't >>clearly anything - the reader will have to go off and work out what >>the 's' object is. > > +1. > > If there is one coding convention which is constant through the Python > world, it's that the first argument to a class method is named > "self". Using anything else, while legal, is just being different for > the sake of being different. Didn't you mean instance method? Class methods are a different beast, and the few examples I've seen seem to use the word "klas". John Roth From fperez.net at gmail.com Sun Jan 9 05:39:20 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Sun, 09 Jan 2005 03:39:20 -0700 Subject: Display Function Code Body? References: <1105130263.788520.96710@f14g2000cwb.googlegroups.com> Message-ID: Haibao Tang wrote: > > Hail Python pals! I played with the R (http://r-project.cran.org) last > night to do some statistics and it has an interactive session too, and > I found a feature that is quite useful. [...] > # or any shallow function code from a file >>>> import calendar; disp(calendar.isleap) > > def isleap(year): > """Return 1 for leap years, 0 for non-leap years.""" > return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) > > > # surely the compiled function code cannot be displayed >>>> disp(blabla) > > : internal/compiled function > > > Can someone please point out how this can be achieved nicely. I've > tried some text searching approach, too dirty I must say. > Oh! Thank you ... [~/tmp]> ipython Python 2.3.4 (#1, Oct 26 2004, 16:42:40) Type "copyright", "credits" or "license" for more information. IPython 0.6.7_rc1 -- An enhanced Interactive Python. ? -> Introduction to IPython's features. %magic -> Information about IPython's 'magic' % functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: import calendar In [2]: calendar.isleap?? Type: function Base Class: String Form: Namespace: Interactive File: /usr/src/build/475206-i386/install/usr/lib/python2.3/calendar.py Definition: calendar.isleap(year) Source: def isleap(year): """Return 1 for leap years, 0 for non-leap years.""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) Note that the source display won't work for interactively defined functions, because their source is thrown away by the bytecode compiler. There are discussions of a PEP for adding a __source__ attribute to functions which would solve this limitation, but that is still in the future. Cheers, f From xah at xahlee.org Wed Jan 26 14:19:00 2005 From: xah at xahlee.org (Xah Lee) Date: 26 Jan 2005 11:19:00 -0800 Subject: [perl-python] 20050126 find replace strings in file Message-ID: <1106767140.027944.93380@c13g2000cwb.googlegroups.com> ? # -*- coding: utf-8 -*- ? # Python ? ? import sys ? ? nn = len(sys.argv) ? ? if not nn==5: ? print "error: %s search_text replace_text in_file out_file" % sys.argv[0] ? else: ? stext = sys.argv[1] ? rtext = sys.argv[2] ? input = open(sys.argv[3]) ? output = open(sys.argv[4],'w') ? ? for s in input: ? output.write(s.replace(stext,rtext)) ? output.close() ? input.close() ------------------------- save this code as find_replace.py run it like this: python find_replace.py findtext replacetext in_file out_file the sys.argv is from sys. sys.argv[0] is the program's name itself. note the idiom "for variable_name in file_object" note that since this code reads each line in turn, so huge file is of no-problemo the code is based from Python Cookbook of Alex Martelli & David Ascher, page 121 in Python terminal, type help() then 'FILES' and or 'sys' for reference. try to modify this file for your needs. -------------------------------------- In perl, similar code can be achieved. the following code illustrates. if (scalar @ARGV != 4) {die "Wrong arg! Unix BNF: $0 \n"} $stext=$ARGV[0]; $rtext=$ARGV[1]; $infile = $ARGV[2]; $outfile = $ARGV[3]; open(F1, "<$infile") or die "Perl fucked up. Reason: $!"; open(F2, ">$outfile") or die "Perl fucked up. Reason: $!"; while ($line = ) { chomp($line); $line =~ s/$stext/$rtext/g; print F2 "$line\n"; } close(F1) or die "Perl fucked up. Reason: $!"; close(F2) or die "Perl fucked up. Reason: $!"; Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From gmane-schpam at joefrancia.com Thu Jan 27 14:00:04 2005 From: gmane-schpam at joefrancia.com (Joe Francia) Date: Thu, 27 Jan 2005 14:00:04 -0500 Subject: python without OO In-Reply-To: References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> <1106710590.312881.222520@c13g2000cwb.googlegroups.com> <1106716951.060290.253010@z14g2000cwz.googlegroups.com> Message-ID: Timo Virkkala wrote: > This guy has got to be a troll. No other way to understand. > > -- > Timo Virkkala Not a troll, just another case of premature optimization run amok. From Serge.Orlov at gmail.com Mon Jan 17 03:56:59 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: Mon, 17 Jan 2005 11:56:59 +0300 Subject: how to print unicode structures? References: Message-ID: Timothy Babytch wrote: > Imagine you have some list that looks like > ('unicode', 'not-acii', 'russian') and contains characters not from > acsii. or list of dicts, or dict of dicts. > > how can I print it? not on by one, with "for" - but with just a simple > print? My debugging would be MUCH simpler. I think the best (in terms of time) way to do it is to copy pprint.py to upprint.py and hack it. > > Now when I try print or pprint that variable I get a page full of > '\xe4\xeb\xa2\xa0\xe6\xe3\xaa\xe6\xe3\xaa' and so on. It looks like bytes, you should get rid of them as soon as possible. If you're not looking for speed hacks, as a rule of thumb you should convert bytes to unicode characters as soon as possible. When I try to print Russian characters I get unicode escapes (\u) not byte escapes (\x) like you: >>> print unicode([u'???']) [u'\u0430\u0431\u0432'] Serge. From levub137 at wi.rr.com Sun Jan 2 19:01:16 2005 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sun, 02 Jan 2005 18:01:16 -0600 Subject: [ANN] ratfun-1.0 Polynomials And Rational Functions Message-ID: The ratfun module provides classes for defining polynomial and rational function (ratio of two polynomials) objects. These objects can be used in arithmetic expressions and evaluated at a particular point. Home page: http://calcrpnpy.sourceforge.net/ratfun.html Note: If you are using rpncalc-1.2 or later, this module is already included. This release is for folks who don't want rpncalc. From tim.golden at viacom-outdoor.co.uk Tue Jan 25 04:04:22 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 25 Jan 2005 09:04:22 -0000 Subject: how to ncurses on win32 platform Message-ID: <9A28C052FF32734DACB0A288A35339910359E5@vogbs009.gb.vo.local> [Jorgen Grahn] | [Alan Gauld ] | > You can use ncurses via cygwin. | > There are DOS ports too but I couldn't get any of them to | > work on my XP box, YMMV... | | Or, as Alex Martelli wrote in "Python in a nutshell": | | "The curses package works only on Unix-like platforms | (there are persis- | tent rumors of Windows ports of it, but I've never found a | working one)." This is the only one I've seen which claims (at least partial) compatibility. I've looked it over, but never had a chance to try it out: http://flangy.com/dev/python/curses/ TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From jfine at pytex.org Wed Jan 5 15:49:14 2005 From: jfine at pytex.org (Jonathan Fine) Date: Wed, 05 Jan 2005 20:49:14 +0000 Subject: What could 'f(this:that=other):' mean? Message-ID: <41DC52CA.5070104@pytex.org> Giudo has suggested adding optional static typing to Python. (I hope suggested is the correct word.) http://www.artima.com/weblogs/viewpost.jsp?thread=85551 An example of the syntax he proposes is: > def f(this:that=other): > print this This means that f() has a 'this' parameter, of type 'that'. And 'other' is the default value. I'm going to suggest a different use for a similar syntax. In XML the syntax > is used for name spaces. Name spaces allow independent attributes to be applied to an element. For example, 'fo' attributes for fonts and layout. XSLT is of course a big user of namespaces in XML. Namespaces seems to be a key idea in allow independent applications to apply attributes to the same element. For various reasons, I am interested in wrapping functions, and supplying additional arguments. Namespaces would be useful here. Decorators, by the way, are ways of wrapping functions. Namespaces might make decorators a bit easier to use. Here's an example of how it might work. With f as above: > f(this:that='value') {'that': 'value'} Do you see? The syntax of def makes 'this' a dictionary. And the syntax of the call adds an item to 'this'. This aligns nicely with XML syntax and semantics. One could extend **kwargs similarly. > def g(***nsargs): > print ***nsargs > > g(this:that='other', that:this='more') {'this': {'that': 'other'}; {'that': {'this': 'more'}} All the namespace args are gathered into a dict of dicts. Thus, this suggestion is mostly syntactic sugar for f(this=dict(that='other), that=dict('this'=other)) (Have I got this right? - I'm only up to Python 2.2 at home. This is how I remember 2.4.) Back to optional static typing. A common idiom is > def return_dict(data=None): > if data is None: > data = {} # etc This avoid the newbie gotcha in > def return_dict(data={}: > # etc So to write this using the suggested syntax one has: > def return_dict(data:dict=None): > # oops! So now some final comments. 1. I have no opinion yet about optional static typing. 2. Calls of function f() should outnumber definitions of f(). (I'm not totally convinced of this - for example __eq__ may be defined in many classes, but called by few functions. Frameworks often have functions as parameters.) 3. Granted (2), perhaps function calls are first in the queue for syntactic sugar. -- Jonathan http://www.pytex.org From andre.roberge at gmail.com Fri Jan 21 14:19:38 2005 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Fri, 21 Jan 2005 15:19:38 -0400 Subject: short programming projects for kids In-Reply-To: <1106332638.595750.150590@c13g2000cwb.googlegroups.com> References: <1106332638.595750.150590@c13g2000cwb.googlegroups.com> Message-ID: bobdc wrote: > I will be teaching an "Introduction to Programming" class to some > middle school aged children and will be using Python, obviously. Does > anyone have suggestions for simple little programs to create and > analyze with them after I get past turtle graphics? > > Turtle graphics will be plenty for the first session, and I will leave > time to ask them what they'd like to do in later sessions, but I was > curious if anyone on the list has experience picking pedagogical > programming examples appropriate for twelve-year-olds' attention spans. > thanks, > > Bob > While it is not python per se, I suggest you have a look at GvR (Guido van Robot) (The app is written in Python but is too complicated for beginners). It is hosted on sourceforge (gvr.sourceforge.net). It is a very interesting way (imho) to learn about programming, in a pythonic way. (somewhat shameless plug follows:) A 'more advanced version' of GvR which uses the full Python syntax is RUR-PLE (rur-ple.sourceforge.net). The version currently hosted there does NOT work under Linux (untested on Mac). It uses wxPython 2.4 and will not work with 2.5. An updated release that will work under both Linux and Windows, and under both wxPython 2.4 and 2.5 will come out very soon, I hope. I'm working on it :-) I have two kids (ages 11 and 13) and plan to use rur-ple to teach them about programming. Note that, even though I plan it to be suitable for motivated children (with some guidance), the end product (to be finished in a year?) is planned to be suitable for a complete first-year university computer science. Andre Roberge From ajsiegel at optonline.com Thu Jan 13 06:40:58 2005 From: ajsiegel at optonline.com (Arthur) Date: Thu, 13 Jan 2005 06:40:58 -0500 Subject: java 5 could like python? References: <4MSdnSo5J_xU0HjcRVn-2g@giganews.com> Message-ID: On Wed, 12 Jan 2005 11:18:17 -0500, Istvan Albert wrote: >vegetax wrote: > >> previus two python proyects where relatively big,and python didnt feel >> well suited for the task. > >One typical problem that others might talk about in more detail >is that you might be writing java code in python. That means >using Java style class hierarchies, methods and overall >organization. That does not work well in python. On the other hand in could be argued that the language seems to be evolving in a direction in which this is too possible - the distinctive "voice" of Python being muffled in static and class methods, type declarations and the like. Perhaps Python is forced in this direction as an appropriate admission of the advantages of the architecture encouraged by the Java/C# class of langauge. And is being courageous in these admission. Or perhpas it is an unfortunate result of trying to find acceptance and establish some compatibility in an atmosphere in which these language approaches dominate the current mainstream. And trying too hard to avoid a LISPish fate. Or else everything is just as it should be. I honestly don't pretend to know. But am a little confused about the lack of the discussion here about the developments in this direction. Art From frode.gulbrandsen at adirekta.no Tue Jan 4 02:26:16 2005 From: frode.gulbrandsen at adirekta.no (Frode Gulbrandsen) Date: Tue, 4 Jan 2005 08:26:16 +0100 Subject: Out of Office AutoReply: warning Message-ID: <619BBDD9F5DD574AA2C3EBB46C4BFB9D15F714@adirekta03.adirekta.no> Hei Jeg har sluttet i Adirekta. Ta gjerne kontakt med en av mine kollegaer for hjelp. Jan Ole Nystuen: 22 03 69 60 / 917 70 366, jan.ole.nystuen at adirekta.no eller Lene Andersen: 22 03 69 56 / 481 17 787, lene.andersen at adirekta.no Mvh Frode From bulba at bulba.com Tue Jan 4 10:58:06 2005 From: bulba at bulba.com (Bulba!) Date: Tue, 04 Jan 2005 16:58:06 +0100 Subject: Pythonic search of list of dictionaries Message-ID: Hello everyone, I'm reading the rows from a CSV file. csv.DictReader puts those rows into dictionaries. The actual files contain old and new translations of software strings. The dictionary containing the row data looks like this: o={'TermID':'4', 'English':'System Administration', 'Polish':'Zarzadzanie systemem'} I put those dictionaries into the list: oldl=[x for x in orig] # where orig=csv.DictReader(ofile ... ..and then search for matching source terms in two loops: for o in oldl: for n in newl: if n['English'] == o['English']: ... Now, this works. However, not only this is very un-Pythonic, but also very inefficient: the complexity is O(n**2), so it scales up very badly. What I want to know is if there is some elegant and efficient way of doing this, i.e. finding all the dictionaries dx_1 ... dx_n, contained in a list (or a dictionary) dy, where dx_i contains a specific value. Or possibly just the first dx_1 dictionary. I HAVE to search for values corresponding to key 'English', since there are big gaps in both files (i.e. there's a lot of rows in the old file that do not correspond to the rows in the new file and vice versa). I don't want to do ugly things like converting dictionary to a string so I could use string.find() method. Obviously it does not have to be implemented this way. If data structures here could be designed in a proper (Pythonesque ;-) way, great. I do realize that this resembles doing some operation on matrixes. But I have never tried doing smth like this in Python. #---------- Code follows --------- import sys import csv class excelpoldialect(csv.Dialect): delimiter=';' doublequote=True lineterminator='\r\n' quotechar='"' quoting=0 skipinitialspace=False epdialect=excelpoldialect() csv.register_dialect('excelpol',epdialect) try: ofile=open(sys.argv[1],'rb') except IOError: print "Old file %s could not be opened" % (sys.argv[1]) sys.exit(1) try: tfile=open(sys.argv[2],'rb') except IOError: print "New file %s could not be opened" % (sys.argv[2]) sys.exit(1) titles=csv.reader(ofile, dialect='excelpol').next() orig=csv.DictReader(ofile, titles, dialect='excelpol') transl=csv.DictReader(tfile, titles, dialect='excelpol') cfile=open('cmpfile.csv','wb') titles.append('New') titles.append('RowChanged') cm=csv.DictWriter(cfile,titles, dialect='excelpol') cm.writerow(dict(zip(titles,titles))) print titles print "-------------" oldl=[x for x in orig] newl=[x for x in transl] all=[] for o in oldl: for n in newl: if n['English'] == o['English']: if n['Polish'] == o['Polish']: status='' else: status='CHANGED' combined={'TermID': o['TermID'], 'English': o['English'], 'Polish': o['Polish'], 'New': n['Polish'], 'RowChanged': status} cm.writerow(combined) all.append(combined) # duplicates dfile=open('dupes.csv','wb') dupes=csv.DictWriter(dfile,titles,dialect='excelpol') dupes.writerow(dict(zip(titles,titles))) """for i in xrange(0,len(all)-2): for j in xrange(i+1, len(all)-1): if (all[i]['English']==all[j]['English']) and all[i]['RowChanged']=='CHANGED': dupes.writerow(all[i]) dupes.writerow(all[j])""" cfile.close() ofile.close() tfile.close() dfile.close() -- Real world is perfectly indifferent to lies that are the foundation of leftist "thinking". From __peter__ at web.de Fri Jan 28 03:27:14 2005 From: __peter__ at web.de (Peter Otten) Date: Fri, 28 Jan 2005 09:27:14 +0100 Subject: building Python: up arrow broken on SuSE Linux 8.2 References: <41f6c3f7$1@nntp.zianet.com> <41f85dd8@nntp.zianet.com> <41f97058$1@nntp.zianet.com> Message-ID: Erik Johnson wrote: >> Have you ensured (with yast) that readline-devel is actually installed? > > I had not previously, but (not surprisingly) version 4.3 is installed. :) According to http://cnswww.cns.cwru.edu/php/chet/readline/CHANGES the features you missed were introduced in readline 4.0 and 4.2, so version 4.3 should be sufficient. So let me ask you again, you have both the readline and the readline-devel package installed? If yes, and configure still complains, it may be time to look for something entirely different... Peter From dbickett at gmail.com Mon Jan 31 16:27:48 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Mon, 31 Jan 2005 16:27:48 -0500 Subject: Q: quoting string without escapes In-Reply-To: References: <1107198137.141990.246880@c13g2000cwb.googlegroups.com> Message-ID: <1d6cdae30501311327494bbc49@mail.gmail.com> On Mon, 31 Jan 2005 14:09:10 -0500, Steve Holden wrote: > Use triple-quoting. An example, for the sake of examples: Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> string = """ " ' " ' " ' " ' \""" """ >>> string ' " \' " \' " \' " \' """ ' >>> string = """ ... " ... " ... " ... ' ... ' ... ' ... \""" ... "\"" ... ""\" ... """ >>> string '\n"\n"\n"\n\'\n\'\n\'\n"""\n"""\n"""\n' -- Daniel Bickett dbickett at gmail.com http://heureusement.org/ From elbertlev at hotmail.com Sun Jan 2 22:07:51 2005 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: 2 Jan 2005 19:07:51 -0800 Subject: File locking is impossible in Windows? SOLUTION In-Reply-To: <41C9AE8E.9040502@wlanmail.com> References: <41c899ba$0$15097$39db0f71@news.song.fi> <41C9AE8E.9040502@wlanmail.com> Message-ID: <1103740868.160826.304830@f14g2000cwb.googlegroups.com> Sure it will do if one of the processes needs read access only. Scenario when you need shared rw acces with locking: In the file you have "records" say 30 bytes long, 2 processes are reading/writing these records by: lock-read-unlock or lock-write-unlock . Both processes have to open the file with rw access. But the third process can overwrite the locked file! Actually the common method to prevent file from been overwritten is: lock the region outside the file. Such feacure is added to lock/unlock namely for this purpose. You found the bug in WIN32. PS. When you copy the file (say c:\b) over file with locked region say (c:\a), the length of the file c:\b becomes the length of c:\a, and the content of c:\a is all zeroes. By the way, I would understand the logic if copy copyes bytes outside locked regions but preserves all locks. From ptmcg at austin.rr._bogus_.com Thu Jan 27 16:46:05 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 27 Jan 2005 21:46:05 GMT Subject: Startying with Python, need some pointers with manipulating strings References: <41f95bb2$0$24349$9a6e19ea@unlimited.newshosting.com> Message-ID: "Benji99" wrote in message news:41f95bb2$0$24349$9a6e19ea at unlimited.newshosting.com... > > Basically, I'm getting a htmlsource from a URL and need to > a.) find specific URLs > b.) find specific data > c.) with specific URLs, load new html pages and repeat. > > > Basically, I want to search through the whole string( > htmlSource), for a specific keyword, when it's found, I want to > know which line it's on so that I can retrieve that line and > then I should be able to parse/extract what I need using Regular > Expressions (which I'm getting quite confortable with). So how > can this be accomplished? > If you download pyparsing (at http://pyparsing.sourceforge.net), you'll find in the examples something very close to this called urlextractor.py (lists out all href's and their associated links on the page at www.yahoo.com). -- Paul From rootshell at gazeta.pl Thu Jan 13 13:07:46 2005 From: rootshell at gazeta.pl (rootshell at gazeta.pl) Date: Thu, 13 Jan 2005 19:07:46 +0100 Subject: Free python server. Message-ID: <002301c4f99a$cb4dcd50$55a01d53@unqku4k1fl8nea7> Thank you very much. Arbornet.org seems to be ok Unforutnately I was convinced that I only have to only copy my *.py file to /public_hml directory and everything will be all right. As you expect I was wrong. R. From steve at holdenweb.com Mon Jan 10 20:00:33 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Jan 2005 20:00:33 -0500 Subject: Port blocking In-Reply-To: <34f8ovF47d783U1@individual.net> References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> <34f8ovF47d783U1@individual.net> Message-ID: Mark Carter wrote: > Paul Rubin wrote: > >> Mark Carter writes: >> >>> Supposing I decide to write a server-side application using something >>> like corba or pyro. > > >> Usually you wouldn't run a public corba or pyro service over the >> internet. You'd use something like XMLRPC over HTTP port 80 partly >> for the precise purpose of not getting blocked by firewalls. > > > Although, when you think about it, it kinda defeats the purposes of > firewalls. Not that I'm criticising you personally, you understand. > Yet another brilliant Microsoft marketing concept: "Shit, these bloody firewalls are getting in the way of our new half-baked ideas for application architectures to replace all that funky not-invented-here open source stuff we can't charge money for. Let's design something that completely screws up existing firewall strategies, then we can charge people extra to firewall the new stuff after we've hooked them all on yet another inferior execution of existing ideas". >>> Also, is there a good tool for writing database UIs? >> >> >> >> Yes, quite a few. > > > Ah yes, but is there really? For example, I did a search of the TOC of > GTK+ Reference Manual: > http://developer.gnome.org/doc/API/2.0/gtk/index.html > for the word "data", and there's apparently no widget which is > explicitly tied to databases. So in GTKs case, for instance, it looks > like one has to roll one's own solution, rather than just using one out > of the box. There isn't, IMHO, anything with the polish of (say) Microsoft Access, or even Microsoft SQL Server's less brilliant interfaces. Some things Microsoft *can* do well, it's a shame they didn't just stick to the knitting. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From jonasgalvez at gmail.com Mon Jan 10 08:33:48 2005 From: jonasgalvez at gmail.com (Jonas Galvez) Date: Mon, 10 Jan 2005 11:33:48 -0200 Subject: python3: 'where' keyword In-Reply-To: <3480qqF46jprlU1@individual.net> References: <3480qqF46jprlU1@individual.net> Message-ID: <7c60b60505011005332c2506d7@mail.gmail.com> Andrey Tatarinov wrote: > It would be great to be able to reverse usage/definition parts > in haskell-way with "where" keyword. Hi folks, I really like this idea. But I couldn't help but think of a few alternative ways. I'm no language design expert by any means, but I'm a little concerned with the idea of an 'expression' preceding a 'block'. Maybe I'm naive (actually, I'm pretty sure I am), but I think a decorator-like syntax would be a little more Pythonic. Here's a small example: def where(closure=None, *v): if not False in v: closure(*v) def foo(a, b): @where(a: int, b: int): return str(a) + str(b) raise TypeMismatch The (variable : type) could be turned into a syntact sugar for (type(variable) is type). Basically, this would be a simple implementation of the so called "closures", where a decorator is able to 'receive' a code block, which would be passed as a function as the first argument of the decorator. (Is this clear?) As I said, I'm no language design expert and I'm sure I'm breaking a few important rules here heh. But I find it cool. This is not a proposal. I'm just thinking out loud :) Jonas From robin at reportlab.com Wed Jan 12 04:00:14 2005 From: robin at reportlab.com (Robin Becker) Date: Wed, 12 Jan 2005 09:00:14 +0000 Subject: OT: MoinMoin and Mediawiki? In-Reply-To: <34j1dbF4cd4ocU1@individual.net> References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <34h7m9F43vomsU1@individual.net> <7xsm58lcms.fsf@ruckus.brouhaha.com> <7xu0pn4x88.fsf@ruckus.brouhaha.com> <34j1dbF4cd4ocU1@individual.net> Message-ID: <41E4E71E.9090901@jessikat.fsnet.co.uk> Brion Vibber wrote: > Paul Rubin wrote: > >> I think mod_php doesn't play nice with apache2 but am not aware of any >> cgi interoperability problems. > > > Generally it's recommended to configure apache2 in the child process > mode (eg the way that 1.3 works) when using PHP as many library modules > are alleged not to be threadsafe. Some Linux distributions ship standard > this way. ... unfortunately mod_python3 seems to need exactly the opposite ie apache2 with threads. However, I originally tried to get php going with apache2 in the standard mode and still had problems. -- Robin Becker From whereU at now.com Sun Jan 30 14:40:08 2005 From: whereU at now.com (Eric Pederson) Date: Sun, 30 Jan 2005 11:40:08 -0800 Subject: The next Xah-lee post contest In-Reply-To: References: Message-ID: <20050130114008.797088857.whereU@now.com> > From: Arthur > Not sure how Xah got himself into all this. One can easily see that Java programmers are geeks who secretly wanted to make the football team and are now trying to conform, ignoring their language's critical lack of Prolog syntax. Python coders, similarly, do not recognize that they may be violating several open source patents each time they write: "class(Object):", and both languages may become unusable when the Government changes the inheritance tax. Rather than throw stones or make fun, all but the closet Republicans should examine how poor Xah came to such a state of misunderstanding IPv8, and try to help him. >From Aahz tag line we have a clue: "19. A language that doesn't affect the way you think about programming,is not worth knowing." ?--Alan Perlis Further understanding will require research. Was it Perl that did this to Mr. Lee's brain, or perhaps it was trying to ascertain the web services "standard"? Was it a massive PHP program that simply grew beyond comprehendability and blew all normal circuits? Or perhaps an attempt to jump straight from Fortran 77 into Ruby? Perhaps we will never know the cause, but surely when the ill come to us we must prescribe something. Ah, perhaps if he will join us in a song we will all be OK: Python Choir: Lee's a lumberjack, and he's OK, He codes all night and he posts all day. XL: I cut down trees, I eat my lunch, I go to the lavatory. On Wednesdays I go shopping, And have buttered scones for tea. Python Choir: Lee cuts down trees, He eats his lunch, He goes to the lavatory. On Wednesdays he goes shopping, And have buttered scones for tea. Lees a lumberjack, and he's OK, He codes all night and he posts all day. XL: I cut down trees, I skip and jump, I like to press wild flowers. I put on women's clothing, And hang around in bars. Python Choir: Lee cuts down trees, he skips and jumps, He likes to press wild flowers. He puts on women's clothing And hangs around.... In bars??????? Well. At least I feel better. For now. /Eric - sentenced to re-learn and write an application in Perl 5.0 What will that do to my mind? http://www.songzilla.blogspot.com ::::::::::::::::::::::::::::::::::: domainNot="@something.com" domainIs=domainNot.replace("s","z") ePrefix="".join([chr(ord(x)+1) for x in "do"]) mailMeAt=ePrefix+domainIs ::::::::::::::::::::::::::::::::::: From mikael at isy.liu.se Mon Jan 31 11:59:28 2005 From: mikael at isy.liu.se (Mikael Olofsson) Date: Mon, 31 Jan 2005 17:59:28 +0100 Subject: Twain problems Message-ID: <078d01c507b6$399efc10$4334ec82@guinevere> Hi all! Sorry for this rather lengthy post. It's a long preamble followed by a few questions based on that. Here's my situation: I am trying to write a specialized scanner utility for my own needs, and I want to use the module twain to control my scanner. I haven't used the twain module before, which is most certainly why I'm facing problems. My problem is to interprete some of the information I get from the scanner. The scanner, by the way, is an HP LaserJet 3020, which is a multi-toy (printer/scanner/copyer), and I use Python 2.3 on Windows XP. I set up communication with the scanner as follows (modulo a few ifs to take care of unsuccessful connections). Here self is an instance of a class with Tkinter.Tk as its base class. self.SM = twain.SourceManager(self.winfo_id(),ProductName='foo') self.SD = self.SM.OpenSource() The TWAIN dialog pops up nicely, and I get two options: "hp LaserJet 3020 TWAIN 1.0 (32-32)" and "WIA-hp LaserJet 3020 1.0 (32-32)". The first choice is HPs interface to the scanner, while the second seems to be a scanner interface that comes with Windows. One issue arises if I choose "WIA-hp LaserJet 3020 1.0 (32-32)" and then do the following: capVal=self.SD.GetCapability(twain.ICAP_CONTRAST) After that capVal is {'StepSize': 1, 'DefaultValue': 0, 'CurrentValue': 0, 'MaxValue': 1000, 'MinValue': 64536} My educated guess is that 64536 should be interpreted as -1000, since 64536 is -1000 modulo 2**16. One problem is that the twain type is not specified. So, perhaps I can find the twain type in some other way. The check capDef=self.SD.GetCapabilityDefault(twain.ICAP_CONTRAST) gives me capDef==( 7, 0.0 ). According to my introspection of the twain module, the type 7 is twain.TWTY_FIX32. Googling around gives me the impression that this corresponds to 32 bits of which the first 16 bits correspond to the integer part, and the last 16 bits correspond to the fraction part. I thought that the twain module would take care of sign issues for me, but it does not seem to do so. OK, I can probably live with that. In any case, I guess I'll have to. OK, that's perhaps not so tough. Another issue arises if I choose "hp LaserJet 3020 TWAIN 1.0 (32-32)" and then do the following: capVal=self.SD.GetCapability(twain.ICAP_XSCALING) After that capVal is {'StepSize': 429457408, 'DefaultValue': 1, 'CurrentValue': 1, 'MaxValue': 6, 'MinValue': 429457408} Now I'm in trouble. The problem is to interprete capVal['StepSize'] and capVal['MinValue']. Both should correspond to some small positive value. Here the check capDef=self.SD.GetCapabilityDefault(twain.ICAP_XSCALING) gives me capDef==( 4, 100 ). More introspection says that type 4 is twain.TWTY_UINT16. So, again googling around, and I find that this corresponds to an unsigned 16bit integer, but that doesn't help me much since 429457408 > 2**16. I also notice that capDef[1]==100, while capVal['DefaultValue']==1, so there must be a scaling factor of 100 (percents, yes I know). But that doesn't change the fact that I'm completely lost here. Finally, here are my questions: Can anyone enlighten me? From the above, I get the impression that the dictionary returned by self.SD.GetCapability in these cases give me integer approximations of the current and default values. Is that a correct interpretation? How should I deal with 429457408 in the example above? Are there other twain-type related issues that I haven't seen yet, that I should be aware of? Is there some web-resource out there that answers my questions? Am I simply missing some information that I might already have? At least I haven't been able to find any enlightment in the documentation of the twain module or in the TWAIN specification. It seems to me that I need to be very careful with the type of the capabilities. How careful should I be? Googling for things like TWTY_UINT16 typically results in what I interprete as C or C++ code, which does not help me much. I'm less fluent in C or C++ than I am in Italian (I can order a beer and buy postcards or stamps, that's more or less it). I-cannot-order-a-beer-in-C-but-I-can-in-Python-ly yours /Mikael Olofsson Universitetslektor (Senior Lecturer [BrE], Associate Professor [AmE]) Link?pings universitet ----------------------------------------------------------------------- E-Mail: mikael at isy.liu.se WWW: http://www.dtr.isy.liu.se/en/staff/mikael Phone: +46 - (0)13 - 28 1343 Telefax: +46 - (0)13 - 28 1339 ----------------------------------------------------------------------- Link?pings kammark?r: www.kammarkoren.com Vi s?ker tenorer och basar! From peter at engcorp.com Wed Jan 26 15:47:23 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 26 Jan 2005 15:47:23 -0500 Subject: Set parity of a string In-Reply-To: References: <1f060c4c05012611503090c261@mail.gmail.com> Message-ID: snacktime wrote: > Correction on this, ETX is ok, it seems to be just STX with the data I am using. > On Wed, 26 Jan 2005 11:50:46 -0800, snacktime wrote: > >>I'm trying to figure out why the following code transforms ascii STX >>(control-b) into "\x82". The perl module I use returns a value of >>"^B", and that is also what the application I am communicating with >>expects to see. Some ascii characters such as FS and GS come through >>fine, but STX and ETX get transformed incorrectly (at least for what I >>need they do). I didn't see the first post, which you quoted above... more newsfeed or python-list misalignment I guess. :-( Anyway, since STX '\x02' has only one bit set, if you are setting the parity bit for "even" parity, then naturally it will be set (in order to make the total number of "on" bits an even number), so you get '\x82' (which has two bits set). ETX, on the other hand '\x03' already has two bits set, so the high bit is left alone. It sounds as though you need to examine the specification for the receiving system in more detail, or perhaps seek clarification from the other party involved in this system you're working with. If you have examples that show STX and ETX both being transmitted, around other data which itself has had the parity bit set for even parity, then clearly (a) the folks involved in designing that system are idiots <0.5 wink> and (b) you'll have to modify the way you are forming the transmission packet. It appears they may want the STX/ETX pair to be sent without being affected by the parity process... -Peter From danb_83 at yahoo.com Tue Jan 25 19:46:57 2005 From: danb_83 at yahoo.com (Dan Bishop) Date: 25 Jan 2005 16:46:57 -0800 Subject: string.atoi and string.atol broken? References: Message-ID: <1106700417.482871.45140@z14g2000cwz.googlegroups.com> Peter Otten wrote: > Mike Moum wrote: > > > s.atoi('4',3) should result in 11 > > > > s.atoi('13',4) should result in 31 > > > > s.atoi('12',4) should result in 30 > > > > s.atoi('8',4) is legitimate, but it generates an error. > > > > Is this a bug, or am I missing something obvious? > > You and atoi() seem to disagree about the direction of the conversion, and > atoi() wins :-). It converts a string representation of a number into the > corresponding integer. The second parameter specifies in what base this > string is given. > You seem to want something like > > import string > > def itoa(n, base): > assert 2 <= base <= 16 Why have the restriction base <= 16? int() allows up to 36. All you need to do is BASE36_DIGITS = string.digits + string.lowercase and change > digits.append(string.hexdigits[m]) to > digits.append(BASE36_DIGITS[m]) From tchur at optushome.com.au Mon Jan 17 20:01:39 2005 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 18 Jan 2005 12:01:39 +1100 Subject: Fuzzy matching of postal addresses Message-ID: <200501180101.j0I11dWW015974@mail03.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From fuzzyman at gmail.com Tue Jan 4 09:44:09 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 Jan 2005 06:44:09 -0800 Subject: HTTP GET request with basic authorization? In-Reply-To: References: Message-ID: <1104849849.460174.103100@f14g2000cwb.googlegroups.com> There's example code with discussion at : http://www.voidspace.org.uk/atlantibots/recipebook.html#auth Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From peter at engcorp.com Thu Jan 6 20:47:35 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Jan 2005 20:47:35 -0500 Subject: Python evolution: Unease In-Reply-To: References: <7xacrpdxy3.fsf@ruckus.brouhaha.com><7x652che6z.fsf@ruckus.brouhaha.com><7x4qhw859p.fsf@ruckus.brouhaha.com><7xk6qrnbum.fsf@ruckus.brouhaha.com><41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> Message-ID: <5fGdnfXE0u2qd0DcRVn-iQ@powergate.ca> Terry Reedy wrote: > "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message > news:7x652bnhx0.fsf at ruckus.brouhaha.com... > > >>If I have a 400 gig hard drive, I don't see why I need 99.99% of it >>empty instead of 99.0% after I do my OS install. > > > Even though I currently only have 80 megs (about the minimum one can > currently buy), I've about decided you are right. Having just installed a > 3 CD game last night, I realize that my stinginess with disk space for more > serious stuff is obsolete. (My first hard disk was 5 or 10 megs.) A > gigabyte would cover Python + Wxpython + numarray + scipy + pygame + a lot > of other stuff. > > Would it be possible, at least for Windows, to write a Python script > implementing a 'virtual distribution'? IE, download Python, install it, > download next package, install it, etc. -- prefereably table driven? How would you run the script in the first place? (Assuming that has one of the straightforward answers I can think of, then I would say the answer to your question is "certainly"... I think most installers support a "silent" option so that they could be run from a script.) -Peter From samantha7395 at hotmail.com Tue Jan 18 13:38:33 2005 From: samantha7395 at hotmail.com (Samantha) Date: Tue, 18 Jan 2005 10:38:33 -0800 Subject: Print to Windows default Printer Message-ID: I am new to Python and I am having considerable trouble trying to print (using a simple script) to the default printer rather than the screen. Thanks for any help. S From mb at muenster.de Sun Jan 30 03:56:15 2005 From: mb at muenster.de (Martin Bless) Date: Sun, 30 Jan 2005 08:56:15 GMT Subject: PythonWin (build 203) for Python 2.3 causes Windows 2000 to grind to a halt? References: <3f233389.0501271147.43572416@posting.google.com> <41f9e4a9$1_1@127.0.0.1> <3f233389.0501280813.6be97b74@posting.google.com> Message-ID: <41fc9d4e.1621406@news.muenster.de> [chris.peressotti at utoronto.ca (Chris P.)] >The bug you suggested is exactly the problem that I was having... I >had looked through the bugs being tracked, but the title of that one >didn't jump out at me as something that would help. Thanks! Yes, using Python24 and the latest win32 build on my machine the bug still exists. PythonWin works fine if you don't use the debugger. But since the debugger is the most valuable feature for me I sadly had to stop using PythonWin. For a while I found some help by running the script below every now and then. It deletes the erroneous registry entries. But currently the bugs are stronger. Here's my solution: I spent some money and switched to "WingIde" from wingware.com. Wow, it's breathtaking and worth each penny. Don't compare WingIde with other editors. WingIde really plays in the IDE (integrated development environment) league. And it's very Python aware and knowledgable ... mb - Martin Bless Here's my script to delete the erroneous debugger entries: Script "delete-debugger-entries,pywin,python24.py" #!/usr/bin/env python # -*- coding: iso-8859-1 -*- """Delete problematic registry entries in 'Python for Win32'. Martin Bless, mb, 2004-09-24, 2005-01-05 No warrenties whatsoever. Use at your own risk. """ import win32api import win32con subKey = r'Software\Python 2.4\Python for Win32' subKey = r'Software\Python 2.4\Python for Win32' if 1: #HKEY_CURRENT_USER\Software\Python 2.4\Python for Win32\ToolbarDebugging-Bar0 k = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,subKey,0,win32con.KEY_ALL_ACCESS) nsubkeys,nvalues,timeval = win32api.RegQueryInfoKey(k) keys = [] for i in range(nsubkeys): s = win32api.RegEnumKey(k,i) if (s.startswith('ToolbarDefault-Bar') or s.startswith('ToolbarDebugging-Bar')): keys.append(s) for i,key in enumerate(keys): subKey2 = subKey + '\\' + key print i,':', subKey2 win32api.RegDeleteKey(win32con.HKEY_CURRENT_USER,subKey2) if i>99999: break k.Close() print len(keys),"deleted." From steven.bethard at gmail.com Sat Jan 8 19:57:30 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 08 Jan 2005 17:57:30 -0700 Subject: Speed revisited In-Reply-To: <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> Message-ID: Bulba! wrote: > Following advice of two posters here (thanks) I have written two > versions of the same program, and both of them work, but the > difference in speed is drastic, about 6 seconds vs 190 seconds > for about 15000 of processed records, taken from 2 lists of > dictionaries. > > I've read "Python Performance Tips" at > > http://manatee.mojam.com/~skip/python/fastpython.html > > ..but still don't understand why the difference is so big. > [snip] > > # snippet 1, this runs in about 6 seconds > !def prepend(l): > ! map = {} > ! for d in l: > ! key = d['English'] > ! map[key] = d > ! return map > ! > !old_map = prepend(oldl) > !new_map = prepend(newl) > ! > !for engphrase in old_map: > ! if engphrase in new_map: > ! o = old_map[engphrase] > ! n = new_map[engphrase] > ! cm.writerow(matchpol(o,n)) > > > # snippet 2, this needs 190 seconds > !while 1: > ! if len(oldl) == 0 or len(newl) == 0: > ! break > ! if oldl[o]['English'] == newl[n]['English']: > ! cm.writerow(matchpol(oldl[o], newl[n])) > ! del oldl[o] > ! del newl[n] > ! o, n = 0, 0 > ! continue > ! elif cmp(oldl[o]['English'], newl[n]['English']) < 0: > ! if o == len(oldl): > ! cm.writerow(newl[0]) > ! del(newl[0]) > ! o, n = 0, 0 > ! continue > ! o+=1 > ! elif cmp(oldl[o]['English'], newl[n]['English']) > 0: > ! if n == len(newl): > ! cm.writerow(newl[0]) > ! del(oldl[0]) > ! o, n = 0, 0 > ! continue > ! n+=1 I believe you're running into the fact that deleting from anywhere but the end of a list in Python is O(n), where n is the number of items in the list. Consider: ---------- test.py ---------- def delfromstart(lst): while lst: del lst[0] def delfromend(lst): for i in range(len(lst)-1, -1, -1): del lst[i] ----------------------------- [D:\Steve]$ python -m timeit -s "import test" "test.delfromstart(range(1000))" 1000 loops, best of 3: 1.09 msec per loop [D:\Steve]$ python -m timeit -s "import test" "test.delfromend(range(1000))" 1000 loops, best of 3: 301 usec per loop Note that Python lists are implemented basically as arrays, which means that deleting an item from anywhere but the end of the list is O(n) because all items in the list must be moved down to fill the hole. Repeated deletes from a list are generally not the way to go, as your example shows. =) Steve From http Tue Jan 18 23:53:30 2005 From: http (Paul Rubin) Date: 18 Jan 2005 20:53:30 -0800 Subject: rotor replacement References: Message-ID: <7x1xcidnp1.fsf@ruckus.brouhaha.com> "Reed L. O'Brien" writes: > I see rotor was removed for 2.4 and the docs say use an AES module > provided separately... Is there a standard module that works alike or > an AES module that works alike but with better encryption? If you mean a module in the distribution, the answer is no, for political reasons. There are a number of AES modules available on the net. Most are C extension modules which means you need to compile them, and if you want to deploy them widely, you need binaries for every target platform. There's a few pure-Python AES implementations but they are verrry slow. Here's something written in Python that uses the built-in sha1 module as a crypto primitive. Its security should be better than rotor and performance is reasonable for most applications: http://www.nightsong.com/phr/crypto/p3.py From erikbethke at gmail.com Sun Jan 16 10:55:36 2005 From: erikbethke at gmail.com (Erik Bethke) Date: 16 Jan 2005 07:55:36 -0800 Subject: pygame + py2exe = bad exe. why? References: <1104250152.633279.73360@z14g2000cwz.googlegroups.com> <1104265554.792100.278610@z14g2000cwz.googlegroups.com> <1104546726.494907.3350@z14g2000cwz.googlegroups.com> <1104548988.491087.31240@c13g2000cwb.googlegroups.com> Message-ID: <1105890936.234402.145210@z14g2000cwz.googlegroups.com> M.E.Farmer wrote: > > Erik glad to see you were able to track it down. > Have you been succesful in making the changes they mentioned? > M.E.Farmer Yes below is a simple script that works. The key was that pygame uses freesansbold.ttf as the default font and that is not copied over in the normal py2exe process. See the end of the setup script. #!/usr/bin/env python from distutils.core import setup import py2exe, pygame import glob, shutil setup(windows=["mahjong.py"], name='GoPets Mahjong', version='0.3.1', description='Mahjong for GoPets Users', author='Erik Bethke', author_email='erik at gopetslive.com', url='www.erikbethke.com', py_modules=['mahjong','background','board','tile','textBox'] ) shutil.copytree('data', 'dist/data') shutil.copyfile('freesansbold.ttf', 'dist/freesansbold.ttf') From ncoghlan at iinet.net.au Thu Jan 27 05:19:02 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 27 Jan 2005 20:19:02 +1000 Subject: python without OO In-Reply-To: <1106782923.338506.269250@z14g2000cwz.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <41f6f4ee$1@nntp.zianet.com> <1106718853.867328.55760@z14g2000cwz.googlegroups.com> <1106782923.338506.269250@z14g2000cwz.googlegroups.com> Message-ID: <41F8C016.7070404@iinet.net.au> beliavsky at aol.com wrote: > Then why was C++ invented? What you have described can be done in C, > Pascal, and Fortran 90, all of which are generally classified as > procedural programming languages. As Lutz and Ascher say in "Learning > Python", in object-based programming one can pass objects around, use > them in expressions, and call their methods. "To qualify as being truly > object-oriented (OO), though, objects need to also participate in > something called an inheritance hierarchy." Again, behavioural inheritiance is something which can be done manually via delegation or function tables. What a language with OO support adds is special syntax for something that you could have done anyway - the OO support just makes it easier and clearer (well, C++ aside). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From marklists at mceahern.com Tue Jan 11 19:55:12 2005 From: marklists at mceahern.com (Mark McEahern) Date: Tue, 11 Jan 2005 18:55:12 -0600 Subject: Best way to trap errors in ftplib? In-Reply-To: <45p8u0t9cq0k6ar17s1udt0h3tj70ajhsa@4ax.com> References: <45p8u0t9cq0k6ar17s1udt0h3tj70ajhsa@4ax.com> Message-ID: <41E47570.10901@mceahern.com> Peter A.Schott wrote: >Using ftplib.FTP object for a project we have here to upload/download files. I >know that I can wrap everything in try/except blocks, but I'm having trouble >getting the exact error messages out of the Exceptions. > > Consider using the traceback a la: try: [... whatever ...] except: import sys, traceback t, v, tb = sys.exc_info() # or use StringIO to "print" the traceback to and then log *that* traceback.print_tb(tb) // m From claird at lairds.us Tue Jan 25 18:08:13 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 25 Jan 2005 23:08:13 GMT Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) References: Message-ID: In article , Michael Spencer wrote: . . . >Right - the crux of the problem is how to identify dangerous objects. My point >is that if such as test is possible, then safe exec is very easily implemented >within current Python. If it is not, then it is essentially impossible. > >Let's assume that it is indeed not possible to know in general whether >an object >is safe, either by inspecting its attributes, or by matching its identity >against a black list. > >It might still be possible to have a reliable test within a problem-specific >domain i.e., white-listing. This, I think, is what you meant when you said: > >> I wish there was a way to, say, exec something with no builtins and >with import disabled, so you would have to specify all the available >bindings, e.g.: >> >> exec user_code in dict(ClassA=ClassA, ClassB=ClassB) > >I believe that if you can come up with a white-list, then the rest of the >problem is easy. > >Michael > I'll suggest yet another perspective: add another indirection. As the virtual machine becomes more available to introspection, it might become natural to define a *very* restricted interpreter which we can all agree is safe, PLUS a means to extend that specific instance of the VM with, say, new definitions of bindings for particular AST nodes. Then the developer has the means to "build out" his own VM in a way he can judge useful and safe for his own situation. Rather than the Java there-is-one-"safe"-for- all approach, Pythoneers would have the tools to create safety. From aleaxit at yahoo.com Fri Jan 7 06:06:53 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 7 Jan 2005 12:06:53 +0100 Subject: missing sys.setappdefaultencoding References: Message-ID: <1gq0pd4.id8j3sexmiexN%aleaxit@yahoo.com> Uwe Mayer wrote: > Hi, > > well, I wrote a nice python program which won't work if the default encoding > has not been set from ascii to latin-1 or latin-15. Then your program is not very nice...;-) > However, the command sys.setappdefaultencoding is missing on a Python > installation with Python 2.3.4 on Gentoo where it is present on Debian. > > Any ideas how to deal with this? The site.py module in the standard Python library deliberately REMOVES the setdefaultencoding entry from the sys module (with a del statement) just before it finishes initializing your site-specific environment. This is meant as a very strong indication that you SHOULDN'T rely on setdefaultencoding in your applications. Being more explicit about the codings to/from Unicode is way, way better. I strongly suggest you only use Unicode *within* your programs and transcode only at I/O time (if needed: some good GUI toolkits, including Tkinter which comes with Python by default, use Unocide too). On the activestate's cookbook site you'll find a nice recipe by your compatriot Holger Krekel pointing out the practical course to follow, IMHO (I expand on that in the version of this and other recipes I've edited for the forthcoming 2nd printed edition of the Python Cookbook, but Holger's online recipe already has the salient practical points you'd be well advised to follow). If nevertheless you want to subvert the design intent of Python, Python does give you enough rope to shoot yourself in the foot: import sys reload(sys) and now, after reloading, sys.setdefaultencoding will be there anew. Alex From macrocosm at fastmail.fm Mon Jan 10 10:44:14 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Mon, 10 Jan 2005 10:44:14 -0500 Subject: Python Operating System??? In-Reply-To: <41E200D0.6010402@fastmail.fm> References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> <7x6526otw3.fsf@ruckus.brouhaha.com> <41E200D0.6010402@fastmail.fm> Message-ID: <41E2A2CE.7030308@fastmail.fm> Arich Chanachai wrote: > Paul Rubin wrote: > >> "Roose" writes: >> > > What I really wonder about is the possibility of integrating Mono with a kernel and building upward (the "shell" if you will) using IronPython. From tjreedy at udel.edu Mon Jan 24 17:18:45 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Jan 2005 17:18:45 -0500 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> Message-ID: "George Sakkis" wrote in message news:35kn4mF4o44ufU1 at individual.net... > Why does slicing a tuple returns a new tuple instead of a > view of the existing one, given that > tuples are immutable ? I ended up writing a custom > ImmutableSequence class that does this, but I > wonder why it is not implemented for tuples. Numpy and Numarray both do this -- generate views into arrays -- because they are specifically aimed at large datasets for which the memory savings overrides the complications. Aside from the problem of not being able to delete the underlying object, the view object for a tuple would have to be a new type of object with a new set of methods. So there would be one more thing to learn. And so 'type(o) is tuple' would generally have to be replaced by 'isinstance(type(o), (tuple,tupleview)). For slices that are used within expressions and then discarded, a= (1,2,3) b = a(1:) + a(:1) an internal tuple view might be an interesting optimization. Terry J. Reedy From pythongnome at hotmail.com Mon Jan 17 08:27:25 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Mon, 17 Jan 2005 13:27:25 GMT Subject: List problems in C code ported to Python In-Reply-To: <41eb1cd7$0$10879$a1866201@visi.com> References: <41ead925$0$87061$a1866201@visi.com> <41eb1cd7$0$10879$a1866201@visi.com> Message-ID: <13PGd.1402$Rs.1375@newsread3.news.atl.earthlink.net> Grant Edwards wrote: > On 2005-01-16, Lucas Raab wrote: > > >>>>Please see both the Python and C code at >>>>http://home.earthlink.net/~lvraab. The two files are ENIGMA.C >>>>and engima.py >>> >>> http://www.catb.org/~esr/faqs/smart-questions.html >> >>I didn't expect to get bitched out just because I didn't >>follow "protocol." > > > You didn't get "bitched out". You did get some very sound > advice. You want help solving a problem, and there are ways you > can greatly increase the chances that you'll get help with your > problem. After being told the best ways to get help, you > whined about it rather than following it. > > Nobody owes you anything. > > Remember that. > > [You're darned lucky somebody did take the time to go to your > web site and proof your code for you after your posting said in > effect "I'm too lazy to compose and post a precise question, so > go look at my program and fix it for me."] > > Now, go back and read the smart questions reference. > Sorry about that. I had a bad day. First there was the migraine and then the fight with my significant other, so yesterday was not a good day. I apologize for what I said. From python at hope.cz Mon Jan 17 12:12:59 2005 From: python at hope.cz (python at hope.cz) Date: 17 Jan 2005 09:12:59 -0800 Subject: How to prevent the script from stopping before it should Message-ID: <1105981979.853318.269300@c13g2000cwb.googlegroups.com> I have a script that downloads some webpages.The problem is that, sometimes, after I download few pages the script hangs( stops). (But sometimes it finishes in an excellent way ( to the end) and download all the pages I want to) I think the script stops if the internet connection to the server (from where I download the pages) is rather poor. Is there a solution how to prevent the script from hanging before all pages are downloaded? Thanks for help Lad. From phr at localhost.localdomain Mon Jan 24 17:33:20 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Mon, 24 Jan 2005 22:33:20 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.bro Message-ID: "Fredrik Lundh" writes: > please answer the question: have you done this? what kind of programs > have you successfully delivered as "self-contained apps" for use on arbi- > trary platforms? Here's a simple one: import sha name = raw_input('Enter your name: ') print 'Your name hashes to:', sha.new(name).hexdigest() Maybe the sha module isn't in fact available on all platforms, but it's definitely available on more platforms than I personally have compilers for. Maybe some more complicated app will hit some non-sha-related platform dependency and present a porting problem. But it's worse if it has additional porting problems caused by the sha module. Making the sha module available on multiple platforms is a good thing regardless of what the rest of the app does. Doing that means one less porting problem to worry about. So your question is an irrelevant misdirection. Anyway, I've written Python code that that's run under Linux and Windows and the Macintosh without needing porting. That's not the same as testing on every platform Python runs on, but if one of those platforms fails other than from using a builtin module that's documented as being platform specific, especially if the module is a pure mathematically-defined algorithm like sha and not an OS-interfacing module like threading or Tkinter, then I'd say the portability bug is in Python or its library, not in my app. From http Sat Jan 22 10:48:54 2005 From: http (Paul Rubin) Date: 22 Jan 2005 07:48:54 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> Message-ID: <7xekgdmpll.fsf@ruckus.brouhaha.com> "Fredrik Lundh" writes: > "I'll only work on stuff if I'm sure it's going right into the core" > isn't exactly a great way to develop good Python software. I > recommend the "would anyone except me have any use for this?" > approach. 1. Crypto is an important "battery" for many security applications. As a crypto activist I like to spread crypto, and I therefore think it would be useful if crypto were in the core. That is the reason I was willing to do the work of writing a suitable module. To have it go into the core and further my goal of spreading crypto. That's as good a reason as any to write a crypto module. 2. "Would anyone except me have any use for this?" shows a lack of understanding of how Python is used. Some users (call them "application users" or AU's) use Python to run Python applications for whatever purpose. Some other users (call them "developers") use Python to develop applications that are intended to be run by AU's. Now we're talking about an extension module written in C. There is no way to write AES for Python any other way and still have reasonable perfomance. Modules written in C and distributed separately from the core are a pain in the neck to download and install. You need compilers, which not everyone has access to. AU's often use Windows, which doesn't come with any compilers, so many AU's have no compilers. Developers generally have access to compilers for the platforms they develop on, but usually won't have compilers for every target platform that every AU in their audience might want to run their app on. Even AU's with compilers need to be able to install extension modules before they can run them, which isn't always possible, for example if they're using Python at a web hosting service. What I'm getting at here is that C modules are considerably more useful to AU's if they're in the core than if they're outside it, and the effect is even larger for developers. For developers, extension modules are practically useless unless they're in the core. Depending on extension modules that have to be installed by the AU severely limits the audience for the developer's app. The module we're discussing was intended for developers. "Would anyone except me have any use for this, [even if it doesn't go in the core]?" is a bizarre question. The whole purpose of the module was to let developers ship Python crypto apps that don't making the AU load external C modules. If it's not in the core, it doesn't meet its usefulness criterion. Your proposed question amounts to asking "is this worth doing even if its usefulness is severely limited?". I aleady asked myself that question and the answer was no. I was only interested in the higher-usefulness case, which means putting the module in the core. I don't see anything unreasonable about that. I can only work on a limited number of things, so I pick the most useful ones. From itsme at yahoo.com Wed Jan 5 15:29:47 2005 From: itsme at yahoo.com (It's me) Date: Wed, 05 Jan 2005 20:29:47 GMT Subject: win32com.client problem References: <1104955511.276842.316210@f14g2000cwb.googlegroups.com> Message-ID: <%6YCd.6892$wZ2.3931@newssvr13.news.prodigy.com> Thanks for the reply. I will chew on this a bit. "Kartic" wrote in message news:1104955511.276842.316210 at f14g2000cwb.googlegroups.com... > Hi, > > 1. Put your COM invokations in a try/except loop. From my experience, > that helped me prevent, in most cases, Excel from "hanging" and having > to restart the PC too. In the except part, release the Excel (or other > COM resource) (e.g.calling workbook.Close() or excelobj.Quit(), > depending on the state of your program) > > 2. Look at > http://www.faqts.com/knowledge_base/entry/versions/index.phtml?aid=5847 > to see how to get the actual error. > > 3. Delete instances of the COM connection, RS object or whatever > win32com.client instances you create. I do this: > sheetobj = None > wbkbobj = None > excelobj = None > del sheetobj > del wbkobj > del excelobj > > 4. At the end of my scripts, I do the following during the development > stage: > ActiveComConn = pythoncom._GetInterfaceCount() > print 'Done! Active Com Connections :',ActiveComConn # Print count of > Active COM connections. > > Thank you, > --Kartic > From jfj at freemail.gr Fri Jan 28 16:54:55 2005 From: jfj at freemail.gr (jfj) Date: Fri, 28 Jan 2005 13:54:55 -0800 Subject: Question about 'None' In-Reply-To: References: <1106852591.770254.203560@z14g2000cwz.googlegroups.com> <41F9E081.6050008@freemail.gr> Message-ID: <41FAB4AF.3090200@freemail.gr> Francis Girard wrote: > > What was the goal behind this rule ? > If you have a list which contains integers, strings, tuples, lists and dicts and you sort it and print it, it will be easier to detect what you're looking for:) G. From aleaxit at yahoo.com Mon Jan 24 03:38:25 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 24 Jan 2005 09:38:25 +0100 Subject: compile python to binary References: <1d6cdae3050123080242bf8994@mail.gmail.com> <_YCdnROs58UKfm7cRVn-vA@comcast.com> Message-ID: <1gqvzzs.brv6xu4xrm8hN%aleaxit@yahoo.com> Doug Holton wrote: ... > > oh, you mean that "python compiler" didn't mean "the python compiler". > > I wouldn't assume a novice uses terms the same way you would. It was > quite clear from his message that py2exe and the like were what he was > referring to, if you had read his first sentence: > > "I have seen some software written in python and delivered as binary form." Sorry, Doug, not clear to me. I have seen, for example, some games delivered with binary files with names such as something.pyc -- and those ARE binary files made by the python compiler. Alex From ncoghlan at iinet.net.au Tue Jan 25 09:39:36 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 00:39:36 +1000 Subject: Tuple slices In-Reply-To: <35lm6dF4hr4t2U1@individual.net> References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> Message-ID: <41F65A28.1040504@iinet.net.au> George Sakkis wrote: > You're probably right about the allocation time, but my main concern is the memory required for each > slice, which can be O(n) wrt the length of the whole tuple. I would like this to be constant (at > least if there was a way around to the problem of deleting the underlying sequence). If you really want a view into a tuple (or any sequence for that matter): from itertools import islice islice(iter(seq), start, end, step) Then use the various functions in itertools to work with the resulting iterator (since the syntactic support for working with iterators is currently quite limited - slicing, concatenation and repetition are spelt with itertools.islice(), itertools.chain() and itertools.repeat(), rather than with their standard syntactic equivalents "[x:y:z]", "+" and "*"). The above approach does suffer from the problem of holding a reference to the original sequence, though. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From bill.mill at gmail.com Mon Jan 31 19:28:51 2005 From: bill.mill at gmail.com (Bill Mill) Date: Mon, 31 Jan 2005 19:28:51 -0500 Subject: Java Integer.ParseInt translation to python In-Reply-To: <008d01c507f4$451d9b30$2820790d@stso.xcdg.xerox.com> References: <008d01c507f4$451d9b30$2820790d@stso.xcdg.xerox.com> Message-ID: <797fe3d405013116284ecfab68@mail.gmail.com> Jose, On Mon, 31 Jan 2005 19:23:35 -0500, jose isaias cabrera wrote: > > Greetings! > > I've looked through the internet (not long, though) but I have not been able > to find a python translation to > > buffer[0] = (byte)Integer.parseInt(string,16); Tell me what this does, give me an example or two, and I'll translate it for you. I don't feel like going to read the java docs to figure it out. You probably want to look at the built-in int() function though. Type help(int) at the python prompt. Peace Bill Mill bill.mill at gmail.com From franz.steinhaeusler at utanet.at Fri Jan 28 03:50:50 2005 From: franz.steinhaeusler at utanet.at (Franz Steinhaeusler) Date: Fri, 28 Jan 2005 09:50:50 +0100 Subject: Profiling and speed up Message-ID: Hi Newsgroup, I'm looking for a way to measure the performance of an app, which is built in wxPython and uses the styled text control Then after discovering some bottlenecks, to speed up things; first of all minimize the startup time. and then speed up the stc. Someone is experienced and could show me a way or give me tips? Are there some tools in python (beside of the profile module), best if it would be graphical like performance analysis from DevPartner for Visual C++? Second question: python has a kind of garbage collector. But could it be, because of some bad programming style, that memory is wasted more and more? Many thanks in advance! -- Franz Steinhaeusler From http Sun Jan 30 22:42:55 2005 From: http (Paul Rubin) Date: 30 Jan 2005 19:42:55 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <7xzmysqmxk.fsf@ruckus.brouhaha.com> Message-ID: <7xmzuqqn5s.fsf@ruckus.brouhaha.com> Skip Montanaro writes: > While it might be convenient to not have to distribute some third > party library in addition to Python, there is a fundamental problem > implementing a crypto algorithm from scratch for inclusion into > Python. There is always the problem that the new code has to be > more rigorously tested than typical code Actually and surprisingly, that's not really true. Crypto algorithms are pretty straightforward, so if you examine the code and check that it passes a bunch of test vectors, you can be pretty sure it's correct. It's much harder to check something like a compiler, which has a much bigger state space, far more decision points, etc. The usual bugs in crypto apps (and there are lots of such bugs) are in how the primitives are used, not in the primitives themselves. > and new bugs means a new distribution of Python, not just a > replacement library. Why would that be true of a crypto module and not true of, say, the socket module? If the socket module has a bug that allows a remote takeover of the application, that's as bad as a crypto bug. > A bug in code that is not security-related generally means something > doesn't work and only rarely means a security hole has been opened > on the computer. A bug in security-related code more often means > the latter as well. People often don't understand that that almost all code is security-related. Any code that touches data that came from the internet is security related. If the math library arctangent function has a buffer overflow bug triggered by a certain input number, and someone uses math.arctan in an image viewing program, then maybe a specially concocted image designed to set off the bug can take over the user's computer. So even something like math.arctan is security related. > While I imagine the changes were fairly small, the guys involved are > all very smart, and the code is fairly straightforward (little, if > any, memory allocation going on), there is still the possibility > that a bug lurks in either the incorporated code or in the changes > to it. How quickly could the Python community respond if a bug was > found and fixed in the public domain SHA code? How much harder > would it be for people to adapt if they had to reinstall Python > instead of just an external library? If they're able to install external libraries, what stops them from reinstalling a patched sha module? The hazards of using a crypto module are sort of like the hazards of using the threading module. Unless you know what you're doing and are very careful, it's easy to make an error. But the resulting bugs happen because the module did exactly what you asked for, not because it did something different from what you asked for. If you ever write code that uses the Internet, I highly recommend the book "Security Engineering", by Ross Anderson. It will give you some idea of what you are up against. From fuzzyman at gmail.com Fri Jan 28 03:50:16 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 28 Jan 2005 00:50:16 -0800 Subject: urllib and proxy In-Reply-To: <1106849199.450771.314960@f14g2000cwb.googlegroups.com> References: <1106849199.450771.314960@f14g2000cwb.googlegroups.com> Message-ID: <1106902216.684672.76640@f14g2000cwb.googlegroups.com> See : http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/f1ba0de2c739127c/f694e00b1253da1e For urllib you can pass in the 'proxies={}' keyword to the urlopen function. This disables proxy use. Unfortunately it *doesn't* work for urllib2 which is where I need it. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From godoy at ieee.org Tue Jan 4 13:30:41 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Tue, 04 Jan 2005 16:30:41 -0200 Subject: Pexpect getting a defuct process References: Message-ID: <4127138.ESWWbkVb31@strongwill.g2ctech> Baillargeon, Sonny, Ter?a 04 Janeiro 2005 16:16, wrote: > Nothing...I know that's the default answer but considering I control the > environment, I can assure you that nothing changed. I have no reason to doubt you. :-) Checking pexpect's documentation, and re-reading your code I see that you have not called "close()". As the documentation says: (http://pexpect.sourceforge.net/doc/pexpect.html) """ close(self, wait=1) (...) Only set wait to false if you know the child will continue to run after closing the controlling TTY. Otherwise you will end up with defunct (zombie) processes. """ Be seeing you, -- Godoy. From peter at somewhere.com Wed Jan 26 05:22:06 2005 From: peter at somewhere.com (Peter Maas) Date: Wed, 26 Jan 2005 11:22:06 +0100 Subject: building Python: up arrow broken on SuSE Linux 8.2 In-Reply-To: <41f6c3f7$1@nntp.zianet.com> References: <41f6c3f7$1@nntp.zianet.com> Message-ID: Erik Johnson schrieb: > I am trying to upgrade my Python installation. After downloading > sources and building Python 2.3.4, I am unable to use the command > history editing feature in the interactive interpreter (where the > up-arrow would previously give you the last command line to edit, > it now just prints "^[[A".) Do you have the GNU readline library installed and within Python's reach (lib in LD_LIBRARY_PATH or in /etc/ld.so.conf with subsequent call of ldconfig)? -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From duncan.booth at invalid.invalid Fri Jan 28 07:00:18 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 Jan 2005 12:00:18 GMT Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> Message-ID: grahamd at dscpl.com.au wrote: > I find this response a bit dissappointing frankly. Open Source people > make > such a big deal about having lots of people being able to look at > source > code and from that discover security problems, thus making it somehow > making it better than proprietary source code. I think part of the problem you are having is that Python doesn't make any representations about security, so it is pretty hard to come up with issues which really are security related. Products which are based on Python (e.g. Zope) and which do aim to provide some kind of secure environment probably will have some clear mechanism for reporting security related issues. The only part of Python which used to claim to offer security was rexec and the bastion module, but they had so many security issues that they were removed from the distribution. In other words, I'm intrigued how you managed to come up with something you consider to be a security issue with Python since Python offers no security. Perhaps, without revealing the actual issue in question, you could give an example of some other situation which, if it came up in Python you would consider to be a security issue? From danjr at voyager.net Sat Jan 15 16:15:05 2005 From: danjr at voyager.net (danjr) Date: Sat, 15 Jan 2005 21:15:05 GMT Subject: where can i fins some good pywin32 tutorials? References: Message-ID: "ionel" wrote in message news:mailman.744.1105804723.22381.python-list at python.org... > need somethin to get started with mfc on python > There is an excellent book found at Amazon .... Python Programming on Win32 http://tinyurl.com/3qypz From sjtu.0992 at gmail.com Mon Jan 24 15:44:32 2005 From: sjtu.0992 at gmail.com (Albert Tu) Date: 24 Jan 2005 12:44:32 -0800 Subject: Question about reading a big binary file and write it into several text (ascii) files Message-ID: <1106599472.099182.312130@z14g2000cwz.googlegroups.com> Hi, I am learning and pretty new to Python and I hope your guys can give me a quick start. I have an about 1G-byte binary file from a flat panel x-ray detector; I know at the beggining there is a 128-byte header and the rest of the file is integers in 2-byte format. What I want to do is to save the binary data into several smaller files in integer format and each smaller file has the size of 2*1024*768 bytes. I know I can do something like >>>f=open("xray.seq", 'rb') >>>header=f.read(128) >>>file1=f.read(2*1024*768) >>>file2=f.read(2*1024*768) >>>...... >>>f.close() Bur I don't them how to save files in integer format (converting from binary to ascii files) and how to do this in an elegant and snappy way. Please reply when you guyes can get a chance. Thanks, Warm regards, Albert From pedro.werneck at terra.com.br Mon Jan 24 13:19:13 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Mon, 24 Jan 2005 16:19:13 -0200 Subject: Tuple slices In-Reply-To: References: <35kn4mF4o44ufU1@individual.net> Message-ID: <20050124161913.3c9fc9f8.pedro.werneck@terra.com.br> On Mon, 24 Jan 2005 18:45:46 +0100 "Fredrik Lundh" wrote: > George Sakkis wrote: > > > Why does slicing a tuple returns a new tuple instead of a view of > > the existing one, given that tuples are immutable ? > > really? Well... seems like this case is optimized to return the original tuple just incrementing its reference count and returning tupleobject.c, 330-335 if (ilow == 0 && ihigh == a->ob_size && PyTuple_CheckExact(a)) { Py_INCREF(a); return (PyObject *)a; } > > >>> a = 1, 2, 3 > >>> b = a[:] > >>> a is b > True > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From http Tue Jan 4 10:19:00 2005 From: http (Paul Rubin) Date: 04 Jan 2005 07:19:00 -0800 Subject: Python evolution: Unease References: Message-ID: <7xacrpdxy3.fsf@ruckus.brouhaha.com> Roman Suzi writes: > As for his claims, I am quite surprised that Python lacks > something in the docs. Python is lacking plenty in the docs. Care to figure out from the docs how tkinter works? That's not explained anywhere at all, except in some off-site resources and in some printed books. Even some language features like class methods and slots are explained only in PEP's and release notes, instead of in the language manual where you'd expect to find them since they're part of the language. From deetsNOSPAM at web.de Fri Jan 21 07:22:42 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 21 Jan 2005 13:22:42 +0100 Subject: tkinter socket client ? References: <1106288752.561833.46510@z14g2000cwz.googlegroups.com> <11h1v0lnsoh9l46vmt26umn5kafdk5n7u8@4ax.com> <1106307973.536723.297940@z14g2000cwz.googlegroups.com> Message-ID: <35cae5F4jvrirU1@individual.net> > just one problem - I do not know how to sit in a "loop" accepting > messages on the socket connection - writting them to the Text() widget > - refreshing the the GUI - and then starting all over .... > where do I put the loop for the socket ? Another thread? Or use twisted, it comes with a tkinter-aware exec-loop: http://twistedmatrix.com/documents/howto/choosing-reactor#auto16: -- Regards, Diez B. Roggisch From jbperez808 at wahoo.com Sat Jan 15 04:12:35 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Sat, 15 Jan 2005 17:12:35 +0800 Subject: Producer/consumer Queue "trick" In-Reply-To: References: Message-ID: <34s541F4f5gqiU1@individual.net> I don't get it. If the consumer and the producer are separate threads, why does the consumer thread block when the producer thread is generating a new board? Or why does it take forever for the producer thread to be pre-empted? Also, I don't understand why the solution works. How does sleeping for .001 seconds right after putting a new board on the queue solve the problem? Evan Simpson wrote: > WEBoggle needs a new game board every three minutes. Boards take an > unpredictable (much less than 3min, but non-trivial) amount of time to > generate. The system is driven by web requests, and I don't want the > request that happens to trigger the need for the new board to have to > pay the time cost of generating it. > > I set up a producer thread that does nothing but generate boards and put > them into a length-two Queue (blocking). At the rate that boards are > pulled from the Queue, it's almost always full, but my poor consumer > thread was still being blocked for "a long time" each time it fetched a > board. > > At this point I realized that q.get() on a full Queue immediately wakes > up the producer, which has been blocked waiting to add a board to the > Queue. It sets about generating the next board, and the consumer > doesn't get to run again until the producer blocks again or is preempted. > > The solution was simple: have the producer time.sleep(0.001) when > q.put(board) returns. From steve at holdenweb.com Sun Jan 2 09:47:15 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 02 Jan 2005 09:47:15 -0500 Subject: The Industry choice In-Reply-To: <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: Mark Carter wrote: > > It might be nice if it was widely understood (in IT) that Python was > a language any competent > > programmer could pick up in an afternoon > > I am a programmer who works for a firm of engineers, where they program > in VBA, badly. I've often mentioned Python, whereupon I'm usually > dismissed as a crank. One of them expressed concern that if they used > Python and I left, then nobody would understand what to do. I could have > countered that Python is actually quite an easy language to pick up, but > what's the point. > > We might be doing a project which involves web-type stuff. I pointed out > that if they did, they wouldn't be able to use VB/VBA, and may need to > use something like Python. I didn't get a reaction from that at the > time, but no doubt they'll be telling me that I'll have to make Excel > work through the internet, or something. They'll probably just move to .NET, which allows them to write .aspx pages using VB. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From olsongt at bellatlantic.net Fri Jan 7 18:28:55 2005 From: olsongt at bellatlantic.net (olsongt at bellatlantic.net) Date: 7 Jan 2005 15:28:55 -0800 Subject: OT: google groups bug, or worse? In-Reply-To: <1105127965.616198.302710@z14g2000cwz.googlegroups.com> References: <1105127965.616198.302710@z14g2000cwz.googlegroups.com> Message-ID: <1105140535.472013.237880@f14g2000cwb.googlegroups.com> aaronwmail-usenet at yahoo.com wrote: > I'm concerned that google groups is not correctly reflecting the > python lists. A month ago I announced the xsdbXML framework to the > python list and the python-announce list. As you can see from the > links > below the python announce submission was approved by the moderators > (thanks!) > and the python list submission also went out, but the messages cannot > be found at google groups. > > http://mail.python.org/pipermail/python-list/2004-December/254479.html > http://mail.python.org/pipermail/python-announce-list/2004-December/003583.html > > Is it a google bug? Or is it something darker, like an anti-Python > conspiracy at google? > > Inquiring minds want to know. > > -- Aaron Watters > > === > There are 3 kinds of people, those who can count and those who can't. > -- folklore. Exact same thing happened to me on Jan 2nd. From fredrik at pythonware.com Sat Jan 22 02:34:27 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 08:34:27 +0100 Subject: list unpack trick? References: Message-ID: "aurora" wrote: > The only issue is when s does not contain the character '=', let's say it is 'xyz', the result > list has a len of 1 and the unpacking would fail. Is there some really handy trick to pack the > result list into len of 2 so that it unpack as name='xyz' and value=''? do you need a trick? spelling it out works just fine: try: key, value = field.split("=", 1) except: key = field; value = "" or if "=" in field: key, value = field.split("=", 1) else: key = field; value = "" (the former might be slightly more efficient if the "="-less case is uncommon) or, if you insist: key, value = re.match("([^=]*)(?:=(.*))?", field).groups() or key, value = (field + "="["=" in field:]).split("=", 1) but that's not really worth the typing. better do key, value = splitfield(field) with a reasonable definition of splitfield (I recommend the try-except form). > So more generally, is there an easy way to pad a list into length of n with filler items appended > at the end? some variants (with varying semantics): list = (list + n*[item])[:n] or list += (n - len(list)) * [item] or (readable): if len(list) < n: list.extend((n - len(list)) * [item]) etc. From DoubleMPi at Netscape.com Tue Jan 25 20:06:22 2005 From: DoubleMPi at Netscape.com (Mike Moum) Date: Wed, 26 Jan 2005 01:06:22 GMT Subject: string.atoi and string.atol broken? In-Reply-To: <41f6d96f$1@news.uni-ulm.de> References: <41f6d96f$1@news.uni-ulm.de> Message-ID: Dennis Benzinger wrote: > Just out of curiosty: > What did you think what atoi does? > I don't understand how you came to expect that atoi('4',3) > should result in 11. > > > Bye, > Dennis Mea culpa. For some strange reason, I had it in my mind that atoi would take a base ten number as a string and convert it to the correct representation in the base of the second argument. In other words, atoi('4',3) should take 4 in base 10 and convert it to base 3, resulting in 11. Exactly backwords, as atoi('11',3) = 4, that is, 11 base 3 = 4 base 10. Thanks to all for setting me straight. Mike From http Thu Jan 20 04:54:55 2005 From: http (Paul Rubin) Date: 20 Jan 2005 01:54:55 -0800 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <41EEF691.20706@jessikat.fsnet.co.uk> <7xacr4ewjk.fsf@ruckus.brouhaha.com> <41ef4a7a.1323588509@news.oz.net> <7xwtu8vb17.fsf@ruckus.brouhaha.com> <41EF72DE.5030305@jessikat.fsnet.co.uk> Message-ID: <7xwtu8pgr4.fsf@ruckus.brouhaha.com> Robin Becker writes: > Apparently factorization based crypto is on the way out anyhow (as an > article in Scientific American is reported to claim). I haven't seen that SA article but I saw the Slashdot blurb. They have confused "quantum cryptography" with quantum computation, when they are entirely different things. Quantum cryptography (basically communicating a message over an optical fiber in such a way that any attempt to eavesdrop is supposed destroy the readability of the message) has been done over quite long distances, 10's of km or even more. Quantum computation is mostly a theoretical speculation. The largest quantum computer ever built held seven bits, and factored the number 15 into its factors 3 and 5. Building larger ones seems to have complexity exponential in the number of bits, which is not too much better than using an exponential-time algorithm on a conventional computer. It's not even known in theory whether quantum computing is possible on a significant scale. There are just some theorems about what properties such a computer would have, if it can exist. One of them, however, is being able to factor in P-time, and that caused lots of excitement. From stephen.thorne at gmail.com Tue Jan 18 17:47:16 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Wed, 19 Jan 2005 08:47:16 +1000 Subject: simultaneous multiple requests to very simple database In-Reply-To: <41ED8EB6.503@harvee.org> References: <41ED8EB6.503@harvee.org> Message-ID: <3e8ca5c805011814474969dff1@mail.gmail.com> On Tue, 18 Jan 2005 17:33:26 -0500, Eric S. Johansson wrote: > so in conclusion, my only reason for querying was to see if I was > missing a solution. So far, I have not found any work using because > they add orders of magnitude more complexity than simple dbm with file > locking. Obviously, the simple solution has horrible performance right > now I need simplicity implementation. > > thanks for your commentary. Maybe you can just get the best of both worlds. Have a look at SQLObject. You can ignore the fact that underneath the SQLObject there's a postgres (or mysql, or whatever) database, and get OO based persistance. SQLObject is crippled in that there are degrees of freedom that SQL gives you that SQLObject takes away/makes hard to use, but what you're trying to do, and what most people actually do with databases, can be easily wrapped around with a simple, pythonic wrapper. It even has a .createTable() function for those times when you don't even want to log into the database. Regards, Stephen Thorne. From steven.bethard at gmail.com Wed Jan 26 15:31:47 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 13:31:47 -0700 Subject: access private field in python 2.4 In-Reply-To: <1106769651.371856.107960@f14g2000cwb.googlegroups.com> References: <1106754371.637295.82160@z14g2000cwz.googlegroups.com> <4prkc2-ini.ln1@pluto.i.infosense.no> <1106769651.371856.107960@f14g2000cwb.googlegroups.com> Message-ID: ajikoe at gmail.com wrote: > Hello, if we want to access the private member of object we use the > classname, it doesn't make sense. For example: > I have class A: > > class A: > def __init__(self, i): > self.__i = i; > pass > > __i = 0 > > a = A(22); > b = A(33); > > How can I get field i in object a and how can I get field i in object > b? py> class A: ... def __init__(self, i): ... self.__i = i; ... py> a = A(22) py> a._A__i 22 > Beside I try to call: > print _A__i #fail this create error Looks like you're confused about the difference between instances and modules. The code: print _A__i asks Python to print the attribute _A__i of the given module. But you want the attribute _A__i of the instance 'a'. As you can see in my code, if you want the attribute of the instance, you need to specify it as such. As an additional reminder, you generally *shouldn't* be accessing "private" variables of a class. There's a reason they're declared private. ;) Steve From gandalf at geochemsource.com Fri Jan 28 04:49:46 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Fri, 28 Jan 2005 10:49:46 +0100 Subject: unicode and data strings In-Reply-To: References: <41FA03C1.50404@geochemsource.com> Message-ID: <41FA0ABA.9040801@geochemsource.com> >>ut encodings. How do I do that? >> >> > >Unicode errors only appear if you're converting between "raw 8-bit data" and >Unicode strings (which contain Unicode characters, not bytes or integers). You >cannot do that without caring about encodings... > > I see now. Thanks for your help. It was: seed1 + pwd + seed2 where seed1 was raw and pwd was unicode. Laci 2.0 From vze4rx4y at verizon.net Wed Jan 19 12:52:16 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Wed, 19 Jan 2005 17:52:16 GMT Subject: generator expressions: performance anomaly? References: <377Hd.77904$Jk5.30235@lakeread01> Message-ID: [Steve Holden] > Since it doesn't yet optimize 2+5 to a constant-folded 7 you should > realize that you are suggesting a large increase in the compiler's > analytical powers. FWIW, limited constant folding is already in CVS for Py2.5. Raymond Hettinger From crap1234 at hotmail.com Fri Jan 7 02:47:30 2005 From: crap1234 at hotmail.com (Stefan Axelsson) Date: Fri, 07 Jan 2005 08:47:30 +0100 Subject: The Industry choice In-Reply-To: References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <344l83F45rstqU1@individual.net> Message-ID: <346t4jF481352U1@individual.net> Bulba! wrote: > I've read Novell license of internal development tools it provides > (which I reviewed for some purpose). This is I think relevant > part: > I'm not saying licenses like you claim don't exist. Sure, > they may exist and they suck. > > The point is, they have _limited impact_ and by > the very fact of their "exclusion" nature, this > aspect tends to repel users than attract them to > use this thing. Well, as I didn't catch that we were discussing development tools but even so, I thought the license you quoted rather strengthened my point in the section on 'reverse engineering?. (Then again I've seen other's where that was not the case, was it MS (?) quite a few years back that didn't allow you to develop an OS using their tool chain? And that was a binary license.) If you look at actual end user program licenses (such as Solaris/wxWorks etc) the picture is much clearer. In any case, it's somewhat beside the point as even the license you chose to quote took away precisely all those rights that the GPL grants you. You weren't allowed to (in any way shape or form) to communicate anything you knew about that source to anyone else. And I don't buy into your argument that a use of some source code would go against the 'intended' use by making it GPL. How the hell am I supposed to know what the author 'intends' if he doesn't tell me? Especially if, of all the available licenses, choses one that explicitly permits the sort of use that I envision? I mean, it's not as if many BSD fans complain that MS took much TCP/IP related code and put it in Windows (ftp etc). Without sharing anything back with the community. If that's OK, how am I supposed to know that my use isn't? It's just the same situation as when I lock my house. That's intended as a means of communication with the rest of society. It communicates my intent that I'm not home (or don't want to be disturbed) and that I don't want them in the house, and it does so more strongly than mere social convention does. There are after all several members of community that needs this reminder; notably children. It's emphatically not to keep thieves out (much) as they won't be much hampered by the ordinary lock. If you don't want me to use your code in the way I envision then tell me. The license is the *perfect* place to do so. Stefan, -- Stefan Axelsson (email at http://www.cs.chalmers.se/~sax) From alan.gauld at btinternet.com Sat Jan 1 04:35:32 2005 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Jan 2005 09:35:32 +0000 (UTC) Subject: Complementary language? References: Message-ID: On Sat, 25 Dec 2004 18:40:31 -0500, HackingYodel wrote: > Hello all! I'm learning to program at home. I can't imagine a better > language than Python for this. The ideal situation, for me, would be to > study two languages at the same time. Probably sounds crazy, but it > works out better for me. Me too, thats why my web tutorial features Python, VBSCript and Javascript. (The previous version had BASIC and Tcl with Python) > fascinating. C, D, Objective-C, Ocaml, C++, Lisp, how is a non-tech to > choose? Does any single language do a better job in Python's weaker > areas? C is better at low level stuff, Prolog is better at declaratie programming and Haskell is better at functional programming. Lisp/Scheme are good for giving a good theoretical understanding (try the SICP and HTDP web sites). And Tcl has a really different approach which is plain fun to grapple with :-) I chose VBScript and JavaScript because they have similar structure to Python (traditional imperative programming with OOP) but very different syntax. Plus they were free and easily available (albeit with VBScript limited to Windows users, who are 80+% of my visitors). Javascript is especially useful since its an easy lead in to learning C/C++, Java, even Perl to some extent and a lot of sample code sites use those languages. Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From peter at engcorp.com Thu Jan 27 09:01:22 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 27 Jan 2005 09:01:22 -0500 Subject: Point of Sale In-Reply-To: References: Message-ID: Andreas Pauley wrote: > My company has given me a rather cool project: > I have to provide them with an open-source python-based point-of-sale / > cash register system that can integrate with their existing ERP backend. Do you have information about the interface to the ERP back end? It could be anything just about anything... > The project will include development to ensure that the features they > require are included in the open-source POS system. I read that as "will include automated acceptance tests", but perhaps you meant something else? > Can you recommend anything that I can use? There's a good chance you'll need to use PySerial, if the cash registers are connected via RS-232, but beyond that there's not much to say without more info. I believe I heard somebody talking about a Python POS system before in this newsgroup, but I'm not sure: check the archives? -Peter From Scott.Daniels at Acm.Org Sat Jan 1 18:00:37 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 01 Jan 2005 15:00:37 -0800 Subject: exposing C array to python namespace: NumPy and array module. In-Reply-To: References: <41d71170$1@nntp0.pdx.net> Message-ID: <41d728f5$1@nntp0.pdx.net> Bo Peng wrote: > Scott David Daniels wrote: >> I wrote "blocks and views" to overcome this problem. > I was too impatient to wait for your reply. :-) I call 21-hour turnaround over New Year's Eve pretty good. Clearly I will never be quick enough for you ;-). Since I presented this at the Vancouver Python Workshop last August, I'll claim a negative five months response time (possibly a personal best). --Scott David Daniels Scott.Daniels at Acm.Org From mambuhl at earthlink.net Sat Jan 29 02:42:38 2005 From: mambuhl at earthlink.net (Martin Ambuhl) Date: Sat, 29 Jan 2005 02:42:38 -0500 Subject: what's OOP's jargons and complexities? In-Reply-To: References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> <360244F4lolueU1@individual.net> Message-ID: <360t3iF4rjc9vU1@individual.net> Gabriel Dos Reis wrote: > Martin Ambuhl writes: > > | Dan Perl wrote: > | > | > Actually, it can be as simple as: > | > public class test { > | > | There is no "public" or "class" in C. Please don't post such trash to > | comp.lang.c. In fact, C++ is not topical in any of the five > > But, it was anything but C++. Maybe Java. > And why is Java topical for any of the five newsgroups he spewed on, which deal with perl, python, lisp, scheme, and C? There must be a high correlation between using Java and idiocy. From tdelaney at avaya.com Tue Jan 11 00:08:17 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Tue, 11 Jan 2005 16:08:17 +1100 Subject: shutil.move has a mind of its own Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE72122D@au3010avexu1.global.avaya.com> Daniel Bickett wrote: > shutil.move( "C:\omg.txt" , "C:\folder\subdir" ) ^ ^^ ^ The problem is that backslash is the escape character. In particular, '\f' is a form feed. >>> '\o' '\\o' >>> '\f' '\x0c' >>> '\s' '\\s' Notice how for '\o' and '\s' it doubles-up the backslash - this is because '\o' and '\s' are not valid escapes, and so it treats the backslash as just a backslash. But '\f' is a valid escape. You have a couple of options: 1. Use double-backslashes (to escape the backslash): shutil.move("C:\\omg.txt", "C:\\folder\\subdir") 2. Use forward slashes (they work on Windows for the most part): shutil.move("C:/omg.txt", "C:/folder/subdir") 3. Build your paths using os.path.join (untested): shutil.move(os.path.join("C:", "omg.txt"), os.path.join("C:", "folder", "subdir")) Tim Delaney From gurpreet.sachdeva at gmail.com Thu Jan 13 23:58:17 2005 From: gurpreet.sachdeva at gmail.com (Gurpreet Sachdeva) Date: Fri, 14 Jan 2005 10:28:17 +0530 Subject: pyPgSQL giving error! In-Reply-To: References: Message-ID: And now when I did... cd /usr/local/lib/python2.3/site-packages/pyPgSQL/libpq/ [root at linux libpq]# python __init__.py Traceback (most recent call last): File "__init__.py", line 23, in ? from libpq import * ImportError: ./libpqmodule.so: undefined symbol: PyUnicodeUCS2_EncodeDecimal What is this error??? I saw this error sometimes back... Please help... Thanks, Garry From jdhunter at ace.bsd.uchicago.edu Fri Jan 21 09:53:48 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 21 Jan 2005 08:53:48 -0600 Subject: how to write a tutorial In-Reply-To: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> ("Xah Lee"'s message of "21 Jan 2005 03:08:50 -0800") References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> Message-ID: >>>>> "Xah" == Xah Lee writes: Xah> at places often a whole paragraph on some so called computer Xah> science jargons should be deleted. They are there more to Xah> showcase inane technicality than do help the Xah> reader. (related, many passages with jargons should be Xah> rewritten sans inane jargon. e.g. mutable object.) The concept of mutable objects is extremely important in python, and understanding is the key to answering two recurring newbie questions * Why can't lists or dictionaries be keys to dictionaries? * Why does using a list as a default value for a keyword argument in a function definition often lead to unexpected results? So it is definitely appropriate material in a tutorial. As for jargon, it is hard to argue that "object" is inane jargon in python. In fact, the base class for new-styled classes is indeed "object", and if you want to write one of these classes yourself, you need to do 'class MyClass(object)'. So object is not inane jargon in an object oriented programming language. You still with me? OK, now on to mutable. mutable means changeable, albeit it's a little more of an obscure word than changeable, but it does roll off the tongue a bit more easily. Perhaps 'changeable object' would be more accessible to some readers, but it doesn't flow as well. So the python tutorial should perhaps define mutable when it introduces it. Which it does somewhat implicitly; the first time mutable is mentioned in the docs, in the context of strings Unlike strings, which are immutable, it is possible to change individual elements of a list: And now for my last musing on a new topic "How to write a critique": It is much more constructive to suggest new text for documentation than to brand it inane. JDH From bokr at oz.net Tue Jan 25 04:45:35 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 25 Jan 2005 09:45:35 GMT Subject: is there better 32 clock() timing? References: Message-ID: <41f61372.1768192005@news.oz.net> On Tue, 25 Jan 2005 00:18:44 -0800, Tim Roberts wrote: >Ray Schumacher wrote: >> >>I have a need for a time.clock() with >0.000016 second (16us) accuracy. >>The sleep() (on Python 2.3, Win32, at least) has a .001s limit. >> >>Are they lower/better on other's platforms? > >You need to be careful about describing what you're seeing here. It is not >that time.clock() is inaccurate. The problem is that the "time.clock()" >statement takes several hundred microseconds to execute. What system are you on? This is 300 mhz P2 and py2.4b1 gcc/mingw generated: >>> from time import clock >>> min(abs(clock()-clock()) for i in xrange(10**5)) 5.8666657725137128e-006 >>> min(abs(clock()-clock()) for i in xrange(10**5)) 5.866665771847579e-006 >>> min(abs(clock()-clock()) for i in xrange(10**5)) 5.8666657700712221e-006 >>> import time >>> min(abs(time.clock()-time.clock()) for i in xrange(10**5)) 7.5428559824786134e-006 >>> min(abs(time.clock()-time.clock()) for i in xrange(10**5)) 7.5428559824786134e-006 >>> min(abs(time.clock()-time.clock()) for i in xrange(10**5)) 7.5428559824786134e-006 Even with the attribute lookup overhead, it's not several hundred microseconds as a *minimum*. But on e.g. win32 you can get preempted for a number of milliseconds. E.g., turn that to a max instead of a min: I see a couple 20-30 ms ones ;-/ >>> max(abs(time.clock()-time.clock()) for i in xrange(10**5)) 0.0085142082264155761 >>> max(abs(time.clock()-time.clock()) for i in xrange(10**5)) 0.0088125700856949152 >>> max(abs(time.clock()-time.clock()) for i in xrange(10**5)) 0.0022125710913769581 >>> max(abs(clock()-clock()) for i in xrange(10**5)) 0.023374472628631793 >>> max(abs(clock()-clock()) for i in xrange(10**5)) 0.030183995400534513 >>> max(abs(clock()-clock()) for i in xrange(10**5)) 0.0017130664056139722 >>> max(abs(clock()-clock()) for i in xrange(10**5)) 0.0070844179680875641 > >>I had also considered forking a thread that would spin a loop checking >>time.clock() and firing the TTL pulse after the appropriate interval, >>but the real, ultimate resolution of time.clock() appears to be >>~.00035s. If I increase process priority to real-time, it is ~.00028s >>The alternative appears to be more C code... > >Are you seriously considering writing a real-time application in Python on >Windows? The ONLY way to get small-integer microsecond responses in >Windows is to write a kernel driver, and even then there are no guarantees. >Windows is NOT a real-time system. If you have an environment where an >unexpected delay of a millisecond or more is going to cause damage, then >you need to redesign your application. For sure. The big requirements picture is missing (not uncommon ;-) Regards, Bengt Richter From irmen at -nospam-remove-this-xs4all.nl Sat Jan 8 15:08:59 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sat, 08 Jan 2005 21:08:59 +0100 Subject: tuples vs lists In-Reply-To: References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <41dff650$0$29357$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41e03dda$0$6208$e4fe514c@news.xs4all.nl> Steve Holden wrote: > Well, it might be "Two-Pull" in American, but in English it's "tyoopl" > -- NOT "choopl" (blearch!). I've also heard people say "tuppl". Probably the same ones who attend Tuppl-ware parties. --Irmen From ncoghlan at iinet.net.au Sun Jan 23 02:11:48 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 23 Jan 2005 17:11:48 +1000 Subject: finding name of instances created In-Reply-To: <1106438690.420574.247510@f14g2000cwb.googlegroups.com> References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> <1106438690.420574.247510@f14g2000cwb.googlegroups.com> Message-ID: <41F34E34.2070004@iinet.net.au> Andr? wrote: > I have tried this exact example (using Python 2.3 if it makes any > difference) and what I got was: > robot None moved > robot None moved > > I checked what I wrote, used cut & paste on your code, removing the > leading "junk", tried it again ... to no avail. :-( Worked exactly as written for me, but I believe there were Python 2.4 changes relating to using exec with non-standard dictionaries. Regards, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From roy at panix.com Mon Jan 24 19:40:31 2005 From: roy at panix.com (Roy Smith) Date: Mon, 24 Jan 2005 19:40:31 -0500 Subject: Another scripting language implemented into Python itself? References: Message-ID: In article , Quest Master wrote: > I am interested in developing an application where the user has an > ample amount of power to customize the application to their needs, and > I feel this would best be accomplished if a scripting language was > available. However, I want to code this application in Python, and I > have not yet heard of an implementation of another scripting language > into Python. > > An example of what I mean is this (an implementation of Lua into Ruby > -- which I'd prefer not to use): http://ruby-lua.unolotiene.com/ > > I know C/C++ might be better suited for a task of this kind, but most > of the modules in my application which need speed have already been > coded in C++. I want to use Python as the "glue" for this project; > writing an entire application with a pretty GUI is not fun, as most of > you may know from previous experience. > > So, my question is simply this: is there an implementation of another > scripting language into Python? Python *is* a scripting language. Why not just let your users write Python modules which you them import and execute via some defined API? From peter at engcorp.com Mon Jan 10 19:19:29 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 10 Jan 2005 19:19:29 -0500 Subject: time module precision In-Reply-To: <1105344170.575115.230820@c13g2000cwb.googlegroups.com> References: <1105268967.629064.154850@c13g2000cwb.googlegroups.com> <1105344170.575115.230820@c13g2000cwb.googlegroups.com> Message-ID: janeaustine50 at hotmail.com wrote: > Peter Hansen wrote: >>_Why_ do you want to wait such brief amounts of time? > > What I am trying to do is sending binary data to a serial port. Since > the device attached to the port cannot handle a continous in-flow of > data, I need to make an artificial tiny delay in-between data chunks(a > few hundreds of KBs). The delay might be a few tens to hundreds of us. I guess you've checked that your situation can't take advantage of either hardware handshaking (e.g. RTS/CTS) or software handshaking (Xon/Xoff) to do flow control. Something doesn't quite feel right in your description, however, but it could simply be because the sorts of devices we work with are quite different. I'm very surprised to hear about a device that can manage to absorb *hundreds of KBs* of data without any handshaking, and yet after that much data suddenly manages to have a hiccup on the order of mere microseconds before it can take more data. Also, is your data rate so high that a few hundred microseconds represents a noticeable delay? I'm rarely dealing with data rates higher than, say, 38400bps, where hundreds of KBs would take on the order of minutes, so 100us is effectively instantaneous in my world. I calculate that your data rate would have to be higher than 307Mbps (a third of a gigabit per second) before 100us would represent a large enough delay (measured in bits rather than time) that you would be bothered by it... (defined somewhat arbitrarily as more than 2% of the time required to send 100KB of data at your data rate). > I'd like to make the transmission as fast as possible, uh.. well.. > reasonably fast. I suspect it will be, if you simply do a time.sleep(0.001) and pretend that's shorter than it really is... since WinXP is not a realtime OS, sometimes that could take as long as hundreds of milliseconds, but it's very unlikely that anyone will ever notice. -Peter From aleaxit at yahoo.com Sat Jan 29 04:24:27 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 29 Jan 2005 10:24:27 +0100 Subject: Dynamic class methods misunderstanding References: <35v5jdF4rk3m7U1@individual.net> Message-ID: <1gr5b2x.1s7zqt9ufc993N%aleaxit@yahoo.com> Bill Mill wrote: ... > > class Test: > > def __init__(self, method): > > self.m = new.instancemethod(method, self, Test) > > Beautiful! thank you very much. Looking into the "new" module in > python 2.4, that's equivalent to: > > self.m = type(self.__init__)(method, self, Test) Another approach with the same result is to exploit the fact that a function is a descriptor: self.m = method.__get__(self, Test) Alex From steve at holdenweb.com Mon Jan 17 06:23:13 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 06:23:13 -0500 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> Message-ID: <41EBA021.5060903@holdenweb.com> Antoon Pardon wrote: [...] >>"A foolish consistency is the hobgoblin of little minds". Rules are made >>to be broken. > > > Like only use immutables as dictionary keys. > Fair enough, but don;t go advising newbies to do this. > >>Besides which, if you don't understand the language >>environment, rules alone will do you very little good. Try to focus a >>little more on principles and a little less on minutiae. > > > And what are the difference between those two? > > Sometimes I get the impression that everything is a principle until > one personnaly finds the need to break it. After that it is a rule. > Principle: "Ten angels can dance on the head of a pin". Minutiae: "Well, if they'd all recently been on a diet and they hold on to each other very carefully you can get 10.3. I got eleven once by adding a hash function". regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From fumanchu at amor.org Mon Jan 10 11:32:28 2005 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 10 Jan 2005 08:32:28 -0800 Subject: Writing huge Sets() to disk Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339814E@exchange.hqamor.amorhq.net> Martin MOKREJ? wrote: > I have sets.Set() objects having up to 20E20 items, > each is composed of up to 20 characters. Keeping > them in memory on !GB machine put's me quickly into swap. > I don't want to use dictionary approach, as I don't see a sense > to store None as a value. The items in a set are unique. > > How can I write them efficiently to disk? got shelve*? Robert Brewer MIS Amor Ministries fumanchu at amor.org * the "shelve" module in the standard library, that is. From skip at pobox.com Mon Jan 17 22:11:36 2005 From: skip at pobox.com (Skip Montanaro) Date: Mon, 17 Jan 2005 21:11:36 -0600 Subject: Fuzzy matching of postal addresses In-Reply-To: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <16876.32360.693431.612740@montanaro.dyndns.org> Andrew> I'm 90% of the way there, in the sense that I have a simplistic Andrew> approach that matches 90% of the addresses in database A. But Andrew> the extra cases could be a pain to deal with! Based upon the examples you gave, here are a couple things you might try to reduce the size of the difficult comparisons: * Remove "the" and commas as part of your normalization process * Split each address on white space and convert the resulting list to a set, then consider the size of the intersection with other addresses with the same postal code: >>> a1 = "St John's Presbytery, Shortmoor, BEAMINSTER, DORSET, DT8 3EL".upper().replace(",", "") >>> a1 "ST JOHN'S PRESBYTERY SHORTMOOR BEAMINSTER DORSET DT8 3EL" >>> a2 = "THE PRESBYTERY, SHORTMOOR, BEAMINSTER, DORSET DT8 3EL".upper().replace(",", "").replace("THE ", "") >>> a2 'PRESBYTERY SHORTMOOR BEAMINSTER DORSET DT8 3EL' >>> a1 == a2 False >>> sa1 = set(a1.split()) >>> sa2 = set(a2.split()) >>> len(sa1) 8 >>> len(sa2) 6 >>> len(sa1 & sa2) 6 Skip From wittempj at hotmail.com Mon Jan 24 07:24:11 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 24 Jan 2005 04:24:11 -0800 Subject: Help with Threading In-Reply-To: References: Message-ID: <1106569451.677064.86620@f14g2000cwb.googlegroups.com> I use threading.Thread as outlined in this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448 From bokr at oz.net Tue Jan 18 19:18:48 2005 From: bokr at oz.net (Bengt Richter) Date: Wed, 19 Jan 2005 00:18:48 GMT Subject: generator expressions: performance anomaly? References: <377Hd.77904$Jk5.30235@lakeread01> <41ED1C0F.4030800@holdenweb.com> Message-ID: <41eda453.1215517842@news.oz.net> On Tue, 18 Jan 2005 09:24:15 -0500, Steve Holden wrote: [...] >You probably already know that sensible compiled language systems have >used constant folding since time immemorial, but Python has always >eschewed it. That's what comes of being a pragmatist's language: if such >optimizations really are required the programmer is expected to perform >them. Which make me wonder what plans there are for providing a better mechanism than default arguments as a way of initializing local function variables. Nested def's to create a closure with initialized values is pretty crufty for that, IMO. Maybe extending the default argument space with whatever comes after e.g. a triple star delimiter in the argument list, but which wouldn't be counted as part of the normal arguments? E.g., def foo(x, y=123, *args, **kw, *** i=1, deftime=time.ctime()): return x*y, kw.get('which_time')=='now' and time.ctime() or deftime Seem like a minor extension of the default-arg hack. Regards, Bengt Richter From roy at panix.com Fri Jan 14 09:12:45 2005 From: roy at panix.com (Roy Smith) Date: Fri, 14 Jan 2005 09:12:45 -0500 Subject: Python.org, Website of Satan References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: In article , Michael Hoffman wrote: > Peter Renzland wrote: > > What is the simplest/fastest Python program to determine how many > > IP addresses sum up to 666? > > > > The simplest/fastest enumerator? > > > > The simplest/fastest that determines which ones of them are home pages? > > This seems to work although it could be made more efficient or elegant. > Also, the failed gethostbyaddr() calls take forever. > > from socket import gethostbyaddr, herror > > for a in xrange(256): > if a < 666-255*3: > continue I'm not sure what you meant to do, but note that 'a < 666-255*3' is false for all values of 'a' generated by the xrange() call. Removing that test would make the code more efficient. Hard to say if it would make it more elegant :-) From dbickett at gmail.com Tue Jan 25 13:15:45 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Tue, 25 Jan 2005 13:15:45 -0500 Subject: Help! Host is reluctant to install Python Message-ID: <1d6cdae305012510156f81a74@mail.gmail.com> I've been trying to convince my host to install python/mod_python on his server for a while now, however there are a number of reasons he is reluctant to do so, which I will outline here: 1. His major reason is optimization. He uses Zend's optimization of PHP as an example, and he has stated that python is rather resource consuming. 2. Another one of his points is that he is unexperienced in installing python, and he would not know how to do it securely. By 'securely', I'm assuming he means disallowing a malicious (or ignorant) user from harming the server And, in light of point #1, I suggested that if there wasn't any optimization immediately available, he could just enable it for my account (thus lessening potential resource consumption at any given time), to which he retorted "Do /you/ know how to do that?", and I must say, he has me cornered ;-) I have no experience with this sort of thing, so I'm asking a little assistance in the direction of any documents or websites (or what have you) I could show him in order to answer some of these questions, or perhaps even some unspoken ones -- anything worth noting. (all I'm really going to do is link him to this thread once it has accumulated any answers) Thank you all for your help :) Wishing-to-be-liberated-from-the-clutches-of-PHP-ly y'rs, Daniel Bickett From apardon at forel.vub.ac.be Tue Jan 18 09:05:15 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Jan 2005 14:05:15 GMT Subject: generator expressions: performance anomaly? References: <354esdF4fouh0U1@individual.net> Message-ID: Op 2005-01-18, Diez B. Roggisch schreef : >> Something else I was thinking about. I think it would be nice if the >> python compilor could figure out whether a genexp in a list or tuple >> expression always generates the same list or tuple and then instead >> of generating code would generate the list or tuple in place. > > This won't ever happen in python - at least not in python otherwise similar > to the one we know... > > The thing you're after is known as "common subexpression elemination" and > can only be done in purely functional languages. While that certainly is an > interesting property of a language, it e.g. forbids functions like > time.time() - a too huge paradigm shift for python. > I don't see how generating byte code for a = 9; when seeing the expression a = 3 + 6, would be a problem for non-functional languages. I agree that things like [time.time() for i in xrange(10)] shouldn't be pregenerated and that the problem is more complicated as I thought. But during compilation the compilor could do an anlysis of the code do determine whether there are side effects or not. If the compilor then would store a code in the byte code for functions that are guaranteed side-effect free and only pregenerated objects generated by expressions with no side-effect, some common subexpression elimination could be done even in a non-functional language. -- Antoon Pardon From agriff at tin.it Sun Jan 9 17:51:47 2005 From: agriff at tin.it (Andrea Griffini) Date: Sun, 09 Jan 2005 22:51:47 GMT Subject: Speed revisited References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> <1105237556.402188.126980@c13g2000cwb.googlegroups.com> <1105303172.147395.63580@c13g2000cwb.googlegroups.com> Message-ID: <36c3u0tpbg6f98ta6cm4fkj2kn0dkv624m@4ax.com> On 9 Jan 2005 12:39:32 -0800, "John Machin" wrote: >Tip 1: Once you have data in memory, don't move it, move a pointer or >index over the parts you are inspecting. > >Tip 2: Develop an abhorrence of deleting data. I've to admit that I also found strange that deleting the first element from a list is not O(1) in python. My wild guess was that the extra addition and normalization required to have insertion in amortized O(1) and deletion in O(1) at both ends of a random access sequence was going to have basically a negligible cost for normal access (given the overhead that is already present in python). But I'm sure this idea is too obvious for not having been proposed, and so there must reasons for refusing it (may be the cost to pay for random access once measured was found being far from negligible, or that the extra memory overhead per list - one int for remembering where the live data starts - was also going to be a problem). Andrea From bokr at oz.net Tue Jan 11 16:55:01 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 11 Jan 2005 21:55:01 GMT Subject: Python serial data aquisition References: <41e384d0.552090624@news.oz.net> Message-ID: <41e4483c.602118390@news.oz.net> On 11 Jan 2005 07:51:35 -0800, fccoelho at gmail.com (Flavio codeco coelho) wrote: >bokr at oz.net (Bengt Richter) wrote in message news:<41e384d0.552090624 at news.oz.net>... >> On 9 Jan 2005 14:13:28 -0800, fccoelho at gmail.com (Flavio codeco coelho) wrote: >> >> >Hi, >> > >> >I am using pyserial to acquire data from an A/D converter plugged to >> >my serial port. >> > >> >my hardware represents analog voltages as 12bit numbers. So, according >> >to the manufacturer, this number will be stored in two bytes like >> >this; >> > |-------------bits(1-8)-----------| >> >Byte1: x x x n1 n2 n3 n4 n5 >> >Byte2: x n6 n7 n8 n9 n10 n11 n12 >> > >> >where x is some other information, and nx are the digits of my number. >> > >> >My problem is to how to recover my reading from these bytes, since >> >pyserial gives me a character (string) from each byte... I dont know >> >how to throw away the unneeded bits and concatenate the remaining >> >bits to form a number... >> > >> The others have shown how to recover a 12 bit positive value 0 through 4095, >> but if the number is signed, and you want the signed value, you'll have to >> find out how signed numbers are represented. An offset is common, in which >> case you would subtract 2048 (2**11). If it's two's complement by some chance, >> you'll want (I think -- untested ;-) to do num -= 2*(num&2048) instead of always num -= 2048 >> If you need speed in converting large strings of byte pairs, you could >> convert pairs of bytes with the array module ('H' for unsigned 2-byte numbers) >> and use the resulting 16-bit numbers as indices into another array of final values >> prepared beforehand with redundant information that will accomplish the effect >> of masking and shifting and adjusting sign. >> If you need this speed, volunteers will magically appear. Maybe even if you don't ;-) >> Regards, >> Bengt Richter > > >Hi Bengt, > >The Idea of using Array is realy cool Though I have to think about it >since I would to plot the values as they are sampled... > >Anyway, how would you set up this array to do the shifting and >masking? See below. > >BTW, since this thread is generating quite a bit of attention let me >post a complete description of my problem so that it may serve as >reference to others: > >Hardware: DI-151RS from Dataq (2 analog channels, 2 digital input, >single ended/differential recording, max sampling rate 240Hz) connects >to the serial pro through a standard db9 plug. > >Encryption table: > > > B7 B6 B5 B4 B3 B2 B1 B0 >Byte1 A4 A3 A2 A1 A0 1 Din 0 >Byte2 A11 A10 A9 A8 A7 A6 A5 1 >Byte3 B4 B3 B2 B1 B0 1 Din 1 >Byte4 B11 B10 B9 B8 B7 B6 B5 1 > >first two bytes are for analog ch 1 and remaining two are for ch 2. >Din stands for digital in. AXX and BXX are the nth bits of each >reading. A0 and B0 are the least significant bits. > >The latest and preferred solution on how to convert these bytes is, >according to the suggestion of Chris Liechti (author of pyserial) is: >(this is for the first channel only, repeat for the second) > >import struct > > l, h = struct.unpack(">BB", ser.read(2)) > n = (l >> 3) + ((h >> 1)<<5) > >struct.unpack returns a tuple of values represented by a string(the >output of the read command) packed according to the format specified >by ">BB" >In this forma string, ">" stands for big Endian representation and "B" >stands for unsigned char. > >If anyone has a better suggestion, speack up! > >oof! I started this thread knowing next to nothing about this stuff, >It seem that I am finally getting the idea! :)) > ----< flavio.py >---------------------------------------------------- import array # set up conversion table for all 8-bit little-endian byte pair possibilities convert = array.array('l',[((ahi>>1)<<5)+(alo>>3) for ahi in xrange(256) for alo in xrange(256)]) def samptoval(samples): # convert many-sample string to array of 16-bit unnsigned integers data = array.array('H') data.fromstring(samples) # replace 16-bit byte pair values with 12-bit values for i, v in enumerate(data): data[i] = convert[v] return data def fakedata(i12, b0=0, din=0): """convert unsigned 12-bit integer to little-endian byte string""" return chr(((i12&0x1f)<<3)+4+din*2+b0) + chr(((i12&0xfe0)>>4)+1) def test(v1=0, v2=256): assert 0 <= v1 <= v2 <=4096, "values must be in range(4096)" # default (0, 256) => fake a lot of A, B input pairs like ser.read(4*256) samples = ''.join([fakedata(i)+fakedata(i,1) for i in xrange(v1,v2)]) data = samptoval(samples) for i, v in enumerate(xrange(v1,v2)): #print i, data[i*2:i*2+2], v assert data[i*2] == data[i*2+1] == v return samples, data if __name__ == '__main__': import sys args = sys.argv[1:3] result = test(*map(int, args)) print '%r\n%r' % result --------------------------------------------------------------------- This creates pairs of A and B data for a sequence of 12-bit values and converts them back for a test, e.g., [13:40] C:\pywk\clp>flavio.py 0 4 '\x04\x01\x05\x01\x0c\x01\r\x01\x14\x01\x15\x01\x1c\x01\x1d\x01' array('H', [0, 0, 1, 1, 2, 2, 3, 3]) [13:45] C:\pywk\clp>flavio.py 30 34 '\xf4\x01\xf5\x01\xfc\x01\xfd\x01\x04\x03\x05\x03\x0c\x03\r\x03' array('H', [30, 30, 31, 31, 32, 32, 33, 33]) [13:45] C:\pywk\clp>flavio.py 2046 2050 '\xf4\x7f\xf5\x7f\xfc\x7f\xfd\x7f\x04\x81\x05\x81\x0c\x81\r\x81' array('H', [2046, 2046, 2047, 2047, 2048, 2048, 2049, 2049]) [13:45] C:\pywk\clp>flavio.py 4092 4096 '\xe4\xff\xe5\xff\xec\xff\xed\xff\xf4\xff\xf5\xff\xfc\xff\xfd\xff' array('H', [4092, 4092, 4093, 4093, 4094, 4094, 4095, 4095]) >From your diagram it looks to me like your data is little-endian (least significant data in the first byte) so I did it that way. Actually at 240 hz, I doubt you'd have any problem with speed doing it any which way, so this is premature optimization, and just to explain the technique, in case it's interesting. But if you had a HUGE long string of sample data, samptoval should go fairly fast I would think. You could also use struct to convert two bytes to an unsigned 16-bit number, and then use that number to look up the value as flavio.convert[num] instead of making two numbers and doing the combination yourself. Regards, Bengt Richter From mhartl at post.harvard.edu Thu Jan 6 15:34:52 2005 From: mhartl at post.harvard.edu (mhartl at post.harvard.edu) Date: 6 Jan 2005 12:34:52 -0800 Subject: File Handling Problems Python I/O References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> <1105034789.700445.291380@z14g2000cwz.googlegroups.com> Message-ID: <1105043692.497106.315270@z14g2000cwz.googlegroups.com> You can use the os module to build path names in a platform-independent manner. On my Linux box, I can type >>> BASE = '/' >>> import os >>> os.path.join(BASE, 'foo', 'bar', 'baz') '/foo/bar/baz' On a Windows machine, you get >>> BASE = 'C:' >>> import os >>> os.path.join(BASE, 'foo', 'bar', 'baz') 'C:\\foo\\bar\\baz' This is a little more cumbersome that just typing the string, but using os.path.join makes it easy to port your scripts to a new platform. Check out http://docs.python.org/lib/module-os.path.html for more information. Cheers, Michael -- Michael Hartl http://michaelhartl.org/ From yessireeyesindeedydo at yahoo.ca Tue Jan 11 21:45:28 2005 From: yessireeyesindeedydo at yahoo.ca (=?iso-8859-1?B?TGEgYm91Y2hlIGRlIGxhIHbpcml06SAtIETpauAgVnUgTGUgUHJvcGjpdGU=?=) Date: 11 Jan 2005 18:45:28 -0800 Subject: Python.org, Website of Satan In-Reply-To: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: <1105497928.471241.13590@z14g2000cwz.googlegroups.com> Your Uncle Wally just luuirrrrrrrrrrrrrvs Monty Python -- especially John Clesse, Eric Idle & Michael Palin -- very funny !!!!!!!! he he he ;-) From john at grulic.org.ar Tue Jan 11 00:23:04 2005 From: john at grulic.org.ar (John Lenton) Date: Tue, 11 Jan 2005 02:23:04 -0300 Subject: unicode mystery In-Reply-To: References: Message-ID: <20050111052304.GB29014@grulic.org.ar> On Mon, Jan 10, 2005 at 07:48:44PM -0800, Sean McIlroy wrote: > I recently found out that unicode("\347", "iso-8859-1") is the > lowercase c-with-cedilla, so I set out to round up the unicode numbers > of the extra characters you need for French, and I found them all just > fine EXCEPT for the o-e ligature (oeuvre, etc). I examined the unicode > characters from 0 to 900 without finding it; then I looked at > www.unicode.org but the numbers I got there (0152 and 0153) didn't > work. Can anybody put a help on me wrt this? (Do I need to give a > different value for the second parameter, maybe?) ? isn't part of ISO 8859-1, so you can't get it that way. You can do one of u'\u0153' or, if you must, unicode("\305\223", "utf-8") -- John Lenton (john at grulic.org.ar) -- Random fortune: Lisp, Lisp, Lisp Machine, Lisp Machine is Fun. Lisp, Lisp, Lisp Machine, Fun for everyone. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From snacktime at gmail.com Wed Jan 26 15:22:55 2005 From: snacktime at gmail.com (snacktime) Date: Wed, 26 Jan 2005 12:22:55 -0800 Subject: Set parity of a string In-Reply-To: <1f060c4c05012611554f727d29@mail.gmail.com> References: <1f060c4c05012611503090c261@mail.gmail.com> <1f060c4c05012611554f727d29@mail.gmail.com> Message-ID: <1f060c4c050126122228b0a4e3@mail.gmail.com> Argh, never mind my mistake. I wasn't logging the data correctly the parity conversion works fine. Chris From ajikoe at gmail.com Mon Jan 31 13:25:04 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 31 Jan 2005 10:25:04 -0800 Subject: stop program in komodo In-Reply-To: <41fe750e$0$327$db0fefd9@news.zen.co.uk> References: <1107194102.482439.272480@c13g2000cwb.googlegroups.com> <41fe750e$0$327$db0fefd9@news.zen.co.uk> Message-ID: <1107195904.074522.5550@f14g2000cwb.googlegroups.com> Hello Will, I have received information from Shanec at ActiveState.com That he has already added this problem as bug. "I've added a bug for this: http://bugs.activestate.com/show_bug.cgi?id=36443 Regards, Shane" So stay tune..... Pujo From roy at panix.com Mon Jan 24 21:17:24 2005 From: roy at panix.com (Roy Smith) Date: Mon, 24 Jan 2005 21:17:24 -0500 Subject: Another scripting language implemented into Python itself? References: Message-ID: Rocco Moretti wrote: > The OP doesn't mention his application, but there is something to be > said about domain specific scripting languages. A well designed > domain-specific scripting language(*) with the appropriate high level > constructs can make script writing simpler. This is a bit of a sore point with me. I've been involved with several projects where people felt the need to invent their own scripting languages. It usually starts with "we don't need the power of a full programming language, we only need to be able to do X, Y, and Z". So they write a little language which lets them do X, Y, and Z. Then they discover they need more complex data structures than they originally thought. And nested loops. And functions. And more sophisticated variable scoping rules. And a regex library. And 47 other things. So they duct-tape all those into the system. A few years later, you end up with most of a real programming language, except with a whole bunch of warts. The syntax is usually quirky (the one I'm working with today does not allow any space before the open paren of a function call, but requires it before the opening paren of an "if" statement). It generally has poor error reporting. It doesn't have the whole family of free tools that grow up around any real language (editor customization packages, syntax checkers, debuggers, extensions, etc). You doesn't have a gaggle of tutorial books written about it that you can buy from your favorite on-line bookseller. Worse, when you need more brains/bodies on the project, you can't put an add on Hot Jobs for "experienced OurOwnScriptingLanguage programmer" and expect to get anybody who can be productive quickly. What it does have is a body of code dependent on it which is now so large that porting it to something else is an unthinkably large task. And it's got a small cadre of language gurus who spend all day defending the language with answers like, "But, it was never *intended* that people would do stuff like this with it". Anyway, that's my little rant on inventing your own scripting language. Imbed Python, or Perl, or TCL, or Ruby, or PHP, or Java, or whatever floats your boat. Almost any choice has got to be better than rolling your own. Invest your intellectual capital doing what you can do best, and don't get bogged down developing a new language. From itsme at yahoo.com Wed Jan 12 12:35:14 2005 From: itsme at yahoo.com (It's me) Date: Wed, 12 Jan 2005 17:35:14 GMT Subject: Why would I get a TypeEror? Message-ID: For this code snip: a=3 .... b=(1,len(a))[isinstance(a,(list,tuple,dict))] Why would I get a TypeError from the len function? Thanks, From grante at visi.com Sat Jan 1 17:25:59 2005 From: grante at visi.com (Grant Edwards) Date: 01 Jan 2005 22:25:59 GMT Subject: Approximating scattered data Message-ID: <41d72377$0$31717$a1866201@visi.com> I've been looking for some way to approximate scattered 3D data points in Python. The data doesn't seem to be amenable to fitting functions like polymials, so I may have to use something more like a spline surface. However, I can't find anything usable from Python, and my Fortram skills are pretty rusty. I tried SciPy, but it's spline fitting module doesn't work at all for my data. I've found mentions of a Python port NURBS toolbox, but all the links I can find are broken. I've also found references to Fortran programs from netlib/toms, but I was hoping there might be something that was already usable from Python. Can anybody point me toward a Python module for approximating scattered data using something like a Renka algorithm? -- Grant Edwards grante Yow! How do I get HOME? at visi.com From j.p.t.j.berends at [N0SP4M].nl Thu Jan 6 08:35:16 2005 From: j.p.t.j.berends at [N0SP4M].nl (J Berends) Date: Thu, 06 Jan 2005 14:35:16 +0100 Subject: get the IP address of a host In-Reply-To: References: Message-ID: Lee Harr wrote: > I found that the socket solutions only work if your > DNS entries are correct ... which in my case was not > true. So I came up with this: That is indeed correct, and even if the DNS entries are correct at times it does not give the full list of IPs by gethostbyname or gethostbyaddr. > import commands > ifconfig = '/sbin/ifconfig' > # name of ethernet interface > iface = 'eth0' > # text just before inet address in ifconfig output > telltale = 'inet addr:' > > ... > > Basically, it scrapes the output from ifconfig for the > actual address assigned to the interface. Works perfectly > on FreeBSD and Linux (given the correct configuration). Nice way, have to device something for windows than. From several approached I came up with the following code: def getipaddr(hostname='default'): """Given a hostname, perform a standard (forward) lookup and return a list of IP addresses for that host.""" if hostname == 'default': hostname = socket.gethostname() ips = socket.gethostbyname_ex(hostname)[2] ips = [i for i in ips if i.split('.')[0] != '127'] if len(ips) != 0: # check if we have succes in determining outside IP ip = ips[0] elif len(ips) == 0 and hostname == socket.gethostname(): # when we want to determine local IP and did not have succes # with gethostbyname_ex then we would like to connect to say... # google.com and determine the local ip address bound to the # local socket. try: s = socket.socket() s.connect(('google.com', 80)) print ('___ connecting to internet to determine local ip') ip = s.getsockname()[0] del s except: print ('*** cannot connect to internet in order to \ determine outside IP address') raise Exception if len(ip) != 0: return ip else: print ('*** unable to determine outside IP address') raise Exception It returns the IP address with which it connects to the world (not lo), might be a pvt LAN address or an internet routed IP. Depend on where the host is. I hate the google trick actually, so any suggestions to something better is always welcome. From claird at lairds.us Sun Jan 16 11:08:07 2005 From: claird at lairds.us (Cameron Laird) Date: Sun, 16 Jan 2005 16:08:07 GMT Subject: PyChecker messages References: Message-ID: In article , Roger Binns wrote: . . . >> runner.py:200: Function (detectMimeType) has too many returns (11) >> >> The function is simply a long "else-if" clause, branching out to different >> return statements. What's wrong? It's simply a "probably ugly code" advice? > >That is also advice. Generally you use a dict of functions, or some other >structure to lookup what you want to do. . . . This interests me. Let's be more precise. Use, it's absolutely true that good Python style exploits dicts far more than newcomers realize (although somewhat less than Lua, a language which intriguingly pushes dictionary pragmatics to the limit). In particular, it is frequently the case that beginners' appetite for a "switch" is best met by a lesson in use of a dictionary of functions. HOWEVER, proliferation of functions itself adds weight. My own counsel is that a simple sequence of if ... return ... if ... return ... often is exactly the right definition for a specific function. I, incidentally, prefer this form over the if ... return ... elif ... return ... the original poster described. So: yes, "[g]enerally you use a dict of functions" when PyChecker thinks you have "too many returns", but I do NOT advise it for the specific case that appears to be at hand. From ptmcg at austin.rr._bogus_.com Fri Jan 21 18:42:16 2005 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 21 Jan 2005 23:42:16 GMT Subject: default value in a list References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: "TB" wrote in message news:1106349263.943972.72710 at f14g2000cwb.googlegroups.com... > Hi, > > Is there an elegant way to assign to a list from a list of unknown > size? For example, how could you do something like: > > >>> a, b, c = (line.split(':')) > if line could have less than three fields? > > Thanks, > TB > I asked a very similar question a few weeks ago, and from the various suggestions, I came up with this: line = "AAAA:BBB" expand = lambda lst,default,minlen : (lst + [default]*minlen)[0:minlen] a,b,c = expand( line.split(":"), "", 3 ) print a print b print c -- Paul From peter at somewhere.com Thu Jan 13 15:15:39 2005 From: peter at somewhere.com (Peter Maas) Date: Thu, 13 Jan 2005 21:15:39 +0100 Subject: Refactoring; arbitrary expression in lists In-Reply-To: References: Message-ID: Steven Bethard schrieb: > BJ?rn Lindqvist wrote: [...] >> I believe this can be nicelier written as: >> >> if "Makefile" in basename: >> > > +1 for "nicelier" as VOTW (Vocabulation of the week) =) Me too, because nicelier is nicer than more nicely. :) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From bokr at oz.net Sun Jan 9 15:45:23 2005 From: bokr at oz.net (Bengt Richter) Date: Sun, 09 Jan 2005 20:45:23 GMT Subject: python3: accessing the result of 'if' References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> Message-ID: <41e1939a.424804106@news.oz.net> On Sat, 08 Jan 2005 18:30:25 +1000, Nick Coghlan wrote: >Carl Banks wrote: >> Right. But you know that as soon as you add this to simple >> expressions, a bunch of people are going to come here whining about how >> they don't get to use where with if-expressions. So why shouldn't they get to? >> >> Frankly, they might have a point here. Although we have replacing >> lambda expressions on our minds, I have in mind a different problem >> that a where-statement would solve perfectly. But it would have to be >> used with an if-expression. > >I have a different suggestion for this. > >'as' is used for renaming in import statements. 'as' will be used for exception >naming in Python 3k. > >So let's use it for expression naming in 'if' statements, too. > >if someregexp.match(s) as m: > # blah using m >elif someotherregexp.match(s) as m: > # blah using m > If 'where: ...' were an expression suite ISTM you could write if m where: m = someregexp.match(s) # same-line format blah(m) elif m where: m = someotherregexp(s) # indented suite format blah(m) # dedent from where-suite starts elif-suite Regards, Bengt Richter From itsme at yahoo.com Wed Jan 5 13:19:58 2005 From: itsme at yahoo.com (It's me) Date: Wed, 05 Jan 2005 18:19:58 GMT Subject: Python 2.4 on Windows XP References: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> Message-ID: I am running 2.3 and it's doing the same thing on my computer - except that I can't even get it to start from the command prompt. It used to work but after I switched back and forth between 2.3, and 2.4 and somewhere in between, it stopped working. I hope somebody on the list would have a clue how to fix this. "DavidHolt" wrote in message news:1104946252.430332.226930 at z14g2000cwz.googlegroups.com... > I have a problem that I see on two different machines, one running XP > SP1 and one XP SP 2. > > On both I installed Python 2.4. > > I can't seem to start IDLE. When I try to start it, I get an hourglass > cursor for a short time then nothing more happens. This happens whether > I click the IDLE shortcut or click the pythonw.exe directly, or attempt > to launch pythonw from a command line. > > I don't have any trouble running the python command line version. > > Any ideas? > Thanks, > David Holt > Software Developer > HighJump Software, a 3M Company > From rnd at onego.ru Mon Jan 3 09:59:24 2005 From: rnd at onego.ru (Roman Suzi) Date: Mon, 3 Jan 2005 17:59:24 +0300 (MSK) Subject: Lambda as declarative idiom (was RE: what is lambda used for in real code?) In-Reply-To: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> Message-ID: Hi all, BTW, Alex Martelli and me have created a PEP 312 some time ago (when the debate of inline if was hot). I wish lambdas will not be deprecated in Python but the key to that is dropping the keyword (lambda). If anybody could think of a better syntax for lambdas _with_ arguments, we could develop PEP 312 further. I DO like the idea of support for universal declaratives in Python. (This way SQL, Prolog, grammar, DTD, lazy expressions, decision tables (advanced switch statements) etc things could be added in a Pythonic way.) We only need brief lambdas and lets (for closures), IMHO. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From rogerb at rogerbinns.com Wed Jan 19 23:36:16 2005 From: rogerb at rogerbinns.com (Roger Binns) Date: Wed, 19 Jan 2005 20:36:16 -0800 Subject: FTPLIB & FTPS or SFTP? References: <9b9tu0te197u3bmheldg2hsvkbtuivlov6@4ax.com> Message-ID: <64p3c2-tl1.ln1@home.rogerbinns.com> "Peter A. Schott" wrote in message news:9b9tu0te197u3bmheldg2hsvkbtuivlov6 at 4ax.com... > have a handful of partners who use FTPS or SFTP and I need to pull/push files > to/from them. For SFTP, run don't walk, over to http://www.lag.net/paramiko/ Paramiko is a pure Python(*) implementation of SSH and all the sub-protocols such as SFTP. Works on all platforms, very responsive author, works reliably and LGPL license. (*) It does require PyCrypto which is a native code package available for all platforms. Roger From engsolnorm at peak.org Sat Jan 15 16:59:38 2005 From: engsolnorm at peak.org (engsol) Date: Sat, 15 Jan 2005 13:59:38 -0800 Subject: Com port interrupts again References: <154gu09bghnq674s2nqot9si6d50igueq7@4ax.com> Message-ID: On Fri, 14 Jan 2005 23:25:21 -0500, Peter Hansen wrote: >engsol wrote: >> I didn't fully think through my application before posting my >> question. Async com port routines to handle com port interrups >> only work well if one has access to the low level operating >> system. In that case the receive buffer interrupt would cause >> a jump to an interrupt service routine.. I don't believe that >> Python provides that capabilty directly. The solution then would >> be to write a C extention? > >Maybe, but I doubt that you can or would really want to do this >with modern operating systems anyway. With DOS, and similar >primitive things, glomming onto an interrupt or hooking yourself >into the interrupt table was pretty easy. I don't think either >Windows or Linux is structured such that you just "write a >C extension" to intercept interrupts. Instead, you must write >relatively complicated drivers which have to be loaded at >system startup (more or less) and be tied into the kernel at >a relatively low level. Think "rocket science", at least in >comparison to writing a simple C extension. :-) > >> The suggestions offered by respondents to my original post >> were almost all of a "Use threads, and poll as needed" flavor. >> You're right...I need to learn threads as applied to com ports. > >At least on Windows, I'm fairly sure you can configure the >read timeouts so that you get behaviour on reads that for >all intents and purposes is about as good as an interrupt, >without the difficulties inherent in that approach, but >provided you are willing to dedicate a thread to the task. > >On Linux, it's possible the read timeouts capabilities are >a little less flexible (but I've only just barely glanced >at this area), but as I recall you were on Windows anyway. > >BTW, another post pointed you to USPP. As far as I know, >it hasn't been updated recently and, while I can't say how >it compares to PySerial, I believe it's fair to say at >this point in time that PySerial is the _de facto_ standard >way to do serial port stuff in Python. If it doesn't do >what you need, it's probably a good idea to at least point >that out in its mailing list so that it can be improved. > >-Peter Peter, thanks for the input...good advice. I took a look at USPP, and as you observed, it seems to be a bit dated. Actually, I've violated one of my basic rules: do it the simple way first, then determine what needs to be expanded, improved, speeded up, etc. Norm B From dial#####$#$#NOSPAM####$$##$tone at gmail.com Sun Jan 2 19:38:52 2005 From: dial#####$#$#NOSPAM####$$##$tone at gmail.com (Valentino Volonghi aka) Date: Mon, 3 Jan 2005 01:38:52 +0100 Subject: Continuations Based Web Framework - Seaside. References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <7aTBd.11928$H%6.521997@twister1.libero.it> <7xhdlz8jv6.fsf@ruckus.brouhaha.com> Message-ID: <1gpshts.1o7ja8jqfh5moN%dial#####$#$#NOSPAM####$$##$tone@gmail.com> Paul Rubin wrote: > Since Python doesn't have continuations, that would be a bit tricky. Since I've already said Nevow with wolf works the same as borges. The only thing that wouldn't work without continuations is the back button. With greenlet module (from Armin Rigo) also the back button will work. I've also already posted an url to the svn sandbox with a working example inside. -- Valentino Volonghi aka Dialtone Now Running MacOSX 10.3.7 Blog: http://vvolonghi.blogspot.com http://weever.berlios.de From agriff at tin.it Sun Jan 9 09:51:49 2005 From: agriff at tin.it (Andrea Griffini) Date: Sun, 09 Jan 2005 14:51:49 GMT Subject: mysterious buggy behavior References: Message-ID: On 8 Jan 2005 20:40:37 -0800, sean_mcilroy at yahoo.com (Sean McIlroy) wrote: >def newGame(): > BOARD = [blank]*9 > for x in topButtons+midButtons+botButtons: x['text'] = '' Do you know that "BOARD" here is a local variable and has nothing to do with the global BOARD ? You can change that by doing either BOARD[:] = [blank]*9 or global BOARD BOARD = [blank]*9 HTH Andrea From daranrife at yahoo.com Fri Jan 28 20:03:39 2005 From: daranrife at yahoo.com (drife) Date: 28 Jan 2005 17:03:39 -0800 Subject: LinearAlgebra incredibly slow for eigenvalue problems In-Reply-To: <1106957760.485860.104760@f14g2000cwb.googlegroups.com> References: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> <1106952951.834888.65430@f14g2000cwb.googlegroups.com> <1106957598.136667.45430@z14g2000cwz.googlegroups.com> <1106957760.485860.104760@f14g2000cwb.googlegroups.com> Message-ID: <1106960619.700424.278180@z14g2000cwz.googlegroups.com> David, I noticed that the libraries that ATLAS builds are not shared objects (e.g., liblapack.a). Should these be shared objects? I see nothing in the ATLAS documentation about building things as shared objects. Wondering if this is why the Numeric install is failing. Daran From mefjr75 at hotmail.com Wed Jan 26 16:24:41 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 26 Jan 2005 13:24:41 -0800 Subject: Inherting from object. Or not. References: Message-ID: <1106774681.501533.156220@f14g2000cwb.googlegroups.com> Hello Frans, What you are seeing is a step on the path to unification of types and classes. Now we have that clear ;) Classes that inherit from object are 'new style classes'. They were introduced in 2.2 and they have different internal methods. The ones that have no declaration is an 'old style class'. http://www.python.org/doc/newstyle.html That link may be help. It is not required to write a class as 'class myclass(object)' yet, so many don't. In some cases it will matter which you use. In others cases it won't. Be sure to try this an an interpreter promt: Py> class NewKlass(object): ... pass Py> class OldKlass: ... pass Py> new = NewKlass() Py> old = OldKlass() Py> print dir(new) Py> print dir(old) Also new style classes are faster. Hth, M.E.Farmer Frans Englich wrote: > (Picking up a side track of the "python without OO" thread.) > > On Wednesday 26 January 2005 11:01, Neil Benn wrote: > > > I say this because you do need to be aware of the > > 'mythical python wand' which will turn you from a bad programmer into a > > good programmer simply by typing 'class Klass(object):'. > > What is the difference between inherting form object, and not doing it? E.g, > what's the difference between the two following classes? > > class foo: > pass > > class bar(object): > pass > > Sometimes people inherit from it, and sometimes not. I don't see a pattern in > their choices. > > > Cheers, > > Frans From craig at postnewspapers.com.au Fri Jan 21 09:38:10 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 21 Jan 2005 22:38:10 +0800 Subject: need help on generator... In-Reply-To: <20050121171428.61d80e99.ods@strana.ru> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> Message-ID: <1106318290.19065.11.camel@bucket.localnet> On Fri, 2005-01-21 at 17:14 +0300, Denis S. Otkidach wrote: > On 21 Jan 2005 05:58:03 -0800 > joh12005 at yahoo.fr (Joh) wrote: > > > i'm trying to understand how i could build following consecutive sets > > from a root one using generator : > > > > l = [1,2,3,4] > > > > would like to produce : > > > > [1,2], [2,3], [3,4], [1,2,3], [2,3,4] > > >>> def consecutive_sets(l): > ... for i in xrange(2, len(l)): > ... for j in xrange(0, len(l)-i+1): > ... yield l[j:j+i] Since you have a much faster brain than I (though I ended up with exactly the same thing barring variable names) and beat me to posting the answer, I'll post the inevitable awful generator expression version instead: consecutive_sets = ( x[offset:offset+subset_size] for subset_size in xrange(2, len(x)) for offset in xrange(0, len(x) + 1 - subset_size) ) -- Craig Ringer From ncoghlan at iinet.net.au Fri Jan 21 23:45:10 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 22 Jan 2005 14:45:10 +1000 Subject: need help on need help on generator... In-Reply-To: <200501211605.40696.francis.girard@free.fr> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050121171428.61d80e99.ods@strana.ru> <1106318290.19065.11.camel@bucket.localnet> <200501211605.40696.francis.girard@free.fr> Message-ID: <41F1DA56.4090909@iinet.net.au> Francis Girard wrote: > In particular, I don't know what Python constructs does generate a generator. > I know this is now the case for reading lines in a file or with the new > "iterator" package. But what else ? Does Craig Ringer answer mean that list > comprehensions are lazy ? Where can I find a comprehensive list of all the > lazy constructions built in Python ? (I think that to easily distinguish lazy > from strict constructs is an absolute programmer need -- otherwise you always > end up wondering when is it that code is actually executed like in Haskell). I don't think there is a *list* as such, but there are some rules of thumb for when lazy evaluation will take place (hopefully others will note any cases that I missed): 1. Iterators (classes with a next() method, and an __iter__ method that returns 'self') are lazily evaluated, as itr.next() is called to retrieve each value. I think you will find it is this method, rather than __new__ which is relevant to creating class-based generators. Note that "for x in itr" automatically calls itr.next() in order to obtain each new value of the loop variable. This iterator protocol is the basis of lazy evaluation in Python, and is described here: http://www.python.org/dev/doc/devel/lib/typeiter.html 2. Iterables (classes with an __iter__ method) will return a lazy iterator via iter(obj). Actual iterators return themselves from __iter__, so iter(obj) is a good way to make sure you have an iterator. 3. Generators (functions that use 'yield' instead of 'return') and generator expressions (like list comprehensions, but without the square brackets) are simply concise ways of creating iterators. 4. The utility functions in the itertools module generally return iterators rather than lists (this shouldn't suprise anyone!) 5. Several builtin functions return iterators rather than lists, specifically xrange(), enumerate() and reversed(). Other builtins that yield sequences (range(), sorted(), zip()) return lists. However, be aware that some things which accept any iterable don't take advantage of the lazy evaluation, and still cause the whole thing to be created in memory at once - "".join(itr) is currently one such operation. The sequence vs iterator distinction is somewhat unfortunate (since it breaks with TOOWTDI), but completing the transition to an iterator based approach isn't going to be possible until Python 3.0, when things that currently return lists can be converted to return iterators (i.e. it has been suggested that the fundamental construct in Python 3.x should be an iterator just as a list is the fundamental construct in Python 2.x) Regards, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From nick at craig-wood.com Sun Jan 30 15:30:01 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 30 Jan 2005 20:30:01 GMT Subject: limited python virtual machine References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> <_IadnVdKPJhrTGrcRVn-uA@comcast.com> <1gr3mwj.1mhbjao122j7fxN%aleaxit@yahoo.com> <1gr58wn.m3n0xac2j9qbN%aleaxit@yahoo.com> <41FC3F8B.9080800@iinet.net.au> Message-ID: Jack Diederich wrote: > The Xen virtual server[1] was recently metnioned on slashdot[2]. > It is more lightweight and faster than full scale machine emulators because > it uses a modified system kernel (so it only works on *nixes it has been > ported to). ...it also uses python for its control programs. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From beliavsky at aol.com Wed Jan 5 10:32:37 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 5 Jan 2005 07:32:37 -0800 Subject: is python more popular than coldfusion? References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <1104933800.156835.91350@f14g2000cwb.googlegroups.com> Message-ID: <1104939157.658341.125310@f14g2000cwb.googlegroups.com> OTOH, Here are the numbers for Average Salary by Languages Used (2 numbers, staff and management) in ascending order from the 2004 Salary Survey from Software Development Magazine. I am surprised that there is so little variation across languages: 13 out of 22 are in the $81-$85K range. But Python IS tied for first. This may indicate that the relatively small number of jobs listing Python as a requirement is due in part to a relatively small supply of Python programmers, not lack of demand for such programmers. Delphi/Object Pascal $76K $96K Cobol $76K $95K EDI $78K $98K .NET $79K $98K Oracle/SQL Server/Sybase/database $80K $100K SAP/PeopleSoft/Oracle/ERP $81K $100K C# $81K $100K Perl/Javascript/PHP/scripting $81K $100K Lotus Notes/groupware $82K $101K Java $83K $102K Fortran $83K $102K C++ $84K $103K JavaBeans/ActiveX/component $84K $101K C $84K $104K Ada $84K $105K Biztalk/Crossworlds/bus. integration $84K $99K SOAP $85K $103K J2EE $85K $105K CORBA/COM/middleware $87K $106K J2ME $88K $104K Python $89K $105K Java messaging $89K $106K From steve at holdenweb.com Tue Jan 18 10:17:35 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Jan 2005 10:17:35 -0500 Subject: generator expressions: performance anomaly? In-Reply-To: References: <354esdF4fouh0U1@individual.net> Message-ID: Antoon Pardon wrote: > Op 2005-01-18, Steve Holden schreef : > > >>Python is *designed* as a dynamic language. I wish you would embrace >>this aspect rather than continually trying to shoehorn it into a static >>straitjacket. Efficiency is good. Flexibility is better. > > > Flexibility is better? IMO flexibilty implies more than one way to do > things. But that is a big no no here in c.l.py. > Become one with the language. > I also see a lot of remarks that go: "Don't do this!" when some of > the more dynamic aspects are talked about, because there are > security risks involved. One of the results was that I ended up > writing a parser for some kind of game instead of just dumping the > structure in textual form and doing an eval of the file when reading > it in. But if I need a parser I could just as well used a static > language. > Wow, you mean you actually *took* some advice? :-) Perhaps this whole thing has arisen because you feel you were badly advised. It looks as though your programming skill level might have been underestimated. Your ability to wring an argument to a merciless death could never be. > I'm beginning to guess the dynamic aspect of python is overrated. > You shouldn't have to guess, and it isn't. Certain of its dynamic aspects do demand a certain care rather than casual usage, however, which leads to rules of thumb like "don't use mutables as dictionary keys". Yes, of course you can, but to a newbie your behavior (it seems to me) is a bit like this: Me (to newbie): "... And, of course, you want to be careful not to shoot yourself in the foot." You: ":Well, actually, if you use a .22 and aim very carefully between the big toe and its neighbor there's a 96% chance that you will only suffer serious burns". So, please understand, I'm not trying to say that (most of) your utterances are untrue, or question your knowledge of the Python environment. I'm just trying to bring the day closer when you will be able to watch me write something that's only 99% true and happily walk away without writing a thousand-word essay on the remaining 1% case. This anal behavior is unlikely to win friends and influence people. Anyway, I've just about had my say on this topic now. I'm left with the uncomfortable feeling that having led you patiently (or at least as patiently as I can) down to the water, I will now have to watch you die of thirst rather than take a well-deserved drink. Life's too short. I'm going to stop disagreeing with you now, even if this means stopping communicating with you. I'm sure you won't miss my crotchety ramblings anyway. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From wcn93 at cs.ccu.edu.tw Mon Jan 10 08:28:26 2005 From: wcn93 at cs.ccu.edu.tw (Dave win) Date: Mon, 10 Jan 2005 21:28:26 +0800 Subject: C structure in the Python extension Message-ID: Howdy: When I was writting interface functions of the extending python, I meet a question. As I using the "PyArg_ParseTuple(args,arg_type,...)" function call, if I wanna use the personal defined argument, such as the C structure which I made. How to make it? static PyObject* Call_V_ABSUB(PyObject *self, PyObject* args){ myStruct FU; myStruct result; if(!PyArg_ParseTuple(args,"O&",&FU)) return NULL; ^^^^^^^ How to modify here??? V_ABSUB(FU); return Py_BuildValue("i",result); } Thx. Dave. From gsakkis at rutgers.edu Tue Jan 25 18:41:33 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Tue, 25 Jan 2005 18:41:33 -0500 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net><35lbvdF4k3ss4U1@individual.net><1106666051.334641.70740@z14g2000cwz.googlegroups.com> Message-ID: <35o3p8F4miov7U1@individual.net> "Terry Reedy" wrote in message news:mailman.1308.1106688018.22381.python- > > Unless you are GvR or Tim Peters, Actually I am the OP. I posted my previous mail from Google groups, which for some reason put my email instead of my name; it should be ok now. > throwing 'pythonic' at me doesn't cut it > with me, especially when you use it so shallowly. The current Pythonic > meaning of 'slice', as defined by GvR and implemented in core Python > sequence objects and documented in the reference manuals and reiterated by > GvR on PyDev in just the last day, is to make an independent in-memory > #copy# of the indicated part of a sequence. Both aspects are intentional > and desired features, not accidents. Thanks for the info; a citation that supports your claim that the in-memory copy is part of the *specification* of a tuple slice -- and not a choice that is subject to the implementation -- would be useful. Note that I'm talking only about slices of *tuples* (or any immutable sequence for that matter) here, not all slices. As for the "pythonic", I mentioned it as a loosely speaking synonym to "simpler" or "more intuitive"; I apologize if this term has religious connotations in cl.py. > Yes, slicing, even in the Pythonic sense, may well simplify the OP's > algorithm (of which he gave almost no detail), but the whole point of this > thread is that he does not want to do that (make copy slices). While he > might shortsightedly think that he wants Guido to redefine slice and > replace the current implementation of tuple with a more spacious, possibly > slower one that would allow that definition, that will not solve his > current problem, if indeed he has one. I fail to understand where does your strongly negative tone come from; certainly not from my posts. I asked a simple question and I was expecting a simple answer, not defending myself from a hypothetical shortsighted suggestion to Guido. Thankfully I got one (and only so far) good reason for the current implementation from Fredrik Lundh, namely the reference to the original object. > As George Sakkis the OP noted, the essential data constituting a contiguous > section view are the underlying sequence and two position markers. Whether > one works with these directly or packages them into a tuple or user class > instance is a matter of relative conveniences. As it turns out, I was Honestly, I can't imagine a case where supplying these three associated data packaged is *less* convenient than spelling them out explicitly. > thinking about the design choices involved in a generic sequence view class > just the morning before reading the original post. But I have no idea > whether GS's foo function would justify the added overhead of such a thing. This is not the point; that function was just the motivation for questioning the current tuple slice implementation. I wouldn't start this thread in the first place if I didn't have the impression that tuple views would be beneficial for many (most?) cases. > It partly depends on what he wishes to optimize, which I asked about, but > have not yet seen an answer about. Are you sure you read the whole thread ? I replied explicitly on this to Jeff Shannon: "You're probably right about the allocation time, but my main concern is the memory required for each slice, which can be O(n) wrt the length of the whole tuple. I would like this to be constant (at least if there was a way around to the problem of deleting the underlying sequence)." > So I suggested the simplest approach that would work. And that, to me, *is* pythonic! Simplest to whom ? The user or the py-dev guy that implements tuples ? It sounds as if you have the second in mind. > Terry J. Reedy > George From nick at craig-wood.com Tue Jan 25 13:30:01 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 25 Jan 2005 18:30:01 GMT Subject: Classical FP problem in python : Hamming problem References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> Message-ID: Steven Bethard wrote: > Nick Craig-Wood wrote: > > Thinking about this some more leads me to believe a general purpose > > imerge taking any number of arguments will look neater, eg > > > > def imerge(*generators): > > values = [ g.next() for g in generators ] > > while True: > > x = min(values) > > yield x > > for i in range(len(values)): > > if values[i] == x: > > values[i] = generators[i].next() > > > > This kinda looks like it dies after the first generator is exhausted, > but I'm not certain. Yes it will stop iterating then (rather like zip() on lists of unequal size). Not sure what the specification should be! It works for the hamming problem though. >>> list(imerge(iter([1, 2]), iter([1, 2, 3]), iter([1, 2, 3, 4]))) [1, 2] > An alternate version that doesn't search for 'i': > > py> def imerge(*iterables): > ... iters = [iter(i) for i in iterables] > ... values = [i.next() for i in iters] > ... while iters: > ... x, i = min((val, i) for i, val in enumerate(values)) > ... yield x > ... try: > ... values[i] = iters[i].next() > ... except StopIteration: > ... del iters[i] > ... del values[i] > ... > py> list(imerge([1, 4, 7], [2, 5, 8], [3, 6, 9])) > [1, 2, 3, 4, 5, 6, 7, 8, 9] > py> list(imerge([3, 6, 9], [1, 4, 7], [2, 5, 8])) > [1, 2, 3, 4, 5, 6, 7, 8, 9] > py> list(imerge([1, 4, 7], [3, 6, 9], [2, 5, 8])) > [1, 2, 3, 4, 5, 6, 7, 8, 9] This isn't quite right... >>> list(imerge([1, 2, 3], [1, 2, 3], [1, 2, 3])) [1, 1, 1, 2, 2, 2, 3, 3, 3] This should produce [1, 2, 3] So I'm afraid the searching *is* necessary - you've got to find all the generators with the min value and move them on. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From spam at mouse-potato.com Sun Jan 30 09:30:45 2005 From: spam at mouse-potato.com (Pascal Bourguignon) Date: 30 Jan 2005 15:30:45 +0100 Subject: what's OOP's jargons and complexities? References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> <1107060381.623163.19850@z14g2000cwz.googlegroups.com> Message-ID: <873bwjj8fe.fsf@thalassa.informatimago.com> "Larry" writes: > Xah Lee wrote: > > in computer languages, often a function definition looks like this: > > > xah at xahlee.org > > http://xahlee.org/PageTwo_dir/more.html > > Your ideas are original, insightful and simply reflect incredibly deep > creative genius. I have read your work and I want to hire you for > highly classified work in software design and philosophical writing. > Would you possibly be available to meet with me in my secret mountain > compound to discuss terms? > > Larry You forgot to mention the coordinates of your secret mountain compound: 28 deg 5 min N, 86 deg 58 min E -- __Pascal Bourguignon__ http://www.informatimago.com/ Nobody can fix the economy. Nobody can be trusted with their finger on the button. Nobody's perfect. VOTE FOR NOBODY. From dmerrillq at usaq.netq Mon Jan 10 19:09:06 2005 From: dmerrillq at usaq.netq (Dave Merrill) Date: Mon, 10 Jan 2005 19:09:06 -0500 Subject: Handing a number of methods to the same child class Message-ID: <6cWdnTY8IPa5hH7cRVn-sg@rcn.net> Python newb here. Say a class contains some rich attributes, each defined as a class. If an instance of the parent class recieves a call to a method belonging to one of those attributes, it should be dispatched to the corresponding child class. Somewhat silly example: class Address: def __init__(): self.displayed_name = '' self.adr = '' self.city = '' self.state = '' def set_name(name): self.displayed_name = name def set_adr(adr): self.adr = adr def set_city(city): self.city = city def set_state(state): self.state = state class Phone: def __init__(): self.displayed_name = '' self.number = '' def set_name(name): self.displayed_name = name def set_number(number): self.number = number class Customer: def __init__(): self.last_name = '' self.first_name = '' self.adr = Adr() self.phone = Phone() def set_adr_name(name): self.adr.set_name(name) def set_adr_adr(adr): self.adr.set_adr(adr) def set_adr_city(city): self.adr.set_city(city) def set_adr_state(state): self.adr.set_state(state) def set_phone_name(name): self.phone.set_name(name) def set_phone_number(number): self.phone.set_number(number) IOW, all the adr methods go to the corresponding method in self.adr, all the phone methods go to self.phone, theorectically etc for other rich attributes. What I'd really like is to say, "the following list of methods pass all their arguments through to a method of the same name in self.adr, and the following methods do the same but to self.phone." Is there some sane way to express that in python? Callers should stay ignorant about the internal structure of customer objects; they should be talking only to the customer object itself, not its components. Customer objects should stay ignorant of the internal structure of addresses and phones; they should let those objects handle their own implementation of the methods that apply to them. What customer objects need to do is call the appropriate internal object for each incoming method. How would you implement this? It's unfortunate to have to create individual passthrough methods for everything, like the above, among other reasons because it makes customer objects have to know about each new method implemented by the objects they contain. Am I making sense? Thanks, Dave Merrill From jacek.generowicz at cern.ch Wed Jan 5 04:29:57 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 05 Jan 2005 10:29:57 +0100 Subject: Cookbook 2nd ed Credits (was Re: The Industry choice) References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > ...but each still gets ONE free copy...!-) Who gets Luther Blissett's copy ? :-) And are all the Luther Blissetts the same Luther Blisset ? From ncoghlan at iinet.net.au Wed Jan 19 08:14:03 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 19 Jan 2005 23:14:03 +1000 Subject: lambda In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> <41ed8c13.1209309354@news.oz.net> Message-ID: <41EE5D1B.7080202@iinet.net.au> Antoon Pardon wrote: > I can be wrong, but until now I have seen no indication that I was > using mutable and immutable differently than other people. AFAICT > we all refer to whether an object belongs to a mutable or immutable > class. The difference is that when you take a copy of the key and stick it in the dictionary, such that the dictionary now holds the *sole* reference to that key, you have made that key *effectively* immutable. This is why no-one really batted an eyelid when you mentioned that mutable keys can be used safely by making a copy - doing so makes the key *effectively* immutable, and means that modifying the original key object (i.e. the application's copy, not the dict's copy), and reusing it to look up in the dictionary is likely to give a KeyError. These semantics would be understandably surprising to many users, and hence, are not supplied by default. Additionally, a dictionary's keys are accessible via its API. Accordingly, to preserve this 'effective immutability', making a copy on key input is insufficient - keys must be copied on *output* as well (that is, dict.keys, dict.items etc must return *copies* of the key objects, not the key objects themselves). Since there is no reliable way in Python to tell if an object is mutable or not (the closest equivalent is the presence of __hash__, which clearly can't be used in this example), this copying would need to be done for *every* object. Alternately, the dictionary can say to the API clients, "make an immutable copy and supply that instead. It is left to API clients to decide how best to make the immutable version". The API client copies the key once (to make the immutable version), and everyone lives happily ever after. For example: Py> class mylist(list): ... def __init__(self, arg): ... super(mylist, self).__init__(arg) ... self._tuple = None ... def frozen(self): ... if self._tuple is None: ... self._tuple = tuple(self) ... return self._tuple ... def unfreeze(self): ... self._tuple = None ... Py> x = mylist(range(10)) Py> x [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Py> x.frozen() (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) Py> x.append(10) Py> x.frozen() (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) Py> x.unfreeze() Py> x.frozen() (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) This is much safer than having a list subclass that implements __hash__, and still lets you avoid redundant copy operations. Nicely, so long as you don't unfreeze the object you used to key the dictionary, reusing the same object will always get you the correct dictionary entry, and two lists that compare equal at the time they are frozen will also get you the same dictionary entry. The equivalent tuples can be used for the lookup, too. > I also don't want my values to change when I have sorted a list > and still need to apply a number of algorithms that rely on > that. Nobody seems to have problems with the possibility that > the list items are mutable (and called such). OK, to make this comparison of sorted lists and dictionaries fair: Write a sorted_list class that is like a regular Python list, but maintains as an invariant that the list contents will stay sorted. See how well you go maintaining that invariant while allowing mutable objects in the list. The only way would be to copy them in when they're supplied, and copy them out again when you're done. Otherwise, there is no way the class can keep its promise. The performance will be lousy, since __setitem__ and __getitem__ will be making copies all the time. Alternatively, the class could declare itself to work reliably only with immutable objects. Performance will improve, since copies need only be made when an object *actually* changes (and the old immutable copy is deleted and the new version inserted in its place). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From abigail at abigail.nl Fri Jan 28 16:14:37 2005 From: abigail at abigail.nl (Abigail) Date: 28 Jan 2005 21:14:37 GMT Subject: [perl-python] 20050127 traverse a dir References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> <1106875259.426213.252030@z14g2000cwz.googlegroups.com> Message-ID: Skip Montanaro (skip at pobox.com) wrote on MMMMCLXVIII September MCMXCIII in : __ __ abigail> @@ No. Second, learn Python. Third, learn Perl (optional). :) __ __ abigail> Just leave the third option out. Let him learn Python. We don't __ abigail> want him. ;-) __ __ We don't want him either. Perhaps we can persuade him to learn INTERCAL... Please don't send stealth CCs. Abigail -- perl -wle\$_=\<\ Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 13 Jan 2005 oglycans at yahoo.com wrote: > >What environment? > > It's X. So, for X under Debian, try: apt-get install xwit man xwit It's not python, but you can either use xwit command or read the source code and get knowlegde from it. (hint: -warp, -rwarp options). bye T. - -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** -----BEGIN PGP SIGNATURE----- Version: PGPfreeware 5.0i for non-commercial use Charset: noconv iQA/AwUBQecSpRETUsyL9vbiEQJsCgCg8tkt/dPJu7pajgJrKsiK6tfz/sEAmgI9 28mUchbUqdzjSwUUvezVRnT5 =XJx5 -----END PGP SIGNATURE----- From itsme at yahoo.com Wed Jan 5 15:41:16 2005 From: itsme at yahoo.com (It's me) Date: Wed, 05 Jan 2005 20:41:16 GMT Subject: Python 2.4 on Windows XP References: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> <10toje56oiebq24@corp.supernews.com> Message-ID: In my case, there is *no* error message of any kind. When I run pythonw.exe from the python23 directory, the screen blinked slightly and goes back to the command prompt. "Jeff Shannon" wrote in message news:10toje56oiebq24 at corp.supernews.com... > DavidHolt wrote: > > > I have a problem that I see on two different machines, one running XP > > SP1 and one XP SP 2. > > > > On both I installed Python 2.4. > > > > I can't seem to start IDLE. When I try to start it, I get an hourglass > > cursor for a short time then nothing more happens. This happens whether > > I click the IDLE shortcut or click the pythonw.exe directly, or attempt > > to launch pythonw from a command line. > > Maybe I'm misinterpreting you, here, but pythonw.exe is *not* IDLE. > It is, instead, a console-less version of the Python interpreter, > which can run the Python scripts for IDLE (among other things). > > My version of Python is older, but in %pythondir%/Tools/idle, there is > an idle.pyw file. Try running that. If it doesn't work, then copy & > paste any error messages (you'll probably need to run it from a > command line for this) to your next post here so that we can try to > troubleshoot a bit more effectively. > > Jeff Shannon > Technician/Programmer > Credit International > > > From jbperez808 at wahoo.com Wed Jan 12 02:48:16 2005 From: jbperez808 at wahoo.com (Jon Perez) Date: Wed, 12 Jan 2005 15:48:16 +0800 Subject: Windows GUIs from Python In-Reply-To: References: Message-ID: <34k31tF4bitrcU2@individual.net> Wow, Venster looks cool and to think I've never heard of it before. I knew following this newsgroup would pay off one day... Luke Skywalker wrote: > On Tue, 11 Jan 2005 22:15:36 +0100, Thomas Heller > wrote: > >>Well, venster. Although it is most certainly alpha. But with some >>work... > > > Thx, I'll keep an eye on it. > > http://venster.sourceforge.net/ > > Luke. From premshree.pillai at gmail.com Wed Jan 5 14:04:21 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Thu, 6 Jan 2005 00:34:21 +0530 Subject: Cookbook 2nd ed Credits In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> <1gpxjfg.thnaf0oys6jrN%aleaxit@yahoo.com> Message-ID: On Wed, 5 Jan 2005 13:52:06 -0500, Dan Perl wrote: > > "Alex Martelli" wrote in message > news:1gpxjfg.thnaf0oys6jrN%aleaxit at yahoo.com... > > Dan Perl wrote: > > > >> "Alex Martelli" wrote in message > >> news:1gpvtjk.3jf7dc1cch7yfN%aleaxit at yahoo.com... > >> > Premshree Pillai wrote: > >> >> Btw, is there a comprehensive list of ALL contributors put up > >> >> anywhere? > >> > > >> > Not yet -- do you think I should put it up on my website? > >> > >> Updating the status of the recipes on the web site would be nice. > > > > Please take this up with Activestate guys -- I have no say on what > > happens on the website they own, nor any special status there. > > I was under the impression that the status on the website reflects whether > the recipes are approved or rejected for the book (with a few more states > added: new, deferred, pending). I gather now from your reply that there is > no connection between that status and the book. No connection. > > Okay then, I am adding my vote to posting the list of all the contributors. > I still think that the ActiveState website is an appropriate place to do > that, as they also have the recipes. Actually, what is the exact > relationship between the recipes on the website and the recipes published in > the book? Recipes published in the book are taken from the website, AFAIK. And if you want to know more: http://www.onlamp.com/pub/a/python/2002/08/01/cookbook.html :) > > If not on the ActiveState website, then posting the list to another website > would be good too. Even if the list is not absolutely final and may be > changed later (a disclaimer to that effect would suffice). I have two > recipes submitted (for which I got permission requests) and I am curious. > > BTW, I sent an email to pythoncookbook at activestate.com earlier today, before > I even saw this thread in c.l.p. I haven't received a reply from them yet. > > Dan > > > > > Alex > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From steven.bethard at gmail.com Tue Jan 4 04:50:18 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 04 Jan 2005 09:50:18 GMT Subject: search backward In-Reply-To: <4c57226b.0501040126.7f0eafc2@posting.google.com> References: <4c57226b.0501040126.7f0eafc2@posting.google.com> Message-ID: Robert wrote: > I need to find the location of a short string in a long string. The > problem however is that i need to search backward. > > Does anybody know how to search in reverse direction? How about str.rfind? py> s = 'abc:def:abc' py> s.rfind('abc') 8 Steve From mt at 3planes.com Sat Jan 29 20:46:29 2005 From: mt at 3planes.com (Michael Tobis) Date: 29 Jan 2005 17:46:29 -0800 Subject: naive doc question In-Reply-To: References: Message-ID: <1107049589.559629.313920@c13g2000cwb.googlegroups.com> I wouldn't call the responses here helpful; they seem overspecific. I had a similar problem which led to the follwing code. After I came up with this I saw a very similar utility was derived in Dive into Python. see http://diveintopython.org/power_of_introspection/index.html#apihelper.divein Anyway the following is intended as an interactive utility to explore the callables of modules and classes. I always have it imported into my interactive sessions. So import it and try sm(dict) .######################################################## .# sm() .# showmethods . .def sm(namespace,terse=0,maxchars=300): . . """report the callables of a namespace . .returns a nice string representation of the public callables of the .namespace and the first maxchars bytes of their respective docstrings . .if terse, truncates the docstring at the first newline . """ . . d = namespace.__dict__ . l = [str(x) + "\t\t" + str(d[x].__doc__)[:maxchars] for x in d.keys() \ . if callable(d[x]) and not x.startswith("_")] . if terse: . l = [x.split("\n")[0] for x in l] . l.sort() . return "\n=====\n".join(l) From martinnitram at excite.com Tue Jan 18 22:48:17 2005 From: martinnitram at excite.com (martinnitram at excite.com) Date: 18 Jan 2005 19:48:17 -0800 Subject: safest way to kill a thread Message-ID: <1106106497.429643.307440@f14g2000cwb.googlegroups.com> Dear all, in python, a thread can be created by t = threading.Thread. But i found that when the main (and the thread) program is running and user use Crtl+C/Crtl+Z to break the program abnormally, the thread is still running and needed to kill manually (by the pid). Is there had any safest way to kill/exit the thread program under python (when the thread program part is a forever loop)? Thank a lot From peter at engcorp.com Wed Jan 12 17:45:48 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 12 Jan 2005 17:45:48 -0500 Subject: pyserial and com port interrupts In-Reply-To: References: Message-ID: engsol wrote: > Has anyone done a script that will rspond to the serial com port(s) > receive buffer interrupt, as opposed to polling and timeouts? > Win2000 is the main interest right now. What problem do you hope to avoid by not using "polling and timeouts"? (Note that if you specify a sizable read timeout, you're closer to being interrupt-driven than you are to what is traditionally called "polling".) -Peter From http Sat Jan 8 08:25:19 2005 From: http (Paul Rubin) Date: 08 Jan 2005 05:25:19 -0800 Subject: The best way to do web apps with Python? References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <7xwtuoyrwg.fsf@ruckus.brouhaha.com> "worzel" writes: > What is the best way to web developemnt with Python? Is there > anything close to PHP style in-page script placement that can create > and use other Python objects? I am not really interested in Zope (I > believe that is more a CMS than anything else?) I am also looking > for something a little more structured than a series of CGI Scripts. Basically, yes, there are various Python template systems similar to PHP. I won't name them because other people more knowledgeable than me will do a better job than I could. I'll say that Python is a better language than PHP, but getting a basic dynamic web app running in PHP is much simpler than it is in Python. Python's advantage starts to shine once the app gets complicated. > While on the topic - what is the expectataion of Python for this > kind of stuff? Would one use Python for certain other things but > turn to PHP for web apps - or would one use their Python skills in > place of PHP? TIA It's sort of a difficult trade-off and it depends a lot on your application, who will develop and maintain it, who will use it, where it will be deployed, etc. Lots more people know PHP than Python, PHP is easier to get started with, and cheap PHP hosting is available all over. So if you're building some simple app that you want to distribute widely and run everywhere, PHP is attractive. If you're building a complex system which you'll run on a server that you have more control over, and you'll have relatively high-powered developers on hand to maintain the code, Python beats PHP. From python at hope.cz Thu Jan 20 15:08:35 2005 From: python at hope.cz (python at hope.cz) Date: 20 Jan 2005 12:08:35 -0800 Subject: How to lanch a webbrowser In-Reply-To: References: <1106147035.502646.276860@f14g2000cwb.googlegroups.com> Message-ID: <1106251715.365048.306730@f14g2000cwb.googlegroups.com> Steve Holden wrote: > Ola Natvig wrote: > > > export at hope.cz wrote: > > > >> Does anyone know > >> how to lanch a webbrowser ( from Python) without menu and toolbars? > >> Thanks for help > >> Lad > >> > > > > You've got the webbrowser module which lauches the OS's standard browser > > > > from webbrowser import get > > get("www.example.org") > > > > launches the webbrowser, but how to launch it without menu and toolbar I > > don't know. You could launch a small HTML page containing a javascript > > that launches your wanted page. > > > This would indeed be the best way. The page you launched should contain > a script that creates another window. Since this would be browser-based > javascript, it could specify the appropriate browser window attributes > (see, for example > > http://www.javascripter.net/faq/openinga.htm > > which shows you how to specify the appropriate window characteristics). > > The onload attribute of the first page's body could then specify closing > the window you opened from Python. > > You may find that this close operation generates a warning from the > browser about scripts doing naughty things, however. > > regards > Steve > -- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/ > Holden Web LLC +1 703 861 4237 +1 800 494 3119 Thank you Steve for the http link( was good) and to you all others as well who helped me. Lad From stephen.thorne at gmail.com Wed Jan 26 20:44:19 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 27 Jan 2005 11:44:19 +1000 Subject: python memory blow out In-Reply-To: <4e4a11f805012617082ebd9b80@mail.gmail.com> References: <4e4a11f805012617082ebd9b80@mail.gmail.com> Message-ID: <3e8ca5c8050126174444967112@mail.gmail.com> On Thu, 27 Jan 2005 09:08:59 +0800, Simon Wittber wrote: > According to the above post: > > a) If the allocation is > 256 bytes, call the system malloc. > > b) If the allocation is < 256, use its own malloc implementation, which > > allocates memory in 256 kB chunks and never releases it. > > I imagine this means that large memory allocations are eventually > released back to the operating system. However, in my case, this > appears to be not happening. There was a recent patch posted to python-dev list which allows python to release memory back to the operating system once the 256kb chunk is no longer used. I'm not saying running a bleeding edge CVS HEAD python plus untested development patches is going to be a solution for you in the short term, but I just wanted to mention it because I'm excited about this limitation disappearing in python :). Regards, Stephen Thorne From beliavsky at aol.com Wed Jan 26 18:42:03 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 26 Jan 2005 15:42:03 -0800 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <41f6f4ee$1@nntp.zianet.com> <1106718853.867328.55760@z14g2000cwz.googlegroups.com> Message-ID: <1106782923.338506.269250@z14g2000cwz.googlegroups.com> Nick Coghlan wrote: > Davor wrote: > > thanks for the link > > > > > >>know what's funny: in the Lua mailing list there is currently a > >>discussion about adding OO to Lua. > > > > > > I guess most of these newer languages have no choice but to support OO > > if they want to attract a larger user base :-(... > > Tell me, have you ever defined a C structure, and then written various functions > to operate on that structure (i.e. taking a pointer to the structure as their > first argument)? > > Have you then put both the structure definition and the function prototypes into > a single header file and used that header file from other code? > > That's OO programming: associating several pieces of information as an 'object', > and associating various methods to operate on instances of those objects. Then why was C++ invented? What you have described can be done in C, Pascal, and Fortran 90, all of which are generally classified as procedural programming languages. As Lutz and Ascher say in "Learning Python", in object-based programming one can pass objects around, use them in expressions, and call their methods. "To qualify as being truly object-oriented (OO), though, objects need to also participate in something called an inheritance hierarchy." Whether true OOP is a Good Thing is arguable and depends on the situation. From deetsNOSPAM at web.de Fri Jan 28 07:50:29 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 28 Jan 2005 13:50:29 +0100 Subject: Why do look-ahead and look-behind have to be fixed-width patterns? References: Message-ID: <35uqkjF4p1pd4U1@individual.net> > but I don't understand why regex look-behinds (and look-aheads) have to be > fixed-width patterns. > > i'm getting the impression that it's supposed to make searching > exponentially slower otherwise That's because of the underlying theory of regular expressions. They are modelled using so called finite state automata (FSM). These are very much limited in the complexity of things they can do, and so are regular expressions. Explaining that further would require to dig deep into the details of FSM, grammars and languages - deeper than I'm currently willing to do :) But I wanted to point out that there is a "real" technical reason for that, not just a lack of feature or willingness to implement one. -- Regards, Diez B. Roggisch From jalemkul at vt.edu Wed Jan 26 12:06:32 2005 From: jalemkul at vt.edu (Justin Lemkul) Date: Wed, 26 Jan 2005 12:06:32 -0500 Subject: MMTK Install Problem Message-ID: <42422606@zathras> Hello All, I am hoping that someone out there will be able to help me. During the "build" phase of MMTK installation, I receive the following series of errors: $ python setup.py build running build running build_py running build_ext building 'lapack_mmtk' extension gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DLIBM_HAS_ERFC -DEXTENDED_TYPES -IInclude -I/System/Library/Frameworks/Python.framework/Versions/ 2.3/include/python2.3 -c Src/lapack_mmtk.c -o build/temp.darwin-7.7.0-Power_Macintosh -2.3/Src/lapack_mmtk.o Src/lapack_mmtk.c:2:33: Numeric/arrayobject.h: No such file or directory Src/lapack_mmtk.c:6: warning: function declaration isn't a prototype Src/lapack_mmtk.c:11: warning: function declaration isn't a prototype Src/lapack_mmtk.c: In function `lapack_mmtk_CheckObject': Src/lapack_mmtk.c:29: warning: implicit declaration of function `PyArray_Check' Src/lapack_mmtk.c:34: error: `PyArrayObject' undeclared (first use in this function) Src/lapack_mmtk.c:34: error: (Each undeclared identifier is reported only once Src/lapack_mmtk.c:34: error: for each function it appears in.) Src/lapack_mmtk.c:34: error: parse error before ')' token Src/lapack_mmtk.c:34: error: `CONTIGUOUS' undeclared (first use in this function) Src/lapack_mmtk.c:39: error: parse error before ')' token Src/lapack_mmtk.c: In function `lapack_mmtk_dsyev': Src/lapack_mmtk.c:72: error: `PyArray_DOUBLE' undeclared (first use in this function) Src/lapack_mmtk.c:81: warning: implicit declaration of function `dsyev_' Src/lapack_mmtk.c:81: error: `PyArrayObject' undeclared (first use in this function) Src/lapack_mmtk.c:81: error: parse error before ')' token Src/lapack_mmtk.c:81: error: parse error before ')' token Src/lapack_mmtk.c:81: error: parse error before ')' token Src/lapack_mmtk.c: In function `lapack_mmtk_dgesvd': Src/lapack_mmtk.c:107: error: `PyArray_DOUBLE' undeclared (first use in this function) Src/lapack_mmtk.c:118: warning: implicit declaration of function `dgesvd_' Src/lapack_mmtk.c:118: error: `PyArrayObject' undeclared (first use in this function) Src/lapack_mmtk.c:118: error: parse error before ')' token Src/lapack_mmtk.c:118: error: parse error before ')' token Src/lapack_mmtk.c:118: error: parse error before ')' token Src/lapack_mmtk.c:118: error: parse error before ')' token Src/lapack_mmtk.c:118: error: parse error before ')' token Src/lapack_mmtk.c: At top level: Src/lapack_mmtk.c:134: warning: function declaration isn't a prototype Src/lapack_mmtk.c:132: warning: `lapack_mmtkError' defined but not used error: command 'gcc' failed with exit status 1 I am attempting the install on a Mac OS X v10.3 with Python v2.3, NumPy v23.1, and SciPy v2.4.3 Thanks in advance for any help you can give me. -Justin Lemkul From http Thu Jan 6 09:40:28 2005 From: http (Paul Rubin) Date: 06 Jan 2005 06:40:28 -0800 Subject: sorting on keys in a list of dicts References: Message-ID: <7xmzvmk4df.fsf@ruckus.brouhaha.com> J Berends writes: > Suppose I have a list of dictionaries and each dict has a common > keyname with a (sortable) value in it. > > How can I shuffle their position in the list in such way that they > become sorted. Do I understand the question right? Can't you just say thelist.sort(lambda x,y: cmp(x['keyname'], y['keyname'])) or something like that? From steven.bethard at gmail.com Tue Jan 25 14:10:45 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 25 Jan 2005 12:10:45 -0700 Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) In-Reply-To: References: Message-ID: Toby Dickenson wrote: > I have a counterexample. Consider refactoring a class from.... > > class B(A): > etc > > ....into.... > > class C(A): > etc > class B(C): > etc > > Usage of some double-undescore attributes moved from B to the new intermediate > base class C. Unit tests on B still passed, so that change is safe. right? > > The problem occured because the double-underscore mangling uses the class > name, but ignores module names. A related project already had a class named C > derived from B (same name - different module). My refactoring caused > aliasing of some originally distinct double-underscore attributes. Very interesting. I hadn't ever really thought about it, but I guess this shows that even __-mangling won't solve all of the attribute-renaming problems... A somewhat related problem is briefly discussed in Guido's autosuper example: http://www.python.org/2.2.3/descrintro.html#metaclass_examples where a base class derived from a class using autosuper but with the same name as the superclass might get the wrong self.__super. Steve From kp8 at mac.com Wed Jan 12 10:03:31 2005 From: kp8 at mac.com (kpp9c) Date: 12 Jan 2005 07:03:31 -0800 Subject: Time script help sought! In-Reply-To: References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <1105470872.613166.187800@f14g2000cwb.googlegroups.com> <1105471266.880133.318470@c13g2000cwb.googlegroups.com> <1105474524.083536.129220@f14g2000cwb.googlegroups.com> <1105477084.525279.312970@f14g2000cwb.googlegroups.com> <1105479292.689762.155510@f14g2000cwb.googlegroups.com> <1105480151.431987.327080@c13g2000cwb.googlegroups.com> <1105485509.346577.292130@f14g2000cwb.googlegroups.com> Message-ID: <1105542211.639360.217790@f14g2000cwb.googlegroups.com> paul that is awesome.... so much better than what i did which was lamo brute force method. I formmatted and reformatted my input data and stuffed it in a HUGE dictionary.... it was stupid and kludgy.... i hope to study all these approaches and learn something.... here's what i came up with ... with my pea sized brain... #!/usr/bin/env python # New in version 2.3 is the 'datetime' module (see standard library reference) # http://www.python.org/doc/lib/module-datetime.html import datetime inseqs = { (1) : ['DAT_1', '01', '00:00:23', '00:08:23'], (2) : ['DAT_1', '02', '00:08:23', '00:09:41'], (513) : ['DAT_75', '10', '00:59:55', '01:11:05'], (514) : ['DAT_75', '11', '01:11:05', '01:16:15'], (515) : ['DAT_75', '12', '01:16:15', '01:34:15'], (516) : ['DAT_75', '13', '01:34:15', '01:45:15'], (517) : ['DAT_75', '14', '01:45:15', '01:48:00'] } mykeys = inseqs.keys() # first make a copy of the keys mykeys.sort() # now sort that copy in place for key in mykeys: event = inseqs[key] print '\n','Item #', key, event TD = datetime.timedelta h, m, s = event[2].split(':') zero_adjust = TD(hours=int(h), minutes=int(m),seconds=int(s)) # print ' Q___ ', key, event[:2], ': ', for item in event[2:]: hrs, mins, secs, = item.split(':') time1 = TD(hours=int(hrs), minutes=int(mins),seconds=int(secs)) print time1 - zero_adjust, print From pipene-news at pu.kielce.pl Sat Jan 1 16:07:15 2005 From: pipene-news at pu.kielce.pl (Artur M. Piwko) Date: Sat, 1 Jan 2005 21:07:15 +0000 (UTC) Subject: Clearing the screen References: Message-ID: In the darkest hour on Sat, 25 Dec 2004 09:41:54 +1030, Ishwor screamed: >>>> def cls(): > for i in range(1,40): > print " "; > Slightly ot, but perhaps this'll work for you: def cls(): print "\033[2J" -- [ Artur M. Piwko : Pipen : AMP29-RIPE : RLU:100918 : From == Trap! : SIG:217B ] [ 22:06:17 user up 10478 days, 10:01, 1 user, load average: 0.06, 0.06, 0.06 ] Even God cannot change the past. From golux at comcast.net Fri Jan 7 23:45:51 2005 From: golux at comcast.net (Stephen Waterbury) Date: Fri, 07 Jan 2005 23:45:51 -0500 Subject: Software archeology (was Re: Developing Commercial Applications in Python) In-Reply-To: References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> <87pt0iegga.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: <41DF657F.40503@comcast.net> Aahz wrote: > In article , > Stephen Waterbury wrote: > >>>eeykay at gmail.com writes: >>> >>>>Can somebody there to point me any good commercial applications >>>>developed using python ? >> >>Also see Python Success Stories: http://pythonology.org/success >> >>A notable example is Verity's search engine -- see >>http://python.oreilly.com/news/PythonSS.pdf > > Actually, your statement is slightly inaccurate. The Verity search > engine is more than fifteen years old in its core technology; it was > started as a LISP project at IIRC MIT. (At one point I was much amused > to look at the C source code and find car() and cdr() functions.) As of > my last information, Python isn't used at all in or with the Verity > search engine. What you're referring to is the Verity Ultraseek engine, > originally written and owned by Infoseek before getting transferred to > Verity through a series of dot-bomb transactions. The Ultraseek engine > doesn't use Python, but Python is used to control the engine, and I think > much of the spider is written in Python. Actually, Aahz didn't add anything useful that wasn't explained better in the article itself, pointing to which was the purpose of my post, but he is correct: Python was *not* used to write the Verity search engine ... how the hell do these stupid rumors get started anyhow?? ;). Just read the article, dammit! :) Cheers, Steve From bulba at bulba.com Fri Jan 7 12:15:09 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 18:15:09 +0100 Subject: The Industry choice References: <10trej2fl8dip65@corp.supernews.com> Message-ID: On 6 Jan 2005 19:01:46 -0500, aahz at pythoncraft.com (Aahz) wrote: >>Note that the so-called 'viral' nature of GPL code only applies to >>*modifications you make* to the GPL software. The *only* way in which >>your code can be 'infected' by the GPL is if you copy GPL source. >That's not true -- consider linking to a GPL library. Will someone please explain to me in simple terms what's the difference between linking to LGPLed library and linking to GPLed library - obviously in terms of consequences of what happens to _your_ source code? Because if there isn't any, why bother with distinguishing between the two? Oh, and by the way - since Python bytecode can be relatively easily decompiled to source, could it interpreted to "really" count as source code and not binary? What are the consequences of releasing code _written in Python_ as GPLed? Licenses are frigging cans of worms.. -- It's a man's life in a Python Programming Association. From newgene at bigfoot.com Wed Jan 12 18:21:19 2005 From: newgene at bigfoot.com (Newgene) Date: 12 Jan 2005 15:21:19 -0800 Subject: Dynamically add class method causes "SystemError: ... bad argument to internal function" Message-ID: <1105572079.630658.242210@c13g2000cwb.googlegroups.com> Hi, group, I am trying to dynamically add a method to class by following this post: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2ec2ad7a0a5d54a1/928e91be352c6bfc?q=%22new.code(%22+%22import+new&_done=%2Fgroup%2Fcomp.lang.python%2Fsearch%3Fgroup%3Dcomp.lang.python%26q%3D%22new.code(%22+%22import+new%26qt_g%3D1%26&_doneTitle=Back+to+Search&&d#928e91be352c6bfc But I got the Error like the below: *******Error********************** Traceback (most recent call last): File "C:\Documents and Settings\cwu\Desktop\t1.py", line 36, in ? C().f2(1,2,4,x='x') File "C:\Documents and Settings\cwu\Desktop\t1.py", line 19, in newf2 self.f() SystemError: C:\sf\python\dist\src-maint23\Objects\cellobject.c:22: bad argument to internal function *******Error********************** Anybody has a thought about this problem? My sample code is pasted as the below: *********Code******************************* ##import new ##import sys ## ##def safe_tuple(seq): ## """Force func_code attributes to tuples of strings. ## ## ## Many of the func_code attributes must take tuples, not lists, ## and *cannot* accept unicode items--they must be coerced to strings ## or the interpreter will crash. ## """ ## seq = map(str, seq) ## return tuple(seq) ## ##class C: ## def __init__(self): ## def _generic(*a,**k): ## print vars() ## self.f() ## ## def _newmethod(newname): ## fcode = _generic.func_code ## #code( argcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab) ## fcode_new = new.code(fcode.co_argcount, fcode.co_nlocals, fcode.co_stacksize, ## fcode.co_flags, fcode.co_code, tuple(fcode.co_consts), # Notice co_consts should *not* be safe_tupled. ## safe_tuple(fcode.co_names), safe_tuple(fcode.co_varnames), ## fcode.co_filename, ## newname, ## fcode.co_firstlineno, fcode.co_lnotab) ## return new.function(fcode_new,globals()) ## setattr(self,'f2',_newmethod('newf2')) ## ## def f(): ## print 'from f' ## ##C().f2(1,2,4,x='x') ## ## **********Code************************ *Sorry, I have to put comment chars before the code to preserve the proper indentation. Thanks a lot! CW From fperez.net at gmail.com Fri Jan 28 16:02:05 2005 From: fperez.net at gmail.com (Fernando Perez) Date: Fri, 28 Jan 2005 14:02:05 -0700 Subject: Installing Numeric with ATLAS and LAPACK References: <1106928716.562584.56270@z14g2000cwz.googlegroups.com> <1106940704.164253.134630@c13g2000cwb.googlegroups.com> Message-ID: drife wrote: > Thanks John. Those are the steps I followed, and to no avail. > > Interestingly, I downloaded and installed SciPy, and ran the > same eigenvector problem. SciPy greatly speeds up the > calculation...was 1.5 hours using Numeric, now only 15 min > with SciPy. > > Unfortunately, SciPy only solves ordinary and generalized > eigenvalue problems of a square matrix. They do not test > to see if the matrix is symmetric, then call the appropriate > routine from LAPACK. Note that scipy exposes most of lapack, so you could make the call you need directly: In [3]: scipy.linalg.lapack.get_lapack_funcs? Type: function Base Class: String Form: Namespace: Interactive File: /usr/lib/python2.3/site-packages/scipy/linalg/lapack.py Definition: scipy.linalg.lapack.get_lapack_funcs(names, arrays=(), debug=0, force_clapack=1) Docstring: Return available LAPACK function objects with names. arrays are used to determine the optimal prefix of LAPACK routines. If force_clapack is True then available Atlas routine is returned for column major storaged arrays with rowmajor argument set to False. Cheers, f From nick at craig-wood.com Thu Jan 27 10:30:01 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 27 Jan 2005 15:30:01 GMT Subject: Inherting from object. Or not. References: <1106774681.501533.156220@f14g2000cwb.googlegroups.com> <200501262214.40597.frans.englich@telia.com> Message-ID: Nick Coghlan wrote: > Exactly. My advice is to use new-style classes unless you have a > reason not to (if you're inheriting from a builtin type, then there > is no need to inherit from object as well - the builtin types > already have the correct basic type). Except for Exception! Exception and anything that inherits from it is an old style class. I discovered the other day that you can't throw a new style class as an exception at all, eg >>> class MyException(object): pass ... >>> raise MyException Traceback (most recent call last): File "", line 1, in ? TypeError: exceptions must be classes, instances, or strings (deprecated), not type >>> (not a terribly helpful message - took me a while to work it out!) wheras old style works fine... >>> class MyOldException: pass ... >>> raise MyOldException Traceback (most recent call last): File "", line 1, in ? __main__.MyOldException: <__main__.MyOldException instance at 0xb7df4cac> >>> After that I recalled a thread on python-dev about it http://mail.python.org/pipermail/python-dev/2004-August/046812.html -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bill.mill at gmail.com Mon Jan 24 21:17:08 2005 From: bill.mill at gmail.com (Bill Mill) Date: Mon, 24 Jan 2005 21:17:08 -0500 Subject: Distutils: blurring the file==module borders In-Reply-To: <200501250215.58729.frans.englich@telia.com> References: <200501250215.58729.frans.englich@telia.com> Message-ID: <797fe3d40501241817765fd2b1@mail.gmail.com> read this thread, it should help you: http://mail.python.org/pipermail/tutor/2005-January/035124.html Peace Bill Mill bill.mill at gmail.com On Tue, 25 Jan 2005 02:15:58 +0000, Frans Englich wrote: > > Hello all, > > Due to the size of my source, I want to split it up into multiple > files(basically one class in each file), but then I have difficulties with > the directory layout when the modules are installed with distutils. > > This is my file layout: > > in ./ I have a setup.py which has 'packages="foo"' > > in ./foo/ I have an __init__.py and a handful of files named ClassA.py, > ClassB.py, ClassC.py and so forth. > > The problem is that when installed, in order to reach, say, classB, I need to > do: > > import foo.ClassA > > var = foo.ClassA.ClassA() > > while I want to do var = foo.ClassA() > > In other words, the result I want can be achieved by putting all code in > __init__.py. The problem is that I would find it horrible to have all code in > one file. > > Python have this one-to-one relationship between modules and files; can what I > want somehow be achieved? > > Cheers, > > Frans > > -- > http://mail.python.org/mailman/listinfo/python-list > From jjl at pobox.com Tue Jan 25 18:33:13 2005 From: jjl at pobox.com (John J. Lee) Date: 25 Jan 2005 23:33:13 +0000 Subject: delay and force in Python References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> Message-ID: <878y6hhyo6.fsf@pobox.com> Nick Coghlan writes: [...] > (xrange can't handle Python longs, unfortunately, so we *are* > constrained by sys.maxint. However, since my machine only has half a > gig of RAM, the above is still a damn sight quicker than the > equivalent list comprehension would be!) [...] Other way 'round: if you had even more RAM, the listcomp would be even slower for this job! John From danperl at rogers.com Fri Jan 28 20:31:37 2005 From: danperl at rogers.com (Dan Perl) Date: Fri, 28 Jan 2005 20:31:37 -0500 Subject: what's OOP's jargons and complexities? References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com><3602hiF4tvskbU1@individual.net> Message-ID: "PA" wrote in message news:mailman.1552.1106959836.22381.python-list at python.org... > > On Jan 29, 2005, at 01:09, Martin Ambuhl wrote: > >> Xah Lee wrote his usual masturbatory crap: > > Well... I have to admit that I tremendously enjoyed such "masturbatory > crap" (sic). > > Eagerly looking toward the next installment. At first I thought you were being sarcastic. I doubt that now. Iindulge my curiosity please and tell us what you enjoy about it. From dderakon at hotmail.com Sun Jan 30 02:25:40 2005 From: dderakon at hotmail.com (Chris Weisiger) Date: Sun, 30 Jan 2005 07:25:40 -0000 Subject: Trouble installing numeric Message-ID: <20050129232540162-0800@news.claremont.edu> I'm trying to install numeric on my MacOS X box using Darwin, with the eventual goal of satisfying all of PyGame's dependencies so I can finally start working on my semester project. I would be using MacPython, except that I can't seem to get its Package Manager to work. Anyway, when I try to install numeric, I get the following error: [HMC-58-125:~/proj/Numeric-23.7] chriswei% sudo ./setup.py install Password: running install running build running build_py running build_ext building 'lapack_lite' extension gcc -Wl,-F. -Wl,-F. -bundle -framework Python build/temp.darwin-7.6.0- Power_Macintosh-2.3/Src/lapack_litemodule.o build/temp.darwin-7.6.0- Power_Macintosh-2.3/Src/blas_lite.o build/temp.darwin-7.6.0-Power_ Macintosh-2.3/Src/f2c_lite.o build/temp.darwin-7.6.0-Power_Macintosh-2.3/ Src/zlapack_lite.o build/temp.darwin-7.6.0-Power_Macintosh-2.3/Src/ dlapack_lite.o -L/usr/lib/atlas -llapack -lcblas -lf77blas -latlas -lg2c - o build/lib.darwin-7.6.0-Power_Macintosh-2.3/lapack_lite.so -framework vecLib ld: can't locate file for: -llapack error: command 'gcc' failed with exit status 1 Previously it had been complaining about a missing directory '/usr/lib/ atlas', but I just created that (without any idea what it wanted it for or why it couldn't create it itself, natch). From what I've found online, it's now having problems because a linear algebra module it needs ( lapack) can't be found. However, isn't numeric supposed to have its own "light" linear algebra code? Looking in setup.py, I found the following section: # delete all but the first one in this list if using your own LAPACK/ BLAS sourcelist = [os.path.join('Src', 'lapack_litemodule.c'), # os.path.join('Src', 'blas_lite.c'), # os.path.join('Src', 'f2c_lite.c'), # os.path.join('Src', 'zlapack_lite.c'), # os.path.join('Src', 'dlapack_lite.c') ] ] I tried uncommenting the lines, but no dice. I've also installed the numarray module; it claims to be a descendant of numeric that should be usable for the same thing. If it turns out that I can't use numeric, for whatever reason, does anyone have advice for getting numarray to work with pygame? Thanks for any help you can provide. If I can't get this working soon, I'll have to return to using C++ for this project. I know that at least works. -- "Don't take life so serious, son - it ain't nohow permanent." - Porkypine http://www.cs.hmc.edu/~cweisige From usenet_spam at janc.invalid Mon Jan 3 20:12:33 2005 From: usenet_spam at janc.invalid (JanC) Date: Tue, 04 Jan 2005 01:12:33 GMT Subject: input record sepArator (equivalent of "$|" of perl) References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> <1103657476.495700.191020@f14g2000cwb.googlegroups.com> <1103671235.093738.198680@z14g2000cwz.googlegroups.com> <10she9di9clfc73@corp.supernews.com> Message-ID: Jeff Shannon schreef: > John Machin wrote: > >>Subtle distinction: A metER is a measuring device. A MetRE is a unit of >>distance. > ... except in the US, where we stubbornly apply the same spelling to > both of those. (It figures that we Americans just ignore subtle > distinctions....) Or there is some Dutch influence... ;) (In Dutch it's "meter" for both meanings.) -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From hcslmf at texlife.com Sat Jan 8 16:46:52 2005 From: hcslmf at texlife.com (brolewis) Date: 8 Jan 2005 13:46:52 -0800 Subject: Python Installation Message-ID: <1105220812.579690.292260@c13g2000cwb.googlegroups.com> I need to install Python on a number of laptop computers (at least a dozen). I am needing to install Python 2.4, pycrypto, win32all, wxPython, and pyCurl. Can anyone tell me an easy way to install these onto the laptops? Ideally I would like to have a single executable to handle everything for me. I have also looked into using NSIS to handle the installation, but am still unaware how to install the modules that I need easily. Does anyone have any suggestions? From jeff at ccvcorp.com Tue Jan 25 18:26:56 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 25 Jan 2005 15:26:56 -0800 Subject: Another scripting language implemented into Python itself? In-Reply-To: <41f6a38f$0$2208$a1866201@visi.com> References: <41f6a38f$0$2208$a1866201@visi.com> Message-ID: <10vdl2jf1tv32ba@corp.supernews.com> Grant Edwards wrote: > On 2005-01-25, Rocco Moretti wrote: > >>Bottom line: Don't exec or eval untrusted code. Don't import untrusted >>modules. > > I still don't see how that's any different for Python than for > any other language. Yep, and one should be careful about executing untrusted C code, too. If you're running a webserver, do you let random users upload executables and then run them? Probably not. The key point here, what I was attempting to say in my earlier post, is that while Python can be useful as an internal scripting language inside of an application, it gives users of that application the same power over your system as any arbitrary C code. That's fine if it's an internal application, or the application can be run with (enforceable) restricted permissions, but it's still risky. How many security alerts has Microsoft issued because of some bug that allowed the execution of arbitrary code? Well, having Python scripting access is essentially the same thing. At best, you can use the external environment to limit the process running Python to its own sandbox (e.g. running as a limited-permission user in a chroot jail), but you still can't prevent one user of that application from screwing with other users of the application, or the application's own internal data. In other words, the only difference is that Python makes it much more tempting to hand over the keys to your server. I confess that I jumped to the (apparently unsupported) conclusion that this was some sort of server-based, internet/shared application. If that's not the case, then concerns about security are not so significant. If the users are running this application on their own machines, then letting them script it in Python is a perfectly valid (and probably quite desirable) approach. Jeff Shannon Technician/Programmer Credit International From news at outbacklinux.com Mon Jan 10 07:00:56 2005 From: news at outbacklinux.com (Adrian Casey) Date: Mon, 10 Jan 2005 21:30:56 +0930 Subject: Command line and GUI tools : need a single threading solution Message-ID: <41e26e79@duster.adelaide.on.net> I have a collection of multi-threaded command line tools which I want wrap a PyQt gui around. I'm using queues to route messages from the command line tools to the PyQt gui. The command line tools use python threads to do their work. The gui uses a QThread object to read incoming messages. This does not work consistently - and I've since read that mixing python threads and QThreads is a bad idea. The command line tools work well using python threads. I don't want to maintain two copies of the tools - one for command line and another for the PyQt version. I'm thinking it may be possible to modify the command line tools to use qt threads instead of native python threads. Is this the way to go? Are there other options? Adrian. From steven.bethard at gmail.com Wed Jan 19 15:22:23 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 19 Jan 2005 13:22:23 -0700 Subject: Dictionary keys (again) (was Re: lambda) In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: David Eppstein wrote: > In article , > Nick Coghlan wrote: > > >>For a 'mutable key' to make sense, the following: >> >>lst = [] >>dct = {l: "Hi!"} >>print dct[[]] >>print dct[lst] >>lst.append(1) >>print dct[[1]] >>print dct[lst] >> >>Should print: >>Hi >>Hi >>Hi >>Hi > > > Yes, and what should the following do? > > lst1 = [1] > lst2 = [2] > dct = {lst1: "1", lst2: "2"} > lst2[0]=1 > lst1[0]=2 > print dct[[1]] > print dct[[2]] Depends on when you want the updates done. Since my implementation only rehashes when the dict is accessed, neither key gets overwritten in this case: py> class sillylist(list): ... def __hash__(self): ... return hash(tuple(self)) ... py> class sillydict(dict): ... def _rehash(self): ... items = self.items() ... self.clear() ... self.update(items) ... def __getitem__(self, key): ... self._rehash() ... return super(sillydict, self).__getitem__(key) ... def __setitem__(self, key, value): ... self._rehash() ... return super(sillydict, self).__setitem__(key, value) ... py> lst1 = sillylist([1]) py> lst2 = sillylist([2]) py> dct = sillydict({lst1:"1", lst2:"2"}) py> lst2[0] = 1 py> lst1[0] = 2 py> print dct[sillylist([1])] 2 py> print dct[sillylist([2])] 1 The nastier question is, what should the following code do: lst1 = [1] lst2 = [2] dct = {lst1: "1", lst2: "2"} lst2[0]=1 print dct[[1]] print dct[[2]] My implementation does the following: py> lst1 = sillylist([1]) py> lst2 = sillylist([2]) py> dct = sillydict({lst1:"1", lst2:"2"}) py> lst2[0] = 1 py> print dct[sillylist([1])] 1 py> print dct[sillylist([2])] Traceback (most recent call last): File "", line 1, in ? File "", line 8, in __getitem__ KeyError: [2] which is even sillier when you compare to what happens with the original code you posted. ;) Steve From mwm at mired.org Sat Jan 1 15:29:26 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 01 Jan 2005 14:29:26 -0600 Subject: Python equivalent of script(1) References: <1104607982.132310.181560@c13g2000cwb.googlegroups.com> Message-ID: <86mzvsrizd.fsf@guru.mired.org> cepl at surfbest.net writes: > In my case I wouldn't like to use it as a proof of anything, but I want > to get a script accessing a library system in my school -- it means > many attempts to play with urllib. I would prefer to do it in an > interactive session, but then I would love to have a record of all what > I've done, so I can edit this record into final script. > Thanks for any hint, Emacs will do that for you, either in a shell (command shell) or in a Python shell. Edit a python file, and type C-C ! and it'll start an interactive python in a buffer that will save all the output. Of course, you can also run your python after running script. That will log everything from the python session in the script file. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From http Sat Jan 8 19:29:17 2005 From: http (Paul Rubin) Date: 08 Jan 2005 16:29:17 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> Message-ID: <7x3bxbe97m.fsf@ruckus.brouhaha.com> "Carl Banks" writes: > > # compute sqrt(2) + sqrt(3) > > x = (sqrt(a) where: > > a = 2.) \ > > + sqrt (a) where: > > a = 3. > > > > Hmmm. > > What would be the advantage of that over this? > > . x = sqrt(a) + sqrt(b) where: > . a = 2.0 > . b = 3.0 The idea of "where" is to allow re-using variable names instead of having to keep track of which ones are in use. I just tried to give a very simple example of how you might do that more than once in a statement. From flamesrock at gmail.com Fri Jan 7 21:16:20 2005 From: flamesrock at gmail.com (flamesrock) Date: 7 Jan 2005 18:16:20 -0800 Subject: EOF for binary? In-Reply-To: References: <1105147072.909665.242360@z14g2000cwz.googlegroups.com> Message-ID: <1105150580.770105.205990@c13g2000cwb.googlegroups.com> Thanks! I don't know why, but the most innefficient and unmaintanable means of doing something usually pops into my head before anything else. I solved this by going elif len(header) < 8: break From TheDolphin at ivonet.nl Wed Jan 26 16:26:47 2005 From: TheDolphin at ivonet.nl (Ivo Woltring) Date: Wed, 26 Jan 2005 22:26:47 +0100 Subject: subprocess.Popen() redirecting to TKinter or WXPython textwidget??? Message-ID: <41f80b1b$0$148$3a628fcd@reader1.nntp.hccnet.nl> Hi Pythoneers, I am trying to make my own gui for mencoder.exe (windows port of the terrific linux mencoder/mplayer) to convert divx to Pocket_PC size. My current app creates a batch script to run the mencoder with the needed params, but now I want to integrate mencoder as a subprocess in my app. What already works: the starting of the subprocess.Popen and the subsequent killing of the process if I want it to. My gui does not freeze up as it did in my first tries. What I want to know (what does not yet work ;-)): - Redirecting the output of the subprocess to a textwidget in my GUI Any example or help is much appreceated. I tried the subprocess.PIPE but I think I don't really understand how it is suppost to work The redirecting to a file does work but this not my objective... So I'm stuck..... HELP The started processes are long and I want to be able to show some kind of progress-status. Thanx, Ivo Woltring From phr at localhost.localdomain Fri Jan 28 06:37:15 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Fri, 28 Jan 2005 11:37:15 GMT Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com> <1106911061.429966.303510@f14g2000cwb.googlegroups.com> Message-ID: Nick Coghlan writes: > Is that the sound of a volunteer I hear? > > All you have to do is put your hand up, and the problem will be > solved. If not you, who? Tell me about it. See the "rotor replacement" thread. From mercuryprey at gmail.com Mon Jan 31 00:57:40 2005 From: mercuryprey at gmail.com (mercuryprey at gmail.com) Date: 30 Jan 2005 21:57:40 -0800 Subject: Problem with loading textfiles into dictionaries. In-Reply-To: <1107134167.206620.286290@z14g2000cwz.googlegroups.com> References: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> <1107134167.206620.286290@z14g2000cwz.googlegroups.com> Message-ID: <1107151060.400857.147210@z14g2000cwz.googlegroups.com> Yeah I kind of want to 'reinvent' the pickle and I am aware of that. The problem for me is that the output that pickle dumps to a file is too 'cryptic' as I want the ability to edit the corresponding textfile directly and easily, so I'm going for an own way. But yes, Kartic and you were basically right about the line length and checking it first. Didn't really think about it, maybe I was too tired... :) Thanks again! Hope I'm not bothering you all with my extremely newbie questions. munin From python at hope.cz Tue Jan 18 14:16:39 2005 From: python at hope.cz (python at hope.cz) Date: 18 Jan 2005 11:16:39 -0800 Subject: How to prevent the script from stopping before it should In-Reply-To: References: <1105981979.853318.269300@c13g2000cwb.googlegroups.com> Message-ID: <1106075799.535013.125480@f14g2000cwb.googlegroups.com> Fredrik Lundh wrote: > Steve Holden wrote: > > > You will need to import the socket module and then call socket.setdefaulttimeout() to ensure that > > communication with non-responsive servers results in a socket exception that you can trap. > > or you can use asynchronous sockets, so your program can keep processing > the sites that do respond at once while it's waiting for the ones that don't. for > one way to do that, see "Using HTTP to Download Files" here: > > http://effbot.org/zone/effnews-1.htm > > (make sure you read the second and third article as well) > Dear Fredrik Lundh, Thank you for the link. I checked it. But I have not found an answer to my question. My problem is that I can not finish( sometimes) to download all pages. Sometimes my script freezes and I can not do nothing but restart the script from the last successfully downloaded web page. There is no error saying that was an error. I do not know why; maybe the server is programed to reduce the numbers of connection or there maybe different reasons.So, my idea was two threads. One master ,suprevising the slave thread that would do downloading and if the slave thread stopped, master thread would start another slave. Is it a good solution? Or is there a better solution? Thanks for help Lad From http Sun Jan 23 07:34:39 2005 From: http (Paul Rubin) Date: 23 Jan 2005 04:34:39 -0800 Subject: Textual markup languages (was Re: What YAML engine do you use?) References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> Message-ID: <7xmzv0gw80.fsf@ruckus.brouhaha.com> Alan Kennedy writes: > However, I'm torn on whether to use ReST for textual content. On the > one hand, it's looks pretty comprehensive and solidly implemented. It seemed both unnecessary and horrendously overcomplicated when I looked at it. I'd stay away. > So, I'm hoping that the learned folks here might be able to give me > some pointers to a markup language that has the following > characteristics I'm a bit biased but I've been using Texinfo for a long time and have been happy with it. It's reasonably lightweight to implement, fairly intuitive to use, and doesn't get in the way too much when you're writing. There are several implementations, none in Python at the moment but that would be simple enough. It does all the content semantics you're asking (footnotes etc). It doesn't have an explicit object model, but is straightforward to convert into a number of formats including high-quality printed docs (TeX); the original Info hypertext browser that predates the web; and these days HTML. > If I can't find such a markup language, then I might instead end up > using a WYSIWYG editing component that gives the user a GUI and > generates (x)html.... But I'd prefer a markup solution. Yes, for heavy-duty users, markup is far superior to yet another editor. Everyone has their favorite editor and doesn't want to have to switch to another one, hence the Emacs vs. Vi wars etc. From steven.bethard at gmail.com Mon Jan 24 04:04:31 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 24 Jan 2005 02:04:31 -0700 Subject: best way to do a series of regexp checks with groups In-Reply-To: <1gqvzm0.htfjsq10h8nruN%aleaxit@yahoo.com> References: <1gqvzm0.htfjsq10h8nruN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > class ReWithMemory(object): > def search(self, are, aline): > self.mo = re.search(are, aline) > return self.mo > def group(self, n): > return self.mo.group(n) > > m = ReWithMemory() > > if m.search(r'add (\d+) (\d+)', line): > do_add(m.group(1), m.group(2)) > elif m.search(r'mult (\d+) (\d+)', line): > do_mult(m.group(1), m.group(2)) > elif m.search(r'help (\w+)', line): > show_help(m.group(1)) > > Demeter's Law suggests that the 'm.value.group' accesses in your > approach are better handled by having m delegate to its `value'; and the > repeated m.set(re.search( ... seem to be a slight code smell, violating > "once and only once", which suggests merging into a single `set' method. > Your approach is more general, of course. I get a bit uneasy from the repeated calls to m.group... If I was going to build a class around the re, I think I might lean towards something like: class ReWithMemory(object): def search(self, are, aline): self.mo = re.search(are, aline) return self.mo def groups(self, *indices): return [self.mo.group(i) for i in indices] m = ReWithMemory() if m.search(r'add (\d+) (\d+)', line): do_add(*m.groups(1, 2)) elif m.search(r'mult (\d+) (\d+)', line): do_mult(*m.groups(1, 2)) elif m.search(r'help (\w+)', line): show_help(*m.groups(1)) Of course, this is even less general-purpose than yours... (And if I saw myself using this much regex code, I'd probably reconsider my strategy anyway.) ;) Steve From vincent at visualtrans.de Tue Jan 11 01:02:54 2005 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 11 Jan 2005 07:02:54 +0100 Subject: exceptions and items in a list In-Reply-To: References: Message-ID: Steve Holden wrote: > vincent wehren wrote: > >> rbt wrote: >> >>> If I have a Python list that I'm iterating over and one of the >>> objects in the list raises an exception and I have code like this: >>> >>> try: >>> do something to object in list >>> except Exception: >>> pass >>> >>> Does the code just skip the bad object and continue with the other >>> objects in the list, or does it stop? >>> >>> Thanks >> >> >> >> Fire up a shell and try: >> >> >>> seq = ["1", "2", "a", "4", "5", 6.0] >> >>> for elem in seq: >> .... try: >> .... print int(elem) >> .... except ValueError: >> .... pass >> >> >> and see what happens... >> >> -- >> Vincent Wehren > > > I suspect the more recent versions of Python allow a much more elegant > solution. I can't remember precisely when we were allowed to use > continue in an except suite, but I know we couldn't in Python 2.1. > > Nowadays you can write: > > Python 2.4 (#1, Dec 4 2004, 20:10:33) > [GCC 3.3.3 (cygwin special)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. > >>> for i in [1, 2, 3]: > ... try: > ... print i > ... if i == 2: raise AttributeError, "Bugger!" > ... except AttributeError: > ... print "Caught exception" > ... continue > ... > 1 > 2 > Caught exception > 3 > >>> > > To terminate the loop on the exception you would use "break" instead of > "continue". What do you mean by a more elegant solution to the problem? I thought the question was if a well-handled exception would allow the iteration to continue with the next object or that it would stop. Why would you want to use the continue statement when in the above case that is obviously unnecessary?: $ python Python 2.4 (#1, Dec 4 2004, 20:10:33) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> for i in [1,2,3]: ... try: ... if i == 2: raise AttributeError, "Darn!" ... except AttributeError: ... print "Caught Exception" ... 1 2 Caught Exception 3 >>> Or do you mean that using "continue" is more elegant than using "pass" if there are no other statements in the except block? Regards, -- Vincent Wehren > > regards > Steve From sam.wun at authtec.com Thu Jan 27 01:08:29 2005 From: sam.wun at authtec.com (sam) Date: Thu, 27 Jan 2005 14:08:29 +0800 Subject: python module in webmin Message-ID: Hi, Had anyone written any python module for webmin? Since webmin is written in perl, but I want to write a python app/module used by webmin. If you know the detail of writing a python module for use in perl webmin, please drop me some guideline. Perhaps It is better off to find/write a python version of webmin first. Thanks Sam. From FBatista at uniFON.com.ar Mon Jan 3 09:46:47 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 3 Jan 2005 11:46:47 -0300 Subject: removing comments form a file Message-ID: [Noud Aldenhoven] #- Hello everyone, #- #- I was wondering how to remove comments away form a file. I remade it: -------------------------------- #!/usr/bin/env python import sys import time helptext = "usage: python rmcomment " def rmcomment(oldfilename, newfilename, comment): start = time.time() oldfile = file(oldfilename, 'r') newfile = file(newfilename, 'w') ccount = 0 lcount = 0 for lin in oldfile: pos = lin.find(comment) if pos != -1: lin = lin[:pos] + "\n" ccount += 1 newfile.write(lin) lcount += 1 print "Done... in %.2f seconds\nRemoved comment from %d lines\nWrote %d lines t o %s" % (time.time()-start , ccount, lcount, newfilename) if __name__ == "__main__": if sys.argv[1] == "-h" or sys.argv[1] == "-help": print helptext else: oldfile = sys.argv[1] newfile = sys.argv[2] comment = sys.argv[3] rmcomment(oldfile, newfile, comment) -------------------------------- Some issues: - Used <> instead of [] in the help text, as square brackets mean optional arguments. - Eliminated the raw_input, as in these kind of scripts the user *never* expect to have interact input. - Used file instead of open, to don't read the whole file in memory. But the real change is inside the for loop. Testing it: fbatista at pytonisa ~> cat ww Hello Fuckin' World //how are you doing today //I think it delete this sentence and the next sentence too! But this one not! #Even not this comment fbatista at pytonisa ~> python pru.py ww w2 // Done... in 0.00 seconds Removed comment from 2 lines Wrote 7 lines to w2 fbatista at pytonisa ~> cat w2 Hello Fuckin' World But this one not! #Even not this comment fbatista at pytonisa ~> Regards, . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Thu Jan 13 11:10:34 2005 From: aahz at pythoncraft.com (Aahz) Date: 13 Jan 2005 11:10:34 -0500 Subject: why are people still using classic classes? References: <7x6522gegg.fsf@ruckus.brouhaha.com> Message-ID: In article , Simon Wittber wrote: > >'import this' also provides some good advice: > >"There should be one-- and preferably only one --obvious way to do it." > >It seems to me that python is not as simple/clean as it once was. It >has grown warts, for the sake of backwards compatibility. :( That's progress. One of the primary goals for Python 3.0 is to make a fresh start by removing a lot of the backwards compatibility. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From baoqiu at gmail.com Mon Jan 31 02:26:21 2005 From: baoqiu at gmail.com (Baoqiu Cui) Date: 30 Jan 2005 23:26:21 -0800 Subject: a Python bug in processing __del__ method ?? In-Reply-To: References: <1107154011.859866.23480@z14g2000cwz.googlegroups.com> Message-ID: <1107156381.197033.317590@f14g2000cwb.googlegroups.com> Fredrik and Steve, Thank you so much for the help. Now I know more about Python. :-) Steve's test does explain why 'peter1' is OK while 'peter' is not: 'peter1' appears before 'Person' in the globals while 'peter' is after. The error message is just a little confusing to a Python newbie, I think. Thanks again! - Baoqiu From rnd at onego.ru Tue Jan 4 17:25:57 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 5 Jan 2005 01:25:57 +0300 (MSK) Subject: Python evolution: Unease In-Reply-To: <41DB15AF.6020503@pythonapocrypha.com> References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> <9vqdncpnrbRTNEfcRVn-ug@giganews.com> <98WdnVGqi-yaUkfcRVn-tw@giganews.com> <41DAE9E1.5080105@pythonapocrypha.com> <41DAFF93.7030502@pythonapocrypha.com> <41DB15AF.6020503@pythonapocrypha.com> Message-ID: On Tue, 4 Jan 2005, Dave Brueck wrote: >Roman Suzi wrote: >>>The term "generic programming" is too... er... generic. :) >> Nope. It is not generic. It has it's definition made by the co-author >> of STL - A.Stepanov. And the Boost C++ library (many of us know it as >> Boost Python) standardise on the approach, AFAIK. > >Ok, "too broad" then; Python already supports at least some aspects of generic >programming (at least, in the sense that I think you mean it), so it'd be good >to spell out what specific features you're referring to. > >> Python could have honest support of concepts. Everything else will be >> available with them. > >"Concepts" is a pretty generic term too! ;-) Do you mean concepts as defined >here: http://www.boost.org/more/generic_programming.html >? Yes. >> And BTW, are we really disputing? > >No, not at all - I'm just trying to better understand what you mean. Words >like "generic" and "concepts" don't yet have a widely recognized, strict >definition in the context of programming. If somebody has assigned some >specific definition to them, that's great, it's just not universal yet so >references and additional explanations are helpful. I apologize for not providing URLs to the exact definitions in the first place! I really think there is ONE understanding of GP vs. multitudes of understandings of OOP. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From tech at gpao.cc Mon Jan 31 11:29:47 2005 From: tech at gpao.cc (Olivier Noblanc ATOUSOFT) Date: Mon, 31 Jan 2005 17:29:47 +0100 Subject: import doesn't work as i want References: <41fe5438$0$18865$8fcfb975@news.wanadoo.fr> Message-ID: <41fe5cfd$0$6597$8fcfb975@news.wanadoo.fr> how to move in function ? "Fredrik Lundh" a ?crit dans le message de news: mailman.1643.1107187553.22381.python-list at python.org... > Olivier Noblanc wrote: > >> In the botom of this post you will see my source code. >> >> The problem is when i launch main.py that doesn't make anything why ? > > the "if __name__" statement checks the name of the module. if you run > Python file as a script, by passing a filename to the python interpreter, > the > __name__ variable is set to "__main__". if you import a file as a > module, > the __name__ is the name of the module, not "__main__". > > if you want main.py to do something, move that code to main.py (or move > it into a function, and call it from main.py) > > > > From theller at python.net Wed Jan 5 13:15:43 2005 From: theller at python.net (Thomas Heller) Date: Wed, 05 Jan 2005 19:15:43 +0100 Subject: Is there any way/where to subscribe for automated PEP status emails? References: <41dc24f8.68802652@news.oz.net> Message-ID: bokr at oz.net (Bengt Richter) writes: > I find that threads sometimes mention PEPs that I wasn't aware of, > or that an interesting one has been updated without my noticing. > > I should perhaps check the PEP site more regularly, but ISTM it shouldn't > be that hard to implement an automated notification of PEP status changes > by email. A cron job could just monitor the PEP source directory and > watch for new files and last-mod changes, for starters. Maybe that would > be sufficient, without going into classifying the changes in more detail. > > Subscription/unsubscription could be like an ordinary read-only mail list. > You could just bounce replies with some advice as to where to go ;-) You could probably subscribe to python-checkins, and filter it. Or read it via gmane. Thomas From steven.bethard at gmail.com Mon Jan 31 12:53:44 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 31 Jan 2005 10:53:44 -0700 Subject: how to access class methods via their name-as-string In-Reply-To: <1107193514.516478.155440@f14g2000cwb.googlegroups.com> References: <1107193514.516478.155440@f14g2000cwb.googlegroups.com> Message-ID: <8bmdndduCdQ_7WPcRVn-vw@comcast.com> phil_nospam_schmidt at yahoo.com wrote: > I'd like to be able to look up a method name by passing a string with > the method name. Use getattr: py> class A(object): ... def f(self): ... pass ... def g(self): ... pass ... py> class B(A): ... def h(self): ... pass ... py> getattr(B(), 'f') > py> getattr(B(), 'g') > py> getattr(B(), 'h') > Steve From aorfanakos at gmail.com Wed Jan 26 21:40:02 2005 From: aorfanakos at gmail.com (Aggelos I. Orfanakos) Date: 26 Jan 2005 18:40:02 -0800 Subject: Which is faster? Message-ID: <1106793602.782397.61260@z14g2000cwz.googlegroups.com> Any idea which of the following is faster? 'a/b/c/'[:-1] or 'a/b/c/'.rstrip('/') Thanks in advance. P.S. I could time it but I thought of trying my luck here first, in case someone knows already, and of course the reason. From philippecmartin at sbcglobal.net Fri Jan 7 06:54:03 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Fri, 07 Jan 2005 12:54:03 +0100 Subject: Developing Commercial Applications in Python Message-ID: <1105098843.6909.2.camel@localhost> > >> Can somebody there to point me any good commercial applications >> developed using python ? > Only time will tell if SCF is a _good_ commercial application, but it will be released on my site as soon as I get my export license from the BIS. _and_ I will certainly announce it on this list :-) Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From fredrik at pythonware.com Sun Jan 23 07:26:32 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 23 Jan 2005 13:26:32 +0100 Subject: Insanity References: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> <3sfcc2-b6v1.ln1@eskimo.tundraware.com> Message-ID: Tim Daneliuk wrote: > Thanks - very helpful. One followup - your re works as advertised. But > if I use: r'\[PROMPT:[^]].*\]' it seems not to. the '.*' instead of just '*' > it matches the entire string ... it's not "just '*'", it's "[^]]*". it's the "^]" set (anything but ]) that's repeated. "[^]].*\]" means match a single non-] character, and then match as many characters as you possibly can, as long as the next character is a ]. "[^]]*\]" means match as many non-] characters as possible, plus a single ]. > which seems counterintutive to me. then you need to study RE:s a bit more. (hint: an RE isn't a template, it's a language description, and the RE engine is designed to answer the question "does this string belong to this language" (for match) or "is there any substring in this string that belongs to this language" (for search) as quickly as possible. things like match locations etc are side effects). From tbolands at yahoo.com Mon Jan 24 19:36:56 2005 From: tbolands at yahoo.com (TB) Date: 24 Jan 2005 16:36:56 -0800 Subject: default value in a list In-Reply-To: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: <1106613416.417645.41070@z14g2000cwz.googlegroups.com> Thanks very much for all the responses. They were useful to me and I'll probably refer back to them again in the future. TB From jcribbs at twmi.rr.com Sun Jan 30 17:36:38 2005 From: jcribbs at twmi.rr.com (Jamey Cribbs) Date: Sun, 30 Jan 2005 17:36:38 -0500 Subject: ANNOUNCE: KirbyBase 1.7 Message-ID: <41FD6176.4000202@twmi.rr.com> KirbyBase is a simple, plain-text, database management system written in Python. It can be used either embedded in a python script or in a client/server, multi-user mode. You use python code to express your queries instead of having to use another language such as SQL. KirbyBase is disk-based, not memory-based. Database changes are immediately written to disk. You can find more information on KirbyBase at: http://www.netpromi.com/kirbybase.html You can download KirbyBase for Python at: http://www.netpromi.com/files/KirbyBase_Python_1.7.zip Wow! It's been almost two years since the initial release of KirbyBase. Time sure does fly! Version 1.7 includes most of the bug fixes that have accumulated over the months and a few enhancements that I hope you will enjoy. I would like to thank everyone who has emailed me with comments, bug reports, and enhancement requests/ideas. Hearing from people who actually use KirbyBase is what makes working on it worthwhile. Please keep the emails coming! I would particularly like to thank Pierre Quentel, the author of Karrigell (http://karrigell.sourceforge.net), for his contribution of ideas and code for many of the enhancements in version 1.7 of KirbyBase. For those of you who requested better documentation, the manual has been completely re-written. I'm not saying it's any better, but at least it's different. :) Changes in Version 1.7: ***IMPORTANT - IF YOU ARE UPGRADING THIS COULD BITE YOU!!!*** * Changed the default value for the keyword argument 'useRegExp' to be false instead of true. This means that, when doing a update, delete, or select, records being selected on string fields will be matched using exact matching instead of regular expression matching. If you want to do regular expression matching, pass 'useRegExp = True' to the method. ***IMPORTANT*** * Added a keyword argument to select() called returnType. If set to 'object', the result list returned will contain Record objects where each field name is an attribute of the object, so you could refer to a record's field as plane.speed instead of plane[4]. If set to 'dict', the result list returned will contain dictionaries where each key is a field name and each value is a field value. If set to 'list', the default, the result is a list of lists. * Added a new method, insertBatch. It allows you to insert multiple records at one time into a table. This greatly improves the speed of batch inserts. * Added a new public method called validate. Calling this method with a table name will check each record of that table and validate that all of the fields have values of the correct type. This can be used to validate data you have put into the table by means other than through KirbyBase, perhaps by opening the table in a text editor and typing in information. * Fixed a bug in _closeTable where if an exception occurred it was blowing up because the variable 'name' did not exist. * Fixed a bug in _writeRecord where if an exception occured it was blowing up because the variable 'name' did not exist. * Fixed a bug in _getMatches where I was referencing self.field_names as a method instead of as a dictionary. * Added a new private method, _strToBool, that converts string values like 'True' to boolean values. * Added a new private method, _convertInput, and moved to it the code that ensures that the data on an insert is in proper list format. I did this so that I did not have duplicate code in both the insert and insertBatch methods. * To accomodate the fact that users can now send a large batch of records to be inserted, I changed _sendSocket so that it first sends the length of the database command to the server, then it actually sends the command itself, which can now be any length. * Changed the code in _getMatches to precompile the regular expression pattern instead of dynamically compiling every time the pattern is compared to a table record. This should speed up queries a little bit. * Changed the code in select that converts table fields back to their native types to be more efficient. * Changed _sendSocket to use StringIO (actually cStringIO) to hold the result set of a client/server-based query instead of just capturing the result by concatenating records to one big string. In informal testing on large result sets, it shaves a few tenths of a second off the query time. Jamey Cribbs jcribbs at twmi.rr.com From steve at holdenweb.com Mon Jan 10 20:29:00 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 10 Jan 2005 20:29:00 -0500 Subject: Chicago Python Users Group: Thu 13 Jan Meeting In-Reply-To: References: Message-ID: <41E32BDC.2060105@holdenweb.com> Ian Bicking wrote: > The Chicago Python User Group, ChiPy, will have its next meeting on > Thursday, 13 January 2005, starting at 7pm. For more information on > ChiPy see http://chipy.org > [...] > > About ChiPy > ----------- > > We meet once a month, on the second Thursday of the month. If you > can't come this month, please join our mailing list: > http://lonelylion.com/mailman/listinfo/chipy Ian: I am teaching class in Chicago the week of February 22 (I'll be in Schaumberg and available any evening from 21-24). Since that doesn't coincide woth your regular schedule, I wonder if you'd like to mention that I'd be up for a beer and/or meal and a natter with any Chicago Pythonistas who happen to fancy it. Anyone who so wishes can then email me. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From craig at postnewspapers.com.au Fri Jan 7 12:05:40 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 08 Jan 2005 01:05:40 +0800 Subject: sorting on keys in a list of dicts In-Reply-To: References: <10tr9ejf05pv660@corp.supernews.com> Message-ID: <1105117539.30384.46.camel@rasputin.localnet> On Sat, 2005-01-08 at 00:26, It's me wrote: > What does it mean by "stability in sorting"? If I understand correctly, it means that when two sorts are performed in sequence, the keys that are equal to the second sort end up ordered the way they were left by the first sort. I'm far from certain of this, but at least I'm presenting an opportunity for someone to yell "no, you're wrong!" and in the process definitively answer the question. For example, given the list: .>>> l = [(1,2), (8,2), (2,2), (3,2), (4,3), (5,3), (8,9)] if we sort by the first element of each tuple then the second (the default), we get: .>>> l.sort() .>>> l [(1, 2), (2, 2), (3, 2), (4, 3), (5, 3), (8, 2), (8, 9)] Now, if we sort based on the second element we get: .>>> def seconditem(x): .... return x[1] .... .>>> l.sort(key=seconditem) .>>> l [(1, 2), (2, 2), (3, 2), (8, 2), (4, 3), (5, 3), (8, 9)] You'll note that there are several correct answers to the request "sort the list 'l' by the second element of each item", including: [(1, 2), (2, 2), (3, 2), (8, 2), (4, 3), (5, 3), (8, 9)] [(2, 2), (1, 2), (8, 2), (3, 2), (4, 3), (5, 3), (8, 9)] [(1, 2), (2, 2), (3, 2), (8, 2), (5, 3), (4, 3), (8, 9)] and many others. Because we didn't specify that the first item in the value tuples should be used in the sort key, so long as the second key is equal for a group of items it doesn't matter what order items in that group appear in. Python (at least 2.4), however, returns those groups where the order isn't defined in the same order they were before the sort. Look at this, for example: .>>> l.sort() .>>> l.reverse() .>>> l [(8, 9), (8, 2), (5, 3), (4, 3), (3, 2), (2, 2), (1, 2)] .>>> l.sort(key=seconditem) .>>> l [(8, 2), (3, 2), (2, 2), (1, 2), (5, 3), (4, 3), (8, 9)] See how the exact same sort command was used this time around, but because the list was reverse-sorted first, the elements are in reverse order by first item when the second item is equal? In the first case we used the same result as the stable sort could be obtained with: .>>> def revitem(x): .... return (x[1], x[0]) >>> l.sort(key=revitem) >>> l [(1, 2), (2, 2), (3, 2), (8, 2), (4, 3), (5, 3), (8, 9)] (in other words, saying "use the value tuple as the sort key, but sort by the second element before the first") That doesn't extend to more complex cases very well though. Imagine you had 3-tuples not 2-tuples, and wanted to maintain the previous sort order of equal groupings when re-sorting by a different key... but you didn't know what key was last used for sorting. A stable sort algorithm means you don't need to care, because the order will be maintained for you not randomized. Well, that's several hundred more words than were probably required, but I hope I made sense. -- Craig Ringer From __peter__ at web.de Sun Jan 16 05:17:01 2005 From: __peter__ at web.de (Peter Otten) Date: Sun, 16 Jan 2005 11:17:01 +0100 Subject: accessing class variables of private classes References: Message-ID: Uwe Mayer wrote: > I need to access class variables of a class I'd like to make private: > > i.e. > class __Bar(object): > pass > > class __Foo(__Bar): > def __init__(self): > super(__Foo, self).__init__() > >>>> __Foo() > Name Error: global name '_Foo__Foo' is not defined > > Here I want to prevent the user of instanciating __Foo from outside of the > module. > > > i.e. > class __A: > a_list = [] > def __init__(self): > __A.a_list.append(self) > >>>> __A() > NameError: global name '_A__A' is not defined > > Here I want to keep a list of instanciated objects of class __A, so I can > update internal values if they are changed. > > > Any ideas? Use single underscores. Even better: don't impose bogus restrictions on users of your module. I know, we're all dissenting children, but still... > > Thanks > Uwe From kohlerj at ukzn.ac.za Wed Jan 26 08:40:36 2005 From: kohlerj at ukzn.ac.za (Johan Kohler) Date: Wed, 26 Jan 2005 15:40:36 +0200 Subject: "pickle" vs. f.write() In-Reply-To: References: Message-ID: Thanks... works like a charm :-) On Wed, 26 Jan 2005 12:55:38 +0100, Peter Maas wrote: > Johan Kohler schrieb: >> class person: >> name ="" >> age = 0 >> friends=[] >> comment="""""" >> me = person() >> Otherwise, what is the best "Python" way to write and read this data >> structure? > > import pickle > > class person: > name ="" > age = 0 > friends=[] > comment="""""" > > me = person() > > # store > pf = file('/tmp/pickletest', 'w') > pickle.dump(me, pf) > pf.close() > > > # load > pf = file('/tmp/pickletest', 'r') > me2 = pickle.load(pf) > pf.close() > > This is sequential access. If you want to have random access, look > for shelve. > -- Using Opera's revolutionary e-mail client: http://www.opera.com/m2/ -------------------------------------------------------------------- Please find our disclaimer at http://www.ukzn.ac.za/disclaimer -------------------------------------------------------------------- <<<>>> From michele.simionato at gmail.com Wed Jan 5 02:32:43 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 4 Jan 2005 23:32:43 -0800 Subject: Python evolution: Unease In-Reply-To: <7x652che6z.fsf@ruckus.brouhaha.com> References: <7xacrpdxy3.fsf@ruckus.brouhaha.com> <7x652che6z.fsf@ruckus.brouhaha.com> Message-ID: <1104910363.381748.105670@z14g2000cwz.googlegroups.com> Paul Rubin: > I'm now running the Python > that was included in Fedora Core 3 GNU/Linux, a complete OS distro on > a DVD-ROM, containing about 3 gigabytes not including sources. And > when a user installs 3 gigabytes of software from a DVD, they can > reasonably expect that they've installed a complete system and > shouldn't need to download anything additional to use all the features > of the programs on the DVD. Now the Fedora maintainers aren't Python > gurus--people ask for Python so they did the obvious thing: downloaded > it, ran its installer, put the output into their distro, and said "ok, > Fedora has Python". That's all they should need to do to incorporate > Python into Fedora. So it's up to the Python maintainers, not the > Fedora maintainers or the user, to make sure that the Python distro > has everything that users need, without further downloading. Dunno about Fedora, I stopped using Red Hat just because they were *not* using the standard Python distribution, and the version they shipped was cripped in various ways. There is nothing the Python developers can do if the OS vendors choose to ship modified Python distributions, with missing modules or splitted in n separated packages to download separately. Michele Simionato From bob at nospam.net Thu Jan 27 16:22:58 2005 From: bob at nospam.net (Benji99) Date: 27 Jan 2005 21:22:58 GMT Subject: Startying with Python, need some pointers with manipulating strings Message-ID: <41f95bb2$0$24349$9a6e19ea@unlimited.newshosting.com> Hi guys, I'm starting to learn Python and so far am very impressed with it's possibilities. I do however need some help with certain things I'm trying to do which as of yet haven't managed to find the answer by myself. Hopefully, someone will be able to give me some pointers :) First my background, I haven't programmed seriously in over 5 years, but recently have started programming again in Delphi/Pascal scripting, and that's what I'm most familiar with right now. I'm also much more confortable with structured programming in contrast to OO (which isn't helping much with Python :)) Anyway, I have a very specific project in mind which I've mostly implemented in Pascal and I'd like to implement it in Python since the possibilities after that are much more interesting. Basically, I'm getting a htmlsource from a URL and need to a.) find specific URLs b.) find specific data c.) with specific URLs, load new html pages and repeat. I've managed to load the html source I want into an object called htmlsource using: >>> import urllib >>> sock = urllib.urlopen("URL Link") >>> htmlSource = sock.read() >>> sock.close() I'm assuming that htmlSource is a string with \n at the end of each line. NOTE: I've become very accustomed with the TStringList class in Delphi so forgive me if I'm trying to work in that way with Python... Basically, I want to search through the whole string( htmlSource), for a specific keyword, when it's found, I want to know which line it's on so that I can retrieve that line and then I should be able to parse/extract what I need using Regular Expressions (which I'm getting quite confortable with). So how can this be accomplished? Second main thing I'd like to know has to do with urllister, I'm very intrigued by it's use of grabbing automatically url links from the source. but I've only managed to get it to retrive everything, which is a lot. what are my options in term of getting it to be more specific? Can I tell it to retrieve a URL IF a keyword is found on the same string line? Hopefully someone will be able able/willing to give me a hand, I think with these roadblocks out of the way, I should be able to figure out the rest of what I need. Thanks in advance! Benji99 ---------------------------------------------- Posted with NewsLeecher v1.0 Final * Binary Usenet Leeching Made Easy * http://www.newsleecher.com/?usenet ---------------------------------------------- From ville at spammers.com Sat Jan 22 12:55:49 2005 From: ville at spammers.com (Ville Vainio) Date: 22 Jan 2005 19:55:49 +0200 Subject: [OT] Good C++ book for a Python programmer References: <1106136496.719185.87850@c13g2000cwb.googlegroups.com> Message-ID: >>>>> "Rick" == rick muller at yahoo com writes: Rick> I was wondering whether anyone could recommend a good C++ Rick> book, with "good" being defined from the perspective of a Rick> Python programmer. I A good C++ book from the perspective of a Python programmer would be one proclaiming that C++ is deprecated as a language, and it has become illegal to develop software with it. Rick> realize that there isn't a book titled "C++ for Python Rick> Programmers", but has anyone found one that they think goes Rick> particularly well with the Python way? I don't think that's possible, considering the nature of the language. Templates are closest to the Python way as far as C++ technologies go, but they are very unpythonic in their complexity. Rick> I'm asking this because evidently the C++ standard has Rick> changed a bit since 1994, when I bought my books. Who knew Rick> that fstream was deprecated? Stroustrup book, already mentioned by others, is the one if you just need a "refresh" your knowledge. "Effective C++" and "More effective C++" are also great to learn about all the nasty gotchas that your Python experience might make you neglect. They are also certain to deepen your appreciation of Python ;-). -- Ville Vainio http://tinyurl.com/2prnb From bvande at po-box.mcgill.ca Mon Jan 24 17:56:30 2005 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon, 24 Jan 2005 17:56:30 -0500 Subject: Python 2.1 - 2.4 differences In-Reply-To: References: Message-ID: <41F57D1E.3020808@po-box.mcgill.ca> > > "BOOGIEMAN" wrote in message > news:tcedpqix23lw$.v3p06vutw05p$.dlg at 40tude.net... > >I found some e-book about Python 2.1, I want to print it but just to check >first if sintax of Python 2.1 is same as 2.4 ? Also does anybody know >where >can I download any newer Python related e-book, because there isn't any >published yet in my country. Hi, Dive Into Python is available both as a physical book and at . It is reported to be a good intro for those with programming experience. I don't and found it quite readable, albeit after looking at some gentler books first. A quick examination of my local copy has a revision date of 2004-05-20. (There may be a more recent version at the site.) I can't seem to find an indication of Python version covered, but some of the interactive prompts have at least the Python 2.3.2 version identifier. HTH, Brian vdB From jzgoda at gazeta.usun.pl Thu Jan 13 14:49:52 2005 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Thu, 13 Jan 2005 20:49:52 +0100 Subject: why are people still using classic classes? In-Reply-To: <7x6522gegg.fsf@ruckus.brouhaha.com> References: <7x6522gegg.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: >>>Is there a reason NOT to use them? If a classic class works fine, what >>>incentive is there to switch to new style classes? >> >>Perhaps classic classes will eventually disappear? > > It just means that the formerly "classic" syntax will define a > new-style class. Try to write code that works either way. Ideally, I'd like to have them working like in Delphi, where it doesn't matter if you declare it as TSomeClass(TObject) or simply TSomeClass, it is assumed that class is inherited from TObject if no other class is specified. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From peter at engcorp.com Sat Jan 8 12:33:52 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Jan 2005 12:33:52 -0500 Subject: OT: spacing of code in Google Groups In-Reply-To: References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> <41DD5C6B.2070708@holdenweb.com> Message-ID: JanC wrote: > Have a look at: > They have native win32 builds of many of the GNU commandline utilities... Thanks, everyone, for all your kind help. (Uh, I thought it was clear I didn't actually *want* a method of cutting columns, since I have needed the functionality once in the last ten years, but on behalf of those who do what it and didn't know how to get it, I give you thanks. ;-) -quite-happy-with-simple-editors-and-a-command-line-ly y'rs, Peter From apardon at forel.vub.ac.be Wed Jan 19 06:17:40 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Jan 2005 11:17:40 GMT Subject: Dictionary keys (again) (was Re: lambda) References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> Message-ID: Op 2005-01-19, Nick Coghlan schreef : > Antoon Pardon wrote: >> A rule of thumb is context sensitive. If circumstances change, >> so do the rules of thumb. Principles have a broader field >> of application. >> >> IMO there is nothing principally wrong with using a mutable object >> as a dictionary key. But avoiding doing so is a good rule of >> thumb if you have a python-like implementation of a dictionary. > > For a 'mutable key' to make sense, the following: As you said yourself, people use shortcuts when they express themselves. With 'mutable key' I mean a mutable object that is used as a key. That doesn't contradict that the key itself can't change because it is inaccessible. > lst = [] > dct = {l: "Hi!"} > print dct[[]] > print dct[lst] > lst.append(1) > print dct[[1]] > print dct[lst] > > Should print: > Hi > Hi > Hi > Hi > That's completely impractical though - for any sane implementation, at least one > of the above print statements will throw a KeyError. > > Your example of a 'safe_dict' that copies mutable keys means that the final > print statement is the one that fails. > > My suggestion of an "identity_dict" means that both of the same-value based > lookups would fail. > > Notice that both of these approaches take a mutable key and make it immutable > (either by holding the sole reference to a copy, or retrieving an immutable > property of the mutable object). > > There's also your solution of "I promise not to mutate the key while it is in > the dictionary". Workable, but opens the door to some entertaining bug hunts > when the promise is broken. That is usually the case when promisses are broken. To mention something different, I guess a number of equally entertaining bug hunts can be caused by the fact that the value in the dictionary is changed. > Which solution is the best default behaviour? IMO a dictionary establisches a relationship between values. The most general implementation that protects this relationship from external tampering is copying the key and value for use in the dictionary. > Well, the Zen of Python states "In the face of ambiguity, refuse the temptation > to guess". But python does guess in the case of the value. If I want to establish a relationship between "foo" and [3, 5, 8] then I can be in big trouble if that list gets mutated in something else. > So that's the policy the builtin dict follows - it doesn't try to guess when to > make a copy, or whether or not to use identity based semantics in the face of > mutability. Instead, it raises an exception at key entry time, asking the > programmer to clarify their intent. > > The principle is *certainly* that hash tables should contain immutable keys. > Your own 'safe_dict' example implicitly concedes this point by making copies > 'when required'. 'When required' for what? When required to preserve > immutability, perhaps? But they don't have to be immutable within the dictionary itself, that is just an implementation detail. The only thing that matters is that the dictionary can reproduce the relationship. How that is done is immaterial. > In short, sane hash tables require immutable keys, and how mutable keys acquire > the requisite immutability is going to be application dependent. No they don't, that is just the most easy implementation. If some implementation would constantly change the internal objects but consulting the dictionary wouldn't show any different effect then that would be fine too. And even in this case a mutation from the outside would probably cause havoc because it would ruin the sanity of the internal structure. > Provision of a safe_dict or identity_dict would merely allow a programmer to > state their intent at the time the container is created, rather than having to > state it whenever keys are generated or referenced. Well that would be a good thing IMO. Good enough in any case for me to spend some time analyzing the requirements. Whether I'll actually implement something depends on how much time I have and how often I need it. -- Antoon Pardon From steven.bethard at gmail.com Thu Jan 20 20:47:36 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 20 Jan 2005 18:47:36 -0700 Subject: problems with duplicating and slicing an array In-Reply-To: References: Message-ID: <542dnVPtl_aqwm3cRVn-uQ@comcast.com> Yun Mao wrote: > Hi python gurus, > I have some questions when I'm using python numeric: > > 1. When I do v = u[:, :], it seems u and v still point to the same > memory. e.g. When I do v[1,1]=0, u[1,1] will be zero out as well. > What's the right way to duplicate an array? Now I have to do v = > dot(u, identity(N)), which is kind of silly. Hmm... I don't know Numeric, but in numarray (Numeric's replacement), you just call the copy method: py> u = na.arange(6, shape=(2, 3)) py> v = u.copy() py> v[0,0] = 100 py> u array([[0, 1, 2], [3, 4, 5]]) py> v array([[100, 1, 2], [ 3, 4, 5]]) > 2. Is there a way to do Matlab style slicing? e.g. if I have > i = array([0, 2]) > x = array([1.1, 2.2, 3.3, 4.4]) > I wish y = x(i) would give me [1.1, 3.3] This also works exactly as you'd hope in numarray. py> i = na.array([0, 2]) py> x = na.array([1.1, 2.2, 3.3, 4.4]) py> x[i] array([ 1.1, 3.3]) Do you have any reason that you have to use Numeric? Or can you upgrade to numarray? Steve From pekka.niiranen at wlanmail.com Sat Jan 1 09:17:54 2005 From: pekka.niiranen at wlanmail.com (Pekka Niiranen) Date: Sat, 01 Jan 2005 16:17:54 +0200 Subject: HELP: Tkinter idiom needed Message-ID: <41d6b0c9$0$16584$39db0f71@news.song.fi> Hi there, after reading TkInter/thread -recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965 I wondered if it was possible to avoid using threads for the following problem: I have script started from W2K console that normally prints ascii messages to the screen. However, I have command line "debug" -flag that might cause printing of UTF-8 data to the screen. This fails occassionally due to Console encoding, of course. What I need is Tkinter window where some printouts are directed when script is run in Debug -mode (Redirection of stdout is out of question). While testing, I have got this far already: ---script starts---- from Tkinter import * from ScrolledText import ScrolledText import os, sys, tkFont, codecs class Pyg_message_box: def __init__(self, parent): self.myParent = parent self.myContainer1 = Frame(parent) self.myContainer1.option_add("*font",\ tkFont.Font(family="Arial Unicode MS", size=8)) self.myContainer1.pack() self.text = ScrolledText() self.text.pack() self.button1 = Button(self.myContainer1, text="Quit",\ command=self.button1Click) self.button1.pack(side=LEFT) self.button1.bind("", self.button1Click) def button1Click(self, event): self.myContainer1.quit() def write(self, s): self.text.insert(END, s) root = Tk() widget = Pyg_message_box(root) sys.stdout = widget a = codecs.open("d:\\test.txt", "r", "utf_16").readlines() for x in a: print x root.mainloop() ---script ends---- My questions are: - Can I open Tk -window without enclosing the whole script between "root=Tk()" and "root.mainloop()"? - What is the idiom of opening Tk -window only when Debug -flag is encountered (the script stops running until window is closed)? Something like: if not my_debug == "ON": print "message" # prints to console else: # 1) open temporary ScrolledText() Tk -window # 2) Print stuff to window # 3) Ask user to close window I would no like to always open Tkwindows just in case user runs script with debug -flag on. -pekka- From frans.englich at telia.com Sun Jan 23 13:35:07 2005 From: frans.englich at telia.com (Frans Englich) Date: Sun, 23 Jan 2005 18:35:07 +0000 Subject: What is print? A function? In-Reply-To: References: Message-ID: <200501231835.07310.frans.englich@telia.com> On Sunday 23 January 2005 18:04, Michael Hoffman wrote: > Frans Englich wrote: [...] > if command_line_debug_option: > debug = _debug_true > else > debug = _debug_false I find this a nice solution. The most practical would be if it was possible to do this with print, of course. But print won't budge. Is it possible to create own statements, such that it would be possible to do: printDebug "test" ? Cheers, Frans From francis.girard at free.fr Wed Jan 26 15:35:30 2005 From: francis.girard at free.fr (Francis Girard) Date: Wed, 26 Jan 2005 21:35:30 +0100 Subject: python without OO In-Reply-To: <1993411a01509c62cae1715b62fe16f5@gmail.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <200501262039.23260.francis.girard@free.fr> <1993411a01509c62cae1715b62fe16f5@gmail.com> Message-ID: <200501262135.30872.francis.girard@free.fr> Le mercredi 26 Janvier 2005 20:47, PA a ?crit?: > Project fails for many reasons but seldomly because one language is > "better" or "worst" than another one. I think you're right. But you have to choose the right tools that fit your needs. But I think that's what you meant anyway. > > Cheers > Cheers too, Francis Girard FRANCE > -- > PA > http://alt.textdrive.com/ From alipolatel at yahoo.com Sat Jan 22 19:46:16 2005 From: alipolatel at yahoo.com (Ali Polatel) Date: Sat, 22 Jan 2005 16:46:16 -0800 (PST) Subject: Python Scripting Message-ID: <20050123004617.43960.qmail@web61007.mail.yahoo.com> Hi Dear Python programmers, I want to ask you a question about python scripting.I want to know if I can design web-pages with python or at least write html files with python. and if I write html files with python and some CGI scripts and upload them to the web-page .. does the people who view those pages have to have python interpreters in their computers? Another question is ... I am writing a bot for a chess server in python and this bot should update a web-page when it gets some commands from the server.How can i make a programme update a web-page? Thanks and regards --------------------------------- Do you Yahoo!? Yahoo! Search presents - Jib Jab's 'Second Term' -------------- next part -------------- An HTML attachment was scrubbed... URL: From wittempj at hotmail.com Fri Jan 14 15:25:43 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 14 Jan 2005 12:25:43 -0800 Subject: Com port interrupts again In-Reply-To: <154gu09bghnq674s2nqot9si6d50igueq7@4ax.com> References: <154gu09bghnq674s2nqot9si6d50igueq7@4ax.com> Message-ID: <1105734343.547195.301160@f14g2000cwb.googlegroups.com> A search on google gave me this library, I haven't tested it though: http://groups-beta.google.com/group/comp.lang.python.announce/browse_frm/thread/6d3263250ed65816/291074d7bd94be63?q=com+port+python&_done=%2Fgroups%3Fhl%3Den%26lr%3D%26safe%3Doff%26q%3Dcom+port+python%26qt_s%3DSearch+Groups%26&_doneTitle=Back+to+Search&&d#291074d7bd94be63 From bulba at bulba.com Wed Jan 5 12:18:29 2005 From: bulba at bulba.com (Bulba!) Date: Wed, 05 Jan 2005 18:18:29 +0100 Subject: Pythonic search of list of dictionaries References: Message-ID: On Tue, 04 Jan 2005 21:57:46 +0100, Marc 'BlackJack' Rintsch wrote: >In , Bulba! wrote: > >> I put those dictionaries into the list: >> >> oldl=[x for x in orig] # where orig=csv.DictReader(ofile ... > >If you don't "do" anything with each `x` you can write this as: > oldl = list(orig) Thanks! I need to wrap my mind around Python more tightly. :-) -- It's a man's life in a Python Programming Association. From http Sat Jan 22 17:34:15 2005 From: http (Paul Rubin) Date: 22 Jan 2005 14:34:15 -0800 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fpq0F4mh1ffU1@individual.net> <7xoefhtavd.fsf@ruckus.brouhaha.com> <1gqtawv.omj416ues6jN%aleaxit@yahoo.com> Message-ID: <7xbrbhm6u0.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > I wonder, however, if, as an even "toyer" exercise, one might not > already do it easily -- by first checking each token (as generated by > tokenize.generate_tokens) to ensure it's safe, and THEN eval _iff_ no > unsafe tokens were found in the check. I don't trust that for one minute. It's like checking a gun to make sure that it has no bullets, then putting it to your head and pulling the trigger. Or worse, it's like checking the gun once, then putting it to your head and pulling the trigger every day for the next N years without checking again to see if someone has inserted some bullets (this is what you basically do if you write your program to check if the tokens are safe, and then let users keep running it without re-auditing it, as newer versions of Python get released). See the history of the pickle module to see how that kind of change has already screwed people (some comments in SF bug #467384). "Don't use eval" doesn't mean mean "check if it's safe before using it". It means "don't use it". From fumanchu at amor.org Thu Jan 13 11:50:19 2005 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 13 Jan 2005 08:50:19 -0800 Subject: module on files & directories Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33981AA@exchange.hqamor.amorhq.net> Sara Fwd wrote: > > Can anybody help me find a module or a function that > > looks in a directory and defines whether the objects > > in there are files or directories? and Simon Brunning replied: > See os.path.isfile() and os.path.isdir() - > . I suspect you will also want to look at os.walk() eventually: for root, dirs, files in os.walk(path): for dir in dirs: do_something_with(dir) Robert Brewer MIS Amor Ministries fumanchu at amor.org From Prikryl at skil.cz Mon Jan 10 04:54:43 2005 From: Prikryl at skil.cz (Petr Prikryl) Date: Mon, 10 Jan 2005 10:54:43 +0100 Subject: Bug in Python 2.4 raw_input(u'xyz') Win/command line? Message-ID: Hi, Could you test the following example for your non-English language with accented characters? I have observed a problem when running Python 2.4, Windows version (python-2.4.msi) and using raw_input() with unicode prompt string in a console program (ran in the DOS window). I do use the following sitecustomize file to set the default encoding: sitecustomize.py ================================= import sys sys.setdefaultencoding('cp1250') ================================= test.py ================================= # -*- coding: cp1250 -*- s = u'string with accented letters' print s # OK val = raw_input(s) # s displayed differently (wrong) ================================= ... when run in a DOS window. See the attached test.png. The "type test.py" displays the string definition also wrong, because the DOS window uses different encoding than cp1250. The print command prints the string correctly, converting the internal unicode string to the encoding that the is defined by the output environment. However, the raw_input() probably does convert the unicode string to the cp1250 and does not do the same (more clever) thing that the print does. Could you confirm the bug? Is it known? Should this be posted into some bug-report list? Petr python test.py I have observed t -- Petr Prikryl (prikrylp at skil dot cz) -------------- next part -------------- A non-text attachment was scrubbed... Name: test.py Type: application/octet-stream Size: 172 bytes Desc: test.py URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: test.png Type: image/png Size: 3689 bytes Desc: test.png URL: From fredrik at pythonware.com Fri Jan 21 15:59:57 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 21 Jan 2005 21:59:57 +0100 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> Message-ID: A.M. Kuchling wrote: > IMHO that's a bit extreme. Specifications are written to be detailed, so > consequently they're torture to read. Seen the ReStructured Text spec > lately? I've read many specs; YAML (both the spec and the format) is easily among the worst ten-or-so specs I've ever seen. ReST and YAML share the same deep flaw: both formats are marketed as simple, readable formats, and at a first glance, they look simple and read- able -- but in reality, they're messy as hell, and chances are that the thing you're looking at doesn't really mean what you think it means (unless you're the official ReST/YAML parser implementation). experienced designers know how to avoid that; the ReST/YAML designers don't even understand why they should. > But YAML seems to have started out with the goal of being human-writable, > something you would write in Emacs, and that seems to have gotten lost; the > format is now just as complicated as Restructured Text, but more cryptic > (the URI namespacing for tags, for example), not really simpler than > XML and in some ways weaker (e.g. only two encodings supported, more > complicated escaping rules). http://www.modelsmodelsmodels.biz/images/hmo033.jpg From claird at lairds.us Thu Jan 27 12:08:04 2005 From: claird at lairds.us (Cameron Laird) Date: Thu, 27 Jan 2005 17:08:04 GMT Subject: Entirely off-topic personal grumble unrelated to original poster (was: Point of Sale) References: Message-ID: <2kgnc2-gn4.ln1@lairds.us> In article , Andreas Pauley wrote: . . . >Actually I just mean that I'm not looking for a 100% feature-fit, if I get >a 70% fit I'll jump in and develop the other 30%. . . . I keep winning contracts where something is a 70% fit, and all I have to do is finish the other 85%. From aleaxit at yahoo.com Sat Jan 22 06:30:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 12:30:36 +0100 Subject: default value in a list References: <1106349263.943972.72710@f14g2000cwb.googlegroups.com> Message-ID: <1gqsi0i.12qbij5okovdeN%aleaxit@yahoo.com> Nick Craig-Wood wrote: ... > Or this version if you want something other than "" as the default > > a, b, b = (line.split(':') + 3*[None])[:3] Either you mean a, b, c -- or you're being subtler than I'm grasping. > BTW This is a feature I miss from perl... Hmmm, I understand missing the ``and all the rest goes here'' feature (I'd really love it if the rejected a, b, *c = whatever suggestion had gone through, ah well), but I'm not sure what exactly you'd like to borrow instead -- blissfully by now I've forgotten a lot of the perl I used to know... care to clarify? Alex From Antigen_UKEXC01 at bag.python.org Wed Jan 5 19:22:21 2005 From: Antigen_UKEXC01 at bag.python.org (Antigen_UKEXC01 at bag.python.org) Date: 6 Jan 2005 00:22:21 +0000 Subject: Mail Delivery (failure letty.leung@maplesandcalder.com) Message-ID: Our AntiVirus scanner detected virus Exploit.IFrame.B in your message. The message has NOT been delivered and the recipient has NOT been notified. Please use an anti-virus scanner to remove the virus before resending. If you continue to have difficulty please contact our IT Help Desk for assistance on:- email: help at maplesandcalder.com Phone: +1 345 814-5123 This e-mail is confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately. You should not copy it or disclose its contents to any other person. Internet Communications are not secure and subject to possible data corruption, either accidentally or on purpose, and may contain viruses. Furthermore, e-mail is an informal method of communication and for these reasons, it will normally be inappropriate to rely on advice contained in an e-mail without obtaining written confirmation of it. If we receive a request from you via e-mail we will treat that as authority to reply by e-mail. From tjreedy at udel.edu Wed Jan 26 18:04:05 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Jan 2005 18:04:05 -0500 Subject: Responding to trollish postings. References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com><1106472508.591411.40140@c13g2000cwb.googlegroups.com><1106723545.429728.308620@f14g2000cwb.googlegroups.com> <41F7F520.8040706@po-box.mcgill.ca> Message-ID: [New subject line] In response to my response to a trollish posting... > There isn't any doubt that these 'tutorials' are generally unwelcome and > unhelpful. Numerous people have kindly taken the time to flag some of the > problems. So much so that any competent google of the archives would > quickly reveal the group consensus on their instructional merit. Yes, having advised many people to use Google, I thought it appropriate to flag one particular section that I thought dangerous. > I submit that continued corrections and advice of this sort are > counter-productive. I agree that 'correcting' Xah's writing is useless, and so I refrained. If asked 'What's wrong with the part you flagged?', I would stick with my original advice: "Ignore it". > Could we try to ignore them in the hopes that without the light of > attention they will wither, meanwhile trusting the many extant reviews > and google to do their work? I only read that particular post because it lacked the [Perl-Python] flag and because I was interested in the subject. Sure, now that I have added my one and presumably only review, let's everyone stop ;-) > (In case it isn't obvious: none of this is intended as a criticism of > Terry or any of the others who have been 'fighting the good fight'; I > just think a change of strategy might be in order.) No offense taken. My personal strategy is to read only as much of trollish threads as I find interesting or somehow instructive, almost never respond, and then ignore the rest. I also mostly ignore discussions about such threads. Terry J. Reedy From elephantum at dezcom.mephi.ru Sun Jan 9 08:12:38 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 16:12:38 +0300 Subject: python3: 'where' keyword In-Reply-To: <1gq4ebf.17qqy8dk9ccr6N%aleaxit@yahoo.com> References: <3480qqF46jprlU1@individual.net> <1gq4ebf.17qqy8dk9ccr6N%aleaxit@yahoo.com> Message-ID: <34cou6F49t8nlU1@individual.net> Alex Martelli wrote: > Indeed, the fact that many MANY more people are familiar with SQL than > with Haskell may be the strongest practical objection to this choice of > syntax sugar; the WHERE clause in an SQL SELECT has such wildly > different semantics from Haskell's "where" that it might engender huge > amounts of confusion. I.e., reasoning by analogy with SQL only, one > might reasonably expect that minor syntax variations on: > > print a, b where a = b > > could mean roughly the same as "if a==b: print a, b", rather than hmm... SQL-ish associations are good too, if you think a little deeper then common post-effect of using SQL "where" keyword. print a, b where a = b means a==b in statement "print a, b" > roughly the same as: > > a = b > print a, b > > I wonder if 'with', which GvR is already on record as wanting to > introduce in 3.0, might not be overloaded instead. using 'with', is some way unnatural for my point of view (may be because translations of 'with' and 'where' into russian, are way different and 'where' translation reads as natural language while 'with' does not). I'd like to keep 'where' keyword for proposal, but semantics are more important, so in case I do not mind for other keyword. From matternc at comcast.net Fri Jan 28 09:02:45 2005 From: matternc at comcast.net (Chris Mattern) Date: Fri, 28 Jan 2005 09:02:45 -0500 Subject: [perl-python] daily tip website References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> <1106875259.426213.252030@z14g2000cwz.googlegroups.com> <1106905338.224003.216840@c13g2000cwb.googlegroups.com> Message-ID: <9MKdnawiNPGY22fcRVn-3g@comcast.com> Xah Lee wrote: > daily tips. The url is: > http://xahlee.org/perl-python/python.html > > Thanks to those who have made useful comments. They will be > assimilated. > Resistance is futile. -- Christopher Mattern "Which one you figure tracked us?" "The ugly one, sir." "...Could you be more specific?" From use-reply at eckeab.de Sun Jan 16 12:02:29 2005 From: use-reply at eckeab.de (Werner Amann) Date: 16 Jan 2005 17:02:29 GMT Subject: nntplib: abstraction of threads References: <1105840367.526347.110160@c13g2000cwb.googlegroups.com> Message-ID: Rakesh schrieb: > What I want is to *group the messages belonging to each thread* . Hello Why not sort with Message-ID and References? Attention - it is a Newbie-Solution. import nntplib hamster = nntplib.NNTP('127.0.0.1', 119, 'user', 'pass') resp, count, first, last, name = hamster.group('comp.lang.python') resp, items = hamster.xover(first,last) start_dic = {} re_dic = {} numb = 1 for id,subject,author,date,message_id,references,size,lines in items: if 'Re:' not in subject: start_dic[subject] = (author, message_id) else: re_dic[numb] = (subject, author, references) numb += 1 resp = hamster.quit() for a in start_dic: print a print start_dic[a][0] for b in re_dic: if start_dic[a][1] in re_dic[b][2]: print '|' print ' ->', re_dic[b][0] print ' ', re_dic[b][1] print -- Werner Amann From vze4rx4y at verizon.net Sun Jan 2 03:01:15 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sun, 02 Jan 2005 08:01:15 GMT Subject: PEP 288 ponderings References: Message-ID: [Steven Bethard] > (1) What's the benefit of the generator versions of these functions over > the class-based versions? Generators are easier to write, are clearer, and run faster. They automatically * create a distinct generator-iterator object upon each invocation * create the next() and idempotent __iter__() methods. * raise StopIteration upon termination * remain stopped if next() is called too many times * save their own local variable state, avoiding the need for self.var references * resume execution at the point of the last yield > (2) Since in all the examples there's a one-to-one correlation between > setting a generator attribute and calling the generator's next function, > aren't these generator attribute assignments basically just trying to > define the 'next' parameter list? They are not the same. The generator needs some way to receive the values. The function arguments cannot be used because they are needed to create the generator-iterator. The yield statements likewise won't work because the first yield is not encountered until well after the first next() call. The given examples are minimal and are intended only to demonstrate the idea. > I definitely don't like the > idea of a magical __self__ variable that isn't declared anywhere. It is no more magical than f.__name__ or f.__doc__ for functions. The concept is almost identical to that for threading.local(). Also, the __self__ argument is a non-issue because there are other alternate approaches such as providing a function that retrieves the currently running generator. Which approach is ultimately taken is a matter of aesthetics -- the PEP itself concentrates on the core idea instead of debating syntax. The real issue with PEP 288's idea for generator attributes is that the current C implementation doesn't readily accommodate this change. Major surgery would be required :-( The more important part of the PEP is the idea for generator exceptions. The need arises in the context of flushing/closing resources upon generator termination. Raymond Hettinger From martin at v.loewis.de Fri Jan 14 12:19:50 2005 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 14 Jan 2005 18:19:50 +0100 Subject: Unicode conversion in 'print' In-Reply-To: References: <1105655600.059496.70350@z14g2000cwz.googlegroups.com> Message-ID: <41e7ff33$0$11648$9b622d9e@news.freenet.de> Ricardo Bugalho wrote: > thanks for the information. But what I was really looking for was > informaion on when and why Python started doing it (previously, it always > used sys.getdefaultencoding())) and why it was done only for 'print' when > stdout is a terminal instead of always. It does that since 2.2, in response to many complains that you cannot print a Unicode string in interactive mode, unless the Unicode string contains only ASCII characters. It does that only if sys.stdout is a real terminal, because otherwise it is not possible to determine what the encoding of sys.stdout is. Regards, Martin From richardjones at optushome.com.au Tue Jan 25 19:58:18 2005 From: richardjones at optushome.com.au (richard) Date: Wed, 26 Jan 2005 11:58:18 +1100 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106696406.515575.84540@z14g2000cwz.googlegroups.com> Message-ID: <41f6eb1f$0$1022$afc38c87@news.optusnet.com.au> Davor wrote: > M.E.Farmer wrote: >> Wrap your head around Python, don't wrap the Python around your head! >> This is NOT Java, or C++ or C , it IS Python. > > that's interesting hypothesis that behavior will vary due to the use of > different language - actually most python scripts that I have seen do > not even use OO which is quite understandable (same with perl, php,..) > and I'm not even sure why all these languages have incorporated OO at > all... Of course, *all* Python programs (whether you call them scripts or otherwise) are using objects. Strings, numbers, files, lists, dictionaries ... they're all objects. You *can't* write a Python program without objects, but you can do so without a single "class" declaration. The point that M.E.Farmer was trying to make is that you should not judge OO by Java or C++. Those languages make OO a burden, with on the one hand excessive requirements to subclass, and on the othe hand ... well, C++ is just a burden all round really :) Richard From paul at boddie.org.uk Fri Jan 21 06:48:58 2005 From: paul at boddie.org.uk (Paul Boddie) Date: 21 Jan 2005 03:48:58 -0800 Subject: Is there a library to parse Mozilla "mork" documents? Message-ID: <5339b60d.0501210348.39033bb9@posting.google.com> John Reese wrote: > > Mozilla, Firefox, Thunderbird, and so forth use this awful format > called MORK to store all kinds of things: which messages you've read > in a newsgroup, headers and indexes into the mbox file of messages in > a mail folder, and address books. It's documented to some extent > here: > http://www.mozilla.org/mailnews/arch/mork/primer.txt Hmmm. Wasn't David McCusker working for the OSA Foundation on Chandler at some point? Anyway, given the references to LDIF (and the fact that I have in the past exported address books from Netscape Communicator in LDIF format), the following specification might help: http://www.faqs.org/rfcs/rfc2849.html > Does anyone know of a Python library for parsing these files? A > single file basically just stores the equivalent of a nested > dictionary with text that can be declared separately and interpolated. > jwz has an over-specific perl version at > http://www.jwz.org/hacks/marginal.html, which I might have to try to > translate if there's nothing already available in Python. I'd look at the python-ldap project: http://python-ldap.sourceforge.net/ The ldif module might be of relevance, but there isn't an example in the documentation which would confirm my suspicions. Paul From franz.steinhaeusler at utanet.at Fri Jan 28 05:16:43 2005 From: franz.steinhaeusler at utanet.at (Franz Steinhaeusler) Date: Fri, 28 Jan 2005 11:16:43 +0100 Subject: Profiling and speed up References: <04CCzECy3g+BFwrK@objmedia.demon.co.uk> Message-ID: <274kv0th5att8ehevsni71j4k5sqj19sgn@4ax.com> On Fri, 28 Jan 2005 10:03:30 +0000, Stephen Kellett wrote: >Python Performance Validator > >http://www.softwareverify.com/pythonPerformanceValidator/index.html Thanks, but I forgot to say, I'm looking for open source or freeware. (I need it also for open source). -- Franz Steinhaeusler From http Sat Jan 22 12:46:01 2005 From: http (Paul Rubin) Date: 22 Jan 2005 09:46:01 -0800 Subject: Zen of Python References: <972ec5bd050119111359e358f5@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> <7xfz0uqe1d.fsf@ruckus.brouhaha.com> <7xu0p9lk4h.fsf@ruckus.brouhaha.com> <7x8y6l8k6l.fsf@ruckus.brouhaha.com> <18wId.68007$w62.25250@bgtnsc05-news.ops.worldnet.att.net> Message-ID: <7xr7kdtl0m.fsf@ruckus.brouhaha.com> "Andrew Koenig" writes: > Actually, I don't think so. If you intend for it to be impossible for "z = > x" to refer to the x in the list comprehension, you shouldn't mind putting > in "from __future__ import lexical_comprehensions." If you don't intend for > it to be impossible, then the program *should* be taken out and shot. I shouldn't have to say "from __future__ import " unless I actually intend to use the feature. The program I posted neither uses lexical comprehensions nor depends on their absence. So it shouldn't have to import anything from __future__. From itsme at yahoo.com Tue Jan 4 01:38:23 2005 From: itsme at yahoo.com (It's me) Date: Tue, 04 Jan 2005 06:38:23 GMT Subject: Hlelp clean up clumpsy code Message-ID: Another newbie question. There must be a cleaner way to do this in Python: #### section of C looking Python code #### a = [[1,5,2], 8, 4] a_list = {} i = 0 for x in a: if isinstance(x, (int, long)): x = [x,] for w in [y for y in x]: i = i + 1 a_list[w] = i print a_list ##### The code prints what I want but it looks so "C-like". How can I make it more Python like? Thanks, From rjhughes at timepilot.gpcc.itd.umich.edu Mon Jan 17 14:27:30 2005 From: rjhughes at timepilot.gpcc.itd.umich.edu (Ryan Jud Hughes) Date: Mon, 17 Jan 2005 19:27:30 GMT Subject: Interpreter Not Initialized (version mismatch?) Message-ID: I'm having trouble with python on MacOSX 10.3. I wrote an extension module, in C, and got it to compile and run just fine, in MacOSX 10.2, using the MacPython 2.3 package that I downloaded. But when I copied my stuff over to my computer that had MacOSX 10.3(.7), and the out-of-the-box MacPython 2.3 that comes installed with it, I can no longer use my extension module, or run any new ones that I compile. It appears to compile just fine (I'm using the distutils setup.py to compile it), but when I import it in my Python script, it says "Fatal Error: Interpreter not initialized (version mismatch?)" I'm pretty sure I deleted all the copies of the version I compiled on my 10.2 machine. Also, I don't seem to be able to create new modules from scratch. What's going wrong here? Am I doomed to never be able to create or run python extension modules on my computer? What can I download and install, to bring my versions in line? Thank you. --Ryan From eurleif at ecritters.biz Wed Jan 12 14:52:50 2005 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 12 Jan 2005 14:52:50 -0500 Subject: counting items In-Reply-To: References: Message-ID: <34lde1F4c1d1vU1@individual.net> Paul McGuire wrote: > Considering how often this comes up, might there be a place for some sort of > flatten() routine in the std dist, perhaps itertools? A problem I see is that itertools tries to work across all iterable types, but flattening can't always be a generalized operation. For instance, a naive flattening function might turn the list ['foo', 'bar'] into ['f', 'o', 'o', 'b', 'a', 'r'] -- or worse, fall into infinite recursion -- when the intended result would be to leave the list unchanged. Of course, a generalized flattening function could take an argument listing types to ignore, but that can get very complicated very fast. From Scott.Daniels at Acm.Org Sat Jan 15 14:00:36 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 15 Jan 2005 11:00:36 -0800 Subject: interpret 4 byte as 32-bit float (IEEE-754) In-Reply-To: <41E96302.4020003@web.de> References: <34t1p2F4foiplU1@individual.net> <41e952b9$1@nntp0.pdx.net> <41E96302.4020003@web.de> Message-ID: <41e964bc$1@nntp0.pdx.net> G.Franzkowiak wrote: > Scott David Daniels schrieb: > >> franzkowiak wrote: >> >>> I've read some bytes from a file and just now I can't interpret 4 >>> bytes in this dates like a real value. An extract from my program: >>> def l32(c): >>> return ord(c[0]) + (ord(c[1])<<8) + (ord(c[2])<<16) + >>> (ord(c[3])<<24) >>> ... >>> value = l32(f.read(4)) <--- 3F 8C CC CD should be 1.11 >>> >> OK, here's the skinny (I used blocks & views to get the answer): >> >> import struct >> bytes = ''.join(chr(int(txt, 16)) for txt in '3F 8C CC CD'.split()) >> struct.unpack('>f', bytes) >> >> I was suspicious of that first byte, thought it might be an exponent, >> since it seemed to have too many on bits in a row to be part of 1.11. >> >> -Scott David Daniels >> Scott.Daniels at Acm.Org > > > Ok, I the string exist with "mystr = f.read(4)" and the solution for > this case is in your line "struct.unpack('>f', bytes)" > But what can I do when I want the interpret the content from the Integer > myInt (*myInt = 0x3F8CCCCD) like 4-byte-real ? > This was stored with an othes system in a binary file to > CD CC 8C 3F and now is it in python in value. The conversion is not > possible. It's right... one of this bytes is an exponent. > I want copy the memory content from the "value address" to "myReal > address" and use print "%f" %myReal. > Is myReal then the right format ? > What can I do with python, in FORTH is it simple > ( >f f. ) > > gf > > > If you really want to do this kind of byte fiddling: http://members.dsl-only.net/~daniels/block.html Then: from block import Block, View b = Block(4) # enough space for one float (more is fine) iv = View('i', b) # getting to it as an integer fv = View('f', b) # same memory as floating point iv[0] = 0x3F8CCCCD # Here is a sample just using the integer print fv[0] On an Intel/Amd/Generic "PC" machine, you should get 1.1 -Scott David Daniels Scott.Daniels at Acm.Org From edreamleo at charter.net Mon Jan 24 11:02:49 2005 From: edreamleo at charter.net (Edward K. Ream) Date: Mon, 24 Jan 2005 10:02:49 -0600 Subject: ANN: Leo 4.3-a1 released Message-ID: Leo 4.3 alpha 1 is now available at http://sourceforge.net/projects/leo/ Leo 4.3 is the culmination of more than four months of work. In spite of its alpha status, I recommend Leo 4.3a1 over any 4.2 release. The defining features of Leo 4.3: --------------------------------- 1. Leo now stores options in @settings trees, that is, outlines whose headline is '@settings'. When opening a .leo file, Leo looks for @settings trees not only in the outline being opened but also in various leoSettings.leo files. The key design goal of @settings trees was that Leo's user options must be infinitely flexible. That goal has been accomplished. Indeed, users can create arbitrarily complex user options with @settings trees. Leo settings outlines are, in fact, infinitely more flexible and powerful than any scheme based on flat text. Readers of Python's configParser shootout take note. 2. The Preferences command temporarily replaces the outline pane with an outline showing all the @settings trees in effect. The Preferences command also replaces the body pane with a "settings pane". This settings pane allows you to change the settings selected in the outline pane using standard gui widgets. The settings pane is dynamically created from nodes in the settings tree; it is as extensible as the @settings tree itself. 3. Leo's read/write code in leoAtFile.py has been rewritten to support user-defined tangling and untangling. This is a major cleanup of Leo's core. 4. Leo now boasts a wonderful new Plugins Manager plugin. This plugin enables and disables plugins automatically. You never have to mess with pluginsManager.txt again. This plugin also tells you everything you need to know about each plugin. Finally, this plugin also lets you download plugins from Leo's cvs site. 5. You can install third-party extensions in Leo's extensions directory. Leo will attempt to import such extensions from the extensions directory if normal imports fail. As usual, version 4.3 contains many other improvements and bug fixes. What people are saying about Leo -------------------------------- "I am using Leo since a few weeks and I brim over with enthusiasm for it. I think it is the most amazing software since the invention of the spreadsheet." -- juergen_r "We who use Leo know that it is a breakthrough tool and a whole new way of writing code." -- Joe Orr "I am a huge fan of Leo. I think it's quite possibly the most revolutionary programming tool I have ever used and it (along with the Python language) has utterly changed my view of programming (indeed of writing) forever." -- Shakeeb Alireza "Thank you very much for Leo. I think my way of working with data will change forever...I am certain [Leo] will be a revolution. The revolution is as important as the change from sequential linear organization of a book into a web-like hyperlinked pages. The main concept that impress me is that the source listing isn't the main focus any more. You focus on the non-linear, hierarchical, collapsible outline of the source code." -- Korakot Chaovavanich "Leo is a quantum leap for me in terms of how many projects I can manage and how much information I can find and organize and store in a useful way." -- Dan Winkler "Wow, wow, and wow...I finally understand how to use clones and I realized that this is exactly how I want to organize my information. Multiple views on my data, fully interlinkable just like my thoughts." -- Anon. "A few years back I would have said Zope was #1 Python showcase, but I agree 100% that Leo is tops now." -- Jason Cunliffe "Leo is the most interesting Python project I know of...I see lots of stuff posted on the Daily Python page, but I usually yawn and come over to this forum to see what's cooking." -- Anon More quotes at: http://webpages.charter.net/edreamleo/testimonials.html What makes Leo special? ----------------------- - Leo's outlines add a new dimension to programming. - Leo shows you your code and data the way _you_ want to see them. - Leo extends, completes and simplifies literate programming. - Leo's script buttons bring scripts to data. What is Leo? ------------ - A programmer's editor, an outlining editor and a flexible browser. - A literate programming tool, compatible with noweb and CWEB. - A data organizer and project manager. Leo provides multiple views of projects within a single outline. - Fully scriptable using Python. Leo saves its files in XML format. - Portable. leo.py is 100% pure Python. - Open Software, distributed under the Python License. Leo requires Python 2.2.1 or above and tcl/tk 8.4 or above. Leo works on Linux, Windows and MacOs X. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://sourceforge.net/cvs/?group_id=3458 Quotes: http://webpages.charter.net/edreamleo/testimonials.html Wiki: http://leo.hd1.org/ Edward K. Ream January 25, 2005 -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From hcslmf at texlife.com Tue Jan 11 09:59:29 2005 From: hcslmf at texlife.com (brolewis) Date: 11 Jan 2005 06:59:29 -0800 Subject: Importing Problem on Windows In-Reply-To: <1105385451.560381.57650@c13g2000cwb.googlegroups.com> References: <1105379352.302141.264580@f14g2000cwb.googlegroups.com> <1105385451.560381.57650@c13g2000cwb.googlegroups.com> Message-ID: <1105455569.346532.256830@f14g2000cwb.googlegroups.com> I launched the interpreter shell from the same directory in both Windows and Linux before posting. That's what sent the red flag up for me. From dbickett at gmail.com Tue Jan 11 06:33:07 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Tue, 11 Jan 2005 06:33:07 -0500 Subject: shutil.move has a mind of its own In-Reply-To: References: Message-ID: <1d6cdae3050111033379f5ee14@mail.gmail.com> Oh, I'm sorry, that was my mistake. The example contained that error, but my code does not. Daniel Bickett From bdesth.quelquechose at free.quelquepart.fr Sat Jan 8 08:46:04 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 08 Jan 2005 14:46:04 +0100 Subject: tuples vs lists In-Reply-To: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfd96b$0$29393$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41dfe2a6$0$22729$636a15ce@news.free.fr> worzel a ?crit : > I get what the difference is between a tuple and a list, but why would I > ever care about the tuple's immuutability? Because, from a purely pratical POV, only an immutable object can be used as kay in a dict. So you can use tuples for 'composed key'. Bruno From ncoghlan at iinet.net.au Fri Jan 14 05:20:57 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 14 Jan 2005 20:20:57 +1000 Subject: python and macros (again) [Was: python3: 'where' keyword] In-Reply-To: References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> <7xacrcdhzh.fsf@ruckus.brouhaha.com> Message-ID: <41E79D09.7040106@iinet.net.au> Antoon Pardon wrote: > No I am applying set logic. Any string that is in the set of > valid expressions is also in the set of valid statements. According to Python's grammar, this is not the case. It requires a NEWLINE or ";" token on the end to turn the expression into a statement. Actually appending either of those tokens means the string is no longer an expression. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From stnchris at xmission.com Tue Jan 25 19:34:57 2005 From: stnchris at xmission.com (Steve Christensen) Date: Wed, 26 Jan 2005 00:34:57 +0000 (UTC) Subject: smtplib bug with Windows XP References: <1106614880.586616.19780@f14g2000cwb.googlegroups.com> <1106673048.851591.324490@f14g2000cwb.googlegroups.com> Message-ID: In article <1106673048.851591.324490 at f14g2000cwb.googlegroups.com>, stewart.midwinter at gmail.com wrote: > thank Peter, elbert, for the suggestions. I hadn't thought of using > telnet to try to connect to the SMTP server. and when I do try, telnet > can't connect either, at least on port 25. On port 110, it has no > problem. So, perhaps the IT people have made some configuration > changes; I'll have a chat with them. I'm relieved that it's not a > Python problem, though. > We had similar issues when our systems were upgraded to McAfee VirusScan 8.0. If you're running that locally (on the system trying to connect to the SMTP server), try disabling the rule in the Access Control dialog that's labeled 'Prevent mass mailing worms from sending email' -Steve From muttu2244 at yahoo.com Mon Jan 31 00:13:02 2005 From: muttu2244 at yahoo.com (muttu) Date: 30 Jan 2005 21:13:02 -0800 Subject: how to find number of processors in python Message-ID: <822e8fe0.0501302113.4716c2ba@posting.google.com> hello everybody am writing a scanner using python which has to get the information for sun's dual processors, so could any one of you please tell me how to find the number of processors . is there any api's for this , and also lemme know how exactly i can write the scannerapi for this, so that it can read the information of all the cpu's. I have the related CFG file for that. with regards thanks in advance From beliavsky at aol.com Wed Jan 19 12:04:22 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 19 Jan 2005 09:04:22 -0800 Subject: [OT] Good C++ book for a Python programmer References: <1106136496.719185.87850@c13g2000cwb.googlegroups.com> Message-ID: <1106151297.339844.95380@c13g2000cwb.googlegroups.com> Rick Muller wrote: >I was wondering whether anyone could recommend a good C++ book, with >"good" being defined from the perspective of a Python programmer. The STL and the template feature of C++ gives the programmer some of the functionality of Python (using templates instead of duck typing, vectors instead of lists etc.), so a book that introduces these features early, such as "Accelerated C++" by Koenig and Moo, could be a good start for a Pythonner. The 4th edition of the well-known "C++ Primer", with Moo as a new co-author, will soon be published. It is a more comprehensive and much longer book. From craig at postnewspapers.com.au Fri Jan 21 13:57:53 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 22 Jan 2005 02:57:53 +0800 Subject: Configuring Python for Tk on Mac In-Reply-To: References: Message-ID: <1106333873.19065.56.camel@bucket.localnet> On Fri, 2005-01-21 at 07:39 -0800, Martyn Quick wrote: > On my desk here at work I have a Mac G4 running Mac OS X v10.2.8. > > When I go into a terminal and type "python" up comes a nice python > interface and all seems great. However when I type "import Tkinter" > I'm greeted by the following error. > > >>> import Tkinter > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/lib-tk/Tkinter.py", line 35, in ? > import _tkinter # If this fails your Python may not be configured > for Tk > ImportError: No module named _tkinter > > So I guess something about this implementation is not appropriately > configured. In general, that error means that Python can't find the C extension module used to provide the low-level interface for Tkinter. It's not installed, can't be found (library path or python path issues), can't be opened (permissions), etc. Note the comment in the error message to that effect. I've just checked the OSX 10.3 machine here, and it fails to import tkinter there too. I'd say Apple just don't build Python with Tk support. > What do I do to set it up so I can use Tkinter? Try Google - this seems to be a moderately FAQ for MacOS/X. -- Craig Ringer From kent3737 at yahoo.com Thu Jan 27 17:21:07 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Thu, 27 Jan 2005 17:21:07 -0500 Subject: Startying with Python, need some pointers with manipulating strings In-Reply-To: <41f95bb2$0$24349$9a6e19ea@unlimited.newshosting.com> References: <41f95bb2$0$24349$9a6e19ea@unlimited.newshosting.com> Message-ID: <41f966bd$1_2@newspeer2.tds.net> Benji99 wrote: > I've managed to load the html source I want into an object > called htmlsource using: > > >>>>import urllib >>>>sock = urllib.urlopen("URL Link") >>>>htmlSource = sock.read() >>>>sock.close() > > > I'm assuming that htmlSource is a string with \n at the end of > each line. > NOTE: I've become very accustomed with the TStringList class in > Delphi so forgive me if I'm trying to work in that way with > Python... > > Basically, I want to search through the whole string( > htmlSource), for a specific keyword, when it's found, I want to > know which line it's on so that I can retrieve that line and > then I should be able to parse/extract what I need using Regular > Expressions (which I'm getting quite confortable with). So how > can this be accomplished? The Pythonic way to do this is to iterate through the lines of htmlSource and process them one at a time. htmlSource = htmlSource.split('\n') # Split on newline, making a list of lines for line in htmlSource: # Do something with line - check to see if it has the text of interest You might want to look at Beautiful Soup. If you can find the links of interest by the tags around them it might do what you want: http://www.crummy.com/software/BeautifulSoup/ Kent From pythongnome at hotmail.com Tue Jan 11 19:57:34 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Wed, 12 Jan 2005 00:57:34 GMT Subject: Python setup question In-Reply-To: References: Message-ID: <2C_Ed.4798$C52.461@newsread2.news.atl.earthlink.net> Robert Lin wrote: > Hi, > > Sorry for this newbie question, I was wondering if anyone knows why when I run the test, the "test_anydbm" test will seg fault and the tests "test_aepack" and "test_al" are skipped? > > Thanks in advance. > > ______________________________________ > > Robert Lin > Eng. Intern | Blue Jungle | Redwood City, CA > rlin at bluejungle.com You might not have the right libraries to run those tests. From elephantum at dezcom.mephi.ru Sun Jan 9 06:33:41 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 14:33:41 +0300 Subject: python3: 'where' keyword In-Reply-To: References: <3480qqF46jprlU1@individual.net> <34ch7gF45vrjoU1@individual.net> Message-ID: <34cj4lF49o2i1U1@individual.net> Nick Coghlan wrote: >> sorry, I used "expression" carelessly. >> >> I mean that >> >>> print words[3], words[5] >> is a single expression >> (and that would be in Python 3, when print would be subtituted with >> write()/writeln()). > > 'statement' is the appropriate word in Python's grammar. thanks ) > And I don't think we'd actually have to wait for Python 3 for this, we'd > just have to do the __future__ dance in order to introduce the new keyword. resonable, I mentioned Python3 as something in not that near future, that'd be great to think of it earlier From beliavsky at aol.com Thu Jan 13 12:35:33 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 13 Jan 2005 09:35:33 -0800 Subject: python 2.3.4 for windows: float("NaN") throws exception References: <1105629033.442397.124820@c13g2000cwb.googlegroups.com> Message-ID: <1105637733.557859.85000@c13g2000cwb.googlegroups.com> Tim Peters wrote: >Neither -- all Python behavior in the presence of float NaNs, infinities, or signed zeroes is a platform-dependent accident. C99 and Fortran 2003 have IEEE arithmetic. If CPython could be compiled with a C99 compiler, would it also have IEEE arithmetic? Do Python number-crunchers think this is important? From greg.lindstrom at novasyshealth.com Mon Jan 3 14:19:15 2005 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Mon, 03 Jan 2005 13:19:15 -0600 Subject: ODBC Connection on Windows XP Message-ID: <41D99AB3.5090601@novasyshealth.com> I am running Python 2.3 on Windows XP and am trying to connect to an ODBC datasource. I have done this many times on this same box but this time I get an error message saying dbi.operation-error: [WSOCK32.DLL]Connection refused, is the host listener running? (#10061) in LOGIN Not having seen this before, and having used the odbc module for about a year now, I'm at a quandary; what does this mean and what do I do to fix it? Thanks! --greg -- Greg Lindstrom 501 975.4859 Computer Programmer greg.lindstrom at novasyshealth.com NovaSys Health Little Rock, Arkansas "We are the music makers, and we are the dreamers of dreams." W.W. From rmemmons at member.fsf.org Tue Jan 4 21:54:37 2005 From: rmemmons at member.fsf.org (Rob Emmons) Date: Tue, 04 Jan 2005 20:54:37 -0600 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> Message-ID: > But the vision of what? Do we have clear, detailed, unambigous vision > _of the process_ or just big ideological axes to grind? I'm afraid > we're close to the latter situation - even though Python is remarkably > different in this area than the "free software": clean, pragmatic, > effective, free to include in closed-source. If Python were GPLed, > I wouldn't use it: attempting to force people to share doesn't work. That is an interesting thing about open source. I'm very surprised and encouraged by the wide slice of philosophical views that it embrases. Me personally, I believe in free software, but always talk about open source. My answer regarding forcing people to share -- I like the GPL -- and I am perfectly happy to have anyone who does not like the GPL not to use any GPLed software. I don't feel compelled to share. > Well, I'd say that lack of interchangeability in software is a big > obstacle on this road: not that there's little source code, but > that it's relatively hard (read: expensive) to combine the pieces. Linux/BSD/Unix in some ways have been the most consistent platforms over time. It is ironic that POSIX like systems are perhaps the only systems that have a pretty set of standards back to the early 1970's. It's a great story of what can be done by sharing. > 'The problem is that for all of the rhetoric about software becoming a > "commodity", most software is still very much not a commodity: one > software product is rarely completely interchangeable with another.' The thing about Open Source -- I don't think I've heard of any other way for software to become commodity. I'd love to hear about other options. > This could be made into a very strong argument for OSS: see the > OSS developers as your "outsourced team" that works for almost > nothing, i.e. "if we want to win them or get them to help, maybe > we should contribute our bugfixes and enhancements to them". I've wondered about this. I think the big issue is that it's not outsourcing where it works -- but the potential for software customization an in-sourcing things. That's why it seems to me that Open Source is portentially the opposite of oursourcing -- though I guess the customization can be outsourced... hmm... > As much as people tend to hate outsourcing, it frequently _does_ > increase the efficiency of the industries. I actually don't have a problem with outsourcing if it makes sense. The big issue I have with this sort of thing is that often the numbers look good only because hidden costs are transfered to other parts of the organization. Often the outsourcing company even participates in this sort of thing -- gives upper management the servicies they have always had, gives the rest of the company poor service. I've seen this in the company I work for. Rob From bokr at oz.net Fri Jan 7 16:31:25 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 07 Jan 2005 21:31:25 GMT Subject: Other notes References: <86r7l7sczp.fsf@guru.mired.org> <1104972047.050366.211670@f14g2000cwb.googlegroups.com> <41DD40F1.5030301@holdenweb.com> <41dda7c5.167823026@news.oz.net> Message-ID: <41def1ea.252340977@news.oz.net> On Fri, 07 Jan 2005 06:04:01 GMT, Andrew Dalke wrote: >Bengt Richter: >> But it does look ahead to recognize += (i.e., it doesn't generate two >> successive also-legal tokens of '+' and '=') >> so it seems it should be a simple fix. > >But that works precisely because of the greedy nature of tokenization. So what happens if you apply greediness to a grammar that has both . and .. as legal tokens? That's the point I was trying to make. The current grammar unfortunately IMHO tries to tokenize floating point numbers, which creates a problem for both numbers and (if you don't isolate it with surrounding spaces) the .. token. There would UIAM be no problem recognizing 1 .. 2 but 1..2 has the problem that the current tokenizer recognizes 1. as number format. Otherwise the greediness would work to solve the 1..2 "problem." IMHO it is a mistake to form floating point at the tokenizer level, and a similar mistake follows at the AST level in using platform-specific floating point constants (doubles) to represent what really should preserve full representational accuracy to enable translation to other potential native formats e.g. if cross compiling. Native floating point should IMO not be formed until the platform to which it is supposed to be native is identified. IOW, I think there is a fix: keep tokenizing greedily and tokenize floating point as a sequence of integers and operators, and let be translated by the compiler to floating point, and be translated to the appropriate generator expression implementation. >Given "a+=2" the longest token it finds first is "a" because "a+" >is not a valid token. The next token is "+=". It isn't just "+" >because "+=" is valid. And the last token is "2". > Exactly. Or I am missing something? (which does happen ;-) >Compare to "a+ =2". In this case the tokens are "a", "+", "=", "2" >and the result is a syntax error. Sure. > >> >>> for t in tokenize.generate_tokens(StringIO.StringIO('a=b+c; a+=2; x..y').readline):print t >> ... > >This reinforces what I'm saying, no? Otherwise I don't understand >your reason for showing it. It does reinforce your saying the matching is greedy, yes. But that led me to think that .. could be recognized without a problem, given a grammar fix. > >> (51, '+=', (1, 8), (1, 10), 'a=b+c; a+=2; x..y') > >As I said, the "+=" is found as a single token, and not as two >tokens merged into __iadd__ by the parser. No argument. > >After some thought I realized that a short explanation may be helpful. >There are two stages in parsing a data file, at least in the standard >CS way of viewing things. First, tokenize the input. This turns >characters into words. Second, parse the words into a structure. >The result is a parse tree. > >Both steps can do a sort of look-ahead. Tokenizers usually only look >ahead one character. These are almost invariably based on regular >expressions. There are many different parsing algorithms, with >different tradeoffs. Python's is a LL(1) parser. The (1) means it >can look ahead one token to resolve ambiguities in a language. >(The LL is part of a classification scheme which summarizes how >the algorithm works.) > >Consider if 1..3 were to be legal syntax. Then the tokenizer >would need to note the ambiguity that the first token could be >a "1." or a "1". If "1." then then next token could be a "." >or a ".3". In fact, here is the full list of possible choices > > <1.> <.> <3> same as getattr(1., 3) > <1> <.> <.> 3 not legal syntax > <1.> <.3> not legal syntax > <1> <..> <3> legal with the proposed syntax. > Right, but a grammar fix to handle floating point "properly" (IMHO ;-) would resolve that. Only the last would be legal at the tokenizer stage. >Some parsers can handle this ambiguity, but Python's >deliberately does not. Why? Because people also find I'm not sure what you mean. If it has a policy of greedy matching, that does handle some ambiguities in a particular way. >it tricky to resolve ambiguity (hence problems with >precedence rules). After all, should 1..2 be interpreted >as 1. . 2 or as 1 .. 2? What about 1...2? (Is it 1. .. 2, ^^^^^^[1] ^^^^^^^[2] [1] plainly (given my grammar changes ;-) [2] as plainly not, since <1> would not greedily accept '.' to make <1.> >1 .. .2 or 1. . .2 ?) ^^^^^^[3] ^^^^^^^[4] [3] no, because greed would recognize an ellipsis <...> [4] ditto. Greedy tokenization would produce <1> <...> <2> for the compiler. Regards, Bengt Richter From fredrik at pythonware.com Fri Jan 28 07:28:14 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 28 Jan 2005 13:28:14 +0100 Subject: Who should security issues be reported to? References: <1106863164.745581.11920@f14g2000cwb.googlegroups.com><1106911061.429966.303510@f14g2000cwb.googlegroups.com> Message-ID: Duncan Booth wrote: > I think part of the problem you are having is that Python doesn't make any > representations about security, so it is pretty hard to come up with issues > which really are security related. Products which are based on Python (e.g. > Zope) and which do aim to provide some kind of secure environment probably > will have some clear mechanism for reporting security related issues. security issues occur when code that claims to do something can be used to do something entirely different, by malevolent application users. (wxPython doesn't make any security claims either, but if it turned out that you could gain root access, modify the underlying database, modify variables in the program, execute arbitrary code, or some other similar thing simply by typing the right things into a password entry field, wouldn't you consider that a security issue?) (no, this issue isn't related to wxPython) From ianb at colorstudy.com Sun Jan 2 01:29:14 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Sun, 02 Jan 2005 00:29:14 -0600 Subject: PEP 288 ponderings In-Reply-To: References: Message-ID: <41D794BA.8090408@colorstudy.com> Steven Bethard wrote: > PEP 288 was mentioned in one of the lambda threads and so I ended up > reading it for the first time recently. I definitely don't like the > idea of a magical __self__ variable that isn't declared anywhere. It > also seemed to me like generator attributes don't really solve the > problem very cleanly. An example from the PEP[1]: > > def mygen(): > while True: > print __self__.data > yield None > > g = mygen() > g.data = 1 > g.next() # prints 1 > g.data = 2 > g.next() # prints 2 I don't get why this isn't good enough: def mygen(data): while True: print data[0] yield None data = [None] g = mygen(data) data[0] = 1 g.next() data[0] = 1 g.next() Using a one-element list is kind of annoying, because it isn't clear out of context that it's just a way of creating shared state. But it's okay, work right now, and provides the exact same functionality. The exception part of PEP 288 still seems interesting. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From fuzzyman at gmail.com Thu Jan 6 19:24:01 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 6 Jan 2005 16:24:01 -0800 Subject: Contributor's List In-Reply-To: <1105006211.527899.318740@c13g2000cwb.googlegroups.com> References: <1105005223.634938.228790@z14g2000cwz.googlegroups.com> <1105006211.527899.318740@c13g2000cwb.googlegroups.com> Message-ID: <1105057441.755424.251430@f14g2000cwb.googlegroups.com> My understanding is that the 2nd edition will *only* have new entries. this may be entirely off the wall of course. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From klapotec at chello.at Mon Jan 3 07:43:52 2005 From: klapotec at chello.at (Christopher Koppler) Date: Mon, 03 Jan 2005 12:43:52 GMT Subject: Python! Is! Truly! Amazing! References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: On Mon, 03 Jan 2005 13:05:48 +0200, Ville Vainio wrote: >>>>>> "jfj" == jfj writes: > > jfj> There were functional and non-functional programming > jfj> languages (the first being *much* simpler to > jfj> implement). There is a *reason* people chose C over > jfj> lisp. It's not that we were all blind and didn't see the > jfj> amazingness of lisp. Procedural languages are simply better, > jfj> and I'm not replying to this flamewar. > > You did already ;). Lisp is not a functional programming language, if > that was the case it would be even less popular than it is now. Lisp > had it's heyday, while pure FP languages didn't even have that much. > > Hey, it's 2005, I don't think we've used up our yearly Lisp flamewar > quota yet. Lisp will strike back! Someday, it will be popular again! When all else is dust, Lisp will rule the skies! In the meantime, let's do Python. -- Christopher root at creation # python Python inf (day 1) [PyPy inf (Pythonix inf)] on pynuxinf Type "help", "copyright", "credits" or "license" for more information. >>> from Creation import lux >>> lux.fiat() From ark at acm.org Wed Jan 19 14:02:57 2005 From: ark at acm.org (Andrew Koenig) Date: Wed, 19 Jan 2005 19:02:57 GMT Subject: [OT] Good C++ book for a Python programmer References: <1106136496.719185.87850@c13g2000cwb.googlegroups.com> <1106151297.339844.95380@c13g2000cwb.googlegroups.com> Message-ID: wrote in message news:1106151297.339844.95380 at c13g2000cwb.googlegroups.com... > The 4th edition of the well-known "C++ Primer", with Moo as a new > co-author, will soon be published. It is a > more comprehensive and much longer book. It is also organized more traditionally than "Accelerated C++." "Accelerated C++" is mostly example-driven: It presents problems, shows how to solve them, and introduces language and library features as needed for particular parts of the solutions. Of course the problems are carefully chosen so that the solutions cover the most important parts of the language and library, but that fact is not immediately obvious from the nature of the problems themselves. "C++ Primer" follows the classical approach of treating each part of the language and library separately in a single place. For example, there are chapters on expressions, statements, functions, templates, object-oriented programming, and so on. It is also much more systematic than "Accelerated C++." It is also nearly three times the size. Which of these books you prefer will depend on your learning style more than anything else. If you are willing to read the entire book sequentially, you will probably learn C++ faster from "Accelerated C++" than from "C++ Primer." On the other hand, if you want to see in one place what all the different kinds of statements are, so that you can learn about them all at once, then you will be more comfortable with "C++ Primer." I'm biased, of course, but I believe that either of these books is a better starting point for someone unfamiliar with C than any other book I can think of. From jeff at ccvcorp.com Thu Jan 13 16:03:09 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 13 Jan 2005 13:03:09 -0800 Subject: reference or pointer to some object? In-Reply-To: References: Message-ID: <10udo6e1bbejhe4@corp.supernews.com> Torsten Mohr wrote: > But i think my understanding was wrong (though it is not yet > clear). If i hand over a large string to a function and the > function had the possibility to change it, wouldn't that mean > that it is necessary to hand over a _copy_ of the string? > Else, how could it be immutable? Anything which might change the string, can only do so by returning a *new* string. >>> a = "My first string" >>> b = a.replace('first', 'second') >>> b 'My second string' >>> a 'My first string' >>> Saying that strings are immutable means that, when 'a' is pointing to a string, the (string) object that 'a' points to will always be the same. (Unless 'a' is re-bound, or someone uses some deep black magic to change things "behind the scenes"...) No method that I call on 'a', or function that I pass 'a' to, can alter that object -- it can only create a new object based off of the original. (You can demonstrate this by checking the id() of the objects.) Mutable objects, on the other hand, can change in place. In the case of lists, for example, it will stay the same list object, but the list contents can change. Note, also, that passing a string into a function does not copy the string; it creates a new name binding (i.e. reference) to the same object. >>> def func(item): ... print "Initial ID:", id(item) ... item = item.replace('first', 'second') ... print "Resulting ID:", id(item) ... >>> id(a) 26278416 >>> func(a) Initial ID: 26278416 Resulting ID: 26322672 >>> id(a) 26278416 >>> > Thinking about all this i came to the idea "How would i write > a function that changes a string with not much overhead?". Since strings cannot really be changed, you simply try to minimize the number of new strings created. For example, appending to a string inside of a for-loop creates a new string object each time, so it's generally more efficient to convert the string to a list, append to the list (which doesn't create a new object), and then join the list together into a string. > def func(s): > change s in some way, remove all newlines, replace some > charaters by others, ... > return s > > s = func(s) > > This seems to be a way to go, but it becomes messy if i hand over > lots of parameters and expect some more return functions. This has the advantage of being explicit about s being (potentially) changed. References, in the way that you mean them, are even messier in the case of numerous parameters because *any* of those parameters might change. By simply returning (new) objects for all changes, the function makes it very clear what's affected and what isn't. Jeff Shannon Technician/Programmer Credit International From mwm at mired.org Wed Jan 5 14:21:46 2005 From: mwm at mired.org (Mike Meyer) Date: Wed, 05 Jan 2005 13:21:46 -0600 Subject: Restore a unified diff References: Message-ID: <86hdlvptpx.fsf@guru.mired.org> Tim Peters writes: > [Nick Allen] >> Unfortunately, restore does not do the same for unified_diff. I do >> not see any similar function that is intended for unified_diff. Does >> anyone know how to "restore" from a unified diff generated delta? > > That's in general impossible, since unified diffs generally omit most > lines that compared equal to begin with. Unified and context diffs > are, in part, compression gimmicks, showing only what changed plus a > bit of context. ndiff shows everything, so can restore everything > too. The unix patch utility seems to do a fine job of handling the unix unified and context diffs. Unified is the preferred format for the open source projects I contribute patches to. Possibly this is some other form of "unified diff" than what you get from "diff -u" on a Unix system? http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From bokr at oz.net Sat Jan 15 18:05:27 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 15 Jan 2005 23:05:27 GMT Subject: java 5 could like python? References: <7umnb2-rd.ln1@lairds.us> Message-ID: <41e99752.950044892@news.oz.net> On Sat, 15 Jan 2005 15:08:05 GMT, claird at lairds.us (Cameron Laird) wrote: >In article , >vegetax wrote: > . > . > . >>For example if i remember a function i want ie:get attribute, i dont >>remember if the module implementer coded it as >>getAttribute,GetAttribute,get_attribute, then i have to go and check the >>doc, every time,which is a waste of time. > . > . > . >Are you comfortable using the base interpreter's built-in >interactive facilities, such as help()? I strongly urge >you to exercise these for at least a few minutes. This triggers a thought: Some are more passive about exploring than others, and think there's nothing to be seen except what's pointed at. Sad for them, but they need help too. One hopes the tutorial stuff will reawaken natural pleasure in finding out neat stuff. After all, they came to the right place :-) But back to my point (it's coming ;-) [1] ... >>> help Type help() for interactive help, or help(object) for help about object. Ok, will do ;-) >>> help(object) Help on class object in module __builtin__: class object | The most base type Taking the 'object' lesson a little too literally, perhaps ;-) >>> help(my_object) Traceback (most recent call last): File "", line 1, in ? NameError: name 'my_object' is not defined Ok, why wasn't I told to expect that in the help() intro? Or that that the following might get me further info? >>> help('my_object') no Python documentation found for 'my_object' [1] Ok, here's the idea that triggered this post: What if help(something) didn't immediately give up with that last message? If instead it looked for helpex.py on the path, and invoked helpex(something) if found? That way, people could easily experiment with site-specific help extensions. ISTR a shell in the deep past sometime that would look for a custom extension before giving up with a parsing error, so I'm not inventing anything new (unless I misremember ;-) That's all. A simple hook could also do it, and site.py could hook it on if desired. E.g., def helpex(*a,**kw): return "helpex doesn't exist yet, but it was called with %r and %r ;-)" %(a, kw) help.helpex = helpex You could get fancy and make that a property or properties of the base help, and have it chain multiple hookings at front or back for priority etc. Maybe we can invent a standard help extension methodology for temporary app stuff as as well as quasi-permanent site-specific stuff. ... just noodling variations on a theme ;-) For reference: >>> help() Welcome to Python 2.4! This is the online help utility. If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://www.python.org/doc/tut/. Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit". To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam". Regards, Bengt Richter From hancock at anansispaceworks.com Fri Jan 7 20:03:44 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 7 Jan 2005 19:03:44 -0600 Subject: Securing a future for anonymous functions in Python In-Reply-To: <10tu91mhv8mn89d@corp.supernews.com> References: <7xvfa90w6g.fsf@ruckus.brouhaha.com> <10tu91mhv8mn89d@corp.supernews.com> Message-ID: <200501071903.45205.hancock@anansispaceworks.com> On Friday 07 January 2005 06:12 pm, Jeff Shannon wrote: > Paul Rubin wrote: > > > Richard Feynman told a story about being on a review committee for > > some grade-school science textbooks. One of these book said something > > about "counting numbers" and it took him a while to figure out that > > this was a new term for what he'd been used to calling "integers". > > With all due respect to Richard Feynman, I'd have thought that > "counting numbers" would be non-negative integers, rather than the > full set of integers... which, I suppose, just goes to show how > perilous it can be to make up new, "more natural" terms for things. ;) Speaking of "natural", I think "counting numbers" would indeed be the "natural numbers" 1,2,3, ... So, yeah, I agree. Jargon definitely has its place: I once told a colleague (in an effort to avoid jargon) that one star was "faster" than another star. Only after registering his incomprehension, did I really think about the fact that that had at least 4 or 5 possible meanings (in fact, I meant that the frequency of its periodic change in radial velocity was higher -- but I could've meant that it was receeding faster, had a higher amplitude of radial velocity change, etc.). I think "lambda" is fine. Basically if you find you need one, you probably ought to be using the CS term anyway. It would make looking up the theory that much easier, anyway. Cheers, Terry -- -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From elephantum at dezcom.mephi.ru Sun Jan 9 08:57:21 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 16:57:21 +0300 Subject: python3: 'where' keyword In-Reply-To: <3480qqF46jprlU1@individual.net> References: <3480qqF46jprlU1@individual.net> Message-ID: <34cri1F47gda5U1@individual.net> And about examples for usage "where" keyword reading http://manatee.mojam.com/~skip/python/fastpython.html I understand that almost every example should use that keyword =) From hoxide_dirac at yahoo.com.cn Wed Jan 19 07:10:16 2005 From: hoxide_dirac at yahoo.com.cn (hoxide) Date: 19 Jan 2005 04:10:16 -0800 Subject: safest way to kill a thread In-Reply-To: <1106121882.809441.12670@z14g2000cwz.googlegroups.com> References: <1106106497.429643.307440@f14g2000cwb.googlegroups.com> <1106115159.200989.60870@c13g2000cwb.googlegroups.com> <1106121882.809441.12670@z14g2000cwz.googlegroups.com> Message-ID: <1106136616.266209.254730@f14g2000cwb.googlegroups.com> To Catch the "SystemExit" import thread from time import sleep import sys def t1(): try: i=0 while 1: print i+1 i += 1 sleep(1) except SystemExit: pass thread.start_new_thread(t1, ()) sleep(3) This Question was also asked in Python-chinese . From ianb at colorstudy.com Mon Jan 3 02:46:54 2005 From: ianb at colorstudy.com (Ian Bicking) Date: Mon, 03 Jan 2005 01:46:54 -0600 Subject: Continuations Based Web Framework - Seaside. In-Reply-To: <20050102183402.GC8357@monkeyfist.com> References: <41d7dad7$0$9355$afc38c87@news.optusnet.com.au> <7aTBd.11928$H%6.521997@twister1.libero.it> <20050102183402.GC8357@monkeyfist.com> Message-ID: <41D8F86E.6030300@colorstudy.com> Kendall Clark wrote: > Between this pressure (which isn't new, since as Steve points out, I > was talking about this in Python community last year, and I wasn't > nearly the first) and the growing popularity of Ruby on Rails, there's > some small hint that Ruby is gaining on Python re: non-Java web app > mind share. I think that's a v. important niche for Python and would > like to see us remain strong there (though I've not *done* much about > this, alas). I think that's probably true -- at least in terms of mindshare, even though that might not reflect on actual work done. But, Rails is really not a very experimental framework, and the existance of continuation-based frameworks for Ruby is an aside. If such frameworks happen at all for Python, I think they will be an aside as well. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Mon Jan 10 19:28:13 2005 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Tue, 11 Jan 2005 01:28:13 +0100 Subject: Python & unicode References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> Message-ID: <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> Hi ! >>> and plain Latin letters But not all letters (no : ? ? ? ? ? ? ? etc.) Therefore, the Python's support of Unicode is... limited. Good night -- Michel Claveau From rootshell at gazeta.pl Thu Jan 13 07:03:15 2005 From: rootshell at gazeta.pl (rootshell at gazeta.pl) Date: Thu, 13 Jan 2005 13:03:15 +0100 (CET) Subject: Free python server. Message-ID: <1105617795770.ew5.rootshell@gazeta.pl> Hello. I need an account no free python server. Would somebody help me? I tried to find one no www.python.org [there are few addresses of free hosts] but unfortunately can't manage with the registration. Best Regards Rootshell From jonasgalvez at gmail.com Sun Jan 2 18:12:39 2005 From: jonasgalvez at gmail.com (Jonas Galvez) Date: Sun, 2 Jan 2005 21:12:39 -0200 Subject: HTTP GET request with basic authorization? In-Reply-To: References: Message-ID: <7c60b60505010215123462c90e@mail.gmail.com> Christopher J. wrote: > I tried this, but it didn't work: > conn.request("GET", "/somepage.html", None, > {"AUTHORIZATION": "Basic username:password"}) Hmm, try this: import re, base64 userpass = base64.encodestring('user:pass').replace('\n', '') authd = {'Authorization':'Basic %s' % userpass} conn.request('GET', '/uri', None, authd) Or this: import re, base64, urllib2 userpass = ('user', 'pass') url = 'http://somewhere' request = urllib2.Request(url) authstring = base64.encodestring('%s:%s' % userpass) authstring = authstring.replace('\n', '') request.add_header("Authorization", "Basic %s" % authstring) content = urllib2.urlopen(request).read() From fredrik at pythonware.com Mon Jan 17 14:42:24 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 17 Jan 2005 20:42:24 +0100 Subject: Interpreter Not Initialized (version mismatch?) References: Message-ID: Ryan Jud Hughes wrote: > I'm having trouble with python on MacOSX 10.3. I wrote an extension module, > in C, and got it to compile and run just fine, in MacOSX 10.2, using the > MacPython 2.3 package that I downloaded. > > But when I copied my stuff over to my computer that had MacOSX 10.3(.7), and > the out-of-the-box MacPython 2.3 that comes installed with it, I can no longer > use my extension module, or run any new ones that I compile. > > It appears to compile just fine (I'm using the distutils setup.py to compile > it), but when I import it in my Python script, it says > "Fatal Error: Interpreter not initialized (version mismatch?)" this appears to be a Python-on-Mac-OS-X FAQ. see this thread for a solution (including a "fix installer"): http://thread.gmane.org/gmane.comp.python.image/1316 From bokr at oz.net Sat Jan 22 07:33:26 2005 From: bokr at oz.net (Bengt Richter) Date: Sat, 22 Jan 2005 12:33:26 GMT Subject: Unbinding multiple variables References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> <35bnkeF4jpeetU1@individual.net> <1106334800.868412.27650@f14g2000cwb.googlegroups.com> Message-ID: <41f232b8.1514053864@news.oz.net> On 21 Jan 2005 11:13:20 -0800, "Johnny Lin" wrote: >thanks everyone for the replies! > >John Hunter, yep, this is Johnny Lin in geosci :). > >re using return: the problem i have is somewhere in my code there's a >memory leak. i realize return is supposed to unbind all the local >variables, but since the memory leak is happening despite return, i >thought it might help me track down the leak if i unbound everything >explicitly that i had defined in local scope before i returned. or if >anyone has recomm. on plugging leaks, would be thankful for any >pointers there too. It helps to clue people into what your real goal is ;-) (Your initial post said nothing about memory leaks). Step 1: How do you know you have a memory leak? Python retains some memory in internal free pools rather than returning it to the OS, so you might not have a memory leak at all, in the true sense. If you are having a real memory leak, look first at any C extensions you've written yourself, then at other's alpha/beta stuff you may be using. Core CPython is probably the last place to look ;-) If you are creating reference loops, I think some may be uncollectable. I'm not sure how you are detecting "memory leaks," but whatever the method, if you can write a test harness that will create a zillion of each suspect thing and delete them in turn, and print out your detection data -- even if you have to run separate processes to do it, that might narrow down your search. E.g., if you write a little test.py that takes a command line argument to choose which object to create zillions of, and print out leak evidence, then you could run that systematically via popen etc. Or just run test.py by hand if you don't have that many suspects (hopefully the case ;-) > >my understanding about locals() from the nutshell book was that i >should treat that dictionary as read-only. is it safe to use it to >delete entries? Well, it's not read-only, but it doesn't write through to the actual locals. Think of it as a temp dict object with copies of the local name:value bindings, but changing anything in it only changes the temp dict object in the usual way. UIAM ;-) (OTOH, deletions of actual local bindings do seem to propagate back into a previously bound value of locals on exit, and a new call to locals() seems to return the same identical object as before, so I'm not sure I believe the , unless it has a special slot and it is automatically updated at exit. But a local bare name assignment or deletion doesn't immediately propagate. But it does on exit. So the returned by locals() has a special relationship to the function it reflects, if it is otherwise a normal dict: >>> def foo(x): ... d = locals() ... print '1:',id(d), type(d), d ... del x ... print '2:',id(d), type(d), d ... del d['x'] ... print '3:',id(d), type(d), d ... y = 123 ... print '4:',id(d), type(d), d ... d['z'] = 'zee' ... print '5:',id(d), type(d), d ... return d, locals() ... >>> dret, endinglocals = foo('arg passed to foo') 1: 49234780 {'x': 'arg passed to foo'} 2: 49234780 {'x': 'arg passed to foo'} 3: 49234780 {} 4: 49234780 {} 5: 49234780 {'z': 'zee'} >>> dret {'y': 123, 'z': 'zee', 'd': {...}} >>> endinglocals {'y': 123, 'z': 'zee', 'd': {...}} >>> dret is endinglocals True >>> dret['d'] is dret True (the {...} is an indication of the recursive reference) Note that at 2: the del x was not reflected, nor did the y = 123 show at 4: But the d['z'] showed up immediately, as you might expect ... but d['z'] also in that last returned locals(), which you might not expect, since there was no assignment to bare z. But they are apparently the same dict object, so you would expect it. So maybe there is some kind of finalization at exit like closure building. Anyway, d = dict(locals()) would probably behave differently, but I'm going to leave to someone else ;-) Regards, Bengt Richter From duncan.booth at invalid.invalid Thu Jan 6 04:27:05 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 Jan 2005 09:27:05 GMT Subject: Building unique comma-delimited list? References: Message-ID: Roy Smith wrote: > The best I've come up with is the following. Can anybody think of a > simplier way? > > -------------------- > words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"] > > # Eliminate the duplicates; probably use set() in Python 2.4 > d = dict() > for w in words: > d[w] = w > > if d.has_key ("foo"): > newWords = ["foo"] > del (d["foo"]) > else: > newWords = [] > > for w in d.keys(): > newWords.append (w) > > s = ', '.join (newWords) > print s > -------------------- > You need to make the dictionary and list types work harder for you. They have a variety of methods you might find useful. >>> words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"] >>> distinguished = ["foo"] >>> d = dict.fromkeys(words, True) >>> newwords = [ w for w in distinguished if d.pop(w, False) ] >>> newwords.extend(d.keys()) >>> newwords ['foo', 'baz', 'bar'] >>> From David.Holt at mmm.com Wed Jan 5 16:44:24 2005 From: David.Holt at mmm.com (DavidHolt) Date: 5 Jan 2005 13:44:24 -0800 Subject: Python 2.4 on Windows XP In-Reply-To: <41dc4ffd$1@nntp0.pdx.net> References: <1104946252.430332.226930@z14g2000cwz.googlegroups.com> <10toje56oiebq24@corp.supernews.com> <41dc4ffd$1@nntp0.pdx.net> Message-ID: <1104961464.126983.185340@c13g2000cwb.googlegroups.com> Thanks--you were all a big help. I'm running now. :) From golux at comcast.net Thu Jan 20 16:55:59 2005 From: golux at comcast.net (Stephen Waterbury) Date: Thu, 20 Jan 2005 16:55:59 -0500 Subject: wxPython unicode/ansi builds [was Re: ElementTree cannot parse UTF-8 Unicode?] In-Reply-To: <41F01B50.8030107@v.loewis.de> References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> <1106230846.455765.7310@c13g2000cwb.googlegroups.com> <1106233137.588111.216480@z14g2000cwz.googlegroups.com> <41F01B50.8030107@v.loewis.de> Message-ID: <41F028EF.3030004@comcast.net> Martin v. L?wis wrote: > Jarek Zgoda wrote: >>> So why are there non-UNICODE versions of wxPython??? To save memory or >>> something??? Robin Dunn has an explanation here: http://wiki.wxpython.org/index.cgi/UnicodeBuild ... which is the first hit from a Google search on "wxpython unicode build". Also, from the wxPython downloads page: "There are two versions of wxPython for each of the supported Python versions on Win32. They are nearly identical, except one of them has been compiled with support for the Unicode version of the platform APIs. If you don't know what that means then you probably don't need the Unicode version, get the ANSI version instead. The Unicode verison works best on Windows NT/2000/XP. It will also mostly work on Windows 95/98/Me systems, but it is based on a Microsoft hack called MSLU (or unicows.dll) that translates unicode API calls to ansi API calls, but the coverage of the API is not complete so there are some difficult bugs lurking in there." Steve From andreasp at qbcon.com Thu Jan 27 10:00:40 2005 From: andreasp at qbcon.com (Andreas Pauley) Date: Thu, 27 Jan 2005 17:00:40 +0200 (SAST) Subject: Point of Sale In-Reply-To: References: Message-ID: On Thu, 27 Jan 2005, Peter Hansen wrote: > Andreas Pauley wrote: >> My company has given me a rather cool project: >> I have to provide them with an open-source python-based point-of-sale / >> cash register system that can integrate with their existing ERP backend. > > Do you have information about the interface to the ERP back end? > It could be anything just about anything... See my reply to Cameron. > >> The project will include development to ensure that the features they >> require are included in the open-source POS system. > > I read that as "will include automated acceptance tests", but perhaps > you meant something else? Actually I just mean that I'm not looking for a 100% feature-fit, if I get a 70% fit I'll jump in and develop the other 30%. > >> Can you recommend anything that I can use? > > There's a good chance you'll need to use PySerial, if the > cash registers are connected via RS-232, but beyond that > there's not much to say without more info. I believe I > heard somebody talking about a Python POS system before > in this newsgroup, but I'm not sure: check the archives? Thanks, I'll keep PySerial in mind. Up to now I've googled a bit, and looked at Sourceforge projects. (I also did a search on the 51664 messages in my local Python-list folder) At the moment I found a POS in GNU Enterprise, a project named "custom" and another project named "Auto Auction". I'm not sure what the features of each system are, I'm busy checking them out one by one. Then there's also 3 or 4 Python systems which haven't released any files yet. Currently I'm evaluating GNU Enterprise. Regards, Andreas From michel.levankiem at free.fr Thu Jan 13 16:43:39 2005 From: michel.levankiem at free.fr (Michel LE VAN KIEM) Date: Thu, 13 Jan 2005 22:43:39 +0100 Subject: How to install pyparallel In-Reply-To: References: <41e689fc$0$15700$626a14ce@news.free.fr> Message-ID: <41e6eb88$0$11956$636a15ce@news.free.fr> The complete error message is : >>> import parallel /usr/lib/python2.3/site-packages/parallel/parallelppdev.py:32: FutureWarning: x<>> p=parallel.Parallel() File "", line 1, in ? File "/usr/lib/python2.3/site-packages/parallel/parallelppdev.py", line 176, in __init__ self.PPCLAIM File "/usr/lib/python2.3/site-packages/parallel/parallelppdev.py", line 203, in PPCLAIM fcntl.ioctl(self._fd, PPCLAIM) ppdev0: [Errno 6] failed to register device ! Peter Hansen a ?crit : > Michel LE VAN KIEM wrote: > >> >> I'm trying to install the pyparallel module for my Python 2.3.4 (runs >> on a FC3) but I do have some troubles. >> >> >>> p=parallel.Parallel() >> ppdev0: failed to register device ! >> ... >> IOError: [No such device or address] >> >> Some help would be appreciated. > > > Did you read the notes in the parallelppydev.py file's > Parallel class? I suspect they may be of some help... > > (I don't see any other significant documentation of > pyParallel, so I'm not sure where else one would look > for assistance.) > > Also, perhaps one of these threads would be of help: > http://groups.google.ca/groups?q=parallel+ppdev0+failed+to+register+device > > -Peter From sjmachin at lexicon.net Mon Jan 3 16:46:02 2005 From: sjmachin at lexicon.net (John Machin) Date: 3 Jan 2005 13:46:02 -0800 Subject: emulating an and operator in regular expressions References: <1104750397.26918.1.camel@rasputin.localnet> Message-ID: <1104788762.853541.97300@c13g2000cwb.googlegroups.com> Terry Reedy wrote: > "Craig Ringer" wrote in message > news:1104750397.26918.1.camel at rasputin.localnet... > > On Mon, 2005-01-03 at 08:52, Ross La Haye wrote: > >> How can an and operator be emulated in regular expressions in Python? > > Regular expressions are designed to define and detect repetition and > alternatives. These are easily implemented with finite state machines. > REs not meant for conjunction. 'And' can be done but, as I remember, only > messily and slowly. The demonstration I once read was definitely > theoretical, not practical. > > Python was designed for and logic (among everything else). If you want > practical code, use it. > > if match1 and match2: do whatever. > Provided you are careful to avoid overlapping matches e.g. data = 'Fred Johnson', query = ('John', 'Johnson'). Even this approach (A follows B or B follows A) gets tricky in the real world of the OP, who appears to be attempting some sort of name matching, where the word order may be scrambled. Problem is, punters can have more than 2 words in their names, e.g. Mao Ze Dong[*], Louise de la Valliere, and Johann Georg Friedrich von und zu Hohenlohe ... or misreading handwriting can change the number of perceived words, e.g. Walenkamp -> Wabu Kamp (no kidding). [*] aka Mao Zedong aka Mao Tse Tung -- difficult enough before we start considering variations in the order of the words. From Scott.Daniels at Acm.Org Wed Jan 12 15:10:33 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 12 Jan 2005 12:10:33 -0800 Subject: complex numbers In-Reply-To: References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: <41e5814b@nntp0.pdx.net> Robert Kern wrote: >> Let's presume for a moment that complex is *not* a native data type in >> Python. How would we implement the above - cleanly? The reason for making complex a builtin is _not_ to ease a single program, but to create a convention allowing different modules which operate on complex numbers to communicate. -Scott David Daniels Scott.Daniels at Acm.Org From kent3737 at yahoo.com Tue Jan 11 07:58:19 2005 From: kent3737 at yahoo.com (Kent Johnson) Date: Tue, 11 Jan 2005 07:58:19 -0500 Subject: Python & unicode In-Reply-To: <1105434900.511862.54740@f14g2000cwb.googlegroups.com> References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <10u6347j23enuc3@news.supernews.com> <34gi0fF4c1lntU1@individual.net> <41e31f50$0$6430$8fcfb975@news.wanadoo.fr> <1105434532.132061.24030@f14g2000cwb.googlegroups.com> <1105434900.511862.54740@f14g2000cwb.googlegroups.com> Message-ID: <41e3cb2a$1_2@newspeer2.tds.net> michele.simionato at gmail.com wrote: > I forgot to add the following: > > >>>>setattr(C, "?", u"The letter ?") >>>>getattr(C, "?") > > u'The letter \xe8' > >>>>print getattr(C, "?") > > The letter ? But try this: >>> C.? File "", line 1 C.?? ^ SyntaxError: invalid syntax > > Python identifiers can be generic strings, including Latin-1 > characters; I don't think so. You have hacked an attribute with latin-1 characters in it, but you haven't actually created an identifier. According to the language reference, identifiers can only contain letters a-z and A-Z, digits 0-9 and underscore. http://docs.python.org/ref/identifiers.html Kent From grante at visi.com Tue Jan 25 14:52:47 2005 From: grante at visi.com (Grant Edwards) Date: 25 Jan 2005 19:52:47 GMT Subject: Another scripting language implemented into Python itself? References: Message-ID: <41f6a38f$0$2208$a1866201@visi.com> On 2005-01-25, Rocco Moretti wrote: > "import module" executes Python code. As such it can do > anything Python can do. Crash your system, wipe the hard > drive, etc. Only if you run as root all the time -- and the same can be said of any library routine you call. > And there is nothing the importing code can do to stop it. Nor is there anything you can to do stop libc from doing stuff. > Now, if you limit yourself to known and trusted modules, that > risk virtually disappears, just like staying on the sidewalk > virtually eliminates the chances of getting hit by a bus. Not > completely, mind you, since someone could have altered the > standard library modules/changed the import path such that > you're importing an unknown module. But most people would > argue if someone has that power, they probably can do anything > they want with your system without you doing "import module." > > Bottom line: Don't exec or eval untrusted code. Don't import untrusted > modules. I still don't see how that's any different for Python than for any other language. -- Grant Edwards grante Yow! I'm EXCITED!! I want at a FLANK STEAK WEEK-END!! I visi.com think I'm JULIA CHILD!! From bills2018 at hotmail.com Fri Jan 7 22:48:39 2005 From: bills2018 at hotmail.com (bill) Date: Sat, 8 Jan 2005 11:48:39 +0800 Subject: The limitation of the Photon Hypothesis Message-ID: <20050108034944.81BBF1E4003@bag.python.org> Please reply to hdgbyi at public.guangzhou.gd.cn, thank you ! The limitation of the Photon Hypothesis According to the electromagnetic theory of light, its energy is related to the amplitude of the electric field of the electromagnetic wave, W=eE^2V(where E is the amplitude and V is the volume). It apparently has nothing to do with the light's frequency f. To explain the photoelectric effect, Einstein put forward the photon hypothesis. His paper hypothesized light was made of quantum packets of energy called photons. Each photon carried a specific energy related to its frequency f, W=hf. This has nothing to do with the amplitude of the electromagnetic wave E. For the electromagnetic wave that the amplitude E has nothing to do with the light's frequency f, if the light's frequency f is high enough, the energy of the photon in light is greater than the light's energy, hf>eE^2V. Apparently, this is incompatible with the electromagnetic theory of light. THE UNCERTAINTY PRINCIPLE IS UNTENABLE By re-analysing Heisenberg's Gamma-Ray Microscope experiment and one of the thought experiment from which the uncertainty principle is demonstrated, it is actually found that the uncertainty principle cannot be demonstrated by them. It is therefore found to be untenable. Key words: uncertainty principle; Heisenberg's Gamma-Ray Microscope Experiment; thought experiment The History Of The Uncertainty Principle If one wants to be clear about what is meant by "position of an object," for example of an electron., then one has to specify definite experiments by which the "position of an electron" can be measured; otherwise this term has no meaning at all. --Heisenberg, in uncertainty paper, 1927 Are the uncertainty relations that Heisenberg discovered in 1927 just the result of the equations used, or are they really built into every measurement? Heisenberg turned to a thought experiment, since he believed that all concepts in science require a definition based on actual, or possible, experimental observations. Heisenberg pictured a microscope that obtains very high resolution by using high-energy gamma rays for illumination. No such microscope exists at present, but it could be constructed in principle. Heisenberg imagined using this microscope to see an electron and to measure its position. He found that the electron's position and momentum did indeed obey the uncertainty relation he had derived mathematically. Bohr pointed out some flaws in the experiment, but once these were corrected the demonstration was fully convincing. Thought Experiment 1 The corrected version of the thought experiment Heisenberg's Gamma-Ray Microscope Experiment A free electron sits directly beneath the center of the microscope's lens (please see AIP page http://www.aip.org/history/heisenberg/p08b.htm or diagram below) . The circular lens forms a cone of angle 2A from the electron. The electron is then illuminated from the left by gamma rays--high-energy light which has the shortest wavelength. These yield the highest resolution, for according to a principle of wave optics, the microscope can resolve (that is, "see" or distinguish) objects to a size of dx, which is related to and to the wavelength L of the gamma ray, by the expression: dx = L/(2sinA) (1) However, in quantum mechanics, where a light wave can act like a particle, a gamma ray striking an electron gives it a kick. At the moment the light is diffracted by the electron into the microscope lens, the electron is thrust to the right. To be observed by the microscope, the gamma ray must be scattered into any angle within the cone of angle 2A. In quantum mechanics, the gamma ray carries momentum as if it were a particle. The total momentum p is related to the wavelength by the formula, p = h / L, where h is Planck's constant. (2) In the extreme case of diffraction of the gamma ray to the right edge of the lens, the total momentum would be the sum of the electron's momentum P'x in the x direction and the gamma ray's momentum in the x direction: P' x + (h sinA) / L', where L' is the wavelength of the deflected gamma ray. In the other extreme, the observed gamma ray recoils backward, just hitting the left edge of the lens. In this case, the total momentum in the X direction is: P''x - (h sinA) / L''. The final x momentum in each case must equal the initial X momentum, since momentum is conserved. Therefore, the final X moment are equal to each other: P'x + (h sinA) / L' = P''x - (h sinA) / L'' (3) If A is small, then the wavelengths are approximately the same, L' ~ L" ~ L. So we have P''x - P'x = dPx ~ 2h sinA / L (4) Since dx = L/(2 sinA), we obtain a reciprocal relationship between the minimum uncertainty in the measured position, dx, of the electron along the X axis and the uncertainty in its momentum, dPx, in the x direction: dPx ~ h / dx or dPx dx ~ h. (5) For more than minimum uncertainty, the "greater than" sign may added. Except for the factor of 4pi and an equal sign, this is Heisenberg's uncertainty relation for the simultaneous measurement of the position and momentum of an object. Re-analysis The original analysis of Heisenberg's Gamma-Ray Microscope Experiment overlooked that the microscope cannot see the object whose size is smaller than its resolving limit, dx, thereby overlooking that the electron which relates to dx and dPx respectively is not the same. According to the truth that the microscope can not see the object whose size is smaller than its resolving limit, dx, we can obtain that what we can see is the electron where the size is larger than or equal to the resolving limit dx and has a certain position, dx = 0. The microscope can resolve (that is, "see" or distinguish) objects to a size of dx, which is related to and to the wavelength L of the gamma ray, by the expression: dx = L/(2sinA) (1) This is the resolving limit of the microscope and it is the uncertain quantity of the object's position. The microscope cannot see the object whose size is smaller than its resolving limit, dx. Therefore, to be seen by the microscope, the size of the electron must be larger than or equal to the resolving limit. But if the size of the electron is larger than or equal to the resolving limit dx, the electron will not be in the range dx. Therefore, dx cannot be deemed to be the uncertain quantity of the electron's position which can be seen by the microscope, but deemed to be the uncertain quantity of the electron's position which can not be seen by the microscope. To repeat, dx is uncertainty in the electron's position which cannot be seen by the microscope. To be seen by the microscope, the gamma ray must be scattered into any angle within the cone of angle 2A, so we can measure the momentum of the electron. But if the size of the electron is smaller than the resolving limit dx, the electron cannot be seen by the microscope, we cannot measure the momentum of the electron. Only the size of the electron is larger than or equal to the resolving limit dx, the electron can be seen by the microscope, we can measure the momentum of the electron. According to Heisenberg's Gamma-Ray Microscope Experiment, the electron??s momentum is uncertain, the uncertainty in its momentum is dPx. dPx is the uncertainty in the electron's momentum which can be seen by microscope. What relates to dx is the electron where the size is smaller than the resolving limit. When the electron is in the range dx, it cannot be seen by the microscope, so its position is uncertain, and its momentum is not measurable, because to be seen by the microscope, the gamma ray must be scattered into any angle within the cone of angle 2A, so we can measure the momentum of the electron. If the electron cannot be seen by the microscope, we cannot measure the momentum of the electron. What relates to dPx is the electron where the size is larger than or equal to the resolving limit dx .The electron is not in the range dx, so it can be seen by the microscope and its position is certain, its momentum is measurable. Apparently, the electron which relates to dx and dPx respectively is not the same. What we can see is the electron where the size is larger than or equal to the resolving limit dx and has a certain position, dx = 0. Quantum mechanics does not rely on the size of the object, but on Heisenberg's Gamma-Ray Microscope experiment. The use of the microscope must relate to the size of the object. The size of the object which can be seen by the microscope must be larger than or equal to the resolving limit dx of the microscope, thus the uncertain quantity of the electron's position does not exist. The gamma ray which is diffracted by the electron can be scattered into any angle within the cone of angle 2A, where we can measure the momentum of the electron. What we can see is the electron which has a certain position, dx = 0, so that in no other position can we measure the momentum of the electron. In Quantum mechanics, the momentum of the electron can be measured accurately when we measure the momentum of the electron only, therefore, we have gained dPx = 0. And, dPx dx =0. (6) Thought Experiment 2 Single Slit Diffraction Experiment Suppose a particle moves in the Y direction originally and then passes a slit with width dx(Please see diagram below) . The uncertain quantity of the particle's position in the X direction is dx, and interference occurs at the back slit . According to Wave Optics , the angle where No.1 min of interference pattern can be calculated by following formula: sinA=L/2dx (1) and L=h/p where h is Planck's constant. (2) So the uncertainty principle can be obtained dPx dx ~ h (5) Re-analysis The original analysis of Single Slit Diffraction Experiment overlooked the corpuscular property of the particle and the Energy-Momentum conservation laws and mistook the uncertain quantity of the particle's position in the X direction is the slit's width dx. According to Newton first law , if an external force in the X direction does not affect the particle, it will move in a uniform straight line, ( Motion State or Static State) , and the motion in the Y direction is unchanged .Therefore , we can learn its position in the slit from its starting point. The particle can have a certain position in the slit and the uncertain quantity of the position is dx =0. According to Newton first law , if the external force at the X direction does not affect particle, and the original motion in the Y direction is not changed , the momentum of the particle in the X direction will be Px=0 and the uncertain quantity of the momentum will be dPx =0. This gives: dPx dx =0. (6) No experiment negates NEWTON FIRST LAW. Whether in quantum mechanics or classical mechanics, it applies to the microcosmic world and is of the form of the Energy-Momentum conservation laws. If an external force does not affect the particle and it does not remain static or in uniform motion, it has disobeyed the Energy-Momentum conservation laws. Under the above thought experiment , it is considered that the width of the slit is the uncertain quantity of the particle's position. But there is certainly no reason for us to consider that the particle in the above experiment has an uncertain position, and no reason for us to consider that the slit's width is the uncertain quantity of the particle. Therefore, the uncertainty principle, dPx dx ~ h (5) which is demonstrated by the above experiment is unreasonable. Conclusion Every physical principle is based on the Experiments, not based on MATHEMATICS, including heisenberg uncertainty principle. Einstein said, One Experiment is enough to negate a physical principle. >From the above re-analysis , it is realized that the thought experiment demonstration for the uncertainty principle is untenable. Therefore, the uncertainty principle is untenable. Reference: 1. Max Jammer. (1974) The philosophy of quantum mechanics (John wiley & sons , Inc New York ) Page 65 2. Ibid, Page 67 3. http://www.aip.org/history/heisenberg/p08b.htm Single Particles Do Not Exhibit Wave-Like Behavior Through a qualitative analysis of the experiment, it is shown that the presumed wave-like behavior of a single particle contradicts the energy-momentum conservation laws and may be expained solely through particle interactions. DUAL SLIT INTERFERENCE EXPERIMENT PART I If a single particle has wave-like behavior, it will create an interference image when it has passed through a single slit. But the experimental result shows that this is not the case Only a large number of particles can create an interference image when they pass through the two slits. PART II In the dual slit interference experiment, the single particle is thought to pass through both slits and interfere with itself at the same time due to its wave-like behavior. The motion of the wave is the same direction as the particle. If the particle passes through a single slit only, it can not be assumed that it has wave-like behavior. If it passes through two slits, it, and also the acompanying wave must be assumed to have motion in two directions. But a wave only has one direction of motion. PART III If one slit is obstructed in the dual slit interference experiment and a particle is launched in this direction, then according to Newton??s first law, (assuming no external forces,) it will travel in a uniform straight line. It will not pass through the closed slit and will not make contact with the screen. If it has wavelike behavior, there is a probability that it will make contact. But this will negate Newton??s first law and the law of conservation of energy and momentum. Both quantum mechanics and classical mechanics are dependent on this law. THE EXPLANATION FOR THE WAVE-LIKE BEHAVIOR OF THE PARTICLE In the dual slit interference experiment, if one slit is unobstructed, particles will impact at certain positions on the screen. But when two slits are open, the particles cannot reach these positions. This phenomenon brings us to the greatest puzzle regarding the image of the particle. But when we consider that the particle may experience two or more reflections, the puzzle may be resolved. As indicated, when one of the slits is obstructed, the particles that move towards this slit cannot get to the screen. However, they can return to the particle source by reflection and then pass through the open slit and reach the above positions since they have different paths when one or two slits are open. This indicates that wave-like behavior may be explained solely on the basis of particle interactions. EXPERIMENTAL TEST The above may be tested by an experiment that can absorb all the particles that move towards the closed slit. If one slit is obstructed by the stuff that can absorb all the particles that move towards it, the intensity of some positions on the screen should decrease THE CONCLUSION Single particles do not exhibit wave-like behavior. The similarity of wave and particle behavior may be attributed to initial impulse and path. The quantum mechanical explanation is suspect, since the probability of one particle and one particle among a large quantity reaching the screen is equal in mathematics and physics. Author : BingXin Gong Postal address : P.O.Box A111 YongFa XiaoQu XinHua HuaDu GuangZhou 510800 P.R.China E-mail: hdgbyi at public.guangzhou.gd.cn Tel: 86---20---86856616 From rparsons at ncable.net.au Sat Jan 8 17:33:44 2005 From: rparsons at ncable.net.au (Rick Parsons) Date: Sat, 08 Jan 2005 22:33:44 GMT Subject: Another look at language comparisons References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> <1105188426.955508.263030@c13g2000cwb.googlegroups.com> Message-ID: On Sat, 08 Jan 2005 14:18:15 +0100, Jan Dries wrote: > > The bottom line of the article is that languages authored by men with > beards are more successful than those authored by people without beards. > At least the anecdotical evidence to that is overwhelming :-) > > And there is hope for Python, as Guido has recently been seen with a > beard :-) > http://www.tbray.org/ongoing/When/200x/2004/12/08/-big/IMG_3061.jpg > > Regards, > Jan What about languages USED by men with beards? There may be hope for me yet. Regards, Rick From hcslmf at texlife.com Wed Jan 26 16:40:43 2005 From: hcslmf at texlife.com (brolewis) Date: 26 Jan 2005 13:40:43 -0800 Subject: MSI Difficulties Message-ID: <1106775643.324169.227970@f14g2000cwb.googlegroups.com> I am trying to deploy Python onto a number of laptops, all running Windows XP, and have been trying to take advantage of Python 2.4's MSI installer. I have tried using the following commands to install, but to no avail: msiexec /i python-2.4.msi /qb ALLUSERS=1 -- and -- msiexec /i python-2.4.msi /qb ALLUSERS=1 ADDLOCAL=ALL However both of these commands fail to update the Windows path to include C:\Python24 and as such creates problems for me when trying to actually use Python. How can I rectify this situation? Is there a command I am missing? Do I need to manually update the Path, and if so, is there a programatic way I can do this? Thanks in advance. From irmen at -nospam-remove-this-xs4all.nl Sun Jan 16 10:03:13 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Sun, 16 Jan 2005 16:03:13 +0100 Subject: there's a socket.sendall(), so why no socket.recvall()? In-Reply-To: References: <41e03ccc$0$6208$e4fe514c@news.xs4all.nl> <41e9e854$0$6212$e4fe514c@news.xs4all.nl> Message-ID: <41ea822e$0$6220$e4fe514c@news.xs4all.nl> Roger Binns wrote: >>>>>there's a socket.sendall(), so why no socket.recvall()? > > > BTW socket.sendall() doesn't actually work for large amounts > of data on Windows 2000 and probably other versions of > Windows as well. Eg if you supply a 1MB buffer then you get > an exception based on some internal Windows error code. > I haven't experimented on Unix yet to see if it has the same > issue. I suspect that this is related to this issue: http://www.python.org/sf/853507 socket.recv() raises MemoryError exception (WindowsXP ONLY) Also see: http://www.python.org/sf/1103350 But I haven't yet experienced this problem yet with sendall (on linux and windows xp) --Irmen From simonwittber at gmail.com Wed Jan 26 20:08:59 2005 From: simonwittber at gmail.com (Simon Wittber) Date: Thu, 27 Jan 2005 09:08:59 +0800 Subject: python memory blow out Message-ID: <4e4a11f805012617082ebd9b80@mail.gmail.com> I have written some software which proxy's SQL Server database services across a network. It uses Pyro, without multiuthreading. It creates and closes a new connection and cursor object for each request. Unfortunately, the memory consumption blows out (consuming all available memory) when a large SQL query is run. This is not a problem in itself; the problem is that Python does not release this memory back to the operating system once it has finished with the result set. I've noticed others have been frustrated by this problem also: http://mail.python.org/pipermail/python-dev/2004-October/049483.html According to the above post: > a) If the allocation is > 256 bytes, call the system malloc. > b) If the allocation is < 256, use its own malloc implementation, which > allocates memory in 256 kB chunks and never releases it. I imagine this means that large memory allocations are eventually released back to the operating system. However, in my case, this appears to be not happening. Does anyone have ideas on why this is occuring, or how I might otherwise prevent memory blow out? Sw. From a at a.invalid Fri Jan 28 06:42:41 2005 From: a at a.invalid (Timo Virkkala) Date: Fri, 28 Jan 2005 11:42:41 GMT Subject: [perl-python] daily tip website In-Reply-To: <1106905338.224003.216840@c13g2000cwb.googlegroups.com> References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> <1106875259.426213.252030@z14g2000cwz.googlegroups.com> <1106905338.224003.216840@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: > Thanks to those who have made useful comments. They will be > assimilated. The comments, or those who have made comments? "Corrections are futile. You will be assimilated." --Xah Lee -- Timo Virkkala From michael.mcgarry at gmail.com Fri Jan 28 16:42:50 2005 From: michael.mcgarry at gmail.com (Michael McGarry) Date: 28 Jan 2005 13:42:50 -0800 Subject: Problems with PyQt Message-ID: <1106948570.216167.302060@z14g2000cwz.googlegroups.com> Hi, I am having a problem making a widget appear. I have 5 widgets which are windows with no parents. 3 of the widgets appear without a problem the other 2 widgets will not appear when I invoke widget.show() from within a handler for another widget. I am completely clueless as to why these 2 widgets will not draw. One of them is simply a wait window I want to appear while I am performing a time consuming task. Here is a snippet of code: def viewSimButton_pressed(self): wait_win.waitProgressBar.setPercentageVisible(1) wait_win.waitProgressBar.setTotalSteps(5) wait_win.waitProgressBar.setProgress(0) wait_win.show() self.hide() self.viewSimButton.setDown(0) for loopIdx in range(self.simListBox.count()): if self.simListBox.isSelected(loopIdx) == 1: simIdx = loopIdx simID = self.simListBox.item(simIdx).text().ascii() # Clear list box sim_view_win.simOutputListBox.clear() if os.path.exists(simID) == 1: os.chdir(simID) wait_win.waitProgressBar.setProgress(1) # Check process ID file if os.path.exists('pid') == 1: time.sleep(1) # wait 1 second, then check again pidFile = open('pid','r') pidStr = pidFile.readline() if pidStr == 'done\n': sim_view_win.simStatusLbl.setText('Completed') else: sim_view_win.simStatusLbl.setText('Running') simData = sims[simID] sim_view_win.simIDEdit.setText(simID) sim_view_win.hostEdit.setText(simData['host']) wait_win.waitProgressBar.setProgress(3) # Fill list box with output files # filedir = os.popen('ls','r') filename = filedir.readline() while filename: filename = string.rstrip(filename) if ((filename != 'pid') and (filename != 'sim_cfg') and (filename != 'sim_log') and (filename != 'sim_core') and (string.find(filename,'.fig') == -1) and (string.find(filename,'.gp') == -1)): sim_view_win.simOutputListBox.insertItem(filename) filename = filedir.readline() os.chdir('..') wait_win.waitProgressBar.setProgress(5) wait_win.hide() sim_view_win.show() wait_win will show on the screen but not with it's progress bar. Can anyone help? Thanks, Michael From thisissantanu at yahoo.com Thu Jan 27 07:20:22 2005 From: thisissantanu at yahoo.com (santanu) Date: 27 Jan 2005 04:20:22 -0800 Subject: Please suggest on the book to follow Message-ID: <1106828422.318953.166680@f14g2000cwb.googlegroups.com> Hi all, I know a little python (not the OOP part) learnt by studying the online tutorial. Now I would like to learn it more thoroughly. I have access to 'Programming Python' which I liked (on flipping through the pages), but the problem is it deals only with version 2.0 of Phython. So, I would be glad if you could suggest me whether it would be really a good idea to learn from this book. In other words, will I have to unlearn too much after I complete this book (by the time I am done with this book, I believe we will be having Python 2.6 or so). Please suggest. Regards, Santanu From daranrife at yahoo.com Thu Jan 27 23:45:13 2005 From: daranrife at yahoo.com (drife) Date: 27 Jan 2005 20:45:13 -0800 Subject: LinearAlgebra incredibly slow for eigenvalue problems Message-ID: <1106887513.865901.154760@z14g2000cwz.googlegroups.com> Hello, I need to calculate the eigenvectors and eigenvalues for a 3600 X 3600 covariance matrix. The LinearAlgebra package in Python is incredibly slow to perform the above calculations (about 1.5 hours). This in spite of the fact that I have installed Numeric with the full ATLAS and LAPACK libraries. Also note that my computer has dual Pentium IV (3.1 GHz) processors with 2Gb ram. Every Web discussion I have seen about such issues indicates that one can expect huge speed ups if one compiles and installs Numeric linked against the ATLAS and LAPACK libraries. Even more perplexing is that the same calculation takes a mere 7 min in Matlab V6.5. Matlab uses both ATLAS and LAPACK. Moreover, the above calculation takes the same amount of time for Numeric to complete with --and-- without ATLAS and PACK. I am certain that I have done the install correctly. Can anyone provide some insight? Thanks in advance for your help. Daran From mrroach at okmaybe.com Sat Jan 1 16:11:45 2005 From: mrroach at okmaybe.com (Mark Roach) Date: Sat, 01 Jan 2005 21:11:45 GMT Subject: Readline configuration Message-ID: I have readline set up pretty much the same way as in the example in the python docs (http://docs.python.org/lib/readline-example.html) and something I find myself doing fairly often is type some code more code more code ... and then wanting to scroll back through the history to run the same code again after a module = reload(module). In Windows, this is pretty convenient as I can use up to move to point x in the history, press enter, and press down to move to point x+1 in history. Is there any way to get the same behavior with readline? It would be great to be able to ctrl+r then just hit down+enter to reenter the rest of the code. Thanks, Mark From tmj at SPAMLESSjarmania.com Wed Jan 19 13:10:37 2005 From: tmj at SPAMLESSjarmania.com (Tim Jarman) Date: Wed, 19 Jan 2005 18:10:37 +0000 Subject: simultaneous multiple requests to very simple database References: <3A81C87DC164034AA4E2DDFE11D258E33981ED@exchange.hqamor.amorhq.net> Message-ID: <357m4tF4j46c9U1@individual.net> Olaf Zetanien wrote: > > Use Firebird as sql backend. Is designed as you request (readers not lock > writers and writers not lock readers). Google for "firebird optimistic > lock". > > Off course, you have python driver: http://kinterbasdb.sf.net and can > deploy on windows and linux with a very little footprint. > And OS X. But it fails the OP's "no SQL" test. -- Website: www DOT jarmania FULLSTOP com From jeff at ccvcorp.com Fri Jan 7 15:53:34 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 07 Jan 2005 12:53:34 -0800 Subject: Calling Function Without Parentheses! In-Reply-To: <1105113743.189469.115440@f14g2000cwb.googlegroups.com> References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> <41D8B5F4.1010903@mxm.dk> <1105113743.189469.115440@f14g2000cwb.googlegroups.com> Message-ID: <10tttc6vblse9@corp.supernews.com> Kamilche wrote: > Yeah, but still. If they even had the most basic check, like 'an object > is being referred to on this line, but you're not doing anything with > it' would be handy in catching that. When you use an object like that, > usually you're doing something with it, like assigning it to a variable. > In many cases, however, it's not possible to distinguish this. def get_pi(): import math return math.pi print my_func(get_pi) Now, am I trying to pass the function object get_pi into my_func(), or do I want to call get_pi() and pass the return value? There are also many times when it's sensible to do nothing with an object reference -- i.e. ignoring the return value of a function which you're calling for its side-effects. It seems to me that it's reasonable for the Python interpreter to *not* attempt to guess at whether a questionable usage is an error or not. Better to have that done by a developer tool (pychecker) than through runtime checks every time the program is used. Jeff Shannon Technician/Programmer Credit International From aleaxit at yahoo.com Fri Jan 21 18:08:46 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 00:08:46 +0100 Subject: Configuring Python for Tk on Mac References: Message-ID: <1gqrk68.zjv42scxdyaqN%aleaxit@yahoo.com> Craig Ringer wrote: ... > I've just checked the OSX 10.3 machine here, and it fails to import > tkinter there too. I'd say Apple just don't build Python with Tk > support. No idea about any 10.2, sorry, but on 10.3 that's not the problem: Tk support is there alright, it's Tcl/Tk which _isn't_. Get MacPython, its PackageManager will explain where to get Tcl/Tk Aqua from, as a prereq for Tkinter and IDLE! Alex From reed at intersiege.com Tue Jan 18 23:33:19 2005 From: reed at intersiege.com (Reed L. O'Brien) Date: Tue, 18 Jan 2005 23:33:19 -0500 Subject: rotor replacement Message-ID: I see rotor was removed for 2.4 and the docs say use an AES module provided separately... Is there a standard module that works alike or an AES module that works alike but with better encryption? cheers, reed From ajsiegel at optonline.net Sat Jan 29 16:59:27 2005 From: ajsiegel at optonline.net (ajsiegel at optonline.net) Date: Sat, 29 Jan 2005 16:59:27 -0500 Subject: Marketing reST (was Re: What YAML engine do you use Message-ID: <158aadb1586c5d.1586c5d158aadb@optonline.net> Aahz writes - >While I can see how you'd get that impression of reST, it's not true: >like Python, reST is intended to be simpl*er* and readable, but not >simple. Really? ;) Thanks for taking this one on. I was tempted. But scared ;) I find reST quite useful. Not a very sophisticated way to judge something designed to be useful. but the best I can do. Art From http Sat Jan 8 17:56:43 2005 From: http (Paul Rubin) Date: 08 Jan 2005 14:56:43 -0800 Subject: Embedding a restricted python interpreter References: Message-ID: <7x4qhr4jis.fsf@ruckus.brouhaha.com> Dieter Maurer writes: > It uses a specialized compiler that prevents dangerous bytecode operations > to be generated and enforces a restricted builtin environment. Does it stop the user from generating his own bytecode strings and demarshalling them? From rschroev_nospam_ml at fastmail.fm Sun Jan 9 14:29:26 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 09 Jan 2005 19:29:26 GMT Subject: windows mem leak In-Reply-To: References: <41XDd.70234$Jk5.40626@lakeread01> <41E06C18.6050407@hotmail.com> Message-ID: Bob Smith wrote: > Peter Hansen wrote: >> How have >> you proven that it is not *that* program which is at fault?) It would surprise me: even if it consumes much CPU-time, memory and other resources, each instances returns all resources when it exits. > I have not. All I know is that on WinXP, the program uses 100% CPU at > times and consumes more Ram than is available (the page file grows to > 700 or 800MB). It runs OK for a few hours and then produces a 'not > enough resources' error. And, the machine is generally unuserable. On > Linux, it has no impact whatsoever on resources. Granted, the Linux > machine is much more robust, but one wouldn't expect this great a > difference. I can rewrite it so that it's pure Pyhton (no calling nmap) > if you think that would be a good idea. Perhaps that would at least > remove nmap from the equation. I wrote a very simple and small fake_nmap that just looks at the IP-address and prints "open", "closed" or "filtered" to stdout. When I run your python program (Python 2.4 on Windows XP, like you), the CPU is utilized 100% (about half of it goes to csrss.exe whatever that may be); about half of the CPU time is spent in the kernel. The system stays usable (at least for now, it's been running for about 5 minutes now), but memory use is increasing, slow but steadily. The task manager shows, in addition to a number of fake_nmap.exe processes, a number of cmd.exe processes. I don't understand where these come from: I know os.system ()uses the shell, but isn't os.popen() supposed to open the process directly? It seems there are a lot more instances of cmd.exe than of fake_nmap.exe; no idea what that tells us. Also, it takes quite some time before "256 threads running incl. main" is printed the first time, so I think the system needs all that time to create all the threads. It would be normal for memory use to keep increasing untill all threads are created, but I'm fairly certain memory use is still increasing now. -- "Codito ergo sum" Roel Schroeven From pdemb at illx.org Sun Jan 2 16:14:28 2005 From: pdemb at illx.org (Peter Dembinski) Date: Sun, 02 Jan 2005 22:14:28 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> <7xsm5kfyse.fsf@ruckus.brouhaha.com> <41d7941f$1_3@127.0.0.1> <7x8y7cjo57.fsf@ruckus.brouhaha.com> <87zmzsax12.fsf@hector.domek> Message-ID: <87pt0na5zf.fsf@hector.domek> Peter Dembinski writes: [...] > str = foo(x) (ick!) it should be: bar = foo(x) From baas at ira.uka.de Thu Jan 20 15:44:58 2005 From: baas at ira.uka.de (Matthias Baas) Date: Thu, 20 Jan 2005 21:44:58 +0100 Subject: ANN: Python Computer Graphics Kit v2.0.0alpha2 Message-ID: <1160v0l7qt8s2do22kbi1pao2q66aiq3pk@4ax.com> The second alpha release of version 2 of the Python Computer Graphics Kit is available at http://cgkit.sourceforge.net What is it? ----------- The Python Computer Graphics Kit is a generic 3D package written in C++ and Python that can be used for a variety of domains such as scientific visualization, photorealistic rendering, Virtual Reality or even games. The package contains a number of generic modules that can be useful for any application that processes 3D data. This includes new types such as vectors, matrices and quaternions. Furthermore, the package can read and store 3D models in memory where they can be manipulated by Python programs. The kit comes with tools that can be used to display the scene either interactively or by rendering it offline via a RenderMan renderer. What's new? ----------- - New module "glove" that wraps the 5DT Data Glove SDK - New module "wintab" that wraps the Wintab API to receive data from tablets (Windows only) - New module "spacedevice" that wraps the 3Dconnexion 3DXWare SDK (currently Windows only) - New class: FreeCamera - STL importer added (ASCII and binary) - some bugfixes and minor enhancements (see changelog) Windows binary versions are available for Python 2.3 and Python 2.4. For more information, visit: http://cgkit.sourceforge.net - Matthias - From kst-u at mib.org Sat Jan 29 03:31:14 2005 From: kst-u at mib.org (Keith Thompson) Date: Sat, 29 Jan 2005 08:31:14 GMT Subject: what's OOP's jargons and complexities? References: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> <41fb3c85$0$10470$8fcfb975@news.wanadoo.fr> Message-ID: jacob navia writes: > Good post. > > First article that demistifies this OO centered approach > in quite a long time. I have no idea whether it was "good" or not, but it was blatantly off-topic in at least comp.lang.c, and probably all the other newsgroups to which it was cross-posted. Jacob, please don't encourage this kind of newsgroup abuse. -- Keith Thompson (The_Other_Keith) kst-u at mib.org San Diego Supercomputer Center <*> We must do something. This is something. Therefore, we must do this. From franz.steinhaeusler at utanet.at Mon Jan 31 08:11:55 2005 From: franz.steinhaeusler at utanet.at (Franz Steinhaeusler) Date: Mon, 31 Jan 2005 14:11:55 +0100 Subject: Where can I find sample "beginner" programs to study? References: <_6CdnWIOB8AaA2fcRVn-rg@speakeasy.net> Message-ID: On Fri, 28 Jan 2005 21:41:05 +0100, moma wrote: >Eggs are here. Bring some bacon. >http://www.python-eggs.org/links.html Hi, interesting site, but who is maintaining this page. I'd like to add some new links. -- Franz Steinhaeusler From aorfanakos at gmail.com Wed Jan 26 22:07:17 2005 From: aorfanakos at gmail.com (Aggelos I. Orfanakos) Date: 26 Jan 2005 19:07:17 -0800 Subject: Which is faster? In-Reply-To: References: <1106793602.782397.61260@z14g2000cwz.googlegroups.com> Message-ID: <1106795237.484955.176360@c13g2000cwb.googlegroups.com> Yes, I could do the timing myself. Sorry if this was impolite -- it was not in my intentions. The main reason I asked was about the reason. Thanks. From ialbert at mailblocks.com Mon Jan 17 10:46:30 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 17 Jan 2005 10:46:30 -0500 Subject: pychecker - sets.Set need to be overridden Message-ID: Hello all, if I have this code: import sets class Foo: x = sets.Set() then pychecker says: test.py:4: Methods (__cmp__, __hash__) in sets.Set need to be overridden in a subclass I don't get this message. What is it trying to say, and why? Istvan. From just at xs4all.nl Sun Jan 16 10:35:20 2005 From: just at xs4all.nl (Just) Date: Sun, 16 Jan 2005 16:35:20 +0100 Subject: Newbie inheritance question. References: <41EA754D.8020307@gmail.com> Message-ID: In article , Ed Leafe wrote: > On Jan 16, 2005, at 9:08 AM, bwobbones wrote: > > > class two(one): > > def __init__(self): > > print "two" > > You need to specifically call the superclass's __init__ here in order > for it to fire. Just add the line > > super(two, self).__init__() > > as the first line of the subclass's __init__. super() only works for new-style classes, ie. class one needs to derive from object for this to work. Just From http Sat Jan 8 18:59:50 2005 From: http (Paul Rubin) Date: 08 Jan 2005 15:59:50 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> Message-ID: <7xk6qnzd3d.fsf@ruckus.brouhaha.com> "Carl Banks" writes: > You misunderstand. There "where" is not part of the expression but the > statement. The above example would be a modified print statement, a > print...where statement, if you will. Under this suggestion, there > would be modified versions of various simple statements. You mean I can't say # compute sqrt(2) + sqrt(3) x = (sqrt(a) where: a = 2.) \ + sqrt (a) where: a = 3. Hmmm. From steve at holdenweb.com Fri Jan 28 09:46:44 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 28 Jan 2005 09:46:44 -0500 Subject: Hey, get this! [was: import from database] Message-ID: <41FA5054.3020309@holdenweb.com> This is even stranger: it makes it if I import the module a second time: import dbimp as dbimp import sys if __name__ == "__main__": dbimp.install() #k = sys.modules.keys() #k.sort() #for kk in k: #print kk #import bsddb.db import a.b.c.d import smtplib import ftplib import fileinput try: print "first import" import bsddb except: print "second import" import bsddb print "Done!" $ python -i test.py dbimporter: item: *db* args: () keywords: {} Accepted *db* dbimporter: item: /c/steve/Projects/Python/dbimp args: () keywords: {} dbimporter: item: /c/steve/Projects/Python/dbimp/c args: () keywords: {} dbimporter: item: /c/steve/Projects/Python/dbimp/\code args: () keywords: {} dbimporter: item: /usr/lib/python24.zip args: () keywords: {} dbimporter: item: /usr/lib/python2.4 args: () keywords: {} dbimporter: item: /usr/lib/python2.4/plat-cygwin args: () keywords: {} dbimporter: item: /usr/lib/python2.4/lib-tk args: () keywords: {} dbimporter: item: /usr/lib/python2.4/lib-dynload args: () keywords: {} dbimporter: item: /usr/lib/python2.4/site-packages args: () keywords: {} dbimporter: item: /usr/lib/python2.4/site-packages/a args: () keywords: {} dbimporter: item: /usr/lib/python2.4/site-packages/a/b args: () keywords: {} dbimporter: item: /usr/lib/python2.4/site-packages/a/b/c args: () keywords: {} found smtplib in db load_module: smtplib found socket in db load_module: socket socket loaded: pkg: 0 found rfc822 in db load_module: rfc822 rfc822 loaded: pkg: 0 found base64 in db load_module: base64 base64 loaded: pkg: 0 found hmac in db load_module: hmac hmac loaded: pkg: 0 dbimporter: item: /usr/lib/python2.4/email args: () keywords: {} found random in db load_module: random random loaded: pkg: 0 found quopri in db load_module: quopri quopri loaded: pkg: 0 smtplib loaded: pkg: 0 found ftplib in db load_module: ftplib dbimporter: item: /usr/lib/python2.4/site-packages/PIL args: () keywords: {} dbimporter: item: /usr/lib/python2.4/site-packages/piddle args: () keywords: {} ftplib loaded: pkg: 0 found fileinput in db load_module: fileinput fileinput loaded: pkg: 0 first import found bsddb in db load_module: bsddb found weakref in db load_module: weakref weakref loaded: pkg: 0 second import Done! >>> So it's clearly something pretty funky. It now "works" (for some value of "work" wiht both MySQL and sqlite. I hope I have this sorted out before PyCon ... I'm currently a bit confused! regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From jeff at ccvcorp.com Thu Jan 6 19:23:36 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 06 Jan 2005 16:23:36 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: Message-ID: <10trlbqnb86tbb0@corp.supernews.com> Alan Gauld wrote: > Can I ask what the objection to lambda is? > 1) Is it the syntax? > 2) Is it the limitation to a single expression? > 3) Is it the word itself? > > I can sympathise with 1 and 2 but the 3rd seems strange since a > lambda is a well defined name for an anonymous function used in > several programming languages and originating in lambda calculus > in math. Lambda therefore seems like a pefectly good name to > choose. I think that the real objection is a little bit of 1), and something that's kinda close to 2), but has nothing to do with 3). The issue isn't that lambdas are bad because they're limited to a single expression. The issue is that they're an awkward special case of a function, which was added to the language to mollify functional-programming advocates but which GvR never felt really "fit" into Python. Other, more pythonic functional-programming features have since been added (like list comprehensions and iterators). It seems to me that in other, less-dynamic languages, lambdas are significantly different from functions in that lambdas can be created at runtime. In Python, *all* functions are created at runtime, and new ones can be defined at any point in execution, so lambdas don't get that advantage. Thus, their advantages are limited to the fact that they're anonymous (but names are treated differently in Python than in most other languages, so this is of marginal utility), and that they can be created inline. This last bit makes them suitable for creating quick closures (wrapping a function and tweaking its parameters/return values) and for creating a delayed-execution object (e.g. callbacks), so there's a lot of pressure to keep them, but they're still a special case, and "special cases aren't special enough to break the rules". Jeff Shannon Technician/Programmer Credit International From marklists at mceahern.com Sat Jan 8 18:11:57 2005 From: marklists at mceahern.com (Mark McEahern) Date: Sat, 08 Jan 2005 17:11:57 -0600 Subject: printing line numbers for debugging purpose In-Reply-To: <1105199963.7467.4.camel@localhost> References: <1105199963.7467.4.camel@localhost> Message-ID: <41E068BD.3090207@mceahern.com> Philippe C. Martin wrote: >Hi, > >All of the methods from my program return None on error (i.e; I do not >want to assert and have the program exit). > >Is it possible to print the current source file name/line number ? > >ex: in C/C++ I would use the macros __FILE__ and __LINE__. > Consider something like this: #!/usr/bin/env python def main(): raise RuntimeError('whatever') if __name__ == '__main__': try: main() except: import sys, traceback t, v, tb = sys.exc_info() traceback.print_tb(tb) From http Sun Jan 23 10:07:59 2005 From: http (Paul Rubin) Date: 23 Jan 2005 07:07:59 -0800 Subject: is there better 32 clock() timing? References: Message-ID: <7xbrbgxjxs.fsf@ruckus.brouhaha.com> Ray Schumacher writes: > I have a need for a time.clock() with >0.000016 second (16us) accuracy. > The sleep() (on Python 2.3, Win32, at least) has a .001s limit. > > Are they lower/better on other's platforms? > > The alternative appears to be more C code... C code is your best bet. The highest resolution timer on x86's these days is the Pentium RTDSC instruction which counts the number of cpu cycles since power-on. There's various C routines floating around that let you access that instruction. From ncoghlan at iinet.net.au Sat Jan 8 01:42:16 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 08 Jan 2005 16:42:16 +1000 Subject: python3: 'where' keyword In-Reply-To: <41DF78EB.6040502@iinet.net.au> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> Message-ID: <41DF80C8.9010407@iinet.net.au> Nick Coghlan wrote: > It also allows the necessary but uninteresting setup for an expression > to be moved "out of the way", bringing the expression that does the real > work to prominence. Killer app for this keyword: class C(object): x = property(get, set) where: def get(self): return "Silly property" def set(self, val): self.x = "Told you it was silly" Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From andre.roberge at gmail.com Fri Jan 21 21:57:09 2005 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 21 Jan 2005 18:57:09 -0800 Subject: finding name of instances created In-Reply-To: References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> <1106353764.19065.89.camel@bucket.localnet> Message-ID: <1106362629.584545.273460@z14g2000cwz.googlegroups.com> Steven Bethard wrote: > Andr? Roberge wrote: > > Behind the scene, I have something like: > > robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') } > > and have mapped move() to correspond to > > robot_dict['robot'].move() > > (which does lots of stuff behind the scene.) > > > > I have tested robot_dict[] with more than one robot (each with > > its own unique name) and am now at the point where I would like > > to have the ability to interpret something like: > > > > alex = CreateRobot() > > anna = CreateRobot() > > > > alex.move() > > anna.move() > > > > etc. Since I want the user to learn Python's syntax, I don't > > want to require him/her to write > > alex = CreateRobot(name = 'alex') > > to then be able to do > > alex.move() > > How do you get the commands from the user? Maybe you can preprocess the > user code? > > py> class Robot(object): > ... def __init__(self, name): > ... self.name = name > ... def move(self): > ... print "robot %r moved" % self.name > ... > py> user_code = """\ > ... alex = Robot() > ... anna = Robot() > ... alex.move() > ... anna.move()""" > py> new_user_code = re.sub(r'(\w+)\s+=\s+Robot\(\)', > ... r'\1 = Robot(name="\1")', > ... user_code) > py> print new_user_code > alex = Robot(name="alex") > anna = Robot(name="anna") > alex.move() > anna.move() > py> exec new_user_code > robot 'alex' moved > robot 'anna' moved > Smack! (sound of hand slapping forehead). Of course! This is *much* better. (In all honesty, I have trouble reading regular expression notation but I can decode it enough to understand that I can do this - and I already asked a question today on the list about regular expressions, so I have not excuse for not having thought of an approach like this.) I will be already 'processing' the code to make sure that statements/words like: import, exec, eval, input, raw_input, vars, chr, .... are not allowed in the user-defined instructions. This will be just a simple addition. Once again, thank you! Both for this, and for the other example which taught me something about the use of locals(), globals(), and functions that return classes. There are so many corners of Python to explore :-) > Steve From philippecmartin at sbcglobal.net Tue Jan 25 10:41:07 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Tue, 25 Jan 2005 09:41:07 -0600 Subject: Crypto in Python: (Was: What's so funny? WAS Re: rotor replacement) Message-ID: <1106667667.7197.13.camel@localhost> >Now what if acipher and this class could be made from part of the core >distro? Any application could have the option of encryption with only a >few lines of code: Just a bit of info on the subject (which you might already have) I do not know in which country the python.msi is compiled (Deuchland ?), but most likely, the county has rules like most other as far as crypto code in binary format export (especially if distributed as part of a commercial package): for instance, if you want to export a .exe in France, you usually have to go through the DCSSI, in the USA, the BIS ..... It is a _long_ and tedious process. Like you I would love to see crypto support built into python but it _might_ have an impact on its distribution. Regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From carribeiro at gmail.com Sun Jan 9 04:00:14 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Sun, 9 Jan 2005 07:00:14 -0200 Subject: The best way to do web apps with Python? In-Reply-To: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41dfdc15$0$29387$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <864d3709050109010051780586@mail.gmail.com> On Sat, 8 Jan 2005 21:11:49 +0800, worzel wrote: > > What is the best way to web developemnt with Python? Is there anything close > to PHP style in-page script placement that can create and use other Python > objects? I am not really interested in Zope (I believe that is more a CMS > than anything else?) I am also looking for something a little more > structured than a series of CGI Scripts. > > While on the topic - what is the expectataion of Python for this kind of > stuff? Would one use Python for certain other things but turn to PHP for web > apps - or would one use their Python skills in place of PHP? Check CherryPy - www.cherrypy.org. It's clean, light, and best of all, includes its own webserver. You can publish a small site with almost *no* configuration effort, and you have to write *very little code*. It's also natively multi-threaded, and supports advanced stuff such as gzip compression on the fly and XMLRPC. Disclaimer: I'm a contributor to CherryPy, so I'm biased. But I had evaluated both Karirgel and Quixote before settling up on CherryPy, and I see no reason to change. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From tim.peters at gmail.com Sun Jan 16 12:28:00 2005 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 16 Jan 2005 12:28:00 -0500 Subject: interpret 4 byte as 32-bit float (IEEE-754) In-Reply-To: <41e9fae6.975536557@news.oz.net> References: <34t1p2F4foiplU1@individual.net> <41e952b9$1@nntp0.pdx.net> <41E96302.4020003@web.de> <41e964bc$1@nntp0.pdx.net> <41e9fae6.975536557@news.oz.net> Message-ID: <1f7befae05011609282c4ab4ec@mail.gmail.com> [Bengt Richter] ... > But I don't know how to build QNaNs: You can subtract infinity from infinity. While all Python behavior in the presence of NaNs, infinities, and signed zeroes is a platform-dependent accident, it you're on a box that has such things, and figure out some (accidental!) way to spell infinity, then inf-inf should return a NaN (although on a WinTel box, it's most likely to be spelled "-1.#IND" when converted to string). ... > Whereas struct does: No, it doesn't. All Python behavior in the presence of NaNs, infinities, and signed zeroes is a platform-dependent accident. > >>> import struct > >>> struct.unpack('f','\x00\x00\x80\x7f')[0] > 1.#INF An accident (both that you got back an infinity, and the string representation of an infinity). > >>> struct.unpack('f','\x01\x00\x80\x7f')[0] > 1.#QNAN Ditto. Those specific accidents are reliable on the box you're using. > BTW, your example: > >>> struct.unpack('f','\xcd\xcc\x8c\x3f')[0] > 1.1000000238418579 > >>> i32f(0x3f8ccccd) > 1.1000000238418579 > > But what does this mean? Mostly just that behavior is predictable when you're *not* using infinities, NaNs or signed zeroes from Python. > (I wanted to test with little endian unpacking, since > that is what I knew I created, but that isn't what '<' means?? ...) Little-endian is part of what '<' means. '<' also means "use standard alignment" and "use standard data size" and "use standard bit representation". As soon as you force anything like that, Python has to try to interpret the bits itself. In the absence of "<", ">" and "!", plain "f" asks for a wholly platform-native result. In that case, Python doesn't have to know anything about what the bits might mean: it stores the bytes into a native sizeof(float)-byte memory area natively aligned for a float, and you get back whatever the native C thinks that means. > >>> struct.unpack('f','\x00\x00\x80\x7f')[0] > 1.#INF Entirely determined by the platform C compiler and hardware. > >>> struct.unpack(' 3.4028236692093846e+038 Entirely determined by what Python thinks the bits should mean, but Python doesn't know anything about infinities, NaNs, or signed zeroes, and C89 library routines Python calls to construct the value (like ldexp()) have no portably defined behavior in their presence either. From francis.girard at free.fr Sun Jan 23 16:55:06 2005 From: francis.girard at free.fr (Francis Girard) Date: Sun, 23 Jan 2005 22:55:06 +0100 Subject: Classical FP problem in python : Hamming problem In-Reply-To: References: <63b5e209.0501210558.686f5c10@posting.google.com> <200501221106.49241.francis.girard@free.fr> Message-ID: <200501232255.08496.francis.girard@free.fr> Hi, First, My deepest thanks to Craig Ringer, Alex Martelli, Nick Coghlan and Terry Reedy for having generously answered on the "Need help on need help on generator" thread. I'm compiling the answers to sketch myself a global pictures about iterators, generators, iterator-generators and laziness in python. In the meantime, I couldn't resist to test the new Python features about laziness on a classical FP problem, i.e. the "Hamming" problem. The name of the game is to produce the sequence of integers satisfying the following rules : (i) The list is in ascending order, without duplicates (ii) The list begins with the number 1 (iii) If the list contains the number x, then it also contains the numbers 2*x, 3*x, and 5*x (iv) The list contains no other numbers. The algorithm in FP is quite elegant. Simply suppose that the infinite sequence is produced, then simply merge the three sequences (2*x,3*x,5*x) for each x in the infinite sequence we supposed as already produced ; this is O(n) complexity for n numbers. I simply love those algorithms that run after their tails. In haskell, the algorithm is translated as such : -- BEGIN SNAP -- hamming.hs -- Merges two infinite lists merge :: (Ord a) => [a] -> [a] -> [a] merge (x:xs)(y:ys) | x == y = x : merge xs ys | x < y = x : merge xs (y:ys) | otherwise = y : merge (x:xs) ys -- Lazily produce the hamming sequence hamming :: [Integer] hamming = 1 : merge (map (2*) hamming) (merge (map (3*) hamming) (map (5*) hamming)) -- END SNAP In Python, I figured out this implementation : -- BEGIN SNAP import sys from itertools import imap ## Merges two infinite lists def imerge(xs, ys): x = xs.next() y = ys.next() while True: if x == y: yield x x = xs.next() y = ys.next() elif x < y: yield x x = xs.next() else: # if y < x: yield y y = ys.next() ## Lazily produce the hamming sequence def hamming(): yield 1 ## Initialize the machine for n in imerge(imap(lambda h: 2*h, hamming()), imerge(imap(lambda h: 3*h, hamming()), imap(lambda h: 5*h, hamming()))): yield n print "Falling out -- We should never get here !!" for n in hamming(): sys.stderr.write("%s " % str(n)) ## stderr for unbuffered output -- END SNAP My goal is not to compare Haskell with Python on a classical FP problem, which would be genuine stupidity. Nevertheless, while the Haskell version prints Hamming sequence for as long as I can stand it, and with very little memory consumation, the Python version only prints : >>>>>> hamming.py 1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 32 36 40 45 48 50 54 60 64 72 75 80 81 90 96 100 108 120 125 128 135 144 150 160 162 180 192 200 216 225 240 243 250 256 270 288 300 320 324 360 375 384 400 405 432 450 480 486 500 512 540 576 600 625 640 648 675 720 729 750 768 800 810 864 900 960 972 1000 1024 1080 1125 1152 1200 1215 1250 1280 1296 1350 1440 1458 1500 1536 1600 1620 1728 1800 1875 1920 1944 2000 2025 2048 2160 2187 2250 2304 2400 2430 2500 2560 2592 2700 2880 2916 3000 3072 3125 3200 3240 3375 3456 3600 3645 3750 3840 3888 4000 4050 4096 4320 4374 4500 4608 4800 4860 5000 5120 5184 5400 5625 5760 5832 6000 6075 6144 6250 6400 6480 6561 6750 6912 7200 7290 7500 7680 7776 8000 8100 8192 8640 8748 9000 9216 9375 9600 9720 10000 10125 10240 10368 10800 10935 11250 11520 11664 12000 12150 12288 12500 12800 12960 13122 13500 13824 14400 14580 15000 15360 15552 15625 16000 16200 16384 16875 17280 17496 18000 18225 18432 18750 19200 19440 19683 20000 20250 20480 20736 21600 21870 22500 23040 23328 24000 24300 24576 25000 25600 25920 26244 27000 27648 28125 28800 29160 30000 30375 30720 31104 31250 32000 32400 32768 32805 33750 34560 34992 36000 36450 36864 37500 38400 38880 39366 40000 40500 40960 41472 43200 43740 45000 46080 46656 46875 48000 48600 49152 50000 50625 51200 51840 52488 54000 54675 55296 56250 57600 Processus arr?t? After 57600, my machine begins swapping like crazy and I do have to kill the python processus. I think I should not have this kind of behaviour, even using recursion, since I'm only using lazy constructs all the time. At least, I would expect the program to produce much more results before surrending. What's going on ? Thank you Francis Girard FRANCE From http Fri Jan 7 07:50:25 2005 From: http (Paul Rubin) Date: 07 Jan 2005 04:50:25 -0800 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> <7xhdluxh4i.fsf@ruckus.brouhaha.com> Message-ID: <7xd5whv1wu.fsf@ruckus.brouhaha.com> Bulba! writes: > From the viewpoint of looking at availability of source code A, > it's completely irrelevant if those guys are fishmongers or > make derived work A' and redistribute only binary of A'. Not > a single line of publicly available source code appeared or > disappeared as the result of whatever they do. Amounts of > binaries - yes, that is affected. But not the source code. >From the viewpoint of the availability of Adobe Photoshop, it's completely irrelevant if I run off a few hundred thousand copies on CD in a warehouse by the waterfront and then sell them out of the back of a truck at the flea market. Not a single shrink-wrapped retail copy of Photoshop disappeared from any stores as the result. But Adobe will still send the US Marshals to raid my operation with guns and stuff. I don't think you would approve of my illicit Photoshop replication either. So why should the situation be any different with GPL code? If someone wants to copy it, they need to do so according to the license. From aahz at pythoncraft.com Sun Jan 2 13:26:06 2005 From: aahz at pythoncraft.com (Aahz) Date: 2 Jan 2005 13:26:06 -0500 Subject: Python! Is! Truly! Amazing! References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: In article , Roy Smith wrote: >In article , > Ron Garret wrote: >> In article <1104657461.868175.252380 at c13g2000cwb.googlegroups.com>, >> "Erik Bethke" wrote: >>> >>> I have NEVER experienced this kind of programming joy. >> >> Just wait until you discover Lisp! Taking this more seriously than it deserves, I've tried poking at Lisp a couple of times -- each time, I walk away shaking my head in disgust. Lisp just ain't as *READABLE* as Python. >> ;-) > >Shouldn't that be ;-)))))))))))))) ? http://www.netfunny.com/rhf/jokes/90q2/lispcode.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From ncoghlan at iinet.net.au Wed Jan 26 02:30:42 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 26 Jan 2005 17:30:42 +1000 Subject: delay and force in Python In-Reply-To: <41f73df2.1844608046@news.oz.net> References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> <41EE6658.8000409@iinet.net.au> <41f73df2.1844608046@news.oz.net> Message-ID: <41F74722.70009@iinet.net.au> Bengt Richter wrote: > You can bail out of a generator expression with a raise-StopIteration expression spelled iter([]).next() ;-) > > >>> list(show(x) for x in xrange(20) if x<8 or iter([]).next() or True) > 0 1 2 3 4 5 6 7 > [0, 1, 2, 3, 4, 5, 6, 7] This is both neat and incredibly arcane at the same time :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tjreedy at udel.edu Wed Jan 12 13:37:47 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Jan 2005 13:37:47 -0500 Subject: complex numbers References: <1105259798.863970.314750@c13g2000cwb.googlegroups.com> Message-ID: "It's me" wrote in message news:ggcFd.10634$5R.9228 at newssvr21.news.prodigy.com... > Precisely. One have to convert complex number into vectors, and vector > of > complex numbers into vector of vectors, list of complex numbers into list > of > vectors, ...., you get the idea. No, one would have a class with all the appropriate special methods defined. This is what people did before complex was made built-in. The advantage of builtin-ness is being able to write complex literals: 1 + 1j, etc, instead of Complex(1,1). This and speed were two reasons to make complex numbers builtin. The new decimal type, in spite of being builtin (written in C), has the same 'problem' because decimal literals were alread being converted to binary floating point. Perhaps some day we might have 1.23d to indicate conversion to decimal instead. Or perhaps 1.23 will become a decimal and 1.23f a float. Terry J. Reedy From tjreedy at udel.edu Wed Jan 12 18:27:24 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 12 Jan 2005 18:27:24 -0500 Subject: Another look at language comparisons References: <41dfb45d$0$19405$8fcfb975@news.wanadoo.fr> <34llf5F4apou6U2@individual.net> Message-ID: "Jon Perez" wrote in message news:34llf5F4apou6U2 at individual.net... > Anyone know of a cached copy where the photos are present? > > The whole thing makes little sense with the photos gone. > > Pierre Quentel wrote: >> http://khason.biz/blog/2004/12/why-microsoft-can-blow-off-with-c.html It would hardly make more sense with the photos. "Not the law is clear? There is a beard - there is a success. There is no beard - you are guilty. " Terry J. Reedy From bill.mill at gmail.com Fri Jan 28 12:04:05 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 28 Jan 2005 12:04:05 -0500 Subject: Dynamic class methods misunderstanding In-Reply-To: References: Message-ID: <797fe3d405012809041dcbdd32@mail.gmail.com> On Fri, 28 Jan 2005 11:59:50 -0500, Hans Nowak wrote: > Bill Mill wrote: > > > On Fri, 28 Jan 2005 11:09:16 -0500, Hans Nowak wrote: > > > > > >>To add m as a new method to the *class*, do this: > >> > >> >>> class test: > >>... def __init__(self, method): > >>... self.__class__.method = method > >>... self.method() > >>... > >> >>> def m(self): print self > >>... > >> >>> test(m) > >><__main__.test instance at 0x0192ED78> > >><__main__.test instance at 0x0192ED78> > > > > > > When I run it, I only get one call to m, which is how I would expect > > python to work; I assume the double printing here is a typo? > > Actually, no. I'm using the interactive interpreter, so doing test(m) > results in two lines: the first one is printed by m, the second one is > the __repr__ of the test instance that was created, displayed by the > interpreter. Compare: > > >>> x = test(m) > <__main__.test instance at 0x0192ED78> > >>> x > <__main__.test instance at 0x0192ED78> > d'oh; that's how I ran it. Thanks a lot. > -- > Hans Nowak > http://zephyrfalcon.org/ > > -- > http://mail.python.org/mailman/listinfo/python-list > From dimitri.pater at gmail.com Mon Jan 31 10:54:52 2005 From: dimitri.pater at gmail.com (dimitri pater) Date: Mon, 31 Jan 2005 16:54:52 +0100 Subject: barchart for webpage needed Message-ID: Hello, I am looking for a Python tool to create graphs and charts on a webpage. Chartdirector is too expensive for me. A simple script for creating a barchart should be sufficient as a starting point. Thanks! Dimitri -- Please visit dimitri's website: www.serpia.com From bday at jvncomm.com Wed Jan 26 10:57:37 2005 From: bday at jvncomm.com (Bernie) Date: 26 Jan 2005 07:57:37 -0800 Subject: Wow! In-Reply-To: <1106685273.094802.41440@c13g2000cwb.googlegroups.com> References: <1106677008.086803.76270@c13g2000cwb.googlegroups.com> <1106685273.094802.41440@c13g2000cwb.googlegroups.com> Message-ID: <1106755057.057558.25450@f14g2000cwb.googlegroups.com> That is clever, gives a lot of insight into how the __dict__ == the object. This is somewhat like the solution I am using from the Cookbook, an Empty object copy. This is cleaner and very much more concise. Thank you! From steve at holdenweb.com Thu Jan 6 10:42:35 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 06 Jan 2005 10:42:35 -0500 Subject: OT: spacing of code in Google Groups In-Reply-To: <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> <41d5c606$0$26890$a1866201@visi.com> <5amdnbMsyqlhx0DcRVn-vw@powergate.ca> Message-ID: <41DD5C6B.2070708@holdenweb.com> Peter Hansen wrote: [...] > > But the whole argument is fairly moot... I've needed a rectangle > operation only once in the last ten years, and if I hadn't known at > the time that my editor could do it (and spent about half an hour > figuring out how it worked), I could have written a utility to > do the job faster if I'd been using Python at the time... Or even used cut(1) from the command line. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From jrlen97 at gmail.com Fri Jan 21 04:26:25 2005 From: jrlen97 at gmail.com (Jan Rienyer Gadil) Date: Fri, 21 Jan 2005 17:26:25 +0800 Subject: Graph and Table implementation Message-ID: could anyone please help me! what and how is the best implementation of creating a table based on data coming from the serial port ? and also how would i be able to create graphs (2D) based on these data? opinions and suggestion are most highly welcome. thanks. jr From http Sat Jan 1 17:33:39 2005 From: http (Paul Rubin) Date: 01 Jan 2005 14:33:39 -0800 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> Message-ID: <7xacrs230c.fsf@ruckus.brouhaha.com> claird at lairds.us (Cameron Laird) writes: > That is, while I have a LOT of respect for Paul's programming > and judgment, and question myself when I'm on the side opposite > him, I ultimately value type declarations in languages such as > Java as more cost than benefit. I don't find static type declarations to have much cost. It's just a few more keystrokes. I'm open to persuasion about whether they have benefit. I do believe that it's a horrible deficiency in Python that it has no declarations at all, even optional ones, like "perl -w" or "use strict". Python's scoping hacks that result from the lack of declarations just seem to me like pure insanity. I was pretty skeptical of Java's checked exceptions when I first used them but have been coming around about them. There's just been too many times when I wrote something in Python that crashed because some lower-level function raised an exception that the upper level hadn't been expecting, after the program had been in use for a while. I'd sure rather find out about that at compile time. From ncoghlan at iinet.net.au Tue Jan 11 04:42:24 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 11 Jan 2005 19:42:24 +1000 Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) In-Reply-To: <41E12700.8000106@iinet.net.au> References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> Message-ID: <41E39F80.5050001@iinet.net.au> Nick Coghlan wrote: > Semantics > --------- > The code:: > > with: > > > translates to:: > > def unique_name(): > > > unique_name() > Bleh. Not only was my proposed grammar change wrong, my suggested semantics are wrong, too. Raise your hand if you can see the problem with applying the above semantics to the property descriptor example. So I think the semantics will need to be more along the lines of "pollute the namespace but mangle the names so they're unique, and the programmer can *act* like the names are statement local". This will be much nicer in terms of run-time performance, but getting the locals() builtin to behave sensibly may be a challenge. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From http Mon Jan 10 06:19:05 2005 From: http (Paul Rubin) Date: 10 Jan 2005 03:19:05 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> <7xllb2f3z4.fsf@ruckus.brouhaha.com> <1105355380.040837.189270@c13g2000cwb.googlegroups.com> Message-ID: <7xis65a5w6.fsf@ruckus.brouhaha.com> "Carl Banks" writes: > > So do you approve of the movement to get rid of the print statement? > > Any little incremental change in Python you could make by having or not > having a print statement would be minor compared to the H-Bomb of > ugliness we'd get if suites of statements were to be allowed inside > Python expressions. Having or not having a print statement might > violate some small aspect of the Zen, but it won't rape the whole list. How about macros? Some pretty horrible things have been done in C programs with the C preprocessor. But there's a movememnt afloat to add hygienic macros to Python. Got any thoughts about that? > So I don't know what point you're trying to make. Why should you care whether the output of a macro is ugly or not, if no human is ever going to look at it? > But to answer your question, I would prefer a Python without a print > statement, since a print method could do anything the print statement > could. A print -method-?!! You /really/ want to say your_name = "Carl" your_favorite_cereal = "cornflakes" ("Hi", your_name, "how about a nice bowl of", your_favorite_cereal).print() instead of your_name = "Carl" your_favorite_cereal = "cornflakes" print "Hi", your_name, "how about a nice bowl of", your_favorite_cereal ???? I've heard of people wanting to replace print with a function, but hadn't heard of replacing it with a method. Are you trying to turn Python into Ruby? From bokr at oz.net Wed Jan 12 22:11:23 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 03:11:23 GMT Subject: pyserial and com port interrupts References: Message-ID: <41e5e4e2.707756109@news.oz.net> On Wed, 12 Jan 2005 14:24:48 -0800, engsol wrote: >Has anyone done a script that will rspond to the serial com port(s) >receive buffer interrupt, as opposed to polling and timeouts? >Win2000 is the main interest right now. Have you looked into letting the OS do it? I.e., reading from COM4: or whatever port in a thread maybe one byte at a time? Maybe you can get your end functionality without writing low levels stuff, depending ;-) I haven't done this, but it seems an easy thing to try a few experiments with. The control panel should let you set baud rates and handshaking etc. I would think. Regards, Bengt Richter From bdesth.quelquechose at free.quelquepart.fr Wed Jan 5 15:24:29 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 05 Jan 2005 21:24:29 +0100 Subject: Working with flat files [LDIF]. In-Reply-To: <1104871974.248122.102230@f14g2000cwb.googlegroups.com> References: <33A3E2B3.7F5CF6F0@whoi.edu> <1104871974.248122.102230@f14g2000cwb.googlegroups.com> Message-ID: <41dc4b89$0$7897$626a14ce@news.free.fr> generate at gmail.com a ?crit : > Scott A. McIntyre wrote: > >>I looked around but didn't see any LDIF tools for perl or python... >> >>Any assistance or advice is appreciated!! >> >>Scott > > > > Hello Scott, > > Did you ever get this issue resolved? I have a similar need to merge > two LDIF files. I did find a program called mmldif, but I believe it > is proprietary to Sun. > The ldap module has some tools related to ldif files, but there is not much documentation and I never had to use it, so I can't say if this can help... From bill.mill at gmail.com Fri Jan 28 11:25:50 2005 From: bill.mill at gmail.com (Bill Mill) Date: Fri, 28 Jan 2005 11:25:50 -0500 Subject: Dynamic class methods misunderstanding In-Reply-To: References: Message-ID: <797fe3d40501280825693b3427@mail.gmail.com> Hans, On Fri, 28 Jan 2005 11:09:16 -0500, Hans Nowak wrote: > > m is a function. When you assign it to self.method, it's still a > function. You don't create a new method that way; all you have is a new > attribute called 'method' containing the function. > I figured as much; I just didn't know how to add it as a method. > To add m as a new method to the *class*, do this: > > >>> class test: > ... def __init__(self, method): > ... self.__class__.method = method > ... self.method() > ... > >>> def m(self): print self > ... > >>> test(m) > <__main__.test instance at 0x0192ED78> > <__main__.test instance at 0x0192ED78> When I run it, I only get one call to m, which is how I would expect python to work; I assume the double printing here is a typo? > >>> > > To add m as a new method to the *instance*, use new.instancemethod, as > Diez B. Roggisch already pointed out. > Thanks, you helped me understand it a lot. Peace Bill Mill bill.mill at gmail.com From peter.sch231aefer at gmx.de Fri Jan 21 02:25:47 2005 From: peter.sch231aefer at gmx.de (Peter Schaefer) Date: Fri, 21 Jan 2005 08:25:47 +0100 Subject: Python and SOAP In-Reply-To: References: Message-ID: On 21.01.2005 01:16, Nelson Minar wrote: > Peter Schaefer writes: > > SOAPy hasn't been maintained in awhile. The two contemporary options > are ZSI or SOAPpy, both at > http://pywebsvcs.sourceforge.net/ > ZSI seems to have more serious development now, but neither is perfect. > > You should consider doing a document/literal service instead of > rpc/encoded, the old way. Unfortunately in my experience doc/lit > doesn't work as well with Python, but it's a better way of doing > things. The ZSI guys are working at it. Great! I took a look, seems promising. Thanks a lot! Best regards, Peter -- Meine E-Mail Adresse enth?lt keine Zahlen. My email address doesn't contain numbers. From http Sat Jan 8 18:50:48 2005 From: http (Paul Rubin) Date: 08 Jan 2005 15:50:48 -0800 Subject: Pre/Postconditions with decorators References: <1105094828.619317.315340@z14g2000cwz.googlegroups.com> <34814fF43bm4cU1@individual.net> Message-ID: <7x1xcvwkdj.fsf@ruckus.brouhaha.com> Stephen Thorne writes: > Unresolved Problems: > 1) How do you handle duck types, i.e. a method that accepts StringIO, > cStringIO or any other object that has a .readlines(), .seek() and > .read() method? That should really be done through having those classes inherit a file-operations mixin, or else through interfaces (which might get added to Python). > 2) How do you turn off the type checking for production code? It should be left on. Leaving it in for development and turning it off for production is like wearing a parachute during ground training and taking it off once you're in the air. From phr at localhost.localdomain Mon Jan 24 21:47:01 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Tue, 25 Jan 2005 02:47:01 GMT Subject: What's so funny? WAS Re: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> <7xekgdmpll.fsf@ruckus.brouhaha.com> <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> Message-ID: [Again I'm having news server trouble and made a previous attempt to post this, so sorry if you see it twice. This version is edited somewhat from the previous.] "Martin v. L?wis" writes: > This is not possible - whether the module is included in Python or not. > People *will* have to download something besides your application, > namely Python - and in the version your require, too. If they cannot > compile Python themselves, they will have to find somebody who did that > for them. Sorry, the presumption is that they already have Python installed. > > So, if your modules are generally useful, I hope you > > will try to get them into the core. > > Right - the critical condition is "if the modules are generally > useful". I cannot possibly know whether they are generally useful > until a general public has commented that they are. There is considerable demand for a crypto module. Note how this thread started: someone who had been using the rotor module complained that it's now missing. > Hmm. Most applications don't have any crypto needs. Those that do > typically need TLS, or secure password hashing (crypt(3) specifically). > So I somehow doubt that an AES module would be generally useful. I believe it's feasible to do TLS in pure Python with acceptable performance, given a DES module and the existing sha module. I think Trevor Perrin has already written something like that. It's feasible because outside of bulk crypto operations using DES and SHA, TLS's execution time is dominated by public-key math calculations, which are acceptably fast using Python's built-in longs. The rest of the stuff like certificate parsing happens just once per session and doing it in Python isn't too awful. On the other hand, it's impossible to do a general purpose TLS stack acceptably without a DES module. According to RFC 2246 sec. 9, supporting TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA is mandatory unless the application profile specifies otherwise. SHA is already in the core and DHE/DSS can be done with Python longs, so DES is the missing critical piece. Also, since DES is in the process of being decertified and AES is its replacement, supporting DES without supporting AES is silly. GnuPG for example uses AES by default, so writing an interoperating Python application (I have some parts of one working) needs AES. If by crypt(3) you mean the old thing of DES with the modified E table, I don't think it's used much any more. I don't see any reason against adding it if people want it, but it's not an encryption function, it's an authentication function, and shouldn't be subject to the legal concerns of a general purpose encryption module. I do think it would be nice to have TLS in the core someday, just like it's already in the Java distro (JSSE). However, that's much more ambitious and anyway it would rely on the block cipher module, so the block cipher module is needed anyway. Meanwhile, a pure-Python TLS implementation outside the core is ok as a workaround. Getting more pure Python modules into the core is in general less valuable than getting more C modules into the core. > For an AES module with an interface nobody has ever used but yourself, > it would be very difficult to argue that the module is generally useful. Eh? Lots of people have asked for general purpose crypto modules, and the interface follows the approach used by any number of existing libraries. It just does exposes the simplest possible interface to the block cipher and then implements the FIPS operating modes in a natural and obvious way. I've used a number of other such libraries and am pretty familiar with what they need to do. The main thing it tries to do differently from PEP 272 is separate the block ciphers from the FIPS modes, so that each new cipher module doesn't have to implement all the different modes. I hadn't thought there was any controversy over the technical side of this. There's the legal/political issue which I can gently suggest is overblown, but since I'm not the one who would have to take the heat if some government bigwig somewhere flipped their lid over crypto in the Python distro, I don't feel entitled to be very vociferous about this aspect. > I'm primarily looking for the user testing. I require that this happens > *outside* the Python distribution. Make a distutils package, and report > the user feedback. Then propose inclusion into the core. I'm happy to have that kind of testing (and I requested it), given that the goal is inclusion in the core, and the core developers have told me (as they did) that the proposal looks good and they'd like to have the module, so I can reasonably expect it to go into the core if it meets its technical expectations. If the developers instead say (as they seemed to somewhat later) that because of legal/political concerns, there's no way the module can possibly go into the core no matter how good it is technically, then my motivation for writing the module dries up quite a bit. If someone wants to pay me a salary to write it anyway, I might be interested, but people who work as volunteers get to pick their own reasons for doing things or not doing them. > It very much depends on the details of the target system. Yes, > it is a bit more tricky to install the additional library - but > that is the case with any additional library, whether it is C or not. I don't see this. If a library is pure Python, I can always include it with the application. If it's in C, somebody has to compile and install it, and I as the app writer may not have access to compilers for the target platform. Of course a Python library might have platform-dependent OS calls or other configuration hair, but that shouldn't apply to a pure mathematical function that's written portably and makes no OS calls at all. > For the CGI user who is not allowed to install binaries into > /usr/local, she can still install the module in her home > directory, no? Evidently not always. And how would the CGI user create a binary anyway, even given a way to install it, if the web hosting service is using a platform that the CGI user doesn't have a compiler for? Think of a Mac user whose web host runs Windows, or vice versa. > See, this is the critical point: "commonly-used functions", not > "functions I believe would be commonly used". You must have > *existing* users for a function to be commonly-used. You're going around in circles. DES and AES have millions of users. They have few Python users because the functions aren't available in Python. To fix that, they must be added to Python. How many users do you think the Python sha module had before it went into Python? --Paul From tom at dtsam.com Tue Jan 25 14:36:09 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Tue, 25 Jan 2005 13:36:09 -0600 Subject: Help! Host is reluctant to install Python References: Message-ID: <2v2dnf68fNEeAmvcRVn-qw@telcove.net> "Daniel Bickett" wrote in message news:mailman.1279.1106676954.22381.python-list at python.org... > I've been trying to convince my host to install python/mod_python on > his server for a while now, however there are a number of reasons he > is reluctant to do so, which I will outline here: I'll second what you are already hearing. Find a new hosting service because the one you have now is not qualified. Thomas Bartkus From g.tagliarettiNO at SPAMparafernalia.org Sun Jan 2 15:56:45 2005 From: g.tagliarettiNO at SPAMparafernalia.org (Gian Mario Tagliaretti) Date: Sun, 02 Jan 2005 21:56:45 +0100 Subject: How to make executable file ? References: Message-ID: <33r5gcF449bt0U1@individual.net> BOOGIEMAN wrote: [...] > and saved it as pyt.txt > Maybe pyt.py is better :) > Now, how do I make pyt.exe file ??? > I want to run it on windows where isn't installed python. Have a look at py2exe: http://starship.python.net/crew/theller/py2exe/ don't be scared when you see the dimension of the files... cheers -- Gian Mario Tagliaretti PyGTK GUI programming http://www.parafernalia.org/pygtk/ From http Fri Jan 7 16:24:39 2005 From: http (Paul Rubin) Date: 07 Jan 2005 13:24:39 -0800 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <7xis6930ah.fsf@ruckus.brouhaha.com> Message-ID: <7xvfa90w6g.fsf@ruckus.brouhaha.com> Nick Coghlan writes: > Add in the fact that there are many, many Python programmers with > non-CS backgrounds, and the term 'lambda' sticks out like a sore thumb > from amongst Python's other English-based keywords. 'def' is probably > the second-most cryptic when you first encounter it, but it is a good > mnemonic for "define a function", so it's still easy to parse. "Lambda > is the term mathematicians use to refer to an anonymous function" is > nowhere near as grokkable ;) Richard Feynman told a story about being on a review committee for some grade-school science textbooks. One of these book said something about "counting numbers" and it took him a while to figure out that this was a new term for what he'd been used to calling "integers". "Integer" is a math term but I think that if we need to use the concept of integers with someone unfamiliar with the term, it's best to just introduce the term and then use it, rather than make up new terminology like "counting numbers" even if those words sound more like conversational English. For the same reason I don't have any problem with "lambda", though it's not that big a deal. I also just can't believe that Pythonistas keep getting into these arguments over whether lambda is too confusing, while at the same time there's no such discussion over far more abstruse Python features like metaclasses. From itsme at yahoo.com Mon Jan 10 01:19:35 2005 From: itsme at yahoo.com (It's me) Date: Mon, 10 Jan 2005 06:19:35 GMT Subject: else condition in list comprehension References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> <1105305000.052714.188980@c13g2000cwb.googlegroups.com> Message-ID: > z = [i + (2, -2)[i % 2] for i in range(10)] But then why would you want to use such feature? Wouldn't that make the code much harder to understand then simply: z=[] for i in range(10): if i%2: z.append(i-2) else: z.append(i+2) Or are we trying to write a book on "Puzzles in Python"? From roy at panix.com Tue Jan 25 11:25:37 2005 From: roy at panix.com (Roy Smith) Date: 25 Jan 2005 11:25:37 -0500 Subject: Another scripting language implemented into Python itself? References: <10vb8cve125v0b0@corp.supernews.com> Message-ID: Cameron Laird wrote: >It's also one that brings Tcl, mentioned several >times in this thread, back into focus. Tcl presents >the notion of "safe interpreter", that is, a sub- >ordinate virtual machine which can interpret only >specific commands. It's a thrillingly powerful and >correct solution to the main problem Jeff and others >have described. Yup, we used that feature. I don't remember the details, but I do remember that you couldn't open files, and the source command only allowed access to files in a specific directory. From http Sun Jan 2 06:56:47 2005 From: http (Paul Rubin) Date: 02 Jan 2005 03:56:47 -0800 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41d7def6$0$74273$ed2619ec@ptn-nntp-reader03.plus.net> Message-ID: <7xk6qwhwn4.fsf@ruckus.brouhaha.com> Mark Carter writes: > We might be doing a project which involves web-type stuff. I pointed > out that if they did, they wouldn't be able to use VB/VBA, and may > need to use something like Python. They'll probably use vb.net. From mfuhr at fuhr.org Sun Jan 9 18:03:15 2005 From: mfuhr at fuhr.org (Michael Fuhr) Date: 9 Jan 2005 16:03:15 -0700 Subject: Python serial data aquisition References: Message-ID: <41e1b833$1_3@omega.dimensional.com> fccoelho at gmail.com (Flavio codeco coelho) writes: > my hardware represents analog voltages as 12bit numbers. So, according > to the manufacturer, this number will be stored in two bytes like > this; > |-------------bits(1-8)-----------| > Byte1: x x x n1 n2 n3 n4 n5 > Byte2: x n6 n7 n8 n9 n10 n11 n12 > > where x is some other information, and nx are the digits of my number. Is byte1 the high-order byte or the low-order byte? Is n1 the high-order bit or the low-order bit? In my example below I'll assume that byte1 and n1 are in the high-order positions. > My problem is to how to recover my reading from these bytes, since > pyserial gives me a character (string) from each byte... You could convert the characters to their integer ASCII values with ord() and perform bitwise operations on them. For example, suppose you have the following characters: byte1 = '\xd2' # 1101 0010 byte2 = '\xb5' # 1011 0101 If byte1 is the high-order byte and n1 is the high-order bit, then you need to mask off the upper three bits of byte1 (giving 0001 0010) and the upper bit of byte2 (giving 0011 0101), then shift byte1 left 7 positions (not 8) and OR it with byte2 (giving 1001 0011 0101). value = ((ord(byte1) & 0x1f) << 7) | (ord(byte2) & 0x7f) If the actual byte and/or bit order is different then you'll have to modify the expression, but this should at least give you ideas. -- Michael Fuhr http://www.fuhr.org/~mfuhr/ From fuzzyman at gmail.com Fri Jan 28 03:48:38 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 28 Jan 2005 00:48:38 -0800 Subject: urllib2 and proxy question In-Reply-To: References: <1106575675.520424.155310@f14g2000cwb.googlegroups.com> Message-ID: <1106902118.218942.4640@c13g2000cwb.googlegroups.com> rbt wrote: > Fuzzyman wrote: > > urllib2 (under windows) will auto-detect your proxy settings and use > > those. > > > > Normally that's a good thing (I guess), except when it's not ! > > > > How do I switch off this behaviour ? I'm behind a censoring proxy and > > wanting to test things *locally*. IE is set to not use the proxy when > > fetching local adresses, but urllib2 ignores that part of the setting > > and uses the proxy for everything. > > > > The only way I can test are changing my IE settings back and forth > > every time. Most annoying. > > > > I can see how to *add* a new proxy to urllib2, but not how to force it > > to not use a proxy. I may well be missing something obvious though. > > Anyone able to help ? > > Regards, > > > > Fuzzy > > http://www.voidspace.org.uk/python/index.shtml > > > > "Alternatively, the optional proxies argument may be used to explicitly > specify proxies. > It must be a dictionary mapping scheme names to proxy URLs, where an > empty dictionary causes no proxies to be used" > > # Don't use any proxies > filehandle = urllib.urlopen(some_url, proxies={}) Rats.. this answer is for urllib - *NOT* urllib2 ! Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From macrocosm at fastmail.fm Thu Jan 6 18:29:17 2005 From: macrocosm at fastmail.fm (Arich Chanachai) Date: Thu, 06 Jan 2005 18:29:17 -0500 Subject: project In-Reply-To: <20050106221443.84741.qmail@web80909.mail.scd.yahoo.com> References: <20050106221443.84741.qmail@web80909.mail.scd.yahoo.com> Message-ID: <41DDC9CD.2060200@fastmail.fm> An HTML attachment was scrubbed... URL: From pythongnome at hotmail.com Thu Jan 13 19:49:09 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Fri, 14 Jan 2005 00:49:09 GMT Subject: porting C code Message-ID: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> I am currently in the process of porting some C code into Python and am stuck. I don't claim to be the greatest C/C++ programmer; in fact, my skills at C are rudimentary at best. My question is I have the statement: "typedef unsigned long int word32" and later on: "word32 b[3]" referencing the third bit of the integer. How do I do the same in Python?? If this is a stupid, I apologize. It's amazing what the lack of sleep does to the brain. TIA, Lucas From ncoghlan at iinet.net.au Fri Jan 28 23:45:47 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 29 Jan 2005 14:45:47 +1000 Subject: Daylight savings and getmtime In-Reply-To: <1106955283.482973.187550@z14g2000cwz.googlegroups.com> References: <8b2d5523.0501281503.253269@posting.google.com> <35vvjmF4sbe8jU1@individual.net> <1106955283.482973.187550@z14g2000cwz.googlegroups.com> Message-ID: <41FB14FB.60107@iinet.net.au> wittempj at hotmail.com wrote: > on my windows xp box os.path.getmtime gives back local time (I just > saved the file): > >>>>os.path.getmtime('c:\\temp\\testset.py') > > 1106955016 > >>>>print time.mktime(time.localtime()) > > 1106955034.0 No. mktime is converting the local time to UTC. Try this instead: Py> time.gmtime(os.path.getmtime("c:/devel/mtime_test.txt")) (2005, 1, 29, 3, 35, 37, 5, 29, 0) Py> time.localtime(os.path.getmtime("c:/devel/mtime_test.txt")) (2005, 1, 29, 15, 35, 37, 5, 29, 1) (This is with my machine set to Sydney time, so that I'm at UTC + 10, with daylight savings currently active) > You can try to figure out if DST is on by comparing time.localtime() > versus time.gmtime(). In the Western European Timezone there's one hour > difference in winter and two hours in summer. To figure out if DST is currently active, you can use: Py> import time Py> time.localtime() (2005, 1, 29, 14, 29, 26, 5, 29, 0) Py> time.localtime().tm_isdst 0 Switching to Sydney time (which actually uses DST, unlike Brisbane) gives: Py> import time Py> time.localtime().tm_isdst 1 The same trick will work on historical dates, too. For instance, consider a file created last winter, when Sydney was NOT on daylight savings: Py> time.localtime(os.path.getmtime("c:/log.txt")) (2004, 7, 20, 19, 46, 35, 1, 202, 0) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From bokr at oz.net Fri Jan 14 09:42:11 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 14 Jan 2005 14:42:11 GMT Subject: Class initialization from a dictionary, how best? References: <1105677379.632236.17020@z14g2000cwz.googlegroups.com> Message-ID: <41e7b80e.827352389@news.oz.net> On 13 Jan 2005 20:36:19 -0800, "brianobush at gmail.com" wrote: ># ># My problem is that I want to create a ># class, but the variables aren't known ># all at once. So, I use a dictionary to ># store the values in temporarily. Why? ># Then when I have a complete set, I want to ># init a class from that dictionary. Why do it that way? ># However, I don't want to specify the ># dictionary gets by hand ># since it is error prone. ># Thanks for any ideas, Brian > > > So I have a class defined that accepts a number of variables ># and they must be all present at object creation time. Why? Why not a method to check if it's valid yet, and then add the attributes as they're available, without intermediaries. You can make Test "smart" so it won't accept any other names than a,b,c and will automatically convert to str, str, and int. Etc. What are you actually doing? Is this a toy example of a more complex class? >class Test: >def __init__(self, a, b, c): >self.a = a >self.b = b >self.c = c >def __str__(self): >return '%s, %s, %d' % (self.a, self.b, self.c) > ># For example: >t1 = Test('asd', 'sdf', 9) >print t1 > ># However, due to parsing XML, I am ># creating the values incrementally ># and I want to store them in a dictionary ># and then map them easily to a class Why store them in a dictionary? Why not create an empty Test instance, and incrementally add the attributes directly as they're available? What are you going to do with t1 and other instances? > >dictionary = {} > ># a mapping from source to destination >mapping = { >'a': str, >'b': str, >'c': int, >} > ># a sample source of values >test_source = { >'a': 'test', >'b': 'asdf', >'c': 45 >} > ># now we go through and extract the values ># from our source and build the dictionary Just the three items in the test_source dictionary? Is that just a 3-item holding place until you > >for attr_name, function in mapping.items(): >dictionary[attr_name] = function(test_source.get(attr_name)) > >print dictionary > ># Here is the problem I want to avoid: ># Having to list the variable names ># as strings in multiple places. It is enought to ># have them in the 'mapping' ># dictionary above > >t2 = Test(dictionary.get('a'), dictionary.get('b'), >dictionary.get('c')) >print t2 > Why don't you just let Test do all the work, and update it incrementally until it is complete. You can use descriptors to manage state. You could do any number of things. The main problem is defining the _requirements_ without premature implementation, never mind premature optimization ;-) You may have good reasons for wanting to do what you seem to want to do, but the picture is not clear to me ;-) Regards, Bengt Richter From jamesthiele.usenet at gmail.com Sun Jan 30 18:58:26 2005 From: jamesthiele.usenet at gmail.com (jamesthiele.usenet at gmail.com) Date: 30 Jan 2005 15:58:26 -0800 Subject: type() takes one or *three* arguments!? In-Reply-To: References: <1107115043.242733.259890@z14g2000cwz.googlegroups.com> Message-ID: <1107129506.634280.167110@f14g2000cwb.googlegroups.com> Thank you - that explains everything quite nicely. From newstonne at web.de Fri Jan 28 12:27:26 2005 From: newstonne at web.de (Roland Heiber) Date: Fri, 28 Jan 2005 18:27:26 +0100 Subject: Best python postgres module? Message-ID: <41fa75ef_1@news.arcor-ip.de> Hi, i recently migrated from mysql to postgresql and did use severel python postgres-modules. All do what they are designed for, so which one would you use? psycopg, pygresql, pypgsql? psycopg seems to be the best solution for heavy traffic/multiple connections .... i have no real testing environment, so any advice which one to use for different usecases would be nice. Thanks, Roland From carribeiro at gmail.com Thu Jan 6 07:58:16 2005 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 6 Jan 2005 10:58:16 -0200 Subject: Python evolution: Unease In-Reply-To: <41DD2AEA.2020301@iinet.net.au> References: <7x652che6z.fsf@ruckus.brouhaha.com> <7xoeg4txrp.fsf@ruckus.brouhaha.com> <1104895842.200010.42720@z14g2000cwz.googlegroups.com> <7xhdlwh5qs.fsf@ruckus.brouhaha.com> <10to8qulnc3vke1@news.supernews.com> <1104982313.217034.308760@z14g2000cwz.googlegroups.com> <864d3709050106020568bd8b8e@mail.gmail.com> <41DD2AEA.2020301@iinet.net.au> Message-ID: <864d3709050106045840155a6b@mail.gmail.com> On Thu, 06 Jan 2005 22:11:22 +1000, Nick Coghlan wrote: > Carlos Ribeiro wrote: > > Couldn't a better document-writing interface be implemented? > > Such as: > http://www.python.org/moin/Documentation > > Or AMK's annotatable docs: > http://pydoc.amk.ca/frame.html Sorry, I wasn't clear. Both are clear steps in the right direction. I was thinking more along the lines of an automated document processing service, to avoid the need to install all the tools to generate the "official" Python docs (latex, sgml, etc.). One could simply "upload" a revised doc and get the processed result back. Of course, such a service can't be open to the public, but it would still be useful. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From deetsNOSPAM at web.de Wed Jan 26 10:24:35 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 26 Jan 2005 16:24:35 +0100 Subject: 4suite XSLT thread safe ? References: <6lkkc2-fbd.ln1@pluto.i.infosense.no> <35pntaF4os76kU1@individual.net> <71nkc2-pbg.ln1@pluto.i.infosense.no> Message-ID: <35pqtvF4p8vohU1@individual.net> > If a thread that are using a XSLT processor looses the GIL within the > transformation process and another one starts processing on the same > processor will this work? > > Will the half-way finished thread be in the way of the one starting the > processing before the stoped thread are done. > > I think that's what I ment. Can a XSLT processor object be shared > between multiple threads? No - as a simple test reveals: #The identity transform: duplicates the input to output TRANSFORM = """ """ #And I don't even like Monty Python, folks SOURCE1 = """What do you mean "bleah"""" SOURCE2 = """I don't like spam""" import threading from Ft.Xml.Xslt import Processor processor = Processor.Processor() import time, sys from Ft.Xml import InputSource transform = InputSource.DefaultFactory.fromString(TRANSFORM, "http://spam.com/identity.xslt") processor.appendStylesheet(transform) #Now the processor is prepped with a transform and ccan be used #over and over for the same transform results = [] source = InputSource.DefaultFactory.fromString(SOURCE1, "http://spam.com/doc1.xml") source2 = InputSource.DefaultFactory.fromString(SOURCE2, "http://spam.com/doc2.xml") threading.Thread(target=lambda: results.append(processor.run(source))).start() # comment the following line to make things crash. time.sleep(5) threading.Thread(target=lambda: results.append(processor.run(source2))).start() time.sleep(5) print results -- Regards, Diez B. Roggisch From jcribbs at twmi.rr.com Mon Jan 31 18:51:04 2005 From: jcribbs at twmi.rr.com (Jamey Cribbs) Date: Mon, 31 Jan 2005 18:51:04 -0500 Subject: ANNOUNCE: KirbyBase 1.7.1 (Bugfix Release) Message-ID: <41FEC468.3090201@twmi.rr.com> After releasing version 1.7 yesterday, I found a bug this afternoon that could result in incorrect query results if you are doing a regular expression query against more than one string field. So, I felt like I needed to get a quick bug-fix version out the door to try to minimize the damage. You can download KirbyBase for Python at: http://www.netpromi.com/files/KirbyBase_Python_1.7.1.zip You can find more information on KirbyBase at: http://www.netpromi.com/kirbybase.html Sorry about this! I hope the bug did not negatively impact anyone. Jamey Cribbs From jack at performancedrivers.com Fri Jan 14 11:07:34 2005 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 14 Jan 2005 11:07:34 -0500 Subject: How to list the global functions from a C program In-Reply-To: <001101c4fa49$e545a5c0$5c673452@genius> References: <001101c4fa49$e545a5c0$5c673452@genius> Message-ID: <20050114160734.GC26167@performancedrivers.com> On Fri, Jan 14, 2005 at 04:01:13PM +0100, Francesco Montorsi wrote: > PyObject *list = PyObject_Dir(m_pGlobals); > if (!list || PyList_Check(list) == FALSE) > return; > > for (int i=0,max=PyList_Size(list); i > PyObject *elem = PyList_GetItem(list, i); > if (PyCallable_Check(elem) != 0) { > > /* this should be a function.. */ > /* HERE IS THE PROBLEM: this code is never reached */ > PyObject *str = PyObject_GetAttrString(elem, "func_name"); > } > } > ============================================== > > Everything seems to work but then when scanning the list returned > by PyObject_Dir() I never find any callable object.... > what am I doing wrong ? You are checking the list of strings returned from the dir() to see if any of them are callable (they aren't). You mean to check the thing that the string is a name for, so instead of # callable(name) PyCallable_Check(elem) use # callable(globals()[name]) PyCallable_Check(PyDict_GetItem(m_pGlobals, elem)) -Jack From pythongnome at hotmail.com Thu Jan 13 08:12:20 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Thu, 13 Jan 2005 13:12:20 GMT Subject: Python.org, Website of Satan In-Reply-To: References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: Jane wrote: > wrote in message > news:1105495569.479185.166340 at z14g2000cwz.googlegroups.com... > >>python.org = 194.109.137.226 >> >>194 + 109 + 137 + 226 = 666 >> >>What is this website with such a demonic name and IP address? What >>evils are the programmers who use this language up to? >> > > Some people have too much time on their hands... > > Jane > > Better get some ointment for that burn!! From rkern at ucsd.edu Wed Jan 12 20:00:20 2005 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 12 Jan 2005 17:00:20 -0800 Subject: Matrix-SIG archives Message-ID: It looks like the mailing list archives for the Matrix-SIG and other retired SIGs are down at the moment. I've alerted the python.org webmaster, but in the meantime, does anyone have the early archives sitting around somewhere? I'm trying to answer a question about the motivations of a particular design decision in Numeric. Thanks in advance. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From steve at holdenweb.com Tue Jan 18 07:23:24 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 18 Jan 2005 07:23:24 -0500 Subject: Integration with java In-Reply-To: <1106033069.070545.265310@z14g2000cwz.googlegroups.com> References: <1106033069.070545.265310@z14g2000cwz.googlegroups.com> Message-ID: <41ECFFBC.9030706@holdenweb.com> Dan Bishop wrote: > Istvan Albert wrote: > >>Joachim Boomberschloss wrote: >> >> >>> the code is already written in Python, using the >>> standard libraries and several extension modules >> >>One thing to keep in mind is that Jython does not >>integrate CPython, instead it "understands" python code >>directly. So if you have a C extension that works with python >>it won't work with Jython. > > > Also, Jython is several versions behind CPython, so any Python code > that uses generators or new-style division won't work either. > > >>My feeling is that if you had a lot of Java code written and >>wanted to build on that with python Jython would be a better >>fit than vice versa. > > > I agree. > Also let's not forget that the PSF has funded a project that's intended to help Jython get up to the curve - see http://www.python.org/psf/grants/Jython_PSF_Grant_Proposal.pdf. If that project succeeds, and if 2.5 development *does* focus mostly on the library, there's a sporting chance that Jython can be fully up to date for the 2.5 release. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From rittersporn at gmail.com Thu Jan 6 16:33:42 2005 From: rittersporn at gmail.com (Rittersporn) Date: 6 Jan 2005 13:33:42 -0800 Subject: Pre/Postconditions with decorators Message-ID: My humble attempt to model pre/postconditions with decorators :-) It's also my first experiment with decorators. If you have any ideas or thoughts on how to improve the code snippet, I'll be happy to learn more. Enjoy :-) def condition(pretext,posttext=""): precode=compile(pretext or "True","","eval") postcode=compile(posttext or "True","","eval") # function -> decorated(function) def decorate_condition(function): # FIXME: Does not work with wrapped functions argcount=function.func_code.co_argcount var=function.func_code.co_varnames[0:argcount] # arguments -> closure(assertion) def evaluate_condition(*args,**kargs): # FIXME: check if "var" always contains ordered list of arguments # map arguments and args_seq=[(argname,args[pos]) for pos,argname in enumerate(var)] # key-arguments to value kargs_seq=[(k,v) for k,v in kargs.itervalues()] environment=args_seq+kargs_seq # precondition assert eval(precode,{},dict(environment)),pretext tmp=function(*args,**kargs) environment2=environment+[('result',tmp)] # postcondition assert eval(postcode,{},dict(environment2)),posttext return tmp return evaluate_condition return decorate_condition @condition("number>0 and number<2","result>=0") def sqrt(number): import math return math.sqrt(number) @condition("list(seq) is not None","sum(seq)==result") def my_sum(seq): tmp=0 for element in seq: tmp+=element return tmp print sqrt(1.2) print my_sum([1,2,3]) From zanesdad at bellsouth.net Thu Jan 27 21:49:33 2005 From: zanesdad at bellsouth.net (Jeremy Jones) Date: Thu, 27 Jan 2005 21:49:33 -0500 Subject: IPython Article on O'Reilly's ONLamp site In-Reply-To: References: Message-ID: <41F9A83D.9080001@bellsouth.net> I've written an article on IPython which is now live on O'Reilly's ONLamp site at http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html. All feedback is welcome. Regardless of what you may think of the article, I hope it encourages everyone to at least try out IPython. IPython has become an indispensible tool in my toolbox. I cannot say enough great things about it. Jeremy Jones From rupole at hotmail.com Fri Jan 28 01:29:08 2005 From: rupole at hotmail.com (Roger Upole) Date: Fri, 28 Jan 2005 01:29:08 -0500 Subject: threading and internet explorer com References: <41f9777f_2@news.tm.net.my> Message-ID: <41f9dc43$1_2@127.0.0.1> You'll need to call pythoncom.CoInitialize() in each thread. Roger "James" wrote in message news:41f9777f_2 at news.tm.net.my... > hi, > > i'm using python 2.4 with pywin32... > I've tried to use internet explorer control with a class. > it was fine until i decided to inherit thread for the class... > > class domain01(threading.Thread): > def __init__(self): > #blabla > threading.Thread.__init__(self) > > def run(self): > self.ie = win32com.client.Dispatch('InternetExplorer.Application.1') #this > line gives error if i use .start(), but if i use .run.. no error... > self.ie.Visibble = 1 > print "running" > > > > xyz = domain() > xyz.start() > > =========== > this is what i get: > Exception in thread Thread-23: > Traceback (most recent call last): > File "C:\Python24\lib\threading.py", line 442, in __bootstrap > self.run() > File "C:\python2exe\domain01.py", line 41, in run > self.dologin() > File "C:\python2exe\domain01.py", line 56, in dologin > self.ie=win32com.client.Dispatch('InternetExplorer.Application.1') > File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line > 95, in Dispatch > dispatch, userName = > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) > File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line > 91, in _GetGoodDispatchAndUserName > return (_GetGoodDispatch(IDispatch, clsctx), userName) > File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line > 79, in _GetGoodDispatch > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, > pythoncom.IID_IDispatch) > com_error: (-2147221008, 'CoInitialize has not been called.', None, None) > > > > ===== > but if i run: > xyz = domain() > xyz.run() > > ##no error! it's weird.... > > anyone know how to solve this problem? > > thank you :) > > best regards, > > James ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From vincent at visualtrans.de Tue Jan 25 15:04:24 2005 From: vincent at visualtrans.de (vincent wehren) Date: Tue, 25 Jan 2005 21:04:24 +0100 Subject: snakespell and myspell In-Reply-To: <41F6A3F6.9020807@visualtrans.de> References: <1106657932.301181.150050@z14g2000cwz.googlegroups.com> <41F6A3F6.9020807@visualtrans.de> Message-ID: vincent wehren wrote: > Fuzzyman wrote: > >> I'm looking to implement a plugin spell checker. >> >> I'm probably going to go with PyEnchant, as it looks to be the most >> promising currently maintained spell checker. > > > What I would like to know about PyEnchant is how to handle non-ascii > input. Through trial & error I've noticed that let's say German Umlauts > are stored in the dictionary as using dead accents (is that the term?) > (as in 'Mu"tter'), however French accented characters appear to be > stored differently (as in '\xc3\xa9levage') The latter of course being utf-8... -- Vincent From ricardo.b at zmail.pt Thu Jan 13 11:24:00 2005 From: ricardo.b at zmail.pt (Ricardo Bugalho) Date: Thu, 13 Jan 2005 16:24:00 +0000 Subject: Unicode conversion in 'print' Message-ID: Hello, I'm using Python 2.3.4 and I noticed that, when stdout is a terminal, the 'print' statement converts Unicode strings into the encoding defined by the locales instead of the one returned by sys.getdefaultencoding(). However, I can't find any references to it. Anyone knows where it's descrbed? Example: !/usr/bin/env python # -*- coding: utf-8 -*- import sys, locale print 'Python encoding:', sys.getdefaultencoding() print 'System encoding:', locale.getpreferredencoding() print 'Test string: ', u'Ol? mundo' If stdout is a terminal, works fine $ python x.py Python encoding: ascii System encoding: UTF-8 Test string: Ol? mundo If I redirect the output to a file, raises an UnicodeEncodeError exception $ python x.py > x.txt Traceback (most recent call last): File "x.py", line 8, in ? print 'Test string: ', u'Ol? mundo' UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 2: ordinal not in range(128) -- Ricardo From ncoghlan at iinet.net.au Sun Jan 9 00:17:17 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 09 Jan 2005 15:17:17 +1000 Subject: python3: accessing the result of 'if' In-Reply-To: <1105236383.521393.40680@c13g2000cwb.googlegroups.com> References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> <1105236383.521393.40680@c13g2000cwb.googlegroups.com> Message-ID: <41E0BE5D.60500@iinet.net.au> Carl Banks wrote: > What if the condition you wanted to test wasn't the same as the thing > you want to save? In other words, how would you convert this? > > . where: > . m = something() > . if m > 20: > . do_something_with(m) Yeah, this problem eventually occurred to me as well. However, I think a little utility function can help solve it: def test(val, condition): if condition(val): return val else: return None if test(something(), lambda x: x < 10) as m: print "Case 1:", m elif test(something(), lambda x: x > 20) as m: print "Case 2:", m else: print "No case at all!" If we were to use a where clause instead, it looks like: if test(something(), less_than(10)) as m: print "Case 1:", m elif test(something(), more_than(20)) as m: print "Case 2:", m else: print "No case at all!" where: def less_than(y): def lt(x): return x < y return lt def more_than(y): def gt(x): return x > y return lt This is an example of why I don't think where clauses would completely eliminate the utility of deferred expressions. Here's a version using my preferred syntax from the AlternateLambdaSyntax page: if test(something(), (def x < 10 from x)) as m: print "Case 1:", m elif test(something(), (def x > 20 from x)) as m: print "Case 2:", m else: print "No case at all!" Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From fumanchu at amor.org Tue Jan 4 18:34:25 2005 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 4 Jan 2005 15:34:25 -0800 Subject: Bug in handling of single underscore identifiers? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33980E7@exchange.hqamor.amorhq.net> Tom Blackwell wrote: > Today I installed the 'mechanoid' package from sourceforge, but the > self-test failed. On looking into it, I noticed odd behaviour in the > handling of single underscore module names. Importing into the > current namespace with 'from' seems to work, but accessing members of > the imported module only works if the imported name is qualified by > the containing module name. > > For example: > >>> from mechanoid import _mechanoid_Common > >>> from _mechanoid_Common import Common > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named _mechanoid_Common > >>> from mechanoid._mechanoid_Common import Common > **succeeds** > >>> _mechanoid_Common > 'mechanoid\_mechanoid_Common.pyc'> > > Is this a bug or a feature? The language reference section 2.3.2 > 'Reserved classes of identifiers' indicates that identifiers starting > with a single underscore are not imported by "from module import *". > However I can't find any indication that "from module import _name" > should work this way. I don't think this has anything to do with the underscore. The import statement doesn't reference module globals; instead, it uses its own mechanism to find the module you specify: >>> from os import path >>> path.sys >>> from path import sys Traceback (most recent call last): File "", line 1, in ? ImportError: No module named path In your example ("from _mechanoid_Common import Common"), import can't find any module named "_mechanoid_Common" in site-packages, PYTHONPATH, or other known sources. Robert Brewer MIS Amor Ministries fumanchu at amor.org From http Sat Jan 29 21:37:25 2005 From: http (Paul Rubin) Date: 29 Jan 2005 18:37:25 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> <7xacqsbfk2.fsf@ruckus.brouhaha.com> Message-ID: <7xk6pv1w2i.fsf@ruckus.brouhaha.com> Nick Craig-Wood writes: > I would hate to see a module which only implemented ECB. Sure its the > only operation necessary to build the others out of, but its the least > secure mode of any block cipher. It's intended as a building block for other modes. Most applications shouldn't use it directly. > If you don't offer users a choice, then they'll use ECB and just that > along with all its pitfalls, meanwhile thinking that they are secure > because they are using AES/DES... The documentation has to be written somewhat forcefully to tell users what not to do. I can help with that. I've had to do that a lot, supporting crypto packages in projects where the other programmers haven't used crypto very much. From phr at localhost.localdomain Tue Jan 25 22:43:49 2005 From: phr at localhost.localdomain (phr at localhost.localdomain) Date: Wed, 26 Jan 2005 03:43:49 GMT Subject: Crypto in Python: (Was: What's so funny? WAS Re: rotor replacement) References: Message-ID: "Philippe C. Martin" writes: > So far getting the agreement for my product has taken two months of work > (http://www.bis.doc.gov/encryption/) .... I hope to get a positive > response this week (wish me luck!) That sounds like you're doing a closed source product and need an ENC exception or something even worse. Python should qualify for the TSU exception which only requires sending an email. http://www.bxa.doc.gov/encryption/PubAvailEncSourceCodeNofify.html From bokr at oz.net Tue Jan 18 08:00:49 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 18 Jan 2005 13:00:49 GMT Subject: List problems in C code ported to Python References: Message-ID: <41ecf382.1170252313@news.oz.net> On Mon, 17 Jan 2005 15:28:56 GMT, Lucas Raab wrote: >Lucas Raab wrote: >> I'm done porting the C code, but now when running the script I >> continually run into problems with lists. I tried appending and >> extending the lists, but with no avail. Any help is much appreciated >> Please see both the Python and C code at >> http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py >> >> TIA > >OK, here's the Python code and the corresponding C code: > >def init_mach(): > import string > #setup rotor data > i=1 > j=0 > for j in j<26, j+1: I urge you to explore interactively. And do it line by line (and even expression by expression when you get mystifying results) until you are more familiar with the language. E.g., what do you think the values of j will be here? >>> j=0 >>> for j in j<26, j+1: print j, ... True 1 Surprised? >>> j<26, j+1 (True, 2) Hm, surprised at the 2 here? >>> j=0 >>> j<26, j+1 (True, 1) IOW, your 'for' line was equivalent to iterating through a length-2 tuple for j in (True, 1): # since if j is 0, j<26 is True, and j+1 is 1 What you probably wanted was j starting with 0 and ending with 25, which you get by >>> for j in xrange(26): print j, ... 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 (The comma at the end of the print statement is to get a space before the next output instead of a newline). > data[4],[j] = (ref_rotor[j] - 'A'+26) % 26 Had you tried an interactive experiment, you would have had some real questions to ask ;-) >>> j=0 >>> for j in xrange(26): ... data[4],[j] = (ref_rotor[j] - 'A'+26) % 26 ... Traceback (most recent call last): File "", line 2, in ? NameError: name 'ref_rotor' is not defined Ok, fix that with something >>> ref_rotor = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # something legal >>> j=0 >>> for j in xrange(26): ... data[4],[j] = (ref_rotor[j] - 'A'+26) % 26 ... Traceback (most recent call last): File "", line 2, in ? TypeError: unsupported operand type(s) for -: 'str' and 'str' You might have had to ask at this point what that meant, but you could get closer by trying the expressions and their terms: >>> (ref_rotor[j] - 'A'+26) % 26 Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for -: 'str' and 'str' Pare it down >>> (ref_rotor[j] - 'A'+26) Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for -: 'str' and 'str' Check pieces >>> j 0 >>> ref_rotor[j] 'A' Substitute to make painfully clear >>> ('A' - 'A'+26) Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for -: 'str' and 'str' >>> ('A' - 'A') Traceback (most recent call last): File "", line 1, in ? TypeError: unsupported operand type(s) for -: 'str' and 'str' What is 'A' ? >>> type('A') Hm, characters are strings, not char types that are directly type compatible with int. It takes a conversion. To get from single-char string to its integer code and back: >>> ord('A') 65 >>> chr(65) 'A' Another experiment: >>> ord('AB') Traceback (most recent call last): File "", line 1, in ? TypeError: ord() expected a character, but string of length 2 found Now you are in a position to use ord, and get a little further: >>> j=0 >>> for j in xrange(26): ... data[4],[j] = (ord(ref_rotor[j]) - ord('A')+26) % 26 ... Traceback (most recent call last): File "", line 2, in ? TypeError: unpack non-sequence Was the right hand side a problem? >>> j 0 >>> (ord(ref_rotor[j]) - ord('A')+26) % 26 0 Apparently not, so what it was trying to do was >>> data[4],[j] = 0 Traceback (most recent call last): File "", line 1, in ? TypeError: unpack non-sequence What was it trying to unpack? And why? Well, you might have known if you had been through the tutorial, but at least you would have had a specific question about a specific error at this point. Note: >>> a, b = 0 Traceback (most recent call last): File "", line 1, in ? TypeError: unpack non-sequence I.e., when you have commas (or even one) on the left hand side of an assignment, that is asking python to unpack a sequence on the right hand side and assign to corresponding items on the left. So e.g., >>> a, b = 0, 1 will unpack the tuple formed by 0, 1 >>> a 0 >>> b 1 You can unpack any sequence of the same length, and strings happen to be sequences: >>> a,b = 'XY' >>> a 'X' >>> b 'Y' Ok, enough of that. The comma was obviously a problem so, try it without: >>> data[4][j] = 0 Traceback (most recent call last): File "", line 1, in ? NameError: name 'data' is not defined I could go on, but IMO if you expect help, you should do your part, and at least post code that you have tried and which compiles or runs up to the point where it shows an error that you need help with. And show a verbatim copy/paste from your interactive session, not uncompilable and obviously totally untested stuff. > > for i in i<4, i+1: > step[i-1] = step_data[order[i-1]] > for j in j<26, j+1: > data[i],[j] = (rotor[order[i-1]],[j]-'A'+26)%26 > data[8-i],[data[i],[j]] = j > > >void >init_mach( void ) >{ > int i, j; > int ds; > int u, v; > > /* setup rotor data */ > for (j=0;j<26;j++) > data[4][j] = ((int)ref_rotor[j]-'A'+26)%26; > > for (i=1;i<4;i++) > { > step[i-1] = step_data[order[i-1]]; > for (j=0;j<26;j++) > { > data[i][j] = ((int)(rotor[order[i-1]][j])-'A' + 26) % 26; > data[8-i][data[i][j]] = j; > } > } > >Now, do I need to start boning up on lists and how to use them or am I >missing the bigger picture?? Again, for the complete code see >http://home.earthlink.net/~lvraab. I'm not asking you to do it for me, >just some pointers on going about this. You are obviously not yet familiar with python, but a few hours with the introduction and tutorials should help a lot. Then post something that compiles. Or a snippet that does something you don't understand. This is about all I have patience for this time. I really have other stuff to do. Regards, Bengt Richter From craig at postnewspapers.com.au Thu Jan 13 14:45:27 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 14 Jan 2005 03:45:27 +0800 Subject: counting items In-Reply-To: References: Message-ID: <1105645527.4001.5.camel@albert.localnet> On Wed, 2005-01-12 at 20:10 +0100, Bernhard Herzog wrote: > "It's me" writes: > > > May be flatten should be build into the language somehow.... > > That shouldn't be necessary as it can easily be written in a single list > comprehension: > > a = [[1,2,4],4,5,[2,3]] > flat_a = [x for cur, rest in [[a[:1], a[1:]]] for x in cur > if (not isinstance(x, (list, tuple)) > and (not rest or not cur.append(rest.pop(0))) > or (x and (cur.append(x[0]) or rest.__setslice__(0, 0, x[1:]))) > or (not x and rest and cur.append(rest.pop(0))))] > > ;-) If it means I _never_ have to see that list comprehension again, then seeing 'flatten' go into itertools would make me very, very happy :-P -- Craig Ringer From kraus at hagen-partner.de Mon Jan 10 04:18:34 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Mon, 10 Jan 2005 10:18:34 +0100 Subject: SuSE 9.1: updating to python-2.4 In-Reply-To: References: Message-ID: Heyho! Torsten Mohr wrote: > Hi, > > along with my distribution SuSE 9.1 came python 2.3.3. > > I'd like to update to 2.4 now, is this an easy thing to do or will > lots of installed modules refuse to work then? I installed Python 2.4 under SuSE 9.1 and had no problems so far. If you install it via "./configure;make;make install", python 2.4 will be installed in /usr/local/lib/python2.4 parallel to your existing 2.3 installation under /usr/lib/python2.3. > Is there an easy way to find out what i need to update? Just check out, which version comes up when you call "python" from the shell. If this is version 2.3 you can start 2.4 with "python2.4" All the installed packages for python2.3 (e.g. PIL, MySQLdb, wxPython, ...) need to be installed for the new version, too. > > Thanks for any hints, Torsten. HTH, Wolfram From michele.simionato at gmail.com Thu Jan 27 09:18:30 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 27 Jan 2005 06:18:30 -0800 Subject: python without OO In-Reply-To: <1106834280.360742.116380@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> <1106694083.199064.240680@f14g2000cwb.googlegroups.com> <1106814263.835719.181360@z14g2000cwz.googlegroups.com> <1106826024.655143.227050@c13g2000cwb.googlegroups.com> <1106834280.360742.116380@c13g2000cwb.googlegroups.com> Message-ID: <1106835510.378060.207950@c13g2000cwb.googlegroups.com> > "Perfection is achieved, not when there is nothing more to add, but > when there is nothing left to take away." Thanks, that was it! ;) From foo at bar.com Sun Jan 23 01:13:01 2005 From: foo at bar.com (Steve Menard) Date: Sun, 23 Jan 2005 01:13:01 -0500 Subject: embedding jython in CPython... In-Reply-To: References: Message-ID: Jim Hargrave wrote: > Sorry - should have given more detail. That's what I get for posting at > 1:00AM. > > What I want to do us write scripts in CPython that access Windows > ActiveX such as Word and IE. Obviously Jython can't do this (easily at > least). I also have Jython scripts that provide a high level layer on > top of various Java libraries. I'd like to write as much code in Python > as possible. But I have a mixture of incompatible CPython and Jython > scripts - that's why I would like to embed Jython in CPython. If I can > call my Jython scripts from CPython I can have the best of both world's! > > Would I be able to embed Jython using JPype? The PyLucene approach > (compile Java source with GCJ then wrap with SWIG) looks interesting - > but complicated. > > Here's an example of embedding Jython in a regular Java app: > http://www.jython.org/docs/embedding.html > > Imagine doing the same in CPython, but with JPype or GCJ/SWIG. > > > Certainly! As far as JPype is concerned though, Jython is just another library. What I mean is, the API to lauch your Jython scripts will be identical JPype as though coded in Java. There will be no "magic" to bridge CPython and Jython. The obvious advantage of going that way though, instead of the GCJ approach, is that you keep the full dynamicity of Jython. I am curious to know what makes your Jython code incompatible with CPython. If it is only because it uses Java classes, it might not be too difficult to port them to CPython+Jpype. Let me know if you need any help. -- Steve Menard -------------------- Maintainer of http://jpype.sourceforge.net From tjreedy at udel.edu Fri Jan 28 14:41:16 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Jan 2005 14:41:16 -0500 Subject: Dynamic class methods misunderstanding References: <1106928492.114459.191320@c13g2000cwb.googlegroups.com> Message-ID: "Kamilche" wrote in message news:1106928492.114459.191320 at c13g2000cwb.googlegroups.com... >I see what you're attempting to do. However, your code, if it DID run, > would result in a method being added to the object, not the object's > class! Modify the class itself, not the object, as follows: > > |class Test: > | def __init__(self): > | self.method() > | > |def m(self): > | print self > | > |setattr(Test, 'method', m) # this is a longwinded way to say Test.method = m setattr is for when you do *not* know the attribute name at coding time but will have it in a string at run time, as in methodname = 'method' ......# some time later setattr(Test, methodname, m) Sometime Python makes things easier than people are initially willing to believe ;-) > |Test() Terry J. Reedy From jriveramerla at yahoo.com Tue Jan 25 19:12:53 2005 From: jriveramerla at yahoo.com (Jose Rivera) Date: 25 Jan 2005 16:12:53 -0800 Subject: Is thera a Metakit for Python 2.4 release ?? Message-ID: <11e94203.0501251612.201f7d4d@posting.google.com> Hi Do you know where I can find the Mk4py.dll for Python24 ?. Thanks From donn at drizzle.com Sat Jan 8 12:06:34 2005 From: donn at drizzle.com (Donn Cave) Date: 8 Jan 2005 11:06:34 -0600 Subject: "A Fundamental Turn Toward Concurrency in Software" References: <20050108154453.32125.797079096.divmod.quotient.2429@ohm> Message-ID: <41e0131a$1_3@127.0.0.1> Quoth Skip Montanaro : | | Jp> How often do you run 4 processes that are all bottlenecked on CPU? | | In scientific computing I suspect this happens rather frequently. I think he was trying to say more or less the same thing - responding to "(IBM mainframes) ... All those systems ran multiple programs ... My current system has 42 processes running ...", his point was that however many processes on your desktop, on the rare occasion that your CPU is pegged, it will be 1 process. The process structure of a system workload doesn't make it naturally take advantage of SMP. So "there will still need to be language innovations" etc. -- to accommodate scientific computing or whatever. Your 4 processes are most likely not a natural architecture for the task at hand, but rather a complication introduced specifically to exploit SMP. Personally I wouldn't care to predict anything here. For all I know, someday we may decide that we need cooler and more efficient computers more than we need faster ones. Donn Cave, donn at drizzle.com From aleaxit at yahoo.com Sat Jan 22 03:50:36 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 09:50:36 +0100 Subject: list unpack trick? References: Message-ID: <1gqsalx.4ip95k18168r0N%aleaxit@yahoo.com> Fredrik Lundh wrote: ... > or (readable): > > if len(list) < n: > list.extend((n - len(list)) * [item]) I find it just as readable without the redundant if guard -- just: alist.extend((n - len(alist)) * [item]) of course, this guard-less version depends on N*[x] being the empty list when N<=0, but AFAIK that's always been the case in Python (and has always struck me as a nicely intuitive semantics for that * operator). itertools-lovers may prefer: alist.extend(itertools.repeat(item, n-len(alist))) a bit less concise but nice in its own way (itertools.repeat gives an empty iterator when its 2nd argument is <=0, of course). Alex From mwm at mired.org Sat Jan 1 15:35:09 2005 From: mwm at mired.org (Mike Meyer) Date: Sat, 01 Jan 2005 14:35:09 -0600 Subject: Looping using iterators with fractional values References: <1104609929.888351.8870@c13g2000cwb.googlegroups.com> Message-ID: <86is6gripu.fsf@guru.mired.org> "drife" writes: > Hello, > > Making the transition from Perl to Python, and have a > question about constructing a loop that uses an iterator > of type float. How does one do this in Python? > > In Perl this construct quite easy: > > for (my $i=0.25; $i<=2.25; $i+=0.25) { > printf "%9.2f\n", $i; > } Generally, you don't loop incrementing floating point values, as you're liable to be be surprised. This case will work as you expect because .25 can be represented exactly, but that's not always the case. Python loops are designed to iterate over things, not as syntactic sugar for while. So you can either do the while loop directly: i = 0.25 while i <= 2.25: print "%9.2f" % i i += 0.25 Or - and much safer when dealing with floating point numbers - iterate over integers and generate your float values: for j in range(1, 9): i = j * .25 print "%9.2f" % i http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From __peter__ at web.de Mon Jan 17 14:02:45 2005 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Jan 2005 20:02:45 +0100 Subject: Assigning to self References: Message-ID: Frans Englich wrote: > What the code attempts to do is implementing a, to the API user, > transparent memory-saver by ensuring that no more than one instance of the > class foo exists for a particular id. E.g, the user can simply "create" an > instance and if one not already exists, it is created. By the time __init__() is called, a new Foo instance has already been created. Therefore you need to implement Foo.__new__(). E. g.: >>> class Foo(object): ... cache = {} ... def __new__(cls, id): ... try: ... return cls.cache[id] ... except KeyError: ... pass ... cls.cache[id] = result = object.__new__(cls, id) ... return result ... def __init__(self, id): ... self.id = id ... def __repr__(self): ... return "Foo(id=%r)" % self.id ... >>> foos = map(Foo, "abca") >>> foos [Foo(id='a'), Foo(id='b'), Foo(id='c'), Foo(id='a')] >>> foos[0] is foos[-1] True >>> Foo.cache {'a': Foo(id='a'), 'c': Foo(id='c'), 'b': Foo(id='b')} Note that putting the instances into the cache prevents them from being garbage collected -- you may even end up with higher memory usage. Use a weakref.WeakValueDictionary instead of the normal dict to fix that. Peter From peter at engcorp.com Sun Jan 2 22:20:51 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 02 Jan 2005 22:20:51 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <1104620491.542938.92100@z14g2000cwz.googlegroups.com> <7xsm5kfyse.fsf@ruckus.brouhaha.com> <41d7941f$1_3@127.0.0.1> <7x8y7cjo57.fsf@ruckus.brouhaha.com> <87zmzsax12.fsf@hector.domek> <87pt0na5zf.fsf@hector.domek> <87llbba55t.fsf@hector.domek> Message-ID: Roy Smith wrote: > "Terry Reedy" wrote: > >>None has been reserved because there is no known good use for overriding >>it. > > Should I infer from the above that there's a known bad use? Yes: making None equal to the integer 3. That's one of six known bad uses.... it's possible there are more. ;-) -Peter From jlenton at gmail.com Wed Jan 12 15:09:20 2005 From: jlenton at gmail.com (John Lenton) Date: 12 Jan 2005 12:09:20 -0800 Subject: Iteration over two sequences In-Reply-To: <1gq9z5q.1x7si1us4kgmcN%news+0409@henrikholm.com> References: <1gq9qs9.3snutr1s4mcn2N%news+0409@henrikholm.com> <1105549514.563799.307030@z14g2000cwz.googlegroups.com> <1gq9z5q.1x7si1us4kgmcN%news+0409@henrikholm.com> Message-ID: <1105560560.837493.229310@f14g2000cwb.googlegroups.com> > Downloading, installing, and getting to know numerical modules for > Python is mext on my list :). However, I was under the impression that > Numarray is preferred to Numeric -- is that correct? Are these two > competing packages? (Hopefully this is not flame war bait...) Numeric's dot uses, if the appropriate libraries are installed, processor-tuned code (it tries to load blas, and an attempt to load blas will load atlas if present). Last time I checked numarray did not, and so Numeric's dot is (or was) faster than numarray's dot by an order of magnitude (and more, as the size of the array grew). From adam.vandenberg at gmail.com Thu Jan 27 02:31:01 2005 From: adam.vandenberg at gmail.com (adam.vandenberg at gmail.com) Date: 26 Jan 2005 23:31:01 -0800 Subject: how to ncurses on win32 platform In-Reply-To: References: <3nkds3kzc9mp.18yfed1y3vo9d$.dlg@40tude.net> Message-ID: <1106811061.802365.276930@c13g2000cwb.googlegroups.com> > * Curses for Windows for Python (It was previously > mentioned on a follow-up. there are some missing > features): > http://flangy.com/dev/python/curses/ I've posted an update to this module (better color support, half delay input, some other stuff) and the source code, in case anyone wants to try it on Python 2.4 or tinker with it. From http Fri Jan 7 07:41:54 2005 From: http (Paul Rubin) Date: 07 Jan 2005 04:41:54 -0800 Subject: Securing a future for anonymous functions in Python References: <1105098890.358721.279550@f14g2000cwb.googlegroups.com> <7xis6930ah.fsf@ruckus.brouhaha.com> Message-ID: <7xpt0hjtrh.fsf@ruckus.brouhaha.com> Steve Holden writes: > Perhaps what we really need is a good Lisp subsystem for Python? I've thought the other way around, it would be nice to have a Python subsystem for Lisp. From peter at engcorp.com Thu Jan 6 16:13:28 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 06 Jan 2005 16:13:28 -0500 Subject: File Handling Problems Python I/O In-Reply-To: <1105034402.428393.283930@c13g2000cwb.googlegroups.com> References: <1105025341.708019.126030@f14g2000cwb.googlegroups.com> <1105034402.428393.283930@c13g2000cwb.googlegroups.com> Message-ID: Josh wrote: > He is the function where I am making the call. If I change the open > statment to another file, say "c:\test.txt", a file I know exists, it > will error out stating the file does not exist. Thanks > > def GetStartVars(self): > try: > DOWNFILE = open("c:\fixes.txt","r") Josh, it's surprising that this example worked for you, given that \f is another string escape (in this case it's an ASCII FF (formfeed), character code 12, instead of the TAB (code 8) character that c:\test.txt gives you. Are you sure this was one of the names that worked? BTW, the following link in the docs provides a list of all the recognized escape sequences: http://www.python.org/doc/current/ref/strings.html -Peter From hanchunhui at gmail.com Thu Jan 20 19:53:22 2005 From: hanchunhui at gmail.com (neutrino) Date: 20 Jan 2005 16:53:22 -0800 Subject: Print a string in binary format Message-ID: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> Greetings to the Python gurus, I have a binary file and wish to see the "raw" content of it. So I open it in binary mode, and read one byte at a time to a variable, which will be of the string type. Now the problem is how to print the binary format of that charater to the standard output. It seems a common task but I just cannot find the appropriate method from the documentation. Thanks a lot. From bokr at oz.net Thu Jan 6 14:43:30 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 06 Jan 2005 19:43:30 GMT Subject: Building unique comma-delimited list? References: Message-ID: <41dd9130.162042474@news.oz.net> On 5 Jan 2005 17:05:40 -0500, roy at panix.com (Roy Smith) wrote: >I've got a silly little problem that I'm solving in C++, but I got to >thinking about how much easier it would be in Python. Here's the >problem: > >You've got a list of words (actually, they're found by searching a >data structure on the fly, but for now let's assume you've got them as >a list). You need to create a comma-delimited list of these words. >There might be duplicates in the original list, which you want to >eliminate in the final list. You don't care what order they're in, >except that there is a distinguised word which must come first if it >appears at all. > >Some examples ("foo" is the distinguised word): > >["foo"] => "foo" >["foo", "bar"] => "foo, bar" >["bar", "foo"] => "foo, bar" >["bar", "foo", "foo", "baz", "bar"] => "foo, bar, baz" or "foo, baz, bar" > >The best I've come up with is the following. Can anybody think of a >simplier way? > (Not tested beyond what you see ;-) python 2.4: >>> words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"] >>> w2 = list(t[1] for t in sorted((w!='foo', w) for w in set(words))) >>> w2 ['foo', 'bar', 'baz'] Gets you a sort in the bargain ;-) >-------------------- >words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"] > ># Eliminate the duplicates; probably use set() in Python 2.4 Yup, but 2.3 can be a one-liner too: >>> words = ["foo", "bar", "baz", "foo", "bar", "foo", "baz"] >>> w2 = ('foo' in words and ['foo'] or []) + [w for w in dict(zip(words,words)) if w!='foo'] >>> w2 ['foo', 'baz', 'bar'] Not sorted, but foo is out front. >d = dict() >for w in words: > d[w] = w > >if d.has_key ("foo"): > newWords = ["foo"] > del (d["foo"]) >else: > newWords = [] > >for w in d.keys(): > newWords.append (w) > >s = ', '.join (newWords) >print s >-------------------- Regards, Bengt Richter From maxm at mxm.dk Sun Jan 2 22:03:16 2005 From: maxm at mxm.dk (Max M) Date: Mon, 03 Jan 2005 04:03:16 +0100 Subject: Calling Function Without Parentheses! In-Reply-To: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> References: <1104715584.407505.190910@f14g2000cwb.googlegroups.com> Message-ID: <41D8B5F4.1010903@mxm.dk> Kamilche wrote: > What a debug nightmare! I just spent HOURS running my script through > the debugger, sprinkling in log statements, and the like, tracking down > my problem. > > I called a function without the ending parentheses. I sure do WISH > Python would trap it when I try to do the following: > MyFunc Actually you want use a method as an ordinary variable without calling it in many cases. It is often used in a dynamic language. A simple example is: result = [] a = result.append if something: a('some result') elif something_else: a('another result') else: a('default result') -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From anand at esi-india.com Fri Jan 7 07:00:58 2005 From: anand at esi-india.com (Anand K Rayudu) Date: Fri, 07 Jan 2005 17:30:58 +0530 Subject: Python C Object Comparison In-Reply-To: <1105076609.28776.56.camel@rasputin.localnet> References: <41DD1428.1030503@esi-india.com> <1105076609.28776.56.camel@rasputin.localnet> Message-ID: <41DE79FA.7070905@esi-india.com> Dear Craig, Thanks a lot for the suggestions. I am just considering to create a user defined data type to wrap the C pointer. I can add compare method for that data type. So all my APIs returns the new data type rather than PythonC Object. But hoping that it is not lot of over head with respect to memory usage and performance . I guess that's what you suggested me!! Probably any way to add my own comparison function to pythonC object will be simpler for me, as it calls for very less change, with out disturbing my existing C APIS and python customization code. Thanks again for the suggestion Regards, Anand Craig Ringer wrote: >On Thu, 2005-01-06 at 18:34, Anand K Rayudu wrote: > > > >>Here is my python code >> >>import myModule >> >>a=myModule.myAPI1("1") >>b=myModule.myAPI2("name") >> >># basically both above functions return same C pointer. >># so i want to compare >>if(a==b): print "They are same" >>else : print "They are different" >> >>python always prints they are different, >>I guess this is because in python layer we create PythonCObject for >>every C pointer, and that is how it is exposed to python. Though both >>the APIs are returning the same C pointer, they are different instances >>of PythonCObject. >> >> > >That sounds likely to me. > > > >>So i guess that is the reason comparison is failing. >>How ever is it possible to make python to compare actual C pointer, >>rather than the PythonCObject Pointer. >> >> > >You might be able to subclass PyCObject and work with your subclassed >version (that adds a __eq__ method). In the end, though, I don't think >that's the right path to proceed down. > >My understanding is that CObjects are for passing pointers through >Python code in a safe way. I don't think they're really intended for >uses where the Python code is actually working with the objects, only >pass them around as opaque objects. > >If you want to actually work with the objects you're passing around, I'd >think about implementing my own type that better fits the API my >extension module wants to present to Python code. > >I'm using PyCObjects as a temporary ugly hack in an embedded app I'm >working on... but it's seriously ugly. What I should do, and will soon >do now that I've tested the concept of what I'm doing and it works, is >move all my functions into a class and make the class own and manage the >C++ object (and pointer to it) that it owns. > >Perhaps that's a better solution for you too? > >If you want any opinions from folks here about the best way to solve >your problem, you'll probably need to explain a bit more of your problem >- like what your extension module is doing that makes it have to pass >PyCObjects around and get Python code to work with them. > >-- >Craig Ringer > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From philippecmartin at sbcglobal.net Tue Jan 18 07:23:16 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Tue, 18 Jan 2005 13:23:16 +0100 Subject: how to find site-packages path (Michael Hoffman) - use distutils Message-ID: <1106050997.6665.30.camel@localhost> I actually target Unix and windows so pyexe won't cut it I'm afraid - same issue with Inno. As far as the site-package target, I don't fully understand your relunctancy. Just as my potential users might not own a compiler, they might not be computer proficient enough to easily understand how to change the sys.path. So until I have found a clean cross platform solution I'm going to have to stick to site-packages. Best regards, Philippe -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From grahamd at dscpl.com.au Thu Jan 13 23:52:20 2005 From: grahamd at dscpl.com.au (grahamd at dscpl.com.au) Date: 13 Jan 2005 20:52:20 -0800 Subject: a ConfigParser wtf moment In-Reply-To: References: <1105675916.355620.324340@f14g2000cwb.googlegroups.com> Message-ID: <1105678340.056231.29430@c13g2000cwb.googlegroups.com> True, wasn't thinking. This will affect get() as well. My problem was a slightly different problem. In your case you would have got what you wanted if get()/items() instead of being implemented as: . try: . value = d[option] . except KeyError: . raise NoOptionError(option, section) Was implemented as: . try: . value = self._sections[section][option] . except KeyError: . raise NoOptionError(option, section) That is, get the raw value from the original dictionary for the section. That way you avoid picking up a value from the user supplied vars. It does also avoid picking a key which has come through from the default section, but that could easily be accomodated if that was perceived to be expected behaviour by having the except clause fall through to looking in the default section. Similarly if seen that getting it from vars is okay as well, fall back onto that as file step. All depends on what the perceived overridding priority is. At the moment vars overrides section which overrides default and the document sort of does say that that is what one should expect for vars at least: . Additional substitutions may be provided using the . `vars' argument, which must be a dictionary whose contents overrides . any pre-existing defaults. Probably not what I would have expected either. I would have expected vars to be available for substitution but not for option selection in the first place. It is too late on a Friday, so I may be hallucinating now. :-) From tdelaney at avaya.com Wed Jan 26 21:52:21 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Thu, 27 Jan 2005 13:52:21 +1100 Subject: Which is faster? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE025202E2@au3010avexu1.global.avaya.com> Aggelos I. Orfanakos wrote: > Any idea which of the following is faster? > > 'a/b/c/'[:-1] > > or > > 'a/b/c/'.rstrip('/') > > Thanks in advance. > > P.S. I could time it but I thought of trying my luck here first, in > case someone knows already, and of course the reason. First, it almost certainly doesn't matter. Use the one that is self-documenting. Secondly, time it yourself. It's incredibly easy. There's a module written especially for doing this - and surprise surprise, it's called "timeit.py" and it's in the /Lib directory. Tim Delaney From tchur at optushome.com.au Mon Jan 10 15:27:42 2005 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 11 Jan 2005 07:27:42 +1100 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 9) In-Reply-To: References: Message-ID: <41E2E53E.3030107@optushome.com.au> Josiah Carlson wrote: > QOTW: Jim Fulton: "[What's] duck typing?" > Andrew Koenig: "That's the Australian pronunciation of 'duct taping'." I must protest. 1) No (true-blue) Australian has every uttered the words 'duct taping', because Aussies (and Pommies) know that the universe is held together with gaffer tape, not duct tape. See http://www.exposure.co.uk/eejit/gaffer/ b) If an Australian were ever induced to utter the words 'duct typing', the typical Strine (see http://www.geocities.com/jendi2_2000/strine1.html ) pronunciation would be more like 'duh toypn' - the underlying principle being one of elimination of all unnecessary syllables, vowels and consonants, thus eliminating the need to move the lips (which reduces effort and stops flies getting in). Tim C Sydney, Australia From mercuryprey at gmail.com Sun Jan 30 19:43:26 2005 From: mercuryprey at gmail.com (mercuryprey at gmail.com) Date: 30 Jan 2005 16:43:26 -0800 Subject: Problem with loading textfiles into dictionaries. Message-ID: <1107132206.446722.21720@f14g2000cwb.googlegroups.com> Hello, I want to do the following: def do_load(self, arg): sitefile = file('sitelist', 'r+', 1) while True: siteline = sitefile.readline() site_rawlist = siteline.split() sitelist[site_rawlist[0]] = site_rawlist[1:] if len(siteline) == 0: break I want to load a textfile into a dictionaries and use the first word on a line as the key for the list, then take the remaining words of the line and make them values of the key. This doesn't work: File "ftp.py", line 57, in do_load sitelist[site_rawlist[0]] = site_rawlist[1:] IndexError: list index out of range However, it works flawlessy in another function, where I have: def do_add(self, arg): sitefile = file('sitelist', 'r+', 1) act_addlist = arg.split() sitelist[act_addlist[0]] = act_addlist[1:] sitefile.seek(0,2) sitefile.write(arg + "\n") print "Written to database." Anyone knows why it doesn't work in the first function? Help very much appreciated. munin From invalidemail at aerojockey.com Mon Jan 24 22:46:43 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 24 Jan 2005 19:46:43 -0800 Subject: Another scripting language implemented into Python itself? References: Message-ID: <1106624803.825442.73870@f14g2000cwb.googlegroups.com> Roy Smith wrote: > Rocco Moretti wrote: > > The OP doesn't mention his application, but there is something to be > > said about domain specific scripting languages. A well designed > > domain-specific scripting language(*) with the appropriate high level > > constructs can make script writing simpler. > > This is a bit of a sore point with me. > > I've been involved with several projects where people felt the need to > invent their own scripting languages. It usually starts with "we don't > need the power of a full programming language, we only need to be able > to do X, Y, and Z". So they write a little language which lets them do > X, Y, and Z. > > Then they discover they need more complex data structures than they > originally thought. And nested loops. And functions. And more > sophisticated variable scoping rules. And a regex library. And 47 > other things. So they duct-tape all those into the system. Not only is it short-sighted, I would say it is quite arrogant to believe you can anticipate every possible use of this script you're going to impliement, and can safely hold back essential language features. > Anyway, that's my little rant on inventing your own scripting language. > Imbed EMBED. This spelling error wouldn't bother me if I didn't work with people whose own job title is embedded control engineer, yet who still misspell it "imbedded." > Python, or Perl, or TCL, or Ruby, or PHP, Not PHP. PHP is one of the better (meaning less terrible) examples of what happens when you do this sort of thing, which is not saying a lot. PHP was originally not much more than a template engine with some crude operations and decision-making ability. Only its restricted problem domain has saved it from the junkheap where it belongs. TCL isn't that great in this regard, either, as it makes a lot of common operations that ought to be very simple terribly unweildy. > or Java, or whatever > floats your boat. Almost any choice has got to be better than rolling > your own. Invest your intellectual capital doing what you can do best, > and don't get bogged down developing a new language. You're right. I use a custom, domain-specific language in my work. Whenever I use it, all I can think of is how much better this POS would be if they had just extended Python (probably would even be faster). At least they were smart enough to (try to) make it into a complete programming language. -- CARL BANKS From asda at sdarta.com Wed Jan 5 08:30:40 2005 From: asda at sdarta.com (worzel) Date: Wed, 5 Jan 2005 21:30:40 +0800 Subject: is python more popular than coldfusion? References: <41dbd699$0$23092$5a62ac22@per-qv1-newsreader-01.iinet.net.au><41dbe722$0$23057$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <41dbec00$0$23064$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Wth respect to coldfusion, is there much doubt about the fact that Python is a more prominent and important technology? How is colfusion percieved by the Python community? Many people belive coldfusion is becomeing irrelavant and is on its death bed - do Python folk generally feel this way about it? Thanks for your input on this by the way. "Premshree Pillai" wrote in message news:mailman.192.1104931284.22381.python-list at python.org... > On Wed, 5 Jan 2005 21:09:54 +0800, worzel wrote: >> How seriuosly do folk take the TIOBE index? Is it a good way to ague what >> you should be keeping up to speed with or just a 'vague' guide? > > I use the TIOBE index -- sometimes -- when I give presentations on > Python (and Ruby) to people who haven't heard of the languages. > > The index is not something to be relied upon (take a look at the > calculation mechanism). However, more often than not, the indices > seems to reflect what *I* perceive the indices are in reality. So I > kinda use them. > > The thing about introducing a "new" language to a bunch of folks used > to their "favorite" language is that they wouldn't care much for a > language it isn't popular, or if it isn't "growing in popularity". > > Beyond these things, I don't think anybody uses the index. I mean I > wouldn't tell people to learn languages that hold the top position on > TIOBE ;). > >> >> "Premshree Pillai" wrote in message >> news:mailman.189.1104927428.22381.python-list at python.org... >> > On Wed, 5 Jan 2005 19:59:21 +0800, worzel wrote: >> >> >> >> >> >> >> >> is python more popular than coldfusion? >> > >> > I don't know if Coldfusion _was_ ever more "popular" than Python, but >> > Python is definitely more "popular" _now_. >> > >> > This might be of some help: http://www.tiobe.com/tpci.htm >> > >> >> >> >> I realsie that is a very general question as one thing does not >> >> directly >> >> relate to the other. My issue is that I am ditching coldfusion due to >> >> there >> >> being next to no work for it, and I am thinking of taking on python as >> >> a >> >> second language to java in the hope of improving my resume. >> >> -- >> >> http://mail.python.org/mailman/listinfo/python-list >> >> >> >> >> > >> > >> > -- >> > Premshree Pillai >> > http://www.livejournal.com/~premshree >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > -- > Premshree Pillai > http://www.livejournal.com/~premshree From aleaxit at yahoo.com Sat Jan 1 17:38:53 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 1 Jan 2005 23:38:53 +0100 Subject: UserDict deprecated References: Message-ID: <1gpqh6l.65jemkskbo5eN%aleaxit@yahoo.com> Uwe Mayer wrote: ... > If I used UserDict I would not need to specify all methods UserDict provides > alreay, anyway. The DictMixin class from the UserDict module is *not* deprecated -- only the UserDict class from the same module. (If you found info saying otherwise pls provide a URL: the info is wrong and I'll try to get it fixed -- thanks!). DictMixin's purpose is exactly as you state: letting you make a complete mapping class out of one which only supplies the very basics, by mix-in inheritance. Alex From dbickett at gmail.com Mon Jan 10 23:57:49 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Mon, 10 Jan 2005 23:57:49 -0500 Subject: shutil.move has a mind of its own Message-ID: <1d6cdae305011020574eb10f94@mail.gmail.com> Hello, I'm writing an application in my pastime that moves files around to achieve various ends -- the specifics aren't particularly important. The shutil module was chosen as the means simply because that is what google and chm searches returned most often. My problem has to do with shutil.move actually putting the files where I ask it to. Citing code wouldn't serve any purpose, because I am using the function in the most straight forward manner, ex: shutil.move( "C:\omg.txt" , "C:\folder\subdir" ) In my script, rather than a file being moved to the desired location, it is, rather, moved to the current working directory (in this case, my desktop -- without any exceptions, mind you). As it happens, the desired locations are system folders (running windows xp, the folders are as follows: C:\WINDOWS, C:\WINDOWS\SYSTEM, C:\WINDOWS\SYSTEM32). To see if this factor was causing the problem, I tried it using the interpreter, and found it to be flawless. My question boils down to this: What factors could possibly cause shutil.move to fail to move a file to the desired location, choosing instead to place it in the cwd (without raising any exceptions)? Thank you for your time, Daniel Bickett P.S. I know I said I didn't need to post code, but I will anyway. You never know :) http://rafb.net/paste/results/FcwlEw86.html From usenet_spam at janc.invalid Sat Jan 15 15:15:48 2005 From: usenet_spam at janc.invalid (JanC) Date: Sat, 15 Jan 2005 20:15:48 GMT Subject: Free NNTP (was Re: how to stop google from messing Python code) References: <1105620098.878376.110250@z14g2000cwz.googlegroups.com> <1105666406.272397.170730@c13g2000cwb.googlegroups.com> <1105704548.146263.229220@f14g2000cwb.googlegroups.com> Message-ID: Aahz schreef: > You also have access to the free netnews server http://news.cis.dfn.de/ That address is now for DFN internal use only. Their public service moved to . -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From tom at dtsam.com Tue Jan 11 12:41:41 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Tue, 11 Jan 2005 11:41:41 -0600 Subject: Windows GUIs from Python References: Message-ID: "Bob Swerdlow" wrote in message news:x3TEd.134387$Uf.15318 at twister.nyroc.rr.com... > Anyone have opinions about whether we will be better off using PythonNet or > wxPython for the GUI layer of our application on Windows? Our code is all > Python and is now running on Mac OS X with PyObjC and Cocoa, which works > very well. Our goal is not necessarily to move to a cross-platform > solution, but rather to create a solid Windows version that looks and feels > like a native application. All the code that interacts with the user is > factored out of our business logic, so it is a matter of find a good > view/controller library and writing a thin glue layer. And, of course, we > want to build it as efficiently and robustly as we can. Everyone has opinions :-) I have settled on wxPython principally because of 1) Linux/Gnome <-> MS Windows portablility of the code. 2) The fact that wxPython follows the look and feel of whatever window themes might be installed in Linux/Gnome or MS Windows. 3) Apps so written have that native "look and feel" and fit right in. Thomas Bartkus From tdelaney at avaya.com Mon Jan 17 01:03:42 2005 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Mon, 17 Jan 2005 17:03:42 +1100 Subject: fefinining % of c'm'y and k Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE025202B1@au3010avexu1.global.avaya.com> moshebg at shamaut.co.il wrote: > hello > i need a program (and pleas shoe me the modol in the softwar) that : > if i have a scaned photo > i want to define out of each poligon color ,as it seems in the photo, > the cmyk > in % (percets) of the color/ > 4 exampl from poligon color orang defin the cmyk in % > like that: (example) > c: 30% > m:56% > y:78% > k: 10% This site will assist you greatly. http://www.catb.org/~esr/faqs/smart-questions.html Tim Delaney From lbates at syscononline.com Wed Jan 19 12:09:42 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 19 Jan 2005 11:09:42 -0600 Subject: Has apparent 2.4b1 bug been fixed? flatten in Lib\compiler\ast.py overloads 'list' name In-Reply-To: <41ede67e.1232456679@news.oz.net> References: <41ede67e.1232456679@news.oz.net> Message-ID: You have name clashing between Python's built in list function and the variable called list that you pass into the function. Change the passed in variable name to something else. Larry Bates Try something like (not tested): def flatten(seq): l = [] for elt in seq: if isinstance(elt, (list, tuple): for elt2 in flatten(elt): l.append(elt2) else: l.append(elt) return l Bengt Richter wrote: > What am I missing? (this is from 2.4b1, so probably it has been fixed?) > > > def flatten(list): > l = [] > for elt in list: > ^^^^--must be expecting list instance or other sequence > t = type(elt) > if t is tuple or t is list: > ^^^^--looks like it expects to refer to the type, not the arg > for elt2 in flatten(elt): > l.append(elt2) > else: > l.append(elt) > return l > > > Regards, > Bengt Richter From ken at perfect-image.com Sat Jan 1 12:44:21 2005 From: ken at perfect-image.com (Ken Godee) Date: Sat, 01 Jan 2005 10:44:21 -0700 Subject: PyQT installation In-Reply-To: <871xd5hzfc.fsf@pobox.com> References: <1104370062.562575.88620@f14g2000cwb.googlegroups.com> <1104417268.153983.71970@z14g2000cwz.googlegroups.com> <8SVAd.64014$Jk5.26087@lakeread01> <1gpo9ow.7zqmxi1rwc564N%aleaxit@yahoo.com> <871xd5hzfc.fsf@pobox.com> Message-ID: <41D6E175.70600@perfect-image.com> John J. Lee wrote: > aleaxit at yahoo.com (Alex Martelli) writes: > [...] > >>Basically: if you want it on Windows for free, forget Qt > > > Correct. > I believe the book "C++ GUI programming Qt3" comes with a windows Qt gpl 3.x version. Just have to buy the book. No PyQt version to match thou. Blackadder from the Kompany, while not free, is still a pretty good deal. Like < $100 for personal and around $350 for commercial version. Include current windows/linux versions of (Qt)PyQt along with converted Qt C++ to PyQt docs. > Not correct. It's driven by KDE, and it's more ambitious than that: > > http://kde-cygwin.sourceforge.net/qt3-win32/roadmap.php > > > IIRC, people have already run some KDE apps under Windows (though > still needing X, so far). > > I wonder how TrollTech will react as (and if) it progresses. > I don't think your giving TrollTech any credit here, yes they have a business model and need to make money, but not everybody is Microsoft. They are fully aware and supportive of the project and I remember reading not to long ago they struck an aggrement with the project that if anything ever happened to TrollTech they would release Qt to project under gpl, or something like that. From irmen at -nospam-remove-this-xs4all.nl Mon Jan 3 14:52:23 2005 From: irmen at -nospam-remove-this-xs4all.nl (Irmen de Jong) Date: Mon, 03 Jan 2005 20:52:23 +0100 Subject: website hosting In-Reply-To: <0501031358025172@news.usenetmonster.com> References: <0501031358025172@news.usenetmonster.com> Message-ID: <41d9a274$0$6217$e4fe514c@news.xs4all.nl> forall2see_2000 at yahoo.com wrote: [some spam] Those people don't even provide python hosting, how lame. (Yes, I know, I shouldn't have clicked the link). From walter at livinglogic.de Tue Jan 4 14:11:10 2005 From: walter at livinglogic.de (=?ISO-8859-1?Q?Walter_D=F6rwald?=) Date: Tue, 04 Jan 2005 20:11:10 +0100 Subject: Unicode universe (was Re: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30)) In-Reply-To: <16858.46886.472080.270031@montanaro.dyndns.org> References: <1104846212.355098.186400@c13g2000cwb.googlegroups.com> <1104849206.111461.70500@c13g2000cwb.googlegroups.com> <16858.46886.472080.270031@montanaro.dyndns.org> Message-ID: <41DAEA4E.1090106@livinglogic.de> Skip Montanaro wrote: > aahz> Here's the stark simple recipe: when you use Unicode, you *MUST* > aahz> switch to a Unicode-centric view of the universe. Therefore you > aahz> encode *FROM* Unicode and you decode *TO* Unicode. Period. It's > aahz> similar to the way floating point contaminates ints. > > That's what I do in my code. Why do Unicode objects have a decode method > then? Because MAL implemented it! >;-> It first encodes in the default encoding and then decodes the result with the specified encoding, so if u is a unicode object u.decode("utf-16") is an abbreviation of u.encode().decode("utf-16") In the same way str has an encode method, so s.encode("utf-16") is an abbreviation of s.decode().encode("utf-16") Bye, Walter D?rwald From just at xs4all.nl Thu Jan 13 07:56:33 2005 From: just at xs4all.nl (Just) Date: Thu, 13 Jan 2005 13:56:33 +0100 Subject: how to stop google from messing Python code References: <1105620098.878376.110250@z14g2000cwz.googlegroups.com> Message-ID: In article <1105620098.878376.110250 at z14g2000cwz.googlegroups.com>, "Xah Lee" wrote: > i'm using groups-beta.google.com to post python code. > > Is there a way to stop google from messing with my format? it seems to > have eaten the spaces in my python code. It does that when you cross-post. Just From jerf at jerf.org Wed Jan 19 20:11:09 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 19 Jan 2005 20:11:09 -0500 Subject: ElementTree cannot parse UTF-8 Unicode? References: <1106150061.169027.7010@c13g2000cwb.googlegroups.com> <1106181323.553028.290370@z14g2000cwz.googlegroups.com> Message-ID: On Wed, 19 Jan 2005 16:35:23 -0800, Erik Bethke wrote: > So it seems to me, that ElementTree is just not expecting to run into the > Korean characters for it is at column 16 that these begin. Am I > formatting the XML properly? You should post the file somewhere on the web. (I wouldn't expect Usenet to transmit it properly.) (Just jumping in to possibly save you a reply cycle.) From fumanchu at amor.org Mon Jan 10 14:36:39 2005 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 10 Jan 2005 11:36:39 -0800 Subject: Uploading files Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398152@exchange.hqamor.amorhq.net> Peter Mott wrote: > If you upload a file using the cgi module is there any > way to discover the file name that the user submitted > as well as the file data? I've googled till I squint > but I can't find anything. Working example (for ASP, which uses BinaryRead to get the request stream): contentLength = int(env['CONTENT_LENGTH']) content, size = request.BinaryRead(contentLength) content = StringIO.StringIO(content) form = cgi.FieldStorage(content, None, "", env, True) content.close() for key in form: value = form[key] try: filename = value.filename except AttributeError: filename = None if filename: # Store filename, filedata as a tuple. self.requestParams[key] = (filename, value.value) else: for subValue in form.getlist(key): self.requestParams[key] = subValue Robert Brewer MIS Amor Ministries fumanchu at amor.org From craig at postnewspapers.com.au Fri Jan 21 17:27:54 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 22 Jan 2005 06:27:54 +0800 Subject: Tuple size and memory allocation for embedded Python In-Reply-To: References: Message-ID: <1106346474.19065.72.camel@bucket.localnet> On Fri, 2005-01-21 at 16:03 -0600, Jinming Xu wrote: > Hi Folks, > > Python seems unstable, when allocating big memory. For example, the > following C++ code creates a tuple of tuples: > > PyObject* arCoord = PyTuple_New(n); > double d = 1.5; > for(int i=0; i { > PyObject* coord = PyTuple_New(2); > PyTuple_SetItem(coord,0, PyFloat_FromDouble(d));//x > PyTuple_SetItem(coord,1, PyFloat_FromDouble(d));//y > PyTuple_SetItem(arCoord,i, coord); > } > > When the n is small, say 100, the code works fine. when n is big, say > 10,000, Python has trouble allocating memory, saying: > > "Exception exceptions.IndexError: 'tuple index out of range' in 'garbage > collection' ignored > Fatal Python error: unexpected exception during garbage collection > Aborted" You're not checking for errors from PyTuple_SetItem. You need to do so, otherwise exceptions will go uncaught and may pop up at weird points later in your software's execution, or crash things. int PyTuple_SetItem( PyObject *p, int pos, PyObject *o) Inserts a reference to object o at position pos of the tuple pointed to by p. It returns 0 on success. Note: This function ``steals'' a reference to o. It returns an int result code, so you should probably be checking it. You CERTAINLY should be ensuring that PyTuple_New() doesn't return NULL (meaning a failure, probably of memory allocation). I also don't see anything in there to resize the tuple. http://docs.python.org/api/tupleObjects.html -- Craig Ringer From grig.gheorghiu at gmail.com Sun Jan 16 20:10:29 2005 From: grig.gheorghiu at gmail.com (Grig Gheorghiu) Date: 16 Jan 2005 17:10:29 -0800 Subject: import problems *newbie* In-Reply-To: <1105919586.453157.42550@c13g2000cwb.googlegroups.com> References: <1105682316.601321.118820@f14g2000cwb.googlegroups.com> <41e7959b$0$385$636a15ce@news.free.fr> <1105919586.453157.42550@c13g2000cwb.googlegroups.com> Message-ID: <1105924229.092194.326610@f14g2000cwb.googlegroups.com> In my experience (as a tester), it is easier to deal with PYTHONPATH than to add the my.pth file to the site-packages directory. The main reason is that I have my custom packages and modules in a directory tree that I deploy on many clients/servers/platforms/OS versions, some running different versions of Python. I found that I solve my import problems by adding one line to .bash_profile, which sets PYTHONPATH to the parent directory of my custom directory tree. Or, on Windows, I add an Environment variable, call it PYTHONPATH, and set it to the necessary directory. The alternative would be to hunt for the site-packages directory (of which there might be several) on all my systems. I guess it's a matter of taste in the end, but I do find the PYTHONPATH approach more suitable for automation and scripting, particularly when dealing with a large number of systems. Grig From apardon at forel.vub.ac.be Tue Jan 18 06:21:38 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Jan 2005 11:21:38 GMT Subject: generator expressions: performance anomaly? References: Message-ID: Op 2005-01-18, Nick Coghlan schreef : > Raymond Hettinger wrote: >> [Delaney, Timothy C] >> >>>Nick's other suggestion - that genexps propagate __len__ - might >>>still be interesting. Of course, it would only be applicable for >>>unconditional genexps(i.e. no if clause). >> >> Length transparency for iterators is not as general as one would expect. I once >> spent a good deal of effort exploring where it made sense, and I was surprised >> to find that it only rarely works out. Length transparency is an unexpectedly >> thorny subject with many dead-ends which precludes a fully general solution such >> as that proposed by Nick. >> >> For a recap of my research, see the docstring for Lib/test/test_iterlen.py . > > """The situation slightly more involved whenever an object allows length > mutation during iteration. """ > > Ouch. Nice understatement. > > It's rather unfortunate that we can't make use of the length information even > when the source *doesn't* mutate, though. I'll have to think some more to see if > I can come up with any concrete ideas for you to shoot down :) Something else I was thinking about. I think it would be nice if the python compilor could figure out whether a genexp in a list or tuple expression always generates the same list or tuple and then instead of generating code would generate the list or tuple in place. -- Antoon Pardon From jfine at pytex.org Mon Jan 24 16:11:14 2005 From: jfine at pytex.org (Jonathan Fine) Date: Mon, 24 Jan 2005 21:11:14 +0000 Subject: best way to do a series of regexp checks with groups References: Message-ID: <41F56472.50305@pytex.org> Mark Fanty wrote: > In perl, I might do (made up example just to illustrate the point): > > if(/add (\d+) (\d+)/) { > do_add($1, $2); > } elsif (/mult (\d+) (\d+)/) { > do_mult($1,$2); > } elsif(/help (\w+)/) { > show_help($1); > } > > or even > > do_add($1,$2) if /add (\d+) (\d+)/; > do_mult($1,$2) if /mult (\d+) (\d+)/; > show_help($1) if /help (\w+)/; Here's some Python code (tested). It is not as concise as the Perl code. Which might or might not be a disadvantage. Sometimes, regular expressions are not the right thing. For example, a simple str.startswith() might be better. What about "add 9999999999999999999999999 99999999999999999999999"? Maybe we want to catch the error before we get to the do_add. Can't easily do that with regular expressions. And what about a variable number of arguments. If regular expressions are no longer used, the Perl code seems to loose some of its elegance. I've been arguing for writing small, simple functions that do something. This should make testing much easier. These functions might happen to use regular expressions. The code below is clearly more flexible. It's easy, for example, to add a new command. Just add an entry to dispatch. The thing I like best about it is the passing of a dict. === #!/usr/bin/python import re # here we know about functions and patterns def do_add(arg1, arg2): print "+ %s %s" % (arg1, arg2) def do_times(arg1, arg2): print "* %s %s" % (arg1, arg2) add_re = re.compile(r'add (?P.*) (?P.*)') times_re = re.compile(r'times (?P.*) (?P.*)') def find_add(str): match = add_re.match(str) if match is None: return match return match.groupdict() def find_times(str): match = times_re.match(str) if match is None: return match return match.groupdict() # here we bind everything together dispatch = [ (find_add, do_add), (find_times, do_times), ] def doit(str): for (find, do) in dispatch: d = find(str) if d is not None: return do(**d) return None # or error if __name__ == '__main__': doit('add this that') doit('times this that') === Jonathan From rff_rff at remove-yahoo.it Thu Jan 6 07:50:25 2005 From: rff_rff at remove-yahoo.it (gabriele renzi) Date: Thu, 06 Jan 2005 12:50:25 GMT Subject: Python evolution: Unease In-Reply-To: <1gpyxxv.wxsci81e0054aN%aleaxit@yahoo.com> References: <1gpxk87.zeszum1hfa220N%aleaxit@yahoo.com> <41dcc35a$0$3872$afc38c87@news.optusnet.com.au> <1gpyxxv.wxsci81e0054aN%aleaxit@yahoo.com> Message-ID: Alex Martelli ha scritto: >>But Alex is right; Envisage does hold a lot of promise. > > > The very concept of an architecture based on a spare skeleton and > copious plugins is intrinsically excellent, and I think that by now > eclipse has proven it's also practically viable for real-world powerful > IDEs/platforms/frameworks. > I think this had been demonstrated from emacs long before :) From donald.welch at NOSPAM.hp.com Tue Jan 11 19:22:03 2005 From: donald.welch at NOSPAM.hp.com (Don) Date: Tue, 11 Jan 2005 16:22:03 -0800 Subject: shutil.move has a mind of its own References: Message-ID: <41e46e0d@usenet01.boi.hp.com> I don't know if this is the problem or, not, but: shutil.move( "C:\omg.txt" , "C:\folder\subdir" ) Needs to have some special handling for the backslashes. Either: shutil.move( r"C:\omg.txt" , r"C:\folder\subdir" ) or: shutil.move( "C:\\omg.txt" , "C:\\folder\\subdir" ) -Don Daniel Bickett wrote: > Hello, > > I'm writing an application in my pastime that moves files around to > achieve various ends -- the specifics aren't particularly important. > The shutil module was chosen as the means simply because that is what > google and chm searches returned most often. > > My problem has to do with shutil.move actually putting the files where > I ask it to. Citing code wouldn't serve any purpose, because I am > using the function in the most straight forward manner, ex: > > shutil.move( "C:\omg.txt" , "C:\folder\subdir" ) > > In my script, rather than a file being moved to the desired location, > it is, rather, moved to the current working directory (in this case, > my desktop -- without any exceptions, mind you). As it happens, the > desired locations are system folders (running windows xp, the folders > are as follows: C:\WINDOWS, C:\WINDOWS\SYSTEM, C:\WINDOWS\SYSTEM32). > To see if this factor was causing the problem, I tried it using the > interpreter, and found it to be flawless. > > My question boils down to this: What factors could possibly cause > shutil.move to fail to move a file to the desired location, choosing > instead to place it in the cwd (without raising any exceptions)? > > Thank you for your time, > > Daniel Bickett > > P.S. I know I said I didn't need to post code, but I will anyway. You > never know :) > > http://rafb.net/paste/results/FcwlEw86.html From peter at engcorp.com Thu Jan 20 20:59:35 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 20 Jan 2005 20:59:35 -0500 Subject: spawn syntax + os.P_WAIT mode behavior + spawn stdout redirection In-Reply-To: References: Message-ID: <7OidnfaojPWa_23cRVn-gg@powergate.ca> Derek Basch wrote: > If the syntax of spawnl is: > > spawnl(mode, path, ...) > > Why does everyone write it like: > > os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') > > or: > > os.spawnl(os.P_WAIT, "/var/www/db/smm/smm_train", "smm_train", > "SMMTrainInput.xml") > > How is the first 'cp' a path to a file? why does the desired executable have to > be named again as the first parameter? Marginally educated guessing: 1. "cp" is a shell command, so no path is required or possible. 2. The repetition of the executable name is so that argv[0] can have the expected contents: the name of the executable. -Peter From Scott.Daniels at Acm.Org Tue Jan 4 11:18:58 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 04 Jan 2005 08:18:58 -0800 Subject: Hlelp clean up clumpsy code In-Reply-To: References: Message-ID: <41dabf3d$1@nntp0.pdx.net> Nick Coghlan wrote: > A custom generator will do nicely: > > Py> def flatten(seq): > ... for x in seq: > ... if hasattr(x, "__iter__"): > ... for y in flatten(x): > ... yield y > ... else: > ... yield x Avoiding LBYL gives you: def flatten(seq): for x in seq: try: for y in flatten(x): yield y except TypeError: yield x --Scott David Daniels Scott.Daniels at Acm.Org From rlahaye at new.rr.com Sun Jan 2 19:52:22 2005 From: rlahaye at new.rr.com (Ross La Haye) Date: Sun, 2 Jan 2005 18:52:22 -0600 Subject: emulating an and operator in regular expressions Message-ID: How can an and operator be emulated in regular expressions in Python? Specifically, I want to return a match on a string if and only if 2 or more substrings all appear in the string. For example, for a string s = 'Jones John' and substrings sg0 = 'Jones' and sg1 = 'John', I want to return a match, but for substrings sg0 = 'Jones' and sg2 = 'Frank' I do not want to return a match. Because the expression 'A and B' is logically equivalent to 'not (not A or not B)' I thought I could try something along those lines, but can't crack it. Ross -------------- next part -------------- A non-text attachment was scrubbed... Name: winmail.dat Type: application/ms-tnef Size: 1724 bytes Desc: not available URL: From aldo at nullcube.com Mon Jan 10 20:47:36 2005 From: aldo at nullcube.com (Aldo Cortesi) Date: Tue, 11 Jan 2005 12:47:36 +1100 Subject: Port blocking In-Reply-To: References: <34f6sgF4asjm7U1@individual.net> <7x3bx9sehd.fsf@ruckus.brouhaha.com> <34f8ovF47d783U1@individual.net> <34fdf6F4a7t7uU1@individual.net> Message-ID: <20050111014736.GA2185@nullcube.com> Thus spake Steve Holden (steve at holdenweb.com): > I teach the odd security class, and what you say is far > from true. As long as the service is located behind a > firewall which opens up the correct holes for it, it's > most unlikely that corporate firewalls would disallow > client connections to such a remote port. Don't be too sure about that - most of the well-run corporate networks I have been involved with block outbound traffic by default. It is certainly sound security policy to shunt outbound traffic through intermediary servers (e.g. SMTP) and proxies (e.g. HTTP and FTP) so that it can be logged, monitored, tracked, and controlled. This is the strategy I recommend to my clients - the only sensible one in a world of spyware, worms, insecure web browsers and corporate espionage... Cheers, Aldo -- Aldo Cortesi aldo at nullcube.com http://www.nullcube.com Off: (02) 9283 1131 Mob: 0419 492 863 From vincent at visualtrans.de Mon Jan 10 16:10:38 2005 From: vincent at visualtrans.de (vincent wehren) Date: Mon, 10 Jan 2005 22:10:38 +0100 Subject: exceptions and items in a list In-Reply-To: References: Message-ID: rbt wrote: > If I have a Python list that I'm iterating over and one of the objects > in the list raises an exception and I have code like this: > > try: > do something to object in list > except Exception: > pass > > Does the code just skip the bad object and continue with the other > objects in the list, or does it stop? > > Thanks Fire up a shell and try: >>> seq = ["1", "2", "a", "4", "5", 6.0] >>> for elem in seq: ... try: ... print int(elem) ... except ValueError: ... pass and see what happens... -- Vincent Wehren From ialbert at mailblocks.com Mon Jan 24 09:27:01 2005 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 24 Jan 2005 09:27:01 -0500 Subject: [OT] XML design intent ... further musings In-Reply-To: <7xhdl8pz1j.fsf@ruckus.brouhaha.com> References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> <41F2C840.2050304@comcast.net> <7xhdl8pz1j.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I love this old rant about XML: > > http://groups-beta.google.com/group/comp.lang.lisp/msg/9a30c508201627ee This is my favorite: http://weblog.burningbird.net/archives/2002/10/08/the-parable-of-the-languages "I?m considered the savior, the ultimate solution, the final word. Odes are written to me, flowers strewn at my feet, virgins sacrificed at my altar. Programmers speak my name with awe. Companies insist on using me in all their projects, though they?re not sure why. And whenever a problem occurs, someone somewhere says, ?Let?s use XML", and miracles occur and my very name has become a talisman against evil. And yet, all I am is a simple little markup, from humble origins. It?s a burden, being XML." From fumanchu at amor.org Wed Jan 19 03:57:52 2005 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 19 Jan 2005 00:57:52 -0800 Subject: Solutions for data storage? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33981F8@exchange.hqamor.amorhq.net> Leif K-Brooks wrote: > My ideal solution would be an object database (or object-relational > mapper, I guess) which provided total transparency in all but a few > places, built-in indexing, built-in features for handling schema > changes, the ability to create attributes which are required to be > unique among other instances, and built-in querying with > pretty syntax. Thanks; I'll add unique indexing to the feature list for Dejavu. Should be about 15 lines of code. :) Try svn://casadeamor.com/dejavu/trunk if you want a truly Pythonic query syntax. Wait a couple of days, and I'll have version 1.3 ready and online at http://www.aminus.org/rbre/python -- lots of changes from 1.2.6 which is there now, but at least you can read old docs online now without svn. Robert Brewer MIS Amor Ministries fumanchu at amor.org From invalidemail at aerojockey.com Wed Jan 19 19:52:13 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 19 Jan 2005 16:52:13 -0800 Subject: Zen of Python In-Reply-To: References: Message-ID: <1106182333.832976.38350@z14g2000cwz.googlegroups.com> Timothy Fitz wrote: > While I agree that the Zen of Python is an amazingly concise list of > truisms, I do not see any meaning in: > > Flat is better than nested. > > I strive for balance between flat and nested. Does anyone have a good > example of where this is applied? (specifically to python, or in > general) I think the essence of why this Zen is true is the recognition that the world isn't really organized into a nice, proper, perfect heirarchy, where every node is a perfect little subset of its parent. The fact is, some things are flat. A list is flat. Is is not better to deal with flat things flatly? And some things aren't flat, but they're not nested either. Rather, they are various overlapping sets, but not subsets. It it better to deal with such as mess by shoehorning it into a heirarchy that isn't applicable, or to make it flat and deal with the subsets individually? I shall give two examples of where Python exhibits this Zen, and doing one my favorite things in the process: slamming other languages. ITERATION There are two ways to iterate: the flat way, with a for loop or list comprehension or something like that; and the nested way, recursively. We all know that recursion is often absolutely necessary. But usually flat iteration suffices. In other languages (notoriously LISP and functional languages), there is a tendency to do it recursively anyways. For example, the following Python code illustrates a recursive way to copy a list that would be considered an example of "good code" in a language such as LISP: . def copylist(a): . if a: return a[:1] + copylist(a[1:]) . else: return a LISP, of course, was designed to make recursive processing like this easy and efficient. But it doesn't, IMHO, keep recursion from being much harder to figure out. Although this has a sort of coolness in that you can see the list copy operation reduced to its simplest possible form (in the same way that Game of Life is cool because you get all kinds of complexity from very simple rules), it completely misses the big picture. When I want to copy a list, I want to copy a list; I don't want to figure out the minimal rule set I could use to do it. Iteration fits the mind better. Python, IMO, wisely put the focus on iteration. POLYMORPHISM In many languages, the only way to get dynamic polymorphism is to subclass. If two classes are to share an interface, they have to both be subclasses of a common base class. If you have lots of classes that you want to share parts of their interfaces, you have to put them all into that heirarchy. The problem is, the world isn't a neatly organized tree, where every type of object must have functionality that is an exact proper subset of some other type of object. So what you end up with is this big, messy, inflexible hierarchy of classes that is difficult to make changes or add new options to. Many classes have stuff in them that ought not to be there, just to satisfy the requirements of subclassing. Oftentimes, the root class has lots of methods that many subclasses don't implement. Oftentimes, there will be subclasses with functionality that isn't polymorphic because the root class doesn't define virtual methods for them. (For an example of all this madness: in I/O hierarchies, the base class often has seek() and tell() methods, but since not all streams are seekable, it also has to have a seekable() method. Thus, polymorphic behavior and its benefits are abandoned in favor of the procedural way. Sure, for this case, you could just define a SeekableStream intermediate class, only for seekable streams. But here's the thing: there are any number of functionalities a stream may or may not have. Are you going to design a hierarchy with branches to account for all possible combinations of them?) Not so in Python. In Python, if you want to classes to have the same interface, then write two classes that have the same methods. Bam, you got polymorphism. No shoehorning into a heirarchy necessary. It's what we call duck typing. (If it looks like a duck, and floats like a duck, it's made of wood.) The flat method of polymorphism is so much better it isn't even funny. Again, Python chose wisely. -- CARL BANKS From jerf at jerf.org Mon Jan 24 10:56:30 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 24 Jan 2005 10:56:30 -0500 Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) References: Message-ID: On Mon, 24 Jan 2005 12:17:13 -0600, Philippe C. Martin wrote: > I use "__"for private variables because I must have read on net it was the > way to do so - yet this seems to have changed - It's still as true as ever, at least in terms of language support, it's just that the Python community, and in general the dynamic language community, has become increasingly confident that private variables don't solve *real* problems. The evidence is primarily a lack of evidence against, which is why it has taken a while for everyone to be sure, but while the rare anecdotal bit goes by every now and again, the dynamic languages have conspicuously failed to crash and burn as old hard-line theories about variable privacy would have predicted. I could go on about this for a while, but that's probably enough to explain the apparent contradiction between docs you may find and what you heard here; the docs mention that because people look for it, and if people want to know it, the docs should include it. But that doesn't mean it's a good idea. From danperl at rogers.com Tue Jan 25 12:50:25 2005 From: danperl at rogers.com (Dan Perl) Date: Tue, 25 Jan 2005 12:50:25 -0500 Subject: [perl-python] 20050125 standard modules References: <1106669614.666772.17750@z14g2000cwz.googlegroups.com> Message-ID: <5didnV2i-YV_G2vcRVn-iw@rogers.com> I was wrong. He is just crossposting to the newsgroups without having them as members of the group. I wish there was a good way like that to stop these daily postings! Dan "Dan Perl" wrote in message news:yfSdnWbW5rw84GvcRVn-sw at rogers.com... >I sent the following feedback message to Yahoo! Groups about this abusive >use of their service. > > Feel free to also report this as an abuse of the Yahoo! Groups service > until the problem is resolved. > > Dan > > ----------- > As the owner of the perl-python group, p0lyglut (aka Xah Lee), has added > two newsgroups to the mailing list of the group: comp.lang.perl.misc and > comp.lang.python. > > First of all, I don't think anyone could have given Xah Lee an > authorization on behalf of the newsgroups. I am not sure, but that is > probably a violation of the Terms of Service in itself. I will leave this > matter up to you to investigate. > > The daily messages of the perl-python group are unwanted by the two > newsgroups. Just take a look at the follow-ups in the newsgroups that the > perl-python postings have generated. > > I hope that not only the newsgroups will be removed from the perl-python > group but that such an abuse will also be prevented in the future. > > Thanks, > > Dan Perl > From sjmachin at lexicon.net Tue Jan 25 16:53:21 2005 From: sjmachin at lexicon.net (John Machin) Date: 25 Jan 2005 13:53:21 -0800 Subject: Browsing text ; Python the right tool? References: Message-ID: <1106690001.427396.266560@f14g2000cwb.googlegroups.com> Paul Kooistra wrote: > I need a tool to browse text files with a size of 10-20 Mb. These > files have a fixed record length of 800 bytes (CR/LF), and containt > records used to create printed pages by an external company. > > Each line (record) contains an 2-character identifier, like 'A0' or > 'C1'. The identifier identifies the record format for the line, > thereby allowing different record formats to be used in a textfile. > For example: > > An A0 record may consist of: > recordnumber [1:4] > name [5:25] > filler [26:800] 1. Python syntax calls these [0:4], [4:25], etc. One has to get into the habit of deducting 1 from the start column position given in a document. 2. So where's the "A0"? Are the records really 804 bytes wide -- "A0" plus the above plus CR LF? What is "recordnumber" -- can't be a line number (4 digits -> max 10k; 10k * 800 -> only 8Mb); looks too small to be a customer identifier; is it the key to a mapping that produces "A0", "C1", etc? > > while a C1 record consists of: > recordnumber [1:4] > phonenumber [5:15] > zipcode [16:20] > filler [21:800] > > As you see, all records have a fixed column format. I would like to > build a utility which allows me (in a windows environment) to open a > textfile and browse through the records (ideally with a search > option), where each recordtype is displayed according to its > recordformat ('Attributename: Value' format). This would mean that > browsing from a A0 to C1 record results in a different list of > attributes + values on the screen, allowing me to analyze the data > generated a lot easier then I do now, browsing in a text editor with a > stack of printed record formats at hand. > > This is of course quite a common way of encoding data in textfiles. > I've tried to find a generic text-based browser which allows me to do > just this, but cannot find anything. Enter Python; I know the language > by name, I know it handles text just fine, but I am not really > interested in learning Python just now, I just need a tool to do what > I want. > > What I would REALLY like is way to define standard record formats in a > separate definition, like: > - defining a common record length; > - defining the different record formats (attributes, position of the > line); Add in the type, number of decimal places, etc as well .. > - and defining when a specific record format is to be used, dependent > on 1 or more identifiers in the record. > > I CAN probably build something from scratch, but if I can (re)use > something that already exists it would be so much better and faster... > And a utility to do what I just described would be REALLY usefull in > LOTS of environments. > > This means I have the following questions: > > 1. Does anybody now of a generic tool (not necessarily Python based) > that does the job I've outlined? No, but please post if you hear of one. > 2. If not, is there some framework or widget in Python I can adapt to > do what I want? > 3. If not, should I consider building all this just from scratch in > Python - which would probably mean not only learning Python, but some > other GUI related modules? Approach I use is along the lines of what you suggested, but w/o the GUI. I have a Python script that takes layout info and an input file and can produce an output file in one of two formats: Format 1: something like: Rec:A0 recordnumber:0001 phonenumber:(123) 555-1234 zipcode:12345 This is usually much shorter than the fixed length record, because you leave out the fillers (after checking they are blank!), and strip trailing spaces from alphanumeric fields. Whether you leave integers, money, date etc fields as per file or translated into human-readable form depends on who will be reading it. You then use a robust text editor (preferably one which supports regular expressions in its find function) to browse the output file. Format 2: Rec:A0 recordnumber:0001 etc etc i.e. one field per line? Why, you ask? If you are a consumer of such files, so that you can take small chunks of this, drop it into Excel, testers take copy, make lots of juicy test data, run it through another script which makes a flat file out of it. > 4. Or should I forget about Python and build someting in another > environment? No way! From gsakkis at rutgers.edu Fri Jan 7 13:01:50 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Fri, 7 Jan 2005 20:01:50 +0200 Subject: Pre/Postconditions with decorators References: <1105094828.619317.315340@z14g2000cwz.googlegroups.com> Message-ID: <34814fF43bm4cU1@individual.net> > Hi George, > it would be nice to see how you have tackled > the task. > Maybe we will have a checker > module in Python one day... ;-) I posted my module on http://rafb.net/paste/results/voZYTG78.html and its unit test on http://rafb.net/paste/results/MYxMQW95.html. Any feedback will be appreciated. George From rittersporn at gmail.com Sun Jan 9 06:53:37 2005 From: rittersporn at gmail.com (rittersporn at gmail.com) Date: 9 Jan 2005 03:53:37 -0800 Subject: Pre/Postconditions with decorators References: <1105094828.619317.315340@z14g2000cwz.googlegroups.com> <34814fF43bm4cU1@individual.net> <1105190031.287227.319360@c13g2000cwb.googlegroups.com> Message-ID: <1105271617.865726.308390@c13g2000cwb.googlegroups.com> Thank you very much for reminding me. I have been sloppy. It should have said static type checking. ciao Skip Montanaro wrote: > >> Eiffel (language) has both type checking and design by contract. > >> Python lacks both. > > Actually, Python is strongly typed. It's just dynamically instead of > statically typed. > > Skip From gerrit.muller at embeddedsystems.nl Wed Jan 12 02:49:11 2005 From: gerrit.muller at embeddedsystems.nl (Gerrit Muller) Date: Wed, 12 Jan 2005 08:49:11 +0100 Subject: "Architecture of Python" was removed ? In-Reply-To: References: <004801c4f7cb$f62d1d30$1d02a8c0@cr> Message-ID: Nick Coghlan wrote: > cr999 wrote: >> I found the "Architecture of Python" ( >> http://wiki.cs.uiuc.edu/cs427/PYTHON By Jim Jackson, Kar-Han Tan >> )is very useful for my understanding of the Python's architecture. >> But I found the link is not link to that document today. It seems >> that the document was removed. Who knows what happened? >> >> Does anyone here have a copy of that document? Or who can tell me >> what is the email address of Jim Jackson or Kar-Han Tan. > > > http://web.archive.org/web/20031222201953/http://wiki.cs.uiuc.edu/cs427/PYTHON > > > Cheers, Nick. > This is again a nice document, and an example of a document that presumably has been removed because of maintenance reasons. Shouldn't we have a collection (archive) of these documents at python.org? kind regards, Gerrit -- Gaudi systems architecting: From apardon at forel.vub.ac.be Wed Jan 19 03:46:00 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Jan 2005 08:46:00 GMT Subject: lambda References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> <41ed8c13.1209309354@news.oz.net> Message-ID: Op 2005-01-18, Bengt Richter schreef : > On 18 Jan 2005 13:28:00 GMT, Antoon Pardon wrote: > >>I have implemented a hash table when I was a student and its >>implementation allowed the use of 'mutable' objects as a key >>without a problem. It simply always made copies when appropiate >>and didn't allow external access to the keys. So although the >>key objects were 'mutable' there was no way a user could accidently >>mutate a key. > This is word play IMO. What you describe is effectively using the mutables > to construct immutable keys for actual use, not using immutable keys. No it is not wordplay. There is a difference between inaccessible and immutable. The difference is that the user can mutate his own objects which he wants to use as a key, which wouldn't be the case if he was using immutables as keys. > Having > the immutable (because of access restriction) constructed keys allows > you to check on their consistency with their source any time you want, > but that doesn't change the fact that you have created an alternative dictionary > implementation with immutable keys made immutable by copying and access restriction. > If you update your dictionary when a key no longer matches its source data, you > are just deleting an immutable-by-special-means key and entering the associated > value in association with a new immutable-by-special-means key. The immutable vs mutable as keys IMO refers to the class the key belongs to. Not the accessibiliy of individual instances. >>So don't use a mutable as a dictionary key isn't so much a dictionary >>limitation in general but a specific limitation of the python implementation. >> >>And yes I understand, the current implenatation is the result of the >>fact that the same dictionaries are used internally for variables in >>scopes and attributes in objects and the fact that no copies are >>involved gives a boost to performance. But it could be argued that >>providing these same dictionaries with those semantics to the users >>was a premature optimisation. > > If you see a sign like > > +---------------------------------> > | WILD GOOSE CHASE THIS WAY -> > +-----------------------------> > || > || \|/ > || =o= > || /|\ > .`.||,..__|_,. > > Do you feel that you must make sure? Talk to my wife. She regularly complains that I don't accept her word often enough on what she says. :-) > The sign painter may only be indicating what his own experience was, after all. > But if it was a core developer's experience, it may be prudent to bet on another trail > -- unless you have an extremely interesting hunch. Then you should follow your passion > and have your own experience, and you may wind up being able to contribute something > (even if only an exclamation point on the sign ;-) > >> >>> When stating useful general principles, it is never, ever worth it to get into >>> the quibbly little details about exceptions to the principle. If students ask, >>> admit that they exist, but point out that the exceptions are rare, and not worth >>> worrying about at that point in their learning. >> >>But don't use mutable keys is not a general principle. It is a principle >>introduced by the limitations of the python implementations. > That is so in your mind, and it is so given certain interpretations of the words > you are using, As far as I understand I using them in a standard python interpretation. > but to others "mutable keys" may be a contradiction in terms, because > they do not use the words in the same sense as you. I don't think so. I have seen defenders of only immutables as keys, use the argument that using mutables as keys would require a copy of the key. Therefore using only immutables allows for optimisations in the implementation. I saw nothing in there discourse that implied they saw this copy as immutable. > If you can't see alternative conceptual > constructs you are stuck, and if we can't agree on the meaning of words for a given dialog, > we won't be communicating very well. The difficulty is getting people to recognize their > implicit assumptions and definitions ;-) I can be wrong, but until now I have seen no indication that I was using mutable and immutable differently than other people. AFAICT we all refer to whether an object belongs to a mutable or immutable class. >>I don't like it when a good rule of thumb because of implementation >>limitations is sold as a general principle. > People take short cuts in expressing themselves, just as you do. > E.g., you say "mutable key" when you really mean a value that will > remain constant while you are using it as a dictionary key. What I mean is a key that belongs to a mutable class. Whether I actually mutate it in certain circumstances or not doesn't change that. I also don't want my values to change when I have sorted a list and still need to apply a number of algorithms that rely on that. Nobody seems to have problems with the possibility that the list items are mutable (and called such). -- Antoon Pardon From aleaxit at yahoo.com Sat Jan 22 17:00:35 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 23:00:35 +0100 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <46ednYMe9-q4Om_cRVn-tQ@comcast.com> <35fo4iF4maov2U1@individual.net> <35fpq0F4mh1ffU1@individual.net> <7xoefhtavd.fsf@ruckus.brouhaha.com> Message-ID: <1gqtawv.omj416ues6jN%aleaxit@yahoo.com> Paul Rubin wrote: ... > lists. I think it would be great if the Python library exposed an > interface for parsing constant list and dict expressions, e.g.: > > [1, 2, 'Joe Smith', 8237972883334L, # comment > {'Favorite fruits': ['apple', 'banana', 'pear']}, # another comment > 'xyzzy', [3, 5, [3.14159, 2.71828, []]]] > > I don't see what YAML accomplishes that something like the above wouldn't. > > Note that all the values in the above have to be constant literals. > Don't suggest using eval. That would be a huge security hole. I do like the idea of a parser that's restricted to "safe expressions" in this way. Once the AST branch merge is done, it seems to me that implementing it should be a reasonably simple exercise, at least at a "toy level". I wonder, however, if, as an even "toyer" exercise, one might not already do it easily -- by first checking each token (as generated by tokenize.generate_tokens) to ensure it's safe, and THEN eval _iff_ no unsafe tokens were found in the check. Accepting just square brackets, braces, commas, constant strings and numbers, and comments, should be pretty safe -- we'd no doubt want to also accept minus (for unary minus), plus (to make complex numbers), and specifically None, True, False -- but that, it appears to me, still leaves little margin for an attacker to prepare an evil string that does bad things when eval'd... Alex From simon.brunning at gmail.com Tue Jan 18 06:48:51 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 18 Jan 2005 11:48:51 +0000 Subject: Fuzzy matching of postal addresses In-Reply-To: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <8c7f10c60501180348692b89fc@mail.gmail.com> You might find these at least periperally useful: They refer to address formatting rather than de-duping - but normalising soulds like a useful first step to me. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From max at alcyone.com Sat Jan 15 01:38:35 2005 From: max at alcyone.com (Erik Max Francis) Date: Fri, 14 Jan 2005 22:38:35 -0800 Subject: [perl-python] 20050113 looking up syntax In-Reply-To: References: <1105699357.565028.107750@c13g2000cwb.googlegroups.com> Message-ID: Peter Hansen wrote: > So why duplicate the posts by posting them to the newsgroups? Because he's a well-known pest. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Yes I'm / Learning from falling / Hard lessons -- Lamya From cwilbur at mithril.chromatico.net Mon Jan 17 15:39:46 2005 From: cwilbur at mithril.chromatico.net (Charlton Wilbur) Date: Mon, 17 Jan 2005 20:39:46 GMT Subject: [perl-python] 20050117, filter, map References: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> <41EBA23A.2010005@holdenweb.com> Message-ID: <87wtublrhu.fsf@mithril.chromatico.net> >>>>> "SH" == Steve Holden writes: SH> As I may have mentioned before, egotism can be the only SH> possible reason. Relevant links: "On Ignoring Trolls": http://www.xahlee.org/UnixResource_dir/writ/troll_ignorance.html "A Troll's Anthology": http://www.xahlee.org/UnixResource_dir/writ/troll_anthology.html He admits to being a troll, and he enjoys trolling. I suspect this thread was intended to stir up a flame war among Perl and Python users; all it's done is demonstrate how hopeless Xah is as a programmer even in a language he claims to be an expert in. Charlton -- cwilbur at chromatico dot net cwilbur at mac dot com From kst-u at mib.org Wed Jan 26 04:35:48 2005 From: kst-u at mib.org (Keith Thompson) Date: Wed, 26 Jan 2005 09:35:48 GMT Subject: how to write a tutorial References: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> <1106472508.591411.40140@c13g2000cwb.googlegroups.com> <1106723545.429728.308620@f14g2000cwb.googlegroups.com> Message-ID: "Xah Lee" writes: [snip] > Following is a tutorial on Python's classes. [snip] Please stop posting this to comp.lang.c. I'm sure the folks in most of the other newsgroup aren't interested either -- or if they are, they can find it in comp.lang.python. Followups redirected. -- Keith Thompson (The_Other_Keith) kst-u at mib.org San Diego Supercomputer Center <*> We must do something. This is something. Therefore, we must do this. From vmalloc at gmail.com Fri Jan 7 11:32:12 2005 From: vmalloc at gmail.com (vmalloc at gmail.com) Date: 7 Jan 2005 08:32:12 -0800 Subject: function field in logging formatting Message-ID: <1105115532.460915.272950@z14g2000cwz.googlegroups.com> Hi all. I don't know if this topic has been proposed yet, but I'll try anyways. I thought it would be nice for the built-in version of the logging package (which, I might add, is excellent) to contain a "function" formatting field for log output. It wouldn't be so hard to implement, and it certainly can serve all those out there who've been using this package for debugging, too. What do you think? can this make a PEP? Rotem From martin at v.loewis.de Thu Jan 27 18:21:46 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 28 Jan 2005 00:21:46 +0100 Subject: MSI Difficulties In-Reply-To: <1106775563.795954.50420@z14g2000cwz.googlegroups.com> References: <1106775563.795954.50420@z14g2000cwz.googlegroups.com> Message-ID: <41F9778A.9050106@v.loewis.de> brolewis wrote: > However both of these commands fail to update the Windows path to > include C:\Python24 and as such creates problems for me when trying to > actually use Python. Not surprisingly so. The Python installation makes no attempt to update the PATH, and never did so, in any recent release. > How can I rectify this situation? There shouldn't be any need to. Just invoke .py files at the command line, and Windows will find python.exe itself. If you want to invoke it interactively, either use the Start menu, or invoke c:\python24\python.exe manually (use the Tab key to not spell out the entire path letter-by-letter). Regards, Martin From mirnazim at gmail.com Wed Jan 5 00:44:45 2005 From: mirnazim at gmail.com (mirnazim at gmail.com) Date: 4 Jan 2005 21:44:45 -0800 Subject: Frameworks for "Non-Content Oriented Web Apps" In-Reply-To: <1104827214.733305.273410@z14g2000cwz.googlegroups.com> References: <1104641466.776338.71700@z14g2000cwz.googlegroups.com> <1104827214.733305.273410@z14g2000cwz.googlegroups.com> Message-ID: <1104903885.902484.302760@z14g2000cwz.googlegroups.com> ----------------------- Well, I think a we can say that a framework for "Non Content Oriented Web Apps" is something that can help in (*) creating N tier data aware web applications (*) creating data-aware controls (forms etc.). (*) managing different data sources transparently(ZODB,MySQL,PostGreSQL, etc). (*) de-coupling UI, Business Logic and Data Sources from each other. (*) provide transaction management facilities(am I asking too much). ----------------------- I think there is something more to the above points than just a construction of web interfaces like forms etc. I never said that it should be something really big(like Zope). I have looked at Quixote and is really cool. But I think we need something more than just a forms processing libary. Alext Martelli: >Once you're on a multilayer track, whether the presentation >is on the web or on some other UI should just be an >issue for the very last layer(closest to the user). I agree in an multi-tier application UI is the last layer issue, but the point here is that there should be some thing that can make connection of web controls to various data sources easy. Of course this is just UI issue of many others that are not UI issues. From http Mon Jan 10 09:00:40 2005 From: http (Paul Rubin) Date: 10 Jan 2005 06:00:40 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> <7xllb2f3z4.fsf@ruckus.brouhaha.com> <1105355380.040837.189270@c13g2000cwb.googlegroups.com> <7xis65a5w6.fsf@ruckus.brouhaha.com> <1105357839.696387.309900@c13g2000cwb.googlegroups.com> <7xr7kt314a.fsf@ruckus.brouhaha.com> <1105364925.848973.73080@c13g2000cwb.googlegroups.com> Message-ID: <7xllb1jsdz.fsf@ruckus.brouhaha.com> "Carl Banks" writes: > When I asked you to do this, it was just a rhetorical way to tell you > that I didn't intend to play this game. It's plain as day you're > trying to get me to admit something. I'm not falling for it. > > If you have a point to make, why don't you just make it? You asked me to compare the notion of macros with the Zen list. I did so. I didn't see any serious conflict, and reported that finding. Now you've changed your mind and you say you didn't really want me to make that comparison after all. An amazing amount of the headaches that both newbies and experienced users have with Python, could be solved by macros. That's why there's been an active interest in macros for quite a while. It's not clear what the best way to do design them is, but their existence can have a profound effect on how best to do these ad-hoc syntax extensions like "where". Arbitrary limitations that are fairly harmless without macros become a more serious pain in the neck if we have macros. So, we shouldn't consider these topics separately from each other. They are likely to end up being deeply related. From steve at holdenweb.com Sat Jan 1 11:46:41 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 01 Jan 2005 11:46:41 -0500 Subject: The Industry choice In-Reply-To: <7xfz1lal5d.fsf@ruckus.brouhaha.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xfz1lal5d.fsf@ruckus.brouhaha.com> Message-ID: <41D6D3F1.9080602@holdenweb.com> Paul Rubin wrote: [...] > There's lots of times when I have a cool programming idea, and find > when I sit down at the computer that I can implement the main points > of the idea and get a neat demo running rather quickly. That creates > a very happy, liberating feeling, plus gives me something to show off > to friends or co-workers. But turning it into a finished product with > no rough edges is an order of magnitude more work. It seems to me > that IDLE and a lot of the rest of Python are examples of someone > having a cool idea and writing a demo, then releasing it with a lot of > missing components and rough edges, without realizing that it can't > reasonably be called complete without a lot more work. ^Python^open source^ regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From mmokrejs at ribosome.natur.cuni.cz Mon Jan 10 18:34:08 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?ISO-8859-15?Q?Martin_MOKREJ=A6?=) Date: Tue, 11 Jan 2005 00:34:08 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <8765246hix.fsf@sme.intra.citec.fi> References: <1105390704.241316.267690@f14g2000cwb.googlegroups.com> <8765246hix.fsf@sme.intra.citec.fi> Message-ID: <41E310F0.3050403@ribosome.natur.cuni.cz> Simo Melenius wrote: > "John Lenton" writes: > > >>you probably want to look into building set-like objects ontop of >>tries, given the homogeneity of your language. You should see >>imrpovements both in size and speed. > > > Ternary search trees give _much_ better space-efficiency compared to > tries, at the expense of only slightly slower build and search time. > This is especially essential as the OP mentioned he could have huge > sets of data. Hi Simo and John, would you please point me to some docs so I learn what are you talking about? ;) Many thanks! Martin From rc at vaccaperna.co.uk Fri Jan 21 10:38:38 2005 From: rc at vaccaperna.co.uk (Robert Cowham) Date: 21 Jan 2005 15:38:38 GMT Subject: ANN: P4Python 0.5 - Interface to Perforce Message-ID: Have just released this to PyPI. http://www.python.org/pypi?:action=display&name=P4Python&version=0.5 Name: P4Python Version: 0.5 Author: Robert Cowham Author email: robert at vaccaperna co uk Home page: http://public.perforce.com/guest/robert_cowham/perforce/API/python/index .html Download URL: UNKNOWN Summary: P4Python - Python interface to Perforce API License: http://public.perforce.com/guest/robert_cowham/perforce/API/python/main/ LICENSE.txt Description: Perforce is the fast SCM system at www.perforce.com. This package provides a simple interface from Python wrapping the Perforce C++ API to gain performance and ease of coding. Similar to interfaces available for Ruby and Perl. Platform: UNKNOWN Classifiers: Development Status :: 4 - Beta Intended Audience :: Developers License :: Freely Distributable Operating System :: Microsoft :: Windows Operating System :: Unix Programming Language :: Python Topic :: Software Development Topic :: Software Development :: Libraries :: Python Modules Topic :: Software Development :: Version Control Topic :: Utilities Currently at 0.5 because haven't had too many people using it yet, but it seems fine on my projects! -- Robert Cowham From http Sat Jan 8 17:54:57 2005 From: http (Paul Rubin) Date: 08 Jan 2005 14:54:57 -0800 Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> Message-ID: <7x8y734jlq.fsf@ruckus.brouhaha.com> "Roose" writes: > > Is an OS written in Lisp also ludicrous? Because it's been done. > > Can you point me to this? I'd like to see how "truly" Lisp it is. http://en.wikipedia.org/wiki/Lisp_machine > My first guess would be -- not very. And I'd like to install it on my PC. Although written with federal funds at a university, it was never released to the public, but was instead offered for sale from some companies. The conflicts over this led to the birth of the free software movement. Also, it was never intended to run on PC's (which didn't exist at that time). It needed special hardware that was built for the purpose of running Lisp. Lately there are people trying to program PC's to simulate the Lisp hardware and to get the Lisp Machine software released (now that the commercial market for it has long since dried up). However, both of those projects have a ways to go. From max at alcyone.com Thu Jan 20 02:40:41 2005 From: max at alcyone.com (Erik Max Francis) Date: Wed, 19 Jan 2005 23:40:41 -0800 Subject: iteritems() and enumerate() In-Reply-To: <1106206068.867004.195010@f14g2000cwb.googlegroups.com> References: <1106206068.867004.195010@f14g2000cwb.googlegroups.com> Message-ID: <8bSdnaEf8cvk_XLcRVn-gg@speakeasy.net> Xah Lee wrote: > Python has iteritems() and enumerate() to be used in for loops. > > can anyone tell me what these are by themselves, if anything? > > are they just for idiom? > thanks. You would be funnier if you weren't so incompetent. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Democritus may have come from Abdera, but he was no dummy. -- Carl Sagan From j.p.t.j.berends at [N0SP4M].nl Thu Jan 6 10:26:47 2005 From: j.p.t.j.berends at [N0SP4M].nl (J Berends) Date: Thu, 06 Jan 2005 16:26:47 +0100 Subject: get the IP address of a host In-Reply-To: References: Message-ID: Jp Calderone wrote: > On Thu, 06 Jan 2005 14:35:16 +0100, J Berends wrote: > >> From several approached I came up with the following code: >> >>def getipaddr(hostname='default'): >> """Given a hostname, perform a standard (forward) lookup and return >> a list of IP addresses for that host.""" >> if hostname == 'default': >> hostname = socket.gethostname() >> ips = socket.gethostbyname_ex(hostname)[2] >> ips = [i for i in ips if i.split('.')[0] != '127'] >> if len(ips) != 0: >> # check if we have succes in determining outside IP >> ip = ips[0] >> elif len(ips) == 0 and hostname == socket.gethostname(): >> # when we want to determine local IP and did not have succes >> # with gethostbyname_ex then we would like to connect to say... >> >> # google.com and determine the local ip address bound to the >> # local socket. >> try: >> s = socket.socket() >> s.connect(('google.com', 80)) >> print ('___ connecting to internet to determine local ip') >> ip = s.getsockname()[0] > > > s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > s.connect(('1.2.3.4', 56)) > ip = s.getsockname()[0] > > > >> del s >> except: >> print ('*** cannot connect to internet in order to \ >> determine outside IP address') >> raise Exception >> if len(ip) != 0: >> return ip >> else: >> print ('*** unable to determine outside IP address') >> raise Exception >> >>It returns the IP address with which it connects to the world (not lo), >>might be a pvt LAN address or an internet routed IP. Depend on where the >>host is. >> >>I hate the google trick actually, so any suggestions to something better >>is always welcome. > > > Jp thanks implemented and works like a charm. From chema.rey at gmail.com Fri Jan 7 12:44:13 2005 From: chema.rey at gmail.com (chema.rey at gmail.com) Date: 7 Jan 2005 09:44:13 -0800 Subject: Working with recordsets Message-ID: <1105119853.927871.293390@z14g2000cwz.googlegroups.com> Hi. I have one recorset that I would like to pass to 2 functions, one is for create an CSV file and the other one is to create a HTML file. The problem is that the recordset is totally read in the first function, and then when I pass it to the second funtion the recordset is in the last record. I've read docs, but I think that one cursor doesn't have something like movefirst() method. Anybody have an idea to solve this? Thank's. From martin at v.loewis.de Sat Jan 29 12:46:54 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 29 Jan 2005 18:46:54 +0100 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: <7xzmysqmxk.fsf@ruckus.brouhaha.com> References: <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <7xzmysqmxk.fsf@ruckus.brouhaha.com> Message-ID: <41fbcc01$0$12030$9b622d9e@news.freenet.de> Paul Rubin wrote: > (And > actually: mxCrypto is the most capable of these packages and might be > the one with the most users, but it's completely unsuitable for the > core because of its size). mxCrypto is primarily unsuitable for the core because Marc-Andre Lemburg will never ever contribute it. He is very concerned about including crypto code with the Python distribution, so he certainly won't contribute his own. Regards, Martin From http Wed Jan 12 14:53:30 2005 From: http (Paul Rubin) Date: 12 Jan 2005 11:53:30 -0800 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> <1g4nx7m906q79$.dlg@usenet.alexanderweb.de> <7xekgr7lpy.fsf@ruckus.brouhaha.com> <7x4qhn9q3g.fsf@ruckus.brouhaha.com> <7xr7kq1rk6.fsf@ruckus.brouhaha.com> Message-ID: <7xvfa2toed.fsf@ruckus.brouhaha.com> Paul Rubin writes: > > > How does it do that? It has to scan every page in the entire wiki?! > > > That's totally impractical for a large wiki. > > > > So you want to say that c2 is not a large wiki? :-) > > I don't know how big c2 is. My idea of a large wiki is Wikipedia. > My guess is that c2 is smaller than that. I just looked at c2; it has about 30k pages (I'd call this medium sized) and finds incoming links pretty fast. Is it using MoinMoin? It doesn't look like other MoinMoin wikis that I know of. I'd like to think it's not finding those incoming links by scanning 30k separate files in the file system. Sometimes I think a wiki could get by with just a few large files. Have one file containing all the wiki pages. When someone adds or updates a page, append the page contents to the end of the big file. That might also be a good time to pre-render it, and put the rendered version in the big file as well. Also, take note of the byte position in the big file (e.g. with ftell()) where the page starts. Remember that location in an in-memory structure (Python dict) indexed on the page name. Also, append the info to a second file. Find the location of that entry and store it in the in-memory structure as well. Also, if there was already a dict entry for that page, record a link to the old offset in the 2nd file. That means the previous revisions of a file can be found by following the links backwards through the 2nd file. Finally, on restart, scan the 2nd file to rebuild the in-memory structure. With a Wikipedia-sized wiki, the in-memory structure will be a few hundred MB and the 2nd file might be a few GB. On current 64-bit PC's, neither of these is a big deal. The 1st file might be several TB, which might not be so great; a better strategy is needed, left as an exercise (various straightforward approaches suggest themselves). Also, the active pages should be cached in ram. For a small wiki (up to 1-2 GB) that's no big deal, just let the OS kernel do it or use some LRU scheme in the application. For a large wiki, the cache and possibly the page store might be spread across multiple servers using some pseudo-RDMA scheme. I think the WikiMedia software is sort of barely able to support Wikipedia right now, but it's pushing its scaling limits. Within a year or two, if the limits can be removed, Wikipedia is likely to reach at least 10 times its present size and 1000 times its traffic volume. So the question of how to implement big, high-traffic wikis has been on my mind lately. Specifically I ask myself how Google would do it. I think it's quite feasible to write Wiki software that can handle this amount of load, but none of the current stuff can really do it. From l.cubells at balague.com Mon Jan 3 04:14:28 2005 From: l.cubells at balague.com (l.cubells at balague.com) Date: Mon, 3 Jan 2005 10:14:28 +0100 Subject: MDaemon Warning - virus found: Error Message-ID: <20050103091510.8AC081E4008@bag.python.org> ******************************* WARNING ****************************** Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado un fichero anexo(s) infectado(s). Por favor revise el reporte de abajo. Attachment Virus name Action taken ---------------------------------------------------------------------- file.zip I-Worm.Mydoom.m Removed ********************************************************************** This message was not delivered due to the following reason(s): Your message was not delivered because the destination server was not reachable within the allowed queue period. The amount of time a message is queued before it is returned depends on local configura- tion parameters. Most likely there is a network problem that prevented delivery, but it is also possible that the computer is turned off, or does not have a mail system running right now. Your message could not be delivered within 2 days: Host 7.131.94.177 is not responding. The following recipients did not receive this message: Please reply to postmaster at python.org if you feel this message to be in error. From premshree.pillai at gmail.com Wed Jan 26 04:17:44 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Wed, 26 Jan 2005 14:47:44 +0530 Subject: Help! Host is reluctant to install Python In-Reply-To: <1d6cdae305012510156f81a74@mail.gmail.com> References: <1d6cdae305012510156f81a74@mail.gmail.com> Message-ID: There are quite a few hosts who offer Python support, no? Maybe you could change hosts. Pair offers Python, AFAIK. On Tue, 25 Jan 2005 13:15:45 -0500, Daniel Bickett wrote: > I've been trying to convince my host to install python/mod_python on > his server for a while now, however there are a number of reasons he > is reluctant to do so, which I will outline here: > > 1. His major reason is optimization. He uses Zend's optimization of > PHP as an example, and he has stated that python is rather resource > consuming. > 2. Another one of his points is that he is unexperienced in installing > python, and he would not know how to do it securely. By 'securely', > I'm assuming he means disallowing a malicious (or ignorant) user from > harming the server > > And, in light of point #1, I suggested that if there wasn't any > optimization immediately available, he could just enable it for my > account (thus lessening potential resource consumption at any given > time), to which he retorted "Do /you/ know how to do that?", and I > must say, he has me cornered ;-) > > I have no experience with this sort of thing, so I'm asking a little > assistance in the direction of any documents or websites (or what have > you) I could show him in order to answer some of these questions, or > perhaps even some unspoken ones -- anything worth noting. (all I'm > really going to do is link him to this thread once it has accumulated > any answers) > > Thank you all for your help :) > > Wishing-to-be-liberated-from-the-clutches-of-PHP-ly y'rs, > Daniel Bickett > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From bokr at oz.net Fri Jan 21 00:23:24 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 21 Jan 2005 05:23:24 GMT Subject: Print a string in binary format References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> <1106270502.219126.322790@f14g2000cwb.googlegroups.com> Message-ID: <41f08ba4.1405806763@news.oz.net> On 20 Jan 2005 17:21:42 -0800, "neutrino" wrote: >Mmm, the output format that I want is like: >0001110011111111000000001111111100000000.... > >I tried your code on Cygwin under Windows 2000, and on Linux, but it >prints out ASCII characters. > You can make a 256-length list to translate 0..255 byte codes into binary strings thus: >>> byte2bits = [''.join(['01'[i&(1<0] for b in xrange(7,-1,-1)]) for i in xrange(256)] Then you can look up string representations for bytes thus: >>> byte2bits[10] '00001010' >>> byte2bits[255] '11111111' and if you had a byte (single character string) that was part of a binary file buffer that you had read whose value was e.g., '\xa3' you could get its representation thus: >>> byte2bits[ord('\xa3')] '10100011' and then you can make a generator routine to convert and join little sequences of bytes, e.g., >>> def bytes2bin(byte_chunk_seq, bspacer=' '): ... for byte_chunk in byte_chunk_seq: ... yield bspacer.join([byte2bits[ord(byte)] for byte in byte_chunk]) ... >>> bytes2bin(['\x00\x01', '\xa3\xa4\xa5\xa6', '@ABCDEFG']) >>> for line in bytes2bin(['\x00\x01', '\xa3\xa4\xa5\xa6', '@ABCDEFG']): print line ... 00000000 00000001 10100011 10100100 10100101 10100110 01000000 01000001 01000010 01000011 01000100 01000101 01000110 01000111 If you want to feed bytes2bin with a sequence of 8-byte chunks from a binary file, you can define a chunk sequence thus (the last chunk might not be a full 8 bytes): chunkseq = iter(lambda f=open(filename, 'rb'):f.read(8), '') and then you can use that as above to print a binary file's content. E.g., First we'll make a quick test file >>> open('btest.bin', 'wb').write(''.join([chr(i&0xff) for i in xrange(384)])) Then we'll read, convert and print: >>> chunkseq = iter(lambda f=open('btest.bin','rb'): f.read(8), '') >>> for line in bytes2bin(chunkseq): print line ... 00000000 00000001 00000010 00000011 00000100 00000101 00000110 00000111 00001000 00001001 00001010 00001011 00001100 00001101 00001110 00001111 00010000 00010001 00010010 00010011 00010100 00010101 00010110 00010111 00011000 00011001 00011010 00011011 00011100 00011101 00011110 00011111 [...snip stuff you can infer ...] 11100000 11100001 11100010 11100011 11100100 11100101 11100110 11100111 11101000 11101001 11101010 11101011 11101100 11101101 11101110 11101111 11110000 11110001 11110010 11110011 11110100 11110101 11110110 11110111 11111000 11111001 11111010 11111011 11111100 11111101 11111110 11111111 00000000 00000001 00000010 00000011 00000100 00000101 00000110 00000111 00001000 00001001 00001010 00001011 00001100 00001101 00001110 00001111 00010000 00010001 00010010 00010011 00010100 00010101 00010110 00010111 [...snip stuff you can infer ...] 01110000 01110001 01110010 01110011 01110100 01110101 01110110 01110111 01111000 01111001 01111010 01111011 01111100 01111101 01111110 01111111 Well, you get the idea. Regards, Bengt Richter From lard at tardis.ed.ac.molar.uk Thu Jan 27 06:27:11 2005 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Thu, 27 Jan 2005 11:27:11 GMT Subject: HAVE YOU HEARD THE GOOD NEWS! In-Reply-To: <1106701661.128249.250310@c13g2000cwb.googlegroups.com> References: <1106701661.128249.250310@c13g2000cwb.googlegroups.com> Message-ID: google_groups_web at yahoo.com wrote: > Good News! > > > Do you know how simple it is to go to Heaven after this life has ended? > > > Some people believe that belonging to a local church, temple, mosque or > synagogue will get them to Heaven. > > > Others believe that water baptism, obeying the ten commandments or just > being a good person will get them to Heaven. > > > There are many other beliefs as well, but the good news about God's way > to Heaven is found in the Holy Bible. Boy, are you going to be sorry when Thor sends thunderbolts into your arse. From philippecmartin at sbcglobal.net Mon Jan 3 03:49:34 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 3 Jan 2005 09:49:34 +0100 Subject: Tkinter zoom box = maximize/unmaximize box/button Message-ID: <200501030949.35029.philippecmartin@sbcglobal.net> By zoom box I meant one of the top right button/box one uses to maximize/unmaximize the current window. -- ********************* Philippe C. Martin SnakeCard LLC www.snakecard.com ********************* From firstname.lastname at iki.fi-spam Mon Jan 3 16:38:43 2005 From: firstname.lastname at iki.fi-spam (Simo Melenius) Date: 03 Jan 2005 23:38:43 +0200 Subject: Rebinding stdout (was: Re: Python! Is! Truly! Amazing!) References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> <87u0py6elt.fsf@sme.intra.citec.fi> Message-ID: <87oeg65h24.fsf@sme.intra.citec.fi> Just writes: > In article <87u0py6elt.fsf at sme.intra.citec.fi>, > Simo Melenius wrote: > > ... sys.stdout = sys.__stdout__ > Aargh, I can't believe how widespread this idiom is :-(. See my other > reply in this thread: DON'T use sys.__stdout__. Ever. It probably does the right thing, if someone is copypasting code off the Usenet and tries it out at the Python prompt (and possibly gets stuck in getting nothing printed on his tty). If we're talking about real code it might be advisable to start by first introducing the import statements omitted from the above snippet, then worry about someone copypasting code into a serious program instead of copythinkpasting it. :) br, S From olsongt at verizon.net Sat Jan 1 22:50:16 2005 From: olsongt at verizon.net (olsongt at verizon.net) Date: Sun, 2 Jan 2005 3:50:16 +0000 Subject: ANN: PyXR 0.9.4 - Cross-Referenced HTML from Python Source Message-ID: <20050102035016.MCON4717.out011.verizon.net@outgoing.verizon.net> PyXR 0.9.4 - Cross-Referenced HTML from Python Source PyXR generates pretty-printed HTML pages from python source files to make source browsing easier. It provides extensive cross-referencenced hyperlinks that integrate with the Python Library Reference as well as other python source files. Its cross-referencing capabilities are vastly superior to other source pretty-printing packages that I've seen. 0.9.4 provides compatibility with the new language semantics in Python 2.4 and addresses changes to the format of the Library Reference Manual, in addition to a littany of smaller fixes. Previous versions WILL NOT work with python 2.4. This release does provide backward compatibility to python versions as early as 2.2 and should work on all major OSes. PyXR is available for download here: http://sourceforge.net/projects/pyxr/ PyXR'ed markup of Python 2.4's source is available here: http://pyxr.sourceforge.net/PyXR/ Detailed release notes are available here: http://pyxr.sourceforge.net/ Enjoy! From miki.tebeka at zoran.com Mon Jan 24 14:22:00 2005 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Mon, 24 Jan 2005 21:22:00 +0200 Subject: Help on project, anyone? In-Reply-To: <1106561458.167373.303270@c13g2000cwb.googlegroups.com> References: <35ienhF4lu88lU1@individual.net> <1106561458.167373.303270@c13g2000cwb.googlegroups.com> Message-ID: <20050124192138.GF3332@zoran.com> Hello Fuzzyman, > 3) Simple Version Control program for single programmer. A very simple > way of doing version control/releases for small projects with only a > single programmer. [3] Subversion (and CVS) are dead simple to install and use. IMO in the long run you'll find yourself implementing most of their features anyway. > [3] I think lots of people would find this useful. A version control > system for projects where CVS/Subversion is overkill. This would be > based on DirWatcher/FSDM ( > http://www.voidspace.org.uk/python/programs.shtml#dirwatcher ) - All > the code for finding which files have changed is already there, and > there is an existing Tkinter GUI for Dirwatcher. Adding changes to version control should be done as an explicit action by the developer. Anything else is on the road to disaster, you'll find yourself spending too much time backing out of changes you didn't want in. Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From pedro.werneck at terra.com.br Sun Jan 30 15:41:34 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Sun, 30 Jan 2005 18:41:34 -0200 Subject: type() takes one or *three* arguments!? In-Reply-To: <1107115043.242733.259890@z14g2000cwz.googlegroups.com> References: <1107115043.242733.259890@z14g2000cwz.googlegroups.com> Message-ID: <20050130184134.7dd92241.pedro.werneck@terra.com.br> Hi, Up to Python 2.2, type() was just a function to return an object type. >From 2.2 on, type have this behavior when called with only one argument and is used to create a new type when called with 3 arguments. >From http://www.python.org/2.2/descrintro.html : "The signature of type() requires an explanation: traditionally, type(x) returns the type of object x, and this usage is still supported. However, type(name, bases, methods) is a new usage that creates a brand new type object. (This gets into metaclass programming, and I won't go into this further here except to note that this signature is the same as that used by the Don Beaudry hook of metaclass fame.)" So, an example: Foo = type('Foo', (object,), {}) and... class Foo(object): pass Are the same thing... On 30 Jan 2005 11:57:23 -0800 jamesthiele.usenet at gmail.com wrote: > I was looking at Simon Burton's Povray.py code (part of pypov) and saw > this line: > globals()[name] = type( name, (KWItem,), {} ) # nifty :) > > where 'KWItem' was a class. It did seem nifty, but it was unclear to > me what was happening. > > I went to python.org's online documentation which said that type() > takes one argument. So I fired up python: > >>> type(42) > > >>> type("x", (type(42),), {}) > > > OK, It appears that type() with 3 arguments constructs a class. Is > this documented somewhere? If not can someone explain what is going > on? james > > -- > http://mail.python.org/mailman/listinfo/python-list From xah at xahlee.org Sun Jan 16 21:48:59 2005 From: xah at xahlee.org (Xah Lee) Date: 16 Jan 2005 18:48:59 -0800 Subject: [perl-python] 20050117, filter, map Message-ID: <1105930139.513977.91740@c13g2000cwb.googlegroups.com> ? # -*- coding: utf-8 -*- ? # Python ? ? # the "filter" function can be used to ? # reduce a list such that unwanted ? # elements are removed. ? # example: ? ? def even(n): return n % 2 == 0 ? print filter( even, range(11)) ? ? ? # the "map" function applies a function ? # to all elements of a list. Example: ? ? def square(n): return n*n ? print map(square, range(11)) ? ? ------------------------------------ ? # similar perl versions ? ? use Data::Dumper; ? sub even {return $_[0]%2==0}; ? print Dumper[ grep {even $_} (0..10)]; ? ? ? # sub square {$n=shift;$n**2;}; ? sub square {(shift)**2;}; ? print Dumper [ map {square($_)} (0..10)]; ? ? # the codes above showcase some syntax ? # variations commonly found in perl code ? # base ? ? ------------------------- ? ? # in Mathematica for example, filter is ? # akin to Apply and map is MapThread. ? # The standard Map can be applied ? # according to a level spec of trees ? # and there's also MapAt, Nest, ? # NestList...any many more powerful ? # functions that manipulates trees. ? # lisp languages often have a subset ? # of it. ? ? ---------------------------- ? Note: this post is from the Perl-Python ? a-day mailing list at ? http://groups.yahoo.com/group/perl-python/ ? to subscribe, send an email to ? perl-python-subscribe at yahoogroups.com if ? you are reading it on a web page, ? program examples may not run because ? html conversion often breaks the code. ? ? Xah ? xah at xahlee.org ? http://xahlee.org/PageTwo_dir/more.html From Robert.Lin at bluejungle.com Tue Jan 11 19:06:56 2005 From: Robert.Lin at bluejungle.com (Robert Lin) Date: Tue, 11 Jan 2005 16:06:56 -0800 Subject: Python setup question Message-ID: <45EF7183C1B3154AA96DA7343D29727A0AC227@borabora.bluejungle.com> Hi, Sorry for this newbie question, I was wondering if anyone knows why when I run the test, the "test_anydbm" test will seg fault and the tests "test_aepack" and "test_al" are skipped? Thanks in advance. ______________________________________ ? Robert Lin Eng. Intern?|?Blue Jungle?|?Redwood City, CA rlin at bluejungle.com From fumanchu at amor.org Fri Jan 28 15:26:10 2005 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 28 Jan 2005 12:26:10 -0800 Subject: Best python postgres module? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E33982D6@exchange.hqamor.amorhq.net> Roland Heiber wrote: > i recently migrated from mysql to postgresql and did use > severel python > postgres-modules. All do what they are designed for, so > which one would > you use? psycopg, pygresql, pypgsql? psycopg seems to be the best > solution for heavy traffic/multiple connections .... i have no real > testing environment, so any advice which one to use for different > usecases would be nice. If your "use cases" involve cross-platform development (i.e. Linux and Windows), pypgsql seems to fit the bill nicely. Robert Brewer MIS Amor Ministries fumanchu at amor.org From tim.peters at gmail.com Fri Jan 21 17:51:21 2005 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 21 Jan 2005 17:51:21 -0500 Subject: Tuple size and memory allocation for embedded Python In-Reply-To: <1106346474.19065.72.camel@bucket.localnet> References: <1106346474.19065.72.camel@bucket.localnet> Message-ID: <1f7befae0501211451402a79aa@mail.gmail.com> [Jinming Xu] >> Python seems unstable, when allocating big memory. For >> example, the following C++ code creates a tuple of tuples: >> >> PyObject* arCoord = PyTuple_New(n); >> double d = 1.5; >> for(int i=0; i> { >> PyObject* coord = PyTuple_New(2); >> PyTuple_SetItem(coord,0, PyFloat_FromDouble(d));//x >> PyTuple_SetItem(coord,1, PyFloat_FromDouble(d));//y >> PyTuple_SetItem(arCoord,i, coord); >> } >> >> When the n is small, say 100, the code works fine. when n >> is big, say > 10,000, Python has trouble allocating >> memory, saying: >> >> "Exception exceptions.IndexError: 'tuple index out of range' >> in 'garbage collection' ignored >> Fatal Python error: unexpected exception during garbage >> collection >> Aborted" [Craig Ringer] > You're not checking for errors from PyTuple_SetItem. Or from PyTuple_New(), or from PyFloat_FromDouble(). They can all fail, and indeed: > You need to do so, otherwise exceptions will go uncaught > and may pop up at weird points later in your software's > execution, or crash things. That's right. There's no point thinking about this at all before every C API call is checked for an error return. BTW, since the error occurred during garbage collection, there's really no reason to believe that the true cause of the problem is in the code shown. It could simply be that allocating a whole lot of tuples here triggers a round of garbage collection, which in turn reveals an error in code we haven't been shown. In fact, I expect that's actually the case. The possible errors the OP is ignoring here are overwhemingly possible failures of malloc() to find more memory, and in those cases the C API calls shown would return NULL, and a segfault would be very likely soon after. From P at draigBrady.com Wed Jan 12 05:27:29 2005 From: P at draigBrady.com (P at draigBrady.com) Date: Wed, 12 Jan 2005 10:27:29 +0000 Subject: Python & unicode In-Reply-To: <41e41633$1@nntp0.pdx.net> References: <41e30aab$0$6434$8fcfb975@news.wanadoo.fr> <41e41633$1@nntp0.pdx.net> Message-ID: <41E4FB91.2000106@draigBrady.com> Scott David Daniels wrote: > P at draigBrady.com wrote: > >> Because the coding is only supported in string literals. >> But I'm not sure exactly why. > > The why is the same as why we write in English on this newsgroup. > Not because English is better, but because that leaves a single > language for everyone to use to communicate in. Fair enough. Though people can communicate in other languages if they want, or have specific newsgroups for other languages. > If you allow > non-ASCII characters in symbol names, your source code will be > unviewable (and uneditable) for people with ASCII-only terminals, > never mind how comprehensible it might otherwise be. So how does one edit non ascii string literals at the moment? > It is a > least-common-denominator argument, not a "this is better" > argument. If one edited the whole file in the specified coding then one wouldn't have to switch editing modes when editing strings which is a real pain. -- P?draig Brady - http://www.pixelbeat.org -- From sjmachin at lexicon.net Tue Jan 18 02:36:05 2005 From: sjmachin at lexicon.net (John Machin) Date: 17 Jan 2005 23:36:05 -0800 Subject: Fuzzy matching of postal addresses In-Reply-To: References: <96B2w2E$HF7BFwSq@at-andros.demon.co.uk> Message-ID: <1106033765.623338.184170@f14g2000cwb.googlegroups.com> Ermmm ... only remove "the" when you are sure it is a whole word. Even then it's a dodgy idea. In the first 1000 lines of the nearest address file I had to hand, I found these: Catherine, Matthew, Rotherwood, Weatherall, and "The Avenue". Ermmm... don't rip out commas (or other punctuation); replace them with spaces. That way "SHORTMOOR,BEAMINSTER" doesn't become one word "SHORTMOORBEAMINSTER". A not-unreasonable similarity metric would be float(len(sa1 & sa2)) / len(sa1 | sa2). Even more reasonable would be to use trigrams instead of words -- more robust in the presence of erroneous insertion or deletion of spaces (e.g. Short Moor and Bea Minster are plausible variations) and spelling errors and typos. BTW, the OP's samples look astonishingly clean to me, so unlike real world data. Two general comments addressed to the OP: (1) Your solution doesn't handle the case where the postal code has been butchered. e.g. "DT8 BEL" or "OT8 3EL". (2) I endorse John Roth's comments. Validation against an address data base that is provided by the postal authority, using either an out-sourced bureau service, or buying a licence to use validation/standardisation/repair software, is IMHO the way to go. In Australia the postal authority assigns a unique ID to each delivery point. This "DPID" has to be barcoded onto the mail article to get bulk postage discounts. Storing the DPID on your database makes duplicate detection a snap. You can license s/w (from several vendors) that is certified by the postal authority and has batch and/or online APIs. I believe the situation in the UK is similar. At least one of the vendors in Australia is a British company. Google "address deduplication site:.uk" Actually (3): If you are constrained by budget, pointy-haired boss or hubris to write your own software (a) lots of luck (b) you need to do a bit more research -- look at the links on the febrl website, also Google for "Monge Elkan", read their initial paper, look at the papers referencing that on citeseer; also google for "merge purge"; also google for "record linkage" (what the statistical and medical fraternity call the problem) (c) and have a damn good look at your data [like I said, it looks too clean to be true] and (d) when you add a nice new wrinkle like "strip out 'the'", do make sure to run your regression tests :-) Would you believe (4): you are talking about cross-matching two databases -- don't forget the possibility of duplicates _within_ each database. HTH, John From aleaxit at yahoo.com Tue Jan 4 05:15:54 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 4 Jan 2005 11:15:54 +0100 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> Message-ID: <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> Iwan van der Kleyn wrote: > to be determine the way foreward for Python: more features, increased > complexity, less dynamism. Lots of syntax crud, without addressing the As a student of human nature, I'm _really_ curious as to how one could possibly read the key document: http://www.python.org/peps/pep-3000.html and think in consequence of "more features, increased complexity". Also, you keep talking about "the core python team" on the basis, it would appear, of reading one document by Guido. Have you bothered doing a MINIMUM of homework, such as, looking at http://www.amk.ca/diary/archives/cat_python.html and specifically AMK's entry for September 30? I'm trying to understand whether you completely missed doing the most elementary amount of background searching before venting on the group, or if you did find and read the obvious documents and somehow STILL manage to completely ignore their contents or read them as saying exactly the opposite of what they _do_ say... Alex From gsakkis at rutgers.edu Fri Jan 7 05:29:30 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Fri, 7 Jan 2005 12:29:30 +0200 Subject: Pre/Postconditions with decorators References: Message-ID: <3476kcF47fojaU1@individual.net> "Robert Brewer" wrote: > Ian Bicking was just talking about @require decorators: > http://blog.ianbicking.org/already-under-our-noses.html > > @require(int, int) > def gcd(a, b): > ... > > If we made a "checker" module for such things in the stdlib, we could > write most of that: > > from checker import * > > @args((list, itemsnotNone, )) > @returns((any, )) > def my_sum(seq): > tmp=0 > for element in seq: > tmp+=element > return tmp I recently wrote a similar checker module; apart from regular python types and classes, it supports 'parameterized types', such as 'list of ints', 'container of floats', 'mapping with str keys and tuples of int values', etc. Here's a demo: # >>> from typecheck import * # >>> @returnType(listOf(int, size=3)) # >>> @argTypes(x=str, y=containerOf(int)) # ... def f(x,y): # ... return [len(x)] + list(y) # >>> f('1',[2,3]) # [1, 2, 3] # >>> f('1',(2,3)) # [1, 2, 3] # >>> f(1,[2,3]) # (...) # TypeError: str expected (int given) # >>> f('1',[2,'3']) # (...) # TypeError: container expected ([2, '3'] given) # >>> f('1',[2,3,4]) # (...) # TypeError: Container of size 3 expected ([1, 2, 3, 4] given) I can make it available somewhere (e.g. Vaults of Parnassus) if there's enough interest. George From littlejohn.75 at news.free.fr Fri Jan 7 06:00:14 2005 From: littlejohn.75 at news.free.fr (F. Petitjean) Date: 07 Jan 2005 11:00:14 GMT Subject: Tkinter Puzzler References: Message-ID: <41de6bbe$0$5717$626a14ce@news.free.fr> Le 07 Jan 2005 05:28:31 EST, Tim Daneliuk a ?crit : > I am trying to initialize a menu in the following manner: > > for entry in [("Up", KeyUpDir), ("Back", KeyBackDir), ("Home", KeyHomeDir), ("Startdir", KeyStartDir), ("Root", > KeyRootDir)]: > > func = entry[1] > UI.ShortBtn.menu.add_command(label=entry[0], command=lambda: func(None)) The problem is that you *call* the callback : the command parameter is bound to the result of func(None) > > However, at runtime, each of the menu options binds to the *last* function > named in the list (KeyStartDir). > > Explicitly loading each entry on its own line works fine: > > UI........command=lambda:KeyWHATEVERDir(None) > > Any ideas why the first form does not fly? I would simplify the code like ; add_cmd = UI.ShortBtn.menu.add_command for label, func in (("Up", KeyUpDir), .... ): add_cmd(label=label, command=func) And have def KeyUpDir(arg=None): # whatever > > > TIA, > ---------------------------------------------------------------------------- > Tim Daneliuk tundra at tundraware.com > PGP Key: http://www.tundraware.com/PGP/ From craig at postnewspapers.com.au Wed Jan 5 01:04:53 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Wed, 05 Jan 2005 14:04:53 +0800 Subject: Embedding a restricted python interpreter In-Reply-To: <41db7e8f$1@news.unimelb.edu.au> References: <41db7e8f$1@news.unimelb.edu.au> Message-ID: <1104905093.28560.4.camel@bucket.localnet> On Wed, 2005-01-05 at 13:43, Maurice LING wrote: > Rolf Magnus wrote: > > Hi, > > > > I would like to embed a python interpreter within a program, but since that > > program would be able to automatically download scripts from the internet, > > I'd like to run those in a restricted environment, which basically means > > that I want to allow only a specific set of modules to be used by the > > scripts, so that it wouldn't be possible for them to remove files from the > > hard drive, kill processes or do other nasty stuff. > > Is there any way to do that with the standard python interpreter? > > > > I won't really count on that. In my opinions, which may be wrong, Python > is not constructed to work in a sandbox like Java. That is my understanding. In fact, I'd say with Python it's nearly impossible given how dynamic everything is and the number of tricks that can be used to obfuscate what you're doing. Think of the fun that can be had with str.encode / str.decode and getattr/hasattr . I looked into this, and my conclusion ended up being "Well, I'm using Python because I want it's power and flexibilty. If I want a secure scripting environment, I should use something like Lua or Qt Script for Applications instead." AFAIK that's why the rexec() builtin is disabled - it's just not practical to make a restricted Python execution environment. > You can try to use 'exec' to run your scripts in a constructed > environment. For example, > > global = {} > local = {} > > ... your stuffs .... > > statement = [] # to hold the script to run > > for line in statement: > exec statement in global, local > > global and local are the global and local namespaces respectively. > Although it had been explained to me before but I can't recall the > details of how it works. In gist, you may be able to craft a global and > local environment for your script to run in. > I do not know if it is possible to disable or override 'import'...... You can do a fair bit to it by wrapping/replacing __builtin__.__import__ . Preventing people from getting around what you've done, though... not sure. -- Craig Ringer From rganesan at myrealbox.com Mon Jan 31 00:23:53 2005 From: rganesan at myrealbox.com (Ganesan R) Date: 31 Jan 2005 10:53:53 +0530 Subject: how to find number of processors in python References: <822e8fe0.0501302113.4716c2ba@posting.google.com> Message-ID: >>>>> "muttu" == muttu writes: > hello everybody > am writing a scanner using python which has to get the information for > sun's dual processors, so could any one of you please tell me how to > find the number of processors . is there any api's for this You can run /usr/sbin/psrinfo with os.system() and parse the output. Ganesan From rakesh_usenet at yahoo.com Sat Jan 15 20:52:47 2005 From: rakesh_usenet at yahoo.com (Rakesh) Date: 15 Jan 2005 17:52:47 -0800 Subject: nntplib: abstraction of threads Message-ID: <1105840367.526347.110160@c13g2000cwb.googlegroups.com> For a particular application of mine, I need to get the messages from usenet , (and group them by each thread) . My startup python code looks as follows. <--- Startup code to read messages from a newsgroup --> import nntplib, cStringIO, rfc822, sys SRVR = '' # Your news server newsgroup = 'comp.lang.c' # Group of your choice def inpdflt(s, d): resp = raw_input("%s [%s]: " % (s, d)) return resp or d news = nntplib.NNTP(SRVR) resp, estimate, first, last, name = news.group(newsgroup) if estimate == '0': sys.exit("No messages in " + newsgroup) # # Get (article number, subject, poster, date, id, references, size, lines) # for each of the articles between first and last # xover = news.xover(first, last) # loop through articles, extracting headers for x in xover[1]: # x == (article number, subject, poster, date, id, references, size, lines) try: hdrs = news.head(x[0])[3] mesg = rfc822.Message(cStringIO.StringIO("\r\n".join(hdrs))) print '%s\n+++%s' % (mesg.getheader("from"), mesg.getheader("subject")) except nntplib.NNTPError: pass news.quit() <-- End newsgroup --> I am getting all the messages of the newsgroup stored in the newsgroup server. What I want is to *group the messages belonging to each thread* . How would I do that ? Eg: Topic 1 | -- Re: Topic:1 -- Re: Topic: 1 | -- Re: Re: Topic 1 Topic 2 | -- Re: Topic:2 Total number of messages 6, but number of threads = 2, I want to get an abstraction something similar to this. From DohnoSoft Wed Jan 5 15:08:48 2005 From: DohnoSoft (DohnoSoft) Date: Wed, 05 Jan 05 20:08:48 GMT Subject: Publish your program for free and enjoy worry free earning. 100% !!!!! FREE (AND WE MEAN IT - FREE) Message-ID: <0501052008484@nntp.broadband.rogers.com> Dear software developer!!! Just letting you know that now you can publish your program or link for free on www.dohnosoft.com and enjoy worry free earnings. Thank you, Problems? Questions? info at dohnosoft.com From nick at craig-wood.com Tue Jan 25 05:30:01 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 25 Jan 2005 10:30:01 GMT Subject: Classical FP problem in python : Hamming problem References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> Message-ID: Francis Girard wrote: > The following implementation is even more speaking as it makes self-evident > and almost mechanical how to translate algorithms that run after their tail > from recursion to "tee" usage : > > *** BEGIN SNAP > from itertools import tee, imap > import sys > > def imerge(xs, ys): > x = xs.next() > y = ys.next() > while True: > if x == y: > yield x > x = xs.next() > y = ys.next() > elif x < y: > yield x > x = xs.next() > else: > yield y > y = ys.next() Thinking about this some more leads me to believe a general purpose imerge taking any number of arguments will look neater, eg def imerge(*generators): values = [ g.next() for g in generators ] while True: x = min(values) yield x for i in range(len(values)): if values[i] == x: values[i] = generators[i].next() > def hamming(): > def _hamming(): > yield 1 > hamming2 = hammingGenerators[0] > hamming3 = hammingGenerators[1] > hamming5 = hammingGenerators[2] > for n in imerge(imap(lambda h: 2*h, iter(hamming2)), > imerge(imap(lambda h: 3*h, iter(hamming3)), > imap(lambda h: 5*h, iter(hamming5)))): > yield n > hammingGenerators = tee(_hamming(), 4) > return hammingGenerators[3] This means that this can be further simplified thus, def hamming(): def _hamming(): yield 1 for n in imerge( imap(lambda h: 2*h, hamming2), imap(lambda h: 3*h, hamming3), imap(lambda h: 5*h, hamming5) ): yield n hamming2, hamming3, hamming5, result = tee(_hamming(), 4) return result (Note the iter(...) seemed not to be doing anything useful so I removed them) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From zathras at thwackety.com Tue Jan 11 21:52:25 2005 From: zathras at thwackety.com (Michael Sparks) Date: Wed, 12 Jan 2005 02:52:25 +0000 (GMT) Subject: Game programming in Python In-Reply-To: Message-ID: On Tue, 11 Jan 2005, Baza wrote: > I'm looking for any books or on-line resources on game programming using > Python. Does anyone have any advice? There's a book called "Games programming with Python" that's quite a good read. Any online bookstore should be able to give you more details. A cursory check using their search should have yielded this for you however. Michael. From no-mail-please at nospam.com Fri Jan 21 17:36:16 2005 From: no-mail-please at nospam.com (Robert Oschler) Date: Fri, 21 Jan 2005 17:36:16 -0500 Subject: Anyone interested in a infrared transceiver module? Message-ID: <3cadnTL4VrWEHmzcRVn-2g@adelphia.com> Hello, Recently I made a program to control my Robosapien robot from my PC, via a third party infrared transceiver - Jon Rhee's USB UIRT (http://www.usbuirt.com). I wrote a program in Delphi Pascal to script the robot for a funny movie I made: http://www.robotsrule.com/html/robot.php I'm thinking about making a Python module for Jon's UIRT so that Python developers like myself could use it too. This would allow others to control infrared devices and learn infrared codes from their remote controls with the UIRT. The software would be a free download of course (GPL). Any interest out there? Thanks. From ola.natvig at infosense.no Wed Jan 12 13:21:17 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Wed, 12 Jan 2005 19:21:17 +0100 Subject: Removing M2Crypto debug data in production code Message-ID: Hi all I'm writing a SSL server and we are using M2Crypto as our SSL engine. What bothers me is that on every accept it prints a lot of 'junk-data' to my stdout. It would be nice if someone knew a way to get M2Crypto out of debug mode and into a more silent mode. LOOP: SSL accept: before/accept initialization LOOP: SSL accept: SSLv3 read client hello A LOOP: SSL accept: SSLv3 write server hello A LOOP: SSL accept: SSLv3 write certificate A LOOP: SSL accept: SSLv3 write key exchange A LOOP: SSL accept: SSLv3 write server done A LOOP: SSL accept: SSLv3 flush data LOOP: SSL accept: SSLv3 read client key exchange A LOOP: SSL accept: SSLv3 read finished A LOOP: SSL accept: SSLv3 write change cipher spec A LOOP: SSL accept: SSLv3 write finished A LOOP: SSL accept: SSLv3 flush data INFO: SSL accept: SSL negotiation finished successfully regards Ola Natvig -- -------------------------------------- Ola Natvig infoSense AS / development From mep_ at 163.com Tue Jan 25 22:31:18 2005 From: mep_ at 163.com (mep) Date: Wed, 26 Jan 2005 11:31:18 +0800 Subject: Python with no significant whitespace Message-ID: <35oh4gF4nvvfoU1@individual.net> Hi,all Is there anybody trying to release a modification version to current python source code with no significant whitespace, say replacing whitespace by {} like C or java. I do *NOT* mean whitespace is good or bad, just want to know. Best Regards, mep From grante at visi.com Sun Jan 2 17:17:46 2005 From: grante at visi.com (Grant Edwards) Date: 02 Jan 2005 22:17:46 GMT Subject: How to make executable file ? References: <33r5gcF449bt0U1@individual.net> <1y0ocznzfuzyw.mqrsvollejs5.dlg@40tude.net> Message-ID: <41d8730a$0$34707$a1866201@visi.com> On 2005-01-02, BOOGIEMAN wrote: >> don't be scared when you see the dimension of the files... > > 1.9 Mb for a console application ?! Yup. I know it's rather small for a Windows application. > And is it possible to make Windows application? Yes. > I want to display results in windows message box. -- Grant Edwards grante Yow! Pardon me, but do you at know what it means to be visi.com TRULY ONE with your BOOTH! From flamesrock at gmail.com Mon Jan 3 19:08:21 2005 From: flamesrock at gmail.com (flamesrock) Date: 3 Jan 2005 16:08:21 -0800 Subject: XML: Better way to accomplish this? In-Reply-To: References: <1104728060.417168.277780@c13g2000cwb.googlegroups.com> Message-ID: <1104797301.796020.120870@f14g2000cwb.googlegroups.com> Good idea! Thanks Also, besides the document structure (I appreciate comments on that too, of course,) do you think the code is efficient for xml? Any special tricks you know of? -thanks From http Sat Jan 15 04:35:00 2005 From: http (Paul Rubin) Date: 15 Jan 2005 01:35:00 -0800 Subject: Producer/consumer Queue "trick" References: Message-ID: <7xmzvbnigr.fsf@ruckus.brouhaha.com> Evan Simpson writes: > wakes up the producer, which has been blocked waiting to add a board > to the Queue. It sets about generating the next board, and the > consumer doesn't get to run again until the producer blocks again or > is preempted. That's weird. Preemption should happen every few dozen milliseconds unless you've purposely increased the preemption delay. From yan at NsOeSiPnAeMr.com Tue Jan 25 10:09:27 2005 From: yan at NsOeSiPnAeMr.com (Captain Dondo) Date: Tue, 25 Jan 2005 07:09:27 -0800 Subject: Help on project, anyone? References: <35ienhF4lu88lU1@individual.net> Message-ID: On Sun, 23 Jan 2005 21:11:32 +0100, Georg Brandl wrote: > Hello, > > to train my Python skills I am looking for some project I can contribute > to. I learned Python about one year ago, and had already some > programming background behind (I contributed to SharpDevelop for > instance), so I'm not the complete newbie. > > About myself: I'm a 20 year old German with strong interests in > programming and, of course, especially in Python (I love it...). > > Does anyone run, or participate in, a project looking for fellow > programmers? I don't have a special area of interest, well, perhaps web > programming... > > Thanks, > Georg Well, if you want to help, I've got a project that has been a python learning experience for me, and it has *lots* of potential ( read: very poor code and implementation ;-) ). Basically, it has to do with managing and playing movies on a computer, automatically moving them from recent arrivals to archives, keeping track of how many times each has been played, etc. I'd like to implement a simple text-based record for each movie to set up the brightness, volume, etc. I also need to write a back end that will generate web pages for the web interface; something along the lines of album but the author is taking album in a direction that won't work for me anymore. Email me if interested. Remvoe the obvious from my email, and include this kpwq1jkcsEzdx39gnkVvgycd15ayqq anywhere in your email to get through my spam filters. --Yan From tundra at tundraware.com Sat Jan 8 03:18:30 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 08 Jan 2005 03:18:30 EST Subject: Getting List Of All Filesystem Mounts Message-ID: Is there some pure Python/portable way to get a list of all currently mounted filesystems? ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From jerf at jerf.org Tue Jan 18 13:31:58 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 18 Jan 2005 13:31:58 -0500 Subject: generator expressions: performance anomaly? References: <354esdF4fouh0U1@individual.net> Message-ID: On Tue, 18 Jan 2005 14:05:15 +0000, Antoon Pardon wrote: > I don't see how generating byte code for a = 9; when seeing the > expression a = 3 + 6, would be a problem for non-functional > languages. To answer nearly every post you've made to this thread, "because Python doesn't have the resources to program to special cases". And as is often the case in this sort of discussion, sure, adding this might be only a little work, but there's thousands of enhancements of the same general work level and performance gain. So remember you're not just espousing this particular enhancement, you're implicitly arguing for the entire class (because there is nothing to discriminate in the argument "this is fairly easy" between this particular feature on your mind today and the other thousands of such features). To address your point more specifically, you can do this subexpression elimination to the extent that your expression is a purely functional one. "a = 3 + 6", while written in an imperative language and setting a variable in an imperative manner, has a "functional subexpression" "3 + 6", that has no side-effects, etc., so the compiler could reduce it if it knew how. (In Python, that's a function call, but since you can't change __add__ on ints, you could do this, although there's still some special casing you're doing that will ripple unpleasantly through the code.) But as soon as you call any sort of method or function, you're done. Ultimately, the use is fairly limited; I can't imagine the execution time saved would reach the time of implementation for weeks after a release, even aggregating across all Python use in the world, and "real time gained" (i.e., time useful to a human) would probably never add up to the implementation time. So why bother? That's a horrid trade off when there are so many other real gains to be had. From jatinder at textualanalytics.com Sat Jan 8 01:30:38 2005 From: jatinder at textualanalytics.com (Jatinder Singh) Date: Sat, 8 Jan 2005 12:00:38 +0530 Subject: _tkinter problem Message-ID: <002f01c4f54b$933fc9c0$8301a8c0@sanjay> Hi I am running a script which is importing tkinter from "/usr/local/lib/python2.3/lib-tk/Tkinter.py" and generating an error " import _tkinter ImportError: No module named _tkinter " can anybody tell me what is it? and how to get away with it? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeff at ccvcorp.com Thu Jan 6 22:04:41 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 06 Jan 2005 19:04:41 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: <7xvfaaaxky.fsf@ruckus.brouhaha.com> References: <10trlbqnb86tbb0@corp.supernews.com> <7xvfaaaxky.fsf@ruckus.brouhaha.com> Message-ID: <10trupr9cmrtqd0@corp.supernews.com> Paul Rubin wrote: > Jeff Shannon writes: > >>It seems to me that in other, less-dynamic languages, lambdas are >>significantly different from functions in that lambdas can be created >>at runtime. > > What languages are those, where you can create anonymous functions > at runtime, but not named functions?! That notion is very surprising > to me. Hm, I should have been more clear that I'm inferring this from things that others have said about lambdas in other languages; I'm sadly rather language-deficient (especially as regards *worthwhile* languages) myself. This particular impression was formed from a recent-ish thread about lambdas.... http://groups-beta.google.com/group/comp.lang.python/messages/1719ff05118c4a71,7323f2271e54e62f,a77677a3b8ff554d,844e49bea4c53c0e,c126222f109b4a2d,b1c9627390ee2506,0b40192c36da8117,e3b7401c3cc07939,6eaa8c242ab01870,cfeff300631bd9f2?thread_id=3afee62f7ed7094b&mode=thread (line-wrap's gonna mangle that, but it's all one line...) Looking back, I see that I've mis-stated what I'd originally concluded, and that my original conclusion was a bit questionable to begin with. In the referenced thread, it was the O.P.'s assertion that lambdas made higher-order and dynamic functions possible. From this, I inferred (possibly incorrectly) a different relationship between functions and lambdas in other (static) languages than exists in Python. Jeff Shannon Technician/Programmer Credit International From gabriel.barros at gmail.com Mon Jan 24 16:27:55 2005 From: gabriel.barros at gmail.com (Gabriel B.) Date: Mon, 24 Jan 2005 19:27:55 -0200 Subject: add indexes on the fly to lists Message-ID: <5175a81c0501241327e86c481@mail.gmail.com> I wanted to make a list index work as the index of the data in the database. something like database: idx item_description item_value being imported to my program as: x[idx][0]= item_description x[idx][1]= item_value the problem is that there will be some hundred items and possible the idx wil vary from 1 to 600 (it's not linear as items got deleted the idx should not be reused) will it still be an easy solution or just a waste of resources (having a 600-sized list for 100 elements) I'm very new to python and apreciate any hints on that. Thanks Gabriel From exogen at gmail.com Wed Jan 26 01:33:23 2005 From: exogen at gmail.com (Brian Beck) Date: Wed, 26 Jan 2005 01:33:23 -0500 Subject: alternatives to mod python In-Reply-To: References: Message-ID: > Anyone have any suggestions? The only other thing I looked at was > twisted, which I'm still evaluating. Might as well check out CherryPy as well. www.cherrypy.org Might turn out to be simpler for your needs. -- Brian Beck Adventurer of the First Order From craig at postnewspapers.com.au Fri Jan 21 10:27:28 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 21 Jan 2005 23:27:28 +0800 Subject: Dynamic properties In-Reply-To: References: Message-ID: <1106321248.19065.29.camel@bucket.localnet> On Fri, 2005-01-21 at 06:43 -0800, michael wrote: > setattr (self, key, property (fget, fset, fdel)) > it gives me > > > > What am I doing wrong here Properties must be defined in the class, not the instance, to work as expected. (Edit: Nick Coghlan explained this more accurately). You can dynamically generate properties in a metaclass or class factory, and you can add them to a class after the class is created (even from an instance of that class). If you add properties to an instance of a class rather than the class its self, though, you won't get the expected results. .class Fred(object): . def __init__(self): . self._name = 'fred' . def getname(self): . return self._name . def setname(self, newname): . self._name = newname . name = property(getname, setname) . .f = Fred() .print f.name . .# Works: .class Fred2(object): . def __init__(self): . self._name = 'fred2' . def getname(self): . return self._name . def setname(self, newname): . self._name = newname . .Fred2.name = property(Fred2.getname, Fred2.setname) .f2 = Fred2() .print f2.name . .# Won't work: .class Fred3(object): . def __init__(self): . self._name = 'fred3' . def getname(self): . return self._name . def setname(self, newname): . self._name = newname . .f3 = Fred3() .f3.name = property(f3.getname, f3.setname) .print f3.name . .# Also won't work .f3 = Fred3() .f3.name = property(Fred3.getname, Fred3.setname) .print f3.name . .# This will work, though, because while it adds the property .# after the instance is created, it adds it to the class not .# the instance. .f3 = Fred3() .Fred3.name = property(Fred3.getname, Fred3.setname) .print f3.name The chances are that whatever you want to do with dynamically created properties is better done with __getattr__ and __setattr__ instead. If they don't fit the bill, you can add properties to the class from its instances. I intensely dislike this though, personally. I'd want to look into using a class factory or metaclass to do the job if __getattr__ and __setattr__ are insufficient or unacceptable. -- Craig Ringer From steve at holdenweb.com Thu Jan 13 09:50:12 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 13 Jan 2005 09:50:12 -0500 Subject: Unclear On Class Variables In-Reply-To: References: Message-ID: <41E68AA4.9050104@holdenweb.com> Tim Daneliuk wrote: > I am a bit confused. I was under the impression that: > > class foo(object): > x = 0 > y = 1 > > means that x and y are variables shared by all instances of a class. What it actually does is define names with the given values *in the class namespace*. > But when I run this against two instances of foo, and set the values > of x and y, they are indeed unique to the *instance* rather than the > class. > I imagine here you are setting instance variables, which then *mask* the presence of class variables with the same name, because "self-relative" name resolution looks in the instance namespace before it looks in the class namespace. > It is late and I am probably missing the obvious. Enlightenment > appreciated ... You can refer to class variables using the class name explicitly, both within methods and externally: >>> class X: ... count = 0 ... def getCt(self): ... return self.count ... def inc(self): ... self.count += 1 ... >>> x1 = X() >>> x2 = X() >>> id(x1.count) 168378284 >>> x1.inc() >>> id(x1.count) 168378272 >>> id(x2.count) 168378284 >>> id(X.count) 168378284 >>> x1.getCt() 1 >>> x2.getCt() 0 >>> regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From steven.bethard at gmail.com Fri Jan 28 02:13:47 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 28 Jan 2005 00:13:47 -0700 Subject: Why do look-ahead and look-behind have to be fixed-width patterns? In-Reply-To: <1106882833.528957.18120@c13g2000cwb.googlegroups.com> References: <1106882833.528957.18120@c13g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > To grab the text after the 2nd colon (if indeed there are two or more), > it's much simpler to do this: > >>>>import re >>>>q = re.compile(r'.*?:.*?:(.*)').search >>>>def grab(s): > > ... m = q(s) > ... if m: > ... print m.group(1) > ... else: > ... print 'not found!' > ... > >>>>grab('') > not found! > >>>>grab('::::') > :: > >>>>grab('a:b:yadda') > yadda > >>>>>>>grab('a:b:c:d') > c:d > >>>>grab('a:b:') > > Or without any regular expressions: py> def grab(s): ... try: ... first, second, rest = s.split(':', 2) ... print rest ... except ValueError: ... print 'not found!' ... py> grab('') not found! py> grab('a:b:yadda') yadda py> grab('a:b:c:d') c:d py> grab('a:b:') py> To the OP: what is it you're trying to do? Often there is a much cleaner way to do it without regular expressions... Steve From bpeng at rice.edu Sat Jan 1 17:02:35 2005 From: bpeng at rice.edu (Bo Peng) Date: Sat, 01 Jan 2005 16:02:35 -0600 Subject: exposing C array to python namespace: NumPy and array module. In-Reply-To: <41d71170$1@nntp0.pdx.net> References: <41d71170$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Python's array module is not built to do this well. It can re-size the > array, delete elements inside the array, and other things that don't > work very well with C-managed data. I wrote "blocks and views" to > overcome this problem. As always the case, this problem have been encountered and solved! Your code is exactly what I needed. However, I was too impatient to wait for your reply. :-) I have realized the problems of arraymodule.c and added a ob_ownmem member in the object structure. Existing operations have been modified (mostly unchanged) according to this flag and the new module works well. Thank everyone for the help. especially in thie new year's day. Bo From ionel.mc at gmail.com Tue Jan 11 19:10:22 2005 From: ionel.mc at gmail.com (ionel) Date: Wed, 12 Jan 2005 02:10:22 +0200 Subject: python guy ide Message-ID: i'm looking for a clean gui for python with a visual editor of some sort any sugestions (i know of wxPython but i want to find out if there are other alternatives) and it's on win32 :P -- ionel. From ncoghlan at iinet.net.au Tue Jan 11 09:34:54 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 12 Jan 2005 00:34:54 +1000 Subject: Exception not captured In-Reply-To: <20050111132654.GP3808@zoran.com> References: <20050111132654.GP3808@zoran.com> Message-ID: <41E3E40E.3000505@iinet.net.au> Miki Tebeka wrote: > I get to the second "except" clause, and the printout is: > /home/mikit/work/nightly/scm/common.py:3 > /home/mikit/work/nightly/scm/common.py:3 > False > > How is this possible? Is line 3 inside a function? Then the class will be recreated anew each time the function is run. Has common.py been reload()'ed at some point? Then previously imported modules may still have names bound to the old instances. And so forth. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From fccoelho at gmail.com Mon Jan 10 04:57:54 2005 From: fccoelho at gmail.com (Flavio codeco coelho) Date: 10 Jan 2005 01:57:54 -0800 Subject: Python serial data aquisition References: <41e1b833$1_3@omega.dimensional.com> Message-ID: mfuhr at fuhr.org (Michael Fuhr) wrote in message news:<41e1b833$1_3 at omega.dimensional.com>... > If the actual byte and/or bit order is different then you'll have > to modify the expression, but this should at least give you ideas. Thanks Michael and Steve, I'll put your Ideas to the test ASAP, meanwhile, could you point me to references to these bit operations in Python? I am new to this stuff, and might need to do more of this to support other hardware... I havent been able to find anything about this on the python documentation.. Thanks a lot!! Flavio From cpl.19.ghum at spamgourmet.com Thu Jan 13 16:14:29 2005 From: cpl.19.ghum at spamgourmet.com (Harald Massa) Date: Thu, 13 Jan 2005 21:14:29 +0000 (UTC) Subject: pyPgSQL giving error! References: Message-ID: > I am using Redhat 9.0/python2.3. I installed pyPgSQL-2.4.tar.gz and it > was successfull. Now when I am trying to import that module, I got: > Type "help", "copyright", "credits" or "license" for more information. >>>> from pyPgSQL import PgSQL > Traceback (most recent call last): > File "", line 1, in ? > File "pyPgSQL/PgSQL.py", line 391, in ? > from libpq import * > File "pyPgSQL/libpq/__init__.py", line 23, in ? > from libpq import * > ImportError: No module named libpq did you really do ./configure, make and make install? where is libpq.* was a postgres installation present while doing ./configure et all? From FBatista at uniFON.com.ar Wed Jan 5 15:23:59 2005 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 5 Jan 2005 17:23:59 -0300 Subject: Python evolution: Unease Message-ID: [Daniel Bowett] #- Thanks, typically how long does it take for any documentation to be #- considered and implemented? That depends. If you know that some module is supported by someone in particular, you can asign the bug to him, so it should be attended fast. If not, you depend of that bug to be random reviewed. But once the bug is submitted, you're sure that someone somewhen will take a look at it. . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From greg.lindstrom at novasyshealth.com Fri Jan 28 15:51:47 2005 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Fri, 28 Jan 2005 14:51:47 -0600 Subject: Accessing Postgress from Windows Message-ID: <41FAA5E3.10008@novasyshealth.com> Hello, All- I am running Python 2.3 on a Windows XP box and would like to access a postgres database running on a Linux fileserver. I've googled for Python and Postgres but most of the stuff I saw looked stale. I would like to use a secure connection (ssl) and a direct connection, if possible. What can you recommend for the task? Thanks...and see you all at PyCon! --greg -- Greg Lindstrom 501 975.4859 Computer Programmer greg.lindstrom at novasyshealth.com NovaSys Health Little Rock, Arkansas "We are the music makers, and we are the dreamers of dreams." W.W. Confidentiality Notice ---------------------- This email and any attachments to it are privileged and confidential and are intended solely for use of the individual or entity to which they are addressed. If the reader of this message is not the intended recipient, any use, distribution, or copying of this communication, or disclosure of all or any part of its content to any other person, is strictly prohibited. If you have received this communication in error, please notify the sender by replying to this message and destroy this message and delete any copies held in your electronic files. Thank you. From bokr at oz.net Tue Jan 25 04:18:38 2005 From: bokr at oz.net (Bengt Richter) Date: Tue, 25 Jan 2005 09:18:38 GMT Subject: specifying constants for a function (WAS: generator expressions: performance anomaly?) References: <41f325b5.1576259210@news.oz.net> <6I2dnYLoXdcTmGncRVn-vw@comcast.com> <41f490e8.1669238027@news.oz.net> <41f5568c.1719834331@news.oz.net> Message-ID: <41f60485.1764371081@news.oz.net> On Mon, 24 Jan 2005 20:35:09 GMT, bokr at oz.net (Bengt Richter) wrote: >On Mon, 24 Jan 2005 00:31:17 -0700, Steven Bethard wrote: > >>Bengt Richter wrote: >>> So, e.g., for >>> >>> >>> presets = dict(a=1, b=2, deftime=__import__('time').ctime()) >>> >>> in the decorator args, the next version will act as if the decorated >>> function had the source code >>> >>> >>> print '%s = __frompresets__' % ', '.join(sorted(presets)) >>> a, b, deftime = __frompresets__ >>> >>> for the current version, except that it will be hidden. >> >>Cool! Keep us posted. I assume you'll put this into the Cookbook? >> >Not ready for prime time, I guess, but I made a module that does presets >and also adjusts parameters and count to do currying without nested function >calling in the curried function. > > >>> from presets import presets, curry > >>> @presets(verbose=True, a=1, b=2, deftime=__import__('time').ctime()) > ... def foo(): > ... print (a, b) > ... print deftime > ... > > presets: -- "name(?)" means name may be unused > a = 1 > b = 2 > deftime = 'Mon Jan 24 12:16:07 2005' > > >>> foo() > (1, 2) > Mon Jan 24 12:16:07 2005 > >>> @curry(verbose=True, y=444) > ... def bar(x=3, y=4): > ... return x*y > ... > > presets: -- "name(?)" means name may be unused > y = 444 > > >>> bar(2) > 888 > >>> bar(2, 3) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: bar() takes at most 1 argument (2 given) > >>> bar() > 1332 Not much reaction, so I guess I won't see it if any, since I am going off line for a while. BTW, this exercise makes me realize that you could do some other interesting things too, if you put your mind to it. E.g., it might be interesting to inject properties into the local namespace of a function, so that e.g., x=1 would would trigger an effect like someobj.x = 1, where type(someobj).x was a property. It wouldn't be too hard to make @addprop(verbose=True, x=property(getx, setx, delx)) def foo(): x = 123 return x etc. Maybe could be used to monitor access to specific locals for debug, or other uses. Haven't even begun to think about that. Another thing is to turn selected local defs into constants, since executing the aggregation-of-parts code that accomplished the def may well be unchanging. This would reduce the execution cost of nested functions. I guess that is a specific case of a more general sticky-evaluate-rhs-once kind of directive for locals that are only assigned in one place. special sentinels could be used in the decorator keyword values to indicate this treatment of the associated name, e.g. from presets import presets @presets(x=presets.STICKY, y=123) def foo(y): x = initx() # done once on the first call, making x references constant after that return x*y Another thing that could be done is to inject pre and post things like atexit stuff. Also maybe some adaptation things that is just a buzzword so far that I haven't explored. BTW, is there another op that needs relocation besides JUMP_ABSOLUTE? I was wondering about doing code mods by messing with an ast, but a decorator would have to chase down the source and reparse I guess, in order to do that. It would be interesting to be able to hook into ast stuff with some kind of metacompile hook (hand waving ;-) Bye for a while. Regards, Bengt Richter From jfj at freemail.gr Wed Jan 26 14:55:59 2005 From: jfj at freemail.gr (jfj) Date: Wed, 26 Jan 2005 11:55:59 -0800 Subject: Tuple slices In-Reply-To: <10vdj4s9ib19fe3@corp.supernews.com> References: <35kn4mF4o44ufU1@individual.net> <35lckuF4kbtbfU1@individual.net> <10vb3enf8qvld4@corp.supernews.com> <35lm6dF4hr4t2U1@individual.net> <1106669254.838248.317170@z14g2000cwz.googlegroups.com> <10vdj4s9ib19fe3@corp.supernews.com> Message-ID: <41F7F5CF.5040902@freemail.gr> Jeff Shannon wrote: > > > So, what problem is it, exactly, that you think you'd solve by making > tuple slices a view rather than a copy? > I think views are good for 1) saving memory 2) saving time (as you don't have to copy the elements into the new tuple) And they are worth it. However, (as in other cases with slicing), it is very easy and fast to create a view for a slice with the default step '1', while it's a PITA and totally not worth it to create a view for a slice with non default step. I think it would be good to: if slice_step == 1 create_view else create_new_tuple Actually, i think that slices with step, is a bad feature in general and i think I will write a PEP to suggest their removal in python3k. Gerald From aut_gbarros at uolinc.com Thu Jan 27 10:24:20 2005 From: aut_gbarros at uolinc.com (Gabriel Cosentino de Barros) Date: Thu, 27 Jan 2005 13:24:20 -0200 Subject: leo editor Message-ID: <2814F26DA6908F41927A81C410C4991A02079C75@siamun.server.bl.corp.intranet> A co-worker was trying to convince me that Leo[1] is the better editor of all since it outline the code and let you easily document algoritms and logic. He was writting php code with it. I use jEdit or vi to write my python and my php Then after a day of debates I ended up convincing him that abstracting every algorith and complex logic into a separate class and using the doc inside the class the python way was exactly the same thing that Leo does, if not better hence you don't need an IDE for that. But then, I realised that maybe it's just that we don't get it yet. So, the question i drop here is if anyone uses or is forced to use Leo for bigger projects, does it help or get in the way? Does the project management capabilities pay off the tangling/untangling hassle? Does it make it easier to work if the group is bigger? Thanks! Gabriel [1] http://webpages.charter.net/edreamleo/front.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From sam.wun at authtec.com Wed Jan 12 10:19:44 2005 From: sam.wun at authtec.com (sam) Date: Wed, 12 Jan 2005 23:19:44 +0800 Subject: Excel module for Python In-Reply-To: References: Message-ID: Simon Brunning wrote: > On Wed, 12 Jan 2005 15:18:09 +0800, sam wrote: > >>I m wondering which Excel module is good to be used by Python? > > > If you are on Windows, and you have Excel, then the Python for Windows > extensions[1] are all you need to drive Excel via COM. O'Reilly's > "Python Programming on Win32" covers COM scripting extensively - and > by good fortune, driving Excel is the example they use, and the COM > scripting chapter is on-line[2]. > > You'll also need to know the objects and methods that Excel exposes. > These are documented on Microsoft's web site[3], or in the Excel VBA > help, which is an optional part of they Office installation. > No, I don't use MS windows. I need to generate Excel file by printing data to it, just like Perl module Spreadsheet::WriteExcel. thanks Sam From invalidemail at aerojockey.com Mon Jan 10 06:09:40 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 10 Jan 2005 03:09:40 -0800 Subject: python3: 'where' keyword In-Reply-To: <7xllb2f3z4.fsf@ruckus.brouhaha.com> References: <3480qqF46jprlU1@individual.net> <1105228549.608275.148740@c13g2000cwb.googlegroups.com> <7xk6qnzd3d.fsf@ruckus.brouhaha.com> <1105230350.861683.265970@c13g2000cwb.googlegroups.com> <7x3bxbe97m.fsf@ruckus.brouhaha.com> <7xsm5b2m93.fsf@ruckus.brouhaha.com> <7xr7ku26zs.fsf@ruckus.brouhaha.com> <1105319590.641211.191630@c13g2000cwb.googlegroups.com> <7xllb2f3z4.fsf@ruckus.brouhaha.com> Message-ID: <1105355380.040837.189270@c13g2000cwb.googlegroups.com> Paul Rubin wrote: > "Carl Banks" writes: > > And a suite, be it a def statement, a where block, or whatever, belongs > > in a statement, not an expression. > > So do you approve of the movement to get rid of the print statement? Any little incremental change in Python you could make by having or not having a print statement would be minor compared to the H-Bomb of ugliness we'd get if suites of statements were to be allowed inside Python expressions. Having or not having a print statement might violate some small aspect of the Zen, but it won't rape the whole list. So I don't know what point you're trying to make. But to answer your question, I would prefer a Python without a print statement, since a print method could do anything the print statement could. -- CARL BANKS From tom at dtsam.com Tue Jan 25 17:25:19 2005 From: tom at dtsam.com (Thomas Bartkus) Date: Tue, 25 Jan 2005 16:25:19 -0600 Subject: python without OO References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: "Davor" wrote in message news:1106689788.676121.48490 at c13g2000cwb.googlegroups.com... > Is it possible to write purely procedural code in Python, ... Of course! > or the OO > constructs in both language and supporting libraries have got so > embedded that it's impossible to avoid them? You can always *write your own* purely procedure code. A tougher problem would be living without the wealth of supporting library code that is written OO. > Also, is anyone aware of > any scripting language that could be considered as "Python minus OO > stuff"? Anyone aware? Not I! > (As you can see I'm completely new to Python and initially > believed it's a nice&simple scripting language before seeing all this > OO stuff that was added in over time) Over time ??? Someone can correct me if I'm wrong but I do believe that all that dirty, rotten OO stuff was incorporated in the language right from the start. But If you can live without coding OO, you can do it in Python. I'm not sure what it is, exactly, you are trying to avoid. Much "nice&simple scripting " simply has no need to create and use objects. Of course, the entire structure of Python and all of it's built in data structures are object oriented. But, if you wish to live within the confines of your own strictly procedural code, I don't think you need to deal with the issue. On the other hand, this does beggar for a reason to bother with Python at all. It seems you could be happy doing BASH scripts for Linux or DOS batch files for Windows. Both are "nice&simple" scripting languages free of object oriented contamination. Why would you use an object oriented language if you don't want to? Thomas Bartkus From itsme at yahoo.com Wed Jan 12 13:25:49 2005 From: itsme at yahoo.com (It's me) Date: Wed, 12 Jan 2005 18:25:49 GMT Subject: Why would I get a TypeEror? References: Message-ID: Sorry if my question was a little "lazy" and yes, I was asking about the "lazy evaluation". :=) I am surprised about this (and this can be dangerous, I guess). If this is true, I would run into trouble real quick if I do a: (1/x,1.0e99)[x==0] and that's not good. Something to keep in mind. :-( "harold fellermann" wrote in message news:mailman.578.1105553620.22381.python-list at python.org... > > On 12.01.2005, at 18:35, It's me wrote: > > > For this code snip: > > > > a=3 > > .... > > b=(1,len(a))[isinstance(a,(list,tuple,dict))] > > > > Why would I get a TypeError from the len function? > > the problem is, that (1,len(a)) is evaluated, neither what type a > actually has > (python has no builtin lazy evaluation like ML). You have to do it this > way > instead: > > a=3 > ... > b = isinstance(a,(list,tuple,dict)) and len(a) or 1 > > - harold - > > -- > The opposite of a correct statement is a false statement. > But the opposite of a profound truth may be another profound truth. > -- Niels Bohr > From jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com Sat Jan 1 22:03:11 2005 From: jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com (Miklós P) Date: Sun, 2 Jan 2005 04:03:11 +0100 Subject: Is it possible to open a dbf References: <0F3Ad.3192$5R.2578@newssvr21.news.prodigy.com> <7xy8fjywar.fsf@ruckus.brouhaha.com> Message-ID: > Paul Rubin wrote: > > > John Fabiani writes: > >> I'm wondering if there is a module available that will open a dbf > > > So far (more than a minute) I have discovered a reader only. So if you have > a URL or a search string it would be very helpful. > TIA > John Yes, "dBase Python" yields only some code for reading dBase ... and lots of enquires about such a thing... Mikl?s --- Jegenye 2001 Bt. Egyedi szoftverk?sz?t?s, tan?csad?s | Custom software development, consulting Magyarul: http://jegenye2001.parkhosting.com In English: http://jegenye2001.parkhosting.com/en From helm.volker at gmx.de Wed Jan 12 16:58:33 2005 From: helm.volker at gmx.de (Volker Helm) Date: Wed, 12 Jan 2005 22:58:33 +0100 Subject: cxOracle for python 2.4 In-Reply-To: <1104878161.316087.28080@z14g2000cwz.googlegroups.com> References: <340bheF44qhdtU1@individual.net> <1104878161.316087.28080@z14g2000cwz.googlegroups.com> Message-ID: <34pghmF4eqq98U1@individual.net> Thanks a lot! :-) sigzero at gmail.com wrote: >>does anybody knows where I can get the DB interface cx_Oracle for > > Python > >>2.4 with win32. >> > http://starship.python.net/crew/atuining/cx_Oracle/ Link is saved for some time. Volker From harold.fellermann at upf.edu Tue Jan 11 16:33:10 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 11 Jan 2005 22:33:10 +0100 Subject: how to set doc-string of new-style classes In-Reply-To: <1gq8p18.109u52rvr55yoN%aleaxit@yahoo.com> References: <1gq8p18.109u52rvr55yoN%aleaxit@yahoo.com> Message-ID: <63F4AB4E-6418-11D9-B3E0-003065FB7B26@upf.edu> On 11.01.2005, at 19:35, Alex Martelli wrote: > harold fellermann wrote: > ... >> But, I cannot >> even find out a way to set the doc string, when I CREATE a class using >> type(name,bases,dict) ... At least this should be possible, IMHO. > >>>> x=type('x',(),dict(__doc__='hi there')) >>>> x.__doc__ > 'hi there' yes, you're right ... a subsequent question, that puzzles me: where can I apply for the "most-stupid-question"-award, now *g* thanks anyway, - harold - -- The opposite of a correct statement is a false statement. But the opposite of a profound truth may be another profound truth. -- Niels Bohr From steven.bethard at gmail.com Sun Jan 9 16:45:32 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 09 Jan 2005 14:45:32 -0700 Subject: Python3: on removing map, reduce, filter In-Reply-To: References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> Message-ID: <-7mdndrwD_1qOHzcRVn-qQ@comcast.com> Robert Kern wrote: > Andrey Tatarinov wrote: > >> anyway list comprehensions are just syntaxic sugar for >> >> >>> for var in list: >> >>> smth = ... >> >>> res.append(smth) >> >> (is that correct?) >> >> so there will be no speed gain, while map etc. are C-implemented > > > It depends. > > Try > > def square(x): > return x*x > map(square, range(1000)) > > versus > > [x*x for x in range(1000)] > > Hint: function calls are expensive. > Some timings to verify this: $ python -m timeit -s "def square(x): return x*x" "map(square, range(1000))" 1000 loops, best of 3: 693 usec per loop $ python -m timeit -s "[x*x for x in range(1000)]" 10000000 loops, best of 3: 0.0505 usec per loop Note that list comprehensions are also C-implemented, AFAIK. Steve From claird at lairds.us Tue Jan 4 11:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 04 Jan 2005 16:08:03 GMT Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <41d7941f$1_3@127.0.0.1> <7x8y7cjo57.fsf@ruckus.brouhaha.com> <87zmzsax12.fsf@hector.domek> Message-ID: In article <87zmzsax12.fsf at hector.domek>, Peter Dembinski wrote: . . . >def foo(x): > return str(x) > >str = foo(x) > >And now, let's say that foo()'s definition is in another module. >It is hard for a programmer to quickly determine the type for str, >that's the problem with programming in languages that don't have >type declarations. I think I don't understand. I believe you're saying that Python and C might code homologously as def py_foo(x) return py_bar(x) and char *C_foo(int x) { return C_bar(x); } and that these definitions make it evident that C_foo() returns a (char *), while there's no such manifest restriction on the type of py_foo(). Well, yes, that's so (but what did it have to do with definitions in another module?). There's nothing peculiar in this to functions, right? Python declares types of *no* bindings, so your claim is equally true of local variables, correct? And this is all a *benefit* of Python, at least as I see it. Yes, good style in Python is different from good style in C, but the former's strong implicit typing has, I think, equal claim to virtue. Type in C are so epiphenomenal. They communicate little of what *I* need to know. From dbickett at gmail.com Sun Jan 23 13:34:29 2005 From: dbickett at gmail.com (Daniel Bickett) Date: Sun, 23 Jan 2005 13:34:29 -0500 Subject: on the way to find pi! In-Reply-To: <20050123182847.74790.qmail@web61009.mail.yahoo.com> References: <20050123182847.74790.qmail@web61009.mail.yahoo.com> Message-ID: <1d6cdae30501231034140ba539@mail.gmail.com> Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import math >>> math.pi 3.1415926535897931 Daniel Bickett From rnd at onego.ru Wed Jan 5 09:19:38 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 5 Jan 2005 17:19:38 +0300 (MSK) Subject: Concepts RE: Python evolution: Unease In-Reply-To: <7xwtus9jbn.fsf@ruckus.brouhaha.com> References: <20050105002302.542768387.EP@zomething.com> <7xr7l06qfc.fsf@ruckus.brouhaha.com> <7xwtus9jbn.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 5 Jan 2005, Paul Rubin wrote: >Paul Rubin writes: >> There is nothing in Wikipedia about [Generic programming]. > >Oops: http://en.wikipedia.org/wiki/Generic_programming > >This helps. But I don't see how it's different from what used to >be called polymorphism. I already posted these links. They seem to give more fundamental definitions than wikipedia: ''' 1. http://www.cs.rpi.edu/~musser/gp/ 2. "A Formalization of Concepts for Generic Programming" (google could find PDF of that). If I am correct, this one: http://www.osl.iu.edu/publications/pubs/2004/willcock04:_formal_concep_gener_progr.pdf (it is safe to skip till example on Fig.1 to grasp the idea behind a concept. Relations between concepts are also very logical and remind of inheritance, association and aggregation) 3. "The Boost Graph Library" by Jeremy Siek, et al with A.Stepanov's foreword is a good way to see GP != STL. ''' As for polymorphism, yes, polymorphism. But any decent language has some sort of polymorphism today. The essense of concepts is that they provide formalities for (call them) contracts, interfaces, etc. Concepts from GP gather all these together and call it a concept: a family of similar types. Python already uses concepts implicitly, by convention. And we know them well: file-like objects, sequences, maps, sets, queues, arrays, etc. My "marketing" of GP is directed to formalise on concepts instead of partial cases (design-by-contract, interfaces etc). Thus, concepts control polymorphism not only from liberation side, but from constraint side too. Right now concepts in Python are reused here and there without explicit mentioning. Concepts could help make code even more reusable. Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From duncan.booth at invalid.invalid Mon Jan 10 11:06:33 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Jan 2005 16:06:33 GMT Subject: pulling info from website References: <41e2a556$0$14576$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: bob wrote: > i am trying to write a script for Xbox media center that will pull > information from the bbc news website and display the headlines , how > do i pull this info into a list??? > > Google for "Python RSS reader" and read some of the results. http://effbot.org/zone/effnews.htm probably answers many of your questions, especially since he uses the BBC news headlines as an example. From Benjamin_Schmeling at gmx.de Mon Jan 31 13:07:33 2005 From: Benjamin_Schmeling at gmx.de (Benjamin Schmeling) Date: Mon, 31 Jan 2005 19:07:33 +0100 Subject: implicit conversion Message-ID: <41FE73E5.3030806@gmx.de> Alex Martelli wrote: > Benjamin Schmeling wrote: > ... > > >> I don't know how to achieve implicit conversion at this point, >> turning an >> long automatically into an bigint. The other way round, turning an >> bigint >> into long can be realized by defining __long__. >> > > > Perhaps adding to your bigint class a constructor (not declared as > ``explicit'', if you're coding C++) which accepts as its argument a > python long might help...? > > > Alex > > I have got such an constructor now (my_type(long_)), but nevertheless implicit conversion from long to my_type isn't supported. Any other ideas? Benjamin From peter at somewhere.com Fri Jan 7 08:12:19 2005 From: peter at somewhere.com (Peter Maas) Date: Fri, 07 Jan 2005 14:12:19 +0100 Subject: Embedding a restricted python interpreter In-Reply-To: <7xvfaaurkn.fsf@ruckus.brouhaha.com> References: <345mkrF46jc4cU1@individual.net> <7xvfaaurkn.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schrieb: >>Best solution would probably be to create >>a thread for each request that can operate only with the id of an >>authenticated user. But this seems to be a problem with Apache or >>with Linux? > > > Threads wouldn't do it--you'd need separate processes. For example, > multiple threads in the same process can access each other's file > descriptors. You are probably talking about Unix-like systems. I googled for that and found that on Windows threads inherit the security context of their parent processes but can impersonate as another user after being created. So it seems to be an OS issue. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From jurgenex at hotmail.com Tue Jan 11 05:15:51 2005 From: jurgenex at hotmail.com (Jürgen Exner) Date: Tue, 11 Jan 2005 10:15:51 GMT Subject: 20050110: string join, substring, length References: <1105427394.732934.140900@f14g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: [...] > # perldoc -tf substr Is there a specific reason why you are 'ugly-printing' the doc pages? >From 'perldoc perldoc': -t text output Display docs using plain text converter, instead of nroff. This may be faster, but it won't look as nice. jue From nick at craig-wood.com Thu Jan 13 11:30:03 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 13 Jan 2005 16:30:03 GMT Subject: Debian says "Warning! you are running an untested version of Python." on 2.3 References: Message-ID: Alex Stapleton wrote: > Whenever I run python I get > > "Warning! you are running an untested version of Python." > > prepended to the start of any output on stdout. > > This is with Debian and python 2.3 (running the debian 2.1 and 2.2 binaries > doesn't have this effect) What version of a) Debian and b) python are you running? I don't have that problem here (I'm running testing/sarge) $ python2.4 -c 'pass' $ python2.3 -c 'pass' $ python2.2 -c 'pass' $ python2.1 -c 'pass' $ $ dpkg -l python2.1 python2.2 python2.3 python2.4 ||/ Name Version Description +++-==============-==============-============================================ ii python2.1 2.1.3-25 An interactive high-level object-oriented la ii python2.2 2.2.3-10 An interactive high-level object-oriented la ii python2.3 2.3.4-18 An interactive high-level object-oriented la ii python2.4 2.4-2 An interactive high-level object-oriented la -- Nick Craig-Wood -- http://www.craig-wood.com/nick From lbolognini at gmail.com Mon Jan 10 03:36:36 2005 From: lbolognini at gmail.com (lbolognini at gmail.com) Date: 10 Jan 2005 00:36:36 -0800 Subject: raw sockets ? i need a python sniffer In-Reply-To: References: Message-ID: <1105346196.670668.34080@c13g2000cwb.googlegroups.com> Would this suit you? http://www.nullcube.com/software/pyopenbsd.html Lorenzo From danperl at rogers.com Mon Jan 31 01:19:25 2005 From: danperl at rogers.com (Dan Perl) Date: Mon, 31 Jan 2005 01:19:25 -0500 Subject: Regarding exception handling References: <1107114438.710147.218010@z14g2000cwz.googlegroups.com> <1107114866.965331.158950@f14g2000cwb.googlegroups.com> <1107119504.793109.184450@c13g2000cwb.googlegroups.com> <1107127179.863445.55310@c13g2000cwb.googlegroups.com> <1107140290.363099.273690@c13g2000cwb.googlegroups.com> Message-ID: "Aggelos I. Orfanakos" wrote in message news:1107140290.363099.273690 at c13g2000cwb.googlegroups.com... > Good point, but with your way, if "s = ... # socket opens" fails, then > nothing will catch it. What I usually do is what I wrote above (place > it below the 2nd try), and when attempting to close it, first use an if > like: "if locals().has_key('s'):". Then how about: try: s = ... # socket opens try: # various code ... finally: s.close() # socket closes except socket.error, x: # exception handling This handles all the socket exceptions in one shot. The only problem is that different problems may have to be handled differently. For instance, you may need to handle a transmission that failed in the middle differently than a failure to open the socket. Dan From gabriel.barros at gmail.com Mon Jan 24 20:30:24 2005 From: gabriel.barros at gmail.com (Gabriel B.) Date: Mon, 24 Jan 2005 23:30:24 -0200 Subject: is this use of lists normal? Message-ID: <5175a81c05012417306eb49979@mail.gmail.com> I just sent an email asking for hints on how to import data into a python program As i said earlier i'm really new to python and besides being confortable with the syntax, i'm not sure if i'm on the right track with the logic I'm asking for hints again here at the list because i think i'm already into premature optimization... My object model ended up as DataStorageObj |-itemsIndex (list, could very well be a set...) | |-[0] = 0 | |-[1] = 1 | |-[2] = 5 | '-[3] = 6 '-Items (list) |-[0] = ['cat food', '12,20'] |-[1] = ['dog food', 8,00'] |-[2] = ['dead parrot', '25,00'] '-[3] = ['friendly white bunny', '12,25'] the list itemsindex has the DB index of the data, and the list items has the data. So if i want something like "SELECT * FROM items WHERE idx=5" i'd use in my program self.items[ self.itemsIndex.index(5) ] i reccon that's not much nice to use when you're gona do /inserts/ but my program will just read the entire data and never change it. Was i better with dictionaries? the tutorial didn't gave me a good impression on them for custom data... Tupples? the tutorial mentions one of it's uses 'employee records from a database' but unfortunatly don't go for it... i think the 'ideal' data model should be something like ({'id': 0, 'desc': 'dog food', 'price': '12,20'}, ...) But i have no idea how i'd find some item by the ID within it withouy using some loops Thanks! Gabriel From theller at python.net Tue Jan 18 10:16:32 2005 From: theller at python.net (Thomas Heller) Date: Tue, 18 Jan 2005 16:16:32 +0100 Subject: MemoryError with parser.suite and wrong encoding declaration References: Message-ID: Sylvain Thenault writes: > Hi there ! > I've noticed the following problem with python >= 2.3 (actually 2.3.4 and > 2.4): > > syt at musca:test$ python > Python 2.3.4 (#2, Sep 24 2004, 08:39:09) > [GCC 3.3.4 (Debian 1:3.3.4-12)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import parser >>>> parser.suite('# -*- coding: IBO-8859-1 -*-') > Traceback (most recent call last): > File "", line 1, in ? > MemoryError >>>> parser.suite('# -*- coding: ISO-8859-1 -*-') > > > Shouldn't parser.suite just ignore the wrong encoding declaration, or at > least raise a more appropriate exception. IMHO the first solution > would be better, since that's the behaviour of the (C) python interpreter. Ignore the wrong declaration? All Python's that I have (on windows, at least) raise a SyntaxError: File "x.py", line 1 SyntaxError: 'unknown encoding: IBO-8859-1' See also: http://www.python.org/sf/979739 Thomas From b at b.b Sun Jan 9 22:03:50 2005 From: b at b.b (Roose) Date: Mon, 10 Jan 2005 03:03:50 GMT Subject: Python Operating System??? References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> <7x8y734jlq.fsf@ruckus.brouhaha.com> <7xr7kv8bmt.fsf@ruckus.brouhaha.com> <7xr7kvm72c.fsf@ruckus.brouhaha.com> Message-ID: > I've written file systems in Python, and task schedulers in > Javascript, and they were fine for their purposes Uh, not to be rude, but what are you talking about? If I'm not mistaken Javascript is that scripting language that runs inside a browser, an application. How are you going to save and restore CPU state in Javascript, or even call assembly that does it in Javascript? How do you switch into kernel mode in Javascript? We are on completely different pages apparently. > Huh? That's a non-sequitur, nothing prevents you from running Lisp on > your PC or Mac. The same issues issues that apply to OS code, also > apply to user code. The Lisp machine hardware wasn't needed only to > make the OS run fast. The Lisp machine was developed so that people > could deploy large user-level applications written in Lisp, and the > hardware was there to support those applications. And given such a > good Lisp environment, there was no reason to think of writing the OS > in anything other than Lisp. Upon reading back in the thread I see that you mean compiled Lisp, no? I was thinking that there would be a Lisp interpreter in a kernel, which afaik doesn't exist. In any case, as I said before I don't think it is impossible, just a poor engineering decision and I don't see the rationale behind it. Sure you can do anything for intellectual purposes and you'd probably learn a lot, but the OP is looking for an easier way to write an OS -- and that is not to write it in Python. From lee at example.com Tue Jan 4 17:31:31 2005 From: lee at example.com (Lee Harr) Date: Tue, 04 Jan 2005 22:31:31 GMT Subject: What can I do with Python ?? References: <1ssrl3pa3wawq.l1h3dq25szp9$.dlg@40tude.net> <1gpqhbl.125l3evz09uefN%aleaxit@yahoo.com> <84iCd.67879$Jk5.21234@lakeread01> Message-ID: <7PECd.2360$1Q3.975@news01.roc.ny> On 2005-01-03, Steve Holden wrote: > John J. Lee wrote: > >> Lee Harr writes: >> [...] >> >>>I think it looks pretty good. The only problem I see is section 5 >>>where it says: >>> >>>5. Did we miss your concern? >>> >>> Please add a comment to this page. >>> >>> >>>but the page is immutable. >> >> >> >> Hopefully one of the site maintainers will read this and demonstrate >> that it's actually readonly rather than immutable, then make it >> appendable ;-) >> >> > > To be even more pedantic, I believe it's possible to gain editing > privileges on the Wiki by authenticating yourself to the engine at > > http://www.python.org/moin/UserPreferences > > The point is to be able to track changes and thereby discourage > defacement, which was starting to happen of a depressingly regular basis. > I do not understand. Are you saying that someone who wants to "add a comment to this page" can do so? When I clicked on the "edit" link, it said: "You are not allowed to edit this page." Maybe it should say ... "You are not allowed to edit this page. Try logging in first." From rupole at hotmail.com Mon Jan 24 23:17:23 2005 From: rupole at hotmail.com (Roger Upole) Date: Mon, 24 Jan 2005 23:17:23 -0500 Subject: PyWin32 installation References: Message-ID: <41f5c8e0$1_2@127.0.0.1> Gdi32 needs to be added to the libraries for win32print in setup.py. (just checked it in) Roger "mg" wrote in message news:mailman.1171.1106557219.22381.python-list at python.org... > Hi all, > > I have reinstalled my Win32 computer last week and I did an update of the > project PyWin32 to complete my Python installation. > (I have to use sources from CVS for my project !) > > So, when I run 'python setup.py' in my PyWin32 directory, I have two > problem : the version indacated in windows.h and some symbols who are not > defined. See the trace : > > running install > running build > running build_py > running build_ext > Warning - can't find an installed platform SDK > Found WINDOWS.H version 0x501 in C:\Program Files\Microsoft > Visual Studio .NET 2003\Vc7\PlatformSDK\include > building 'win32print' extension > C:\Program Files\Microsoft Visual Studio .NET > 2003\Vc7\bin\link.exe /DLL /nologo /INCREMENTAL:NO > /LIBPATH:C:\ext_projects\python\dist\src\libs > /LIBPATH:C:\ext_projects\python\dist\src\PCBuild > /LIBPATH:build\temp.win32-2.5\Release winspool.lib user32.lib > /EXPORT:initwin32print > build\temp.win32-2.5\Release\win32\src\win32print\win32print.obj > /OUT:build\lib.win32-2.5\win32\win32print.pyd > /IMPLIB:build\temp.win32-2.5\Release\win32\src\win32print\win32print.lib > /MACHINE:ix86 > Creating library > build\temp.win32-2.5\Release\win32\src\win32print\win32print.lib and > object build\temp.win32-2.5\Release\win32\src\win32print\win32print.exp > win32print.obj : error LNK2019: unresolved external symbol > __imp__StartDocA at 8 referenced in function "struct _object * __cdecl > PyStartDoc(struct _object *,struct _object *)" > (?PyStartDoc@@YAPAU_object@@PAU1 at 0@Z) > win32print.obj : error LNK2019: unresolved external symbol > __imp__EndDoc at 4 referenced in function "struct _object * __cdecl > PyEndDoc(struct _object *,struct _object *)" > (?PyEndDoc@@YAPAU_object@@PAU1 at 0@Z) > > Then, I don't kwnow how to solve theses problem ! Is there someone tho > help me ? > Thank, > > Mathieu G. ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From steven.bethard at gmail.com Wed Jan 12 19:43:28 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 12 Jan 2005 17:43:28 -0700 Subject: reference or pointer to some object? In-Reply-To: <10ubcp136drsu97@corp.supernews.com> References: <10ubcp136drsu97@corp.supernews.com> Message-ID: Jeff Shannon wrote: > Torsten Mohr wrote: > >> I still wonder why a concept like "references" was not >> implemented in Python. I think it is (even if small) >> an overhead to wrap an object in a list or a dictionary. > > Because Python uses a fundamentally different concept for variable names > than C/C++/Java (and most other static languages). In those languages, > variables can be passed by value or by reference; neither term really > applies in Python. (Or, if you prefer, Python always passes by value, > but those values *are* references.) Python doesn't have lvalues that > contain rvalues; Python has names that are bound to objects. Passing a > parameter just binds a new name (in the called function's namespace) to > the same object. Point of clarification: Java objects (but not Java primitive types like ints or doubles) work almost identically to Python objects -- you can basically think of them as references being passed by value. There's no way to pass by reference in Java (even for Java primitive types). Steve From bokr at oz.net Thu Jan 13 17:18:55 2005 From: bokr at oz.net (Bengt Richter) Date: Thu, 13 Jan 2005 22:18:55 GMT Subject: Statement local namespaces summary (was Re: python3: 'where' keyword) References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> <34cieoF489ejfU1@individual.net> <41E12700.8000106@iinet.net.au> Message-ID: <41e6dc9b.771173178@news.oz.net> On Fri, 14 Jan 2005 01:48:48 +1000, Nick Coghlan wrote: >Nick Coghlan wrote: >> Semantics >> --------- >> The code:: >> >> with: >> >> >> translates to:: >> >> def unique_name(): >> >> >> unique_name() > >I've come to the conclusion that these semantics aren't what I would expect from >the construct. Exactly what I would expect can't really be expressed in current >Python due to the way local name bindings work. The main thing to consider is >what one would expect the following to print: > >def f(): > a = 1 > b = 2 > print 1, locals() > print 3, locals() using: > a = 2 > c = 3 > print 2, locals() > print 4, locals() > >I think the least suprising result would be: > >1 {'a': 1, 'b': 2} # Outer scope >2 {'a': 2, 'c': 3} # Inner scope >3 {'a': 2, 'b': 2, 'c': 3} # Bridging scope >4 {'a': 1, 'b': 2} # Outer scope > >In that arrangement, the statement with a using clause is executed normally in >the outer scope, but with the ability to see additional names in its local >namespace. If this can be arranged, then name binding in the statement with the >using clause will work as we want it to. > >Anyway, I think further investigation of the idea is dependent on a closer look >at the feasibility of actually implementing it. Given that it isn't as >compatible with the existing nested scope structure as I first thought, I >suspect it will be both tricky to implement, and hard to sell to the BDFL >afterwards :( > In the timbot's let/in format: def f(): a = 1 b = 2 print 1, locals() let: a = 2 c = 3 print 2, locals() in: print 3, locals() print 4, locals() I think the effect would be as if >>> def f(): ... a = 1 ... b = 2 ... print 1, locals() ... def __unique_temp(): ... a = 2 ... c = 3 ... print 2, locals() ... def __unique_too(): ... print 3, locals() ... __unique_too() ... __unique_temp() ... del __unique_temp ... print 4, locals() ... >>> f() 1 {'a': 1, 'b': 2} 2 {'a': 2, 'c': 3} 3 {} 4 {'a': 1, 'b': 2} print 3, locals() doesn't show a,b,c in locals() unless you use them somehow in that scope, e.g., >>> def f(): ... a = 1 ... b = 2 ... print 1, locals() ... def __unique_temp(): ... a = 2 ... c = 3 ... print 2, locals() ... def __unique_too(): ... print 3, locals(), (a,b,c) # force references for locals() ... __unique_too() ... __unique_temp() ... del __unique_temp ... print 4, locals() ... >>> f() 1 {'a': 1, 'b': 2} 2 {'a': 2, 'c': 3, 'b': 2} 3 {'a': 2, 'c': 3, 'b': 2} (2, 2, 3) 4 {'a': 1, 'b': 2} Of course, locals() does not include globals, even though they're referenced and visible: >>> b 'global b' >>> def bar(): ... print locals(), b ... >>> bar() {} global b The trouble with this is that bindings created in __unique_too all get thrown away, and you wouldn't want that limitation. So I proposed specifying the (re)bindable names in a parenthesized list with the let, like "let(k, q, w): ..." so that those names would be (re)bindable in the same scope as the let(...): statement. As an extension, I also proposed optionally binding __unique_temp to a specified name and not calling it automatically, instead of the automatic call and del. That provides new ways to factor updates to local namespaces into local functions with selective write-through (bind/rebind) to local names. E.g., # define case blocks for switch # better sugar later, this is to demo functinality ;-) #a let(x): k = 123 in foo: x = k #b let(x, y): q = 456 from math import pi as r in bar: x = q y=r # extra binding created if bar is called #c let(x):in baz:x=789 # most compact form, where nothing in the let clause switch = dict(a=foo, b=bar, c=baz) Now you can update local bindings with a case switch: x = 0 case = 'b' print x # => 0 switch[case]() # executes bar() in this example, which assigns local x=456 and y=pi print x # => 456 This spare example is easy to dismiss, but think of foo, bar, and baz as arbitrary sequences of statements in the local namespace, except you can factor them out as a single named group and invoke them safely by name(), and have them affect only the local names you specify in the group's let(x, y, ...): spec. It provides a new way of factoring. As well as things no one has thought of yet ;-) The other thing to think about is that the let suite could be strictly def-time, which would provide the opportunity to avoid re-calculating things in functions without abusing default args, and using the easy closure-variable creation instead. E.g., let(foo): preset = big_calc() in: def foo(x): return x * preset (This "in:" has no "in xxx:" name, so the effect is immediate execution of the anonymously defined function, which writes through to foo with the def, as permitted by let(foo):). Problems? (Besides NIH, which I struggle with regularly, and had to overcome to accept Tim's starting point in this ;-) Regards, Bengt Richter From mfinder at digipen.edu Sat Jan 15 19:35:01 2005 From: mfinder at digipen.edu (M Jared Finder) Date: Sat, 15 Jan 2005 16:35:01 -0800 Subject: python mode indentation problem In-Reply-To: <1105802644.939051.229990@f14g2000cwb.googlegroups.com> References: <1105802644.939051.229990@f14g2000cwb.googlegroups.com> Message-ID: <34tr5lF4ei1kiU1@individual.net> Xah Lee wrote: > does anyone know why the Python mode in emacs uses spaces for first > level indentation but one tab for second level? > > i'm using emacs 21.3.50.1. You probably have tab-width set to 8 spaces, but indentation in python set to 4 spaces. -- MJF From simon.brunning at gmail.com Tue Jan 18 06:55:01 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 18 Jan 2005 11:55:01 +0000 Subject: lambda In-Reply-To: References: <41EBA021.5060903@holdenweb.com> Message-ID: <8c7f10c6050118035565c5e522@mail.gmail.com> On 18 Jan 2005 07:51:00 GMT, Antoon Pardon wrote: > 3 mutating an item in a sorted list *does* *always* cause problems No, it doesn't. It might cause the list no longer to be sorted, but that might or might no be a problem. > More specific the Decimal class is mutable and usable as dict key. Decimal objects are immutable, so far as I know. >>> from decimal import Decimal >>> spam = Decimal('1.2') >>> eggs = spam >>> eggs is spam True >>> eggs += 1 >>> eggs is spam False -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From xah at xahlee.org Fri Jan 28 18:10:49 2005 From: xah at xahlee.org (Xah Lee) Date: 28 Jan 2005 15:10:49 -0800 Subject: what's OOP's jargons and complexities? Message-ID: <1106953849.915440.134710@f14g2000cwb.googlegroups.com> in computer languages, often a function definition looks like this: subroutine f (x1, x2, ...) { variables ... do this or that } in advanced languages such as LISP family, it is not uncommon to define functions inside a function. For example: subroutine f (x1, x2, ...) { variables... subroutine f1 (x1...) {...} subroutine f2 (x1...) {...} } often these f1 f2 inner functions are used inside f, and are not relevant outside of f. Such power of the language gradually developed into a style of programing. For example: subroutine a_surface () { coordinatesList = ...; subroutine translate (distance) {...} subroutine rotate (angle) {..} } such a style is that the a_surface is no longer viewed as a function. But instead, a boxed set of functions, centered around a piece of data. And, all functions for manipulating this piece of data are all embodied in this function. For example: subroutine a_surface (arg) { coordinatesList = ... subroutine translate (distance) {set coordinatesList to translated version} subroutine rotate (angle) {set coordinatesList to rotated version} subroutine return () {return coordinatesList} if (no arg) {return coordinatesList} else { apply arg to coordinatesList } } In this way, one uses a_surface as a data, which comes with its owe set of functions: mySurface = a_surface(); a_surface(rotate(angle)); # now the surface data has been rotated a_surface(translate(distance)); # now its translated myNewSurface = a_surface(return()) So now, a_surface is no longer viewed as a subroutine, but a boxed set of things centered around a piece of data. All functions that work on the data are included in the boxed set. This paradigm available in functional languages has refined so much so that it spread to other groups that it became knows as Object Oriented Programing, and complete languages with new syntax catered to such scheme emerged. In such languages, instead of writing them like this: mySurface = a_surface(); a_surface(rotate(angle)); the syntax is changed to like this, for example: mySurface = new a_surface(); mySurfaceRotated = mySurface.rotate(angle); In such languages, the super subroutine a_surface is no longer called a function or subroutine. They are now called a "Class". And now the variable "mySurface = a_surface()" is now called a "Object". The subroutines inside the function a_surface() is no longer called inner-subroutines. They are called "Methods". This style of programing and language have become so fanatical that in such dedicated languages like Java, everything in the language are "Classes". One can no longer just define a variable or subroutine. Instead, one creates these meta-subroutine "Classes". Everything one do are inside Classes. And one assign variables inside these Classes to create "Objects". And one uses "Methods" to manipulate Objects. In this fashion, even data types like numbers, strings, and lists are no longer atomic data types. They are now Classes. For example, in Java, a string is a class String. And inside the class String, there are Methods to manipulate strings, such as finding the number of chars, or extracting parts of the string. This can get very complicated. For example, in Java, there are actually two Classes of strings: One is String, and the other is StringBuffer. Which one to use depends on whether you intend to change the data. So, a simple code like this in normal languages: a = "a string"; b = "another one"; c = join(a,b); print c; or in lisp style (set a "a string") (set b "another one") (set c (join a b)) (print c) becomes in pure OOP languages: public class test { public static void main(String[] args) { String a = new String("a string"); String b = new String("another one"); StringBuffer c = new StringBuffer(40); c.append(a); c.append(b); System.out.println(c.toString()); } } here, the "new String" creates a String object. The "new StringBuffer(40)" creates the changeable string object StringBuffer, with room for 40 chars. "append" is a method of StringBuffer. It is used to join two Strings. Notice the syntax "c.append(a)", which we can view it as calling a inner subroutine "append", on a super subroutine that has been assigned to c, where, the inner subroutine modifies the inner data by appending a to it. And in the above Java example, StringBuffer class has another method "toString()" used to convert this into a String Class, necessary because System.out.println's parameter requires a String type, not StringBuffer. For a example of the complexity of classes and methods, see the Java documentation for the StringBuffer class at http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StringBuffer.html in the same way, numbers in Java have become a formalization of many classes: Double, Float, Integer, Long... and each has a bunch of "methods" to operate or convert from one to the other. Instead of aNumber = 3; print aNumber^3; in Java the programer needs to master the ins and outs of the several number classes, and decide which one to use. (and if a program later needs to change from one type of number to another, it is often cumbersome.) This Object Oriented Programing style and dedicated languages (such as C++, Java) have become a fad like wild fire among the programing ignoramus mass in the industry. Partly because of the data-centric new perspective, partly because the novelty and mysticism of new syntax and jargonization. It is especially hyped by the opportunist Sun Microsystems with the inception of Java, internet, and web applications booms around 1995. At those times, OOP (and Java) were thought to revolutionize the industry and solve all software engineering problems, in particular by certain "reuse of components" concept that was thought to come with OOP. As part of this new syntax and purity, where everything in a program is of Classes and Objects and Methods, many many complex issues and concept have arisen in OOP. we now know that the jargon Class is originally and effectively just a boxed set of data and subroutines, all defined inside a subroutine. And the jargon "Object" is just a variable that has been set to this super subroutine. And the inner subroutines are what's called Methods. ----------------- because of psychological push for purity, in Java there are no longer plain subroutines. Everything is a method of some class. Standard functions like opening a file, square root a number, for loop thru a list, if else branching statements, or simple arithmetic operations... must now some how become a method of some class. In this way, the OOP Hierarchy is born. Basic data types such as now the various classes of numbers, are now grouped into a Number class hierarchy, each class having their own set of methods. The characters, string or other data types, are lumped into one hierarchy class of data types. Many types of lists (variously known as arrays, vectors, lists, hashes...), are lumped into a one hierarchy, with each node Classe having their own set methods as appropriate. Math functions, are lumped into some math class hierarchy. Now suppose the plus operation +, where does it go? Should it become methods of the various classes under Number headings, or should it be methods of the Math class set? Each language deals with these issues differently. As a example, see this page for the hierarchy of Java's core language classes: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/package-tree.html The hierarchy concept is so entangled in pure OOP such that OOP is erroneously thought of as languages with a hierarchy. (there are now also so-called Object-Oriented databases that are centered on the concept of all data are trees ...) Normally in a program, when we want to do some operation we just call the subroutine on some data. Such as open(this_file) square(4) But now with the pure OOP style, there can no longer be just a number or this_file path, because everything now must be a Object. So, the "this_file", usually being just a string representing the path to a file on the disk, is now some "file object". Initiated by something like this_file = new File("path to file"); where this file class has a bunch of methods such as reading or writing to it. see this page for the complexity of the IO tree http://java.sun.com/j2se/1.4.2/docs/api/java/io/package-tree.html see this page for the documentation of the File class itself, along with its 40 or so methods and other things. http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html Tomorrow i shall cover more manmade jargons and complexities arising out of the OOP hype, in particular Java. instantiation initializer, constructor, assessor access level specifier abstract class and abstract methods instance methods and class methods interface, inheritance, polymorphism. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From elephantum at dezcom.mephi.ru Sun Jan 9 06:21:59 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 14:21:59 +0300 Subject: python3: 'where' keyword In-Reply-To: References: <3480qqF46jprlU1@individual.net> <41DF78EB.6040502@iinet.net.au> <41dfc018.305122743@news.oz.net> Message-ID: <34cieoF489ejfU1@individual.net> Nick Coghlan wrote: > Current: > assignment_stmt ::= (target_list "=")+ expression_list > augmented_assignment_stmt ::= target augop expression_list > > New: > assignment_stmt ::= (target_list "=")+ expression_list [where_clause] > augmented_assignment_stmt ::= target augop expression_list > [where_clause] > where_clause ::= "where" ":" suite > > So the expressions in existing compound statements (for, while, if, > elif) would be out of luck. You could conceivably add the 'where' clause > to the end of those as well, to give statement local variables that > apply to the whole compound statement: Nick, you're good at formalization, thanks again. So it seems that people loved the idea of 'where' keyword, may be it's time to think about PEP draft? I appreciate any help (cause my english is not that good =)). From adam at cognitcorp.com Mon Jan 10 13:28:32 2005 From: adam at cognitcorp.com (Adam DePrince) Date: Mon, 10 Jan 2005 13:28:32 -0500 Subject: Writing huge Sets() to disk In-Reply-To: <41E2A91D.7080006@ribosome.natur.cuni.cz> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> Message-ID: <1105381712.3588.15.camel@localhost.localdomain> On Mon, 2005-01-10 at 11:11, Martin MOKREJ? wrote: > Hi, > I have sets.Set() objects having up to 20E20 items, > each is composed of up to 20 characters. Keeping > them in memory on !GB machine put's me quickly into swap. > I don't want to use dictionary approach, as I don't see a sense > to store None as a value. The items in a set are unique. Lets be realistic. Your house is on fire and you are remodeling the basement. Assuming you are on a 64 bit machine with full 64 bit addressing, your absolute upper limit on the size of a set is 2^64, or 18446744073709551616 byte. Your real upper limit is at least an order of magnitude smaller. You are asking us how to store 20E20, or 2000000000000000000000, items in a Set. That is still an order of magnitude greater than the number of *bits* you can address. Your desktop might not be able to enumerate all of these strings in your lifetime, much less index and store them. We might as well be discussing the number of angles that can sit on the head of a pin. Any discussion of a list vs Set/dict is a small micro optimization matter dwarfed by the fact that there don't exist machines to hold this data. The consideration of Set vs. dict is an even less important matter of syntactic sugar. To me, it sounds like you are taking an AI class and trying to deal with a small search space by brute force. First, stop banging your head against the wall algorithmically. Nobody lost their job for saying NP != P. Then tell us what you are tring to do; perhaps there is a better way, perhaps the problem is unsolvable and there is a heuristic that will satisfy your needs. Adam DePrince From sigzero at gmail.com Tue Jan 4 17:36:01 2005 From: sigzero at gmail.com (sigzero at gmail.com) Date: 4 Jan 2005 14:36:01 -0800 Subject: cxOracle for python 2.4 In-Reply-To: <340bheF44qhdtU1@individual.net> References: <340bheF44qhdtU1@individual.net> Message-ID: <1104878161.316087.28080@z14g2000cwz.googlegroups.com> Volker Helm wrote: > Hi there, > > does anybody knows where I can get the DB interface cx_Oracle for Python > 2.4 with win32. > > On http://www.computronix.com/utilities.shtml exists only the version > for Python 2.3. I would try to compile it myself, if I had a compiler > and would know how to use it ;-) > > Thanks in advance, > > Volker http://starship.python.net/crew/atuining/cx_Oracle/ From peter at engcorp.com Mon Jan 24 09:09:39 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jan 2005 09:09:39 -0500 Subject: Memory Usage In-Reply-To: References: Message-ID: rbt wrote: > Would a Python process consume more memory on a PC with lots of memory? > > For example, say I have the same Python script running on two WinXP > computers that both have Python 2.4.0. One computer has 256 MB of Ram > while the other has 2 GB of Ram. On the machine with less Ram, the > process takes about 1 MB of Ram. On the machine with more Ram, it uses 9 > MB of Ram. > > Is this normal and expected behavior? It's probably not normal if this is *really* the memory usage, but I would expect to see such behaviour, given how difficult it is to measure *actual* memory usage. How are you measuring it? Just by looking at the Mem Usage column in the Task Manager? -Peter From qhfgva at gmail.com Tue Jan 18 00:54:12 2005 From: qhfgva at gmail.com (qhfgva at gmail.com) Date: 17 Jan 2005 21:54:12 -0800 Subject: python execution path References: Message-ID: <1106027652.064860.12650@z14g2000cwz.googlegroups.com> Peter Hansen wrote: > Dustin Lee wrote: > > I'm wondering if there is a way to get python to show each line as it > > is executed, sort of like sh -x does for shell programs. Seems like > > this would be a nice debugging aid. > > The best approach, if it's really intended to be a debugging > aid, might be to learn about "pdb", starting perhaps with the > following line inserted shortly above where you think your > bug might be: > > import pdb; pdb.set_trace() > > (run the code, wait for the prompt, type "?" for help, then > read the docs ;-) ) > > -Peter This is more of a what if-ish question I guess. I use pdb fairly regularly, I'm just looking to extend my debugging toolkit. I saw an article recently about how perl has the sh -x type functionality and I was curious if anything like that was possible in python. Not entirely sure how it would make my life better, but it seems intriguing. From strombrg at dcs.nac.uci.edu Mon Jan 17 16:36:20 2005 From: strombrg at dcs.nac.uci.edu (Dan Stromberg) Date: Mon, 17 Jan 2005 13:36:20 -0800 Subject: buffered socket class Message-ID: I finally took a moment to put my buffered socket class, bufsock.py, on a web page. It's a wrapper class for python sockets. It should reduce tinygrams, as well as provide a more convenient interface to the application programmer. It includes functions for reading a certain number bytes, reading up to the next occurrence of an arbitrary character (newline, null byte, whatever you like), and so on. Conceptually, it is much like stdio for unix file descriptors, but instead for sockets. You can find it at: http://dcs.nac.uci.edu/~strombrg/bufsock.html Enjoy. From steve at holdenweb.com Fri Jan 21 01:33:17 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 21 Jan 2005 01:33:17 -0500 Subject: Zen of Python In-Reply-To: <7x651rwbib.fsf@ruckus.brouhaha.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> <1106177050.630141.33090@c13g2000cwb.googlegroups.com> <972ec5bd0501191641166972b0@mail.gmail.com> <7xis5szpdj.fsf@ruckus.brouhaha.com> <7xekggbrns.fsf@ruckus.brouhaha.com> <7x651rwbib.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steve Holden writes: > [Paul proves his superior Lisp knowledge] >> >>Perhaps because we don't all have your psychic powers? > > > You snipped out the examples I gave, like [x*x for x in range(5)] > leaving unnecessary residue in the name space. Was it not obvious > from the beginning that that was a kludge? If it was obviously > a kludge, was it not obvious that there would be reason to want to > fix it someday? I'm saying that if some new feature is going to > need a fix later, it's better to fix it before releasing it in > the first place. Well no, I certainly have never thought the name droppings from list comprehensions to be anything other than a wart. But my parting shot was simply to point out that you don't always know where you're going until you're at least part of the way there. Until the feature exists, how do you know it needs fixing? The fact that a bright bunch like the Python developers didn't realize that it would be sensible to have a local scope for the list comprehension variable is a perfect demonstration of that point. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From bulba at bulba.com Thu Jan 6 18:11:51 2005 From: bulba at bulba.com (Bulba!) Date: Fri, 07 Jan 2005 00:11:51 +0100 Subject: The Industry choice References: <25mlt05vtce42ohljk32qish66oj9bq049@4ax.com> <7xvfach813.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 06 Jan 2005 09:27:49 -0500, Steve Holden wrote: >>>I'd go further. It's not possible to force anyone to share, but the >>>GPL aims to remove software from a system that instead aims to force >>>people NOT to share. >> Nope. IMHO, GPL attempts to achieve the vendor lock-in. For different >> purposes than another well-known vendor, but it still does. >Well you are entitled to your opinion. But *my* opinion is that the GPL >attempts to ensure that if you re-use code by an author who so desires, >then redistribution of your code is only possible by making your own >extensions to it available on the same terms. This gives you a clear choice. I agree with you. However, I don't see how your statement contradicts mine. >To put it another way, it allows an author to specify that their code >can't be hijacked for proprietary purposes *in distributed programs*. How can the source code that is _guaranteed to stay as public availability_ be _hijacked_? If it's hijacked, it's not available anymore. Making derived work proprietary in no way implies that the base work is publicly unavailable anymore. >I >will specifically point out that there is *nothing* in the GPL that >requires you to reveal the source of program you write but do not >distribute, even when such programs incorporate tons of GPL'd code. Again, I don't see why that negates my thesis of vendor lock-in: whatever software that uses GPLed code crosses inter-organizational or inter-personal border, it has to be released with source. >> It's actually even worse: the only thing you can't share on a >> well-known vendor's platform is the software written by that >> well-known vendor -- you can choose to share or choose not to >> share whatever you or other people write on this platform. >Well that's way over-simplified. And if you mean Microsoft, *say*( >Microsoft. Oh can't you take a little joke, why do we have to be so serious.. If my allusion was not funny, well, sorry. >The GPL folks are quite happy to have you "share" anything that *you* >create. Oh absolutely, and I would be happy with them washing my car for free. ;-) >Their simply-stated and elegantly-achieved intent is that you >don't "share" anything that *they* create except on the terms they have >required for their creations. But their base work is available anyway, regardless of whatever I do or don't do. >So, it seems to me, you are whining because the authors of GPL'd code >don't want you to release *their* code except under the GPL. If that was limited to _primary_ effects, that would be understandable. Which is why I'm rather fine with LGPL for instance. However, an openly stated goal is an indirect effect: achieving the goal of "all the software in the world being free" (as in their definition of freedom). Which means that indirect, _economic_ result they hope to achieve is precisely creating a practical context when this author would have hard time to release his work under license other than GPL. Why do they call "library GPL" a "lesser" GPL, Steve, and do not really like it? Is it not for the sake of this goal? Watch this carefully: if what you claim was ALL they care for, there would be no big difference for them between LGPL and GPL. And yet for them it is quite a big deal. >What gives >*you* the right to dictate to them? Conversely, what gives them the right to dictate the authors of derived works of what they do with THEIR part of work? >How would you like it if Richard >Stallman insisted that you release your code under the GPL? Which, of >course, he doesn't. Oh but he does - just indirectly. He's attempting to create such context. GPL is a sort of wolf in a sheep's skin, while Stallman pretends it's not really a wolf, and then preaches how wonderful it will be when we will sit with millions of such sheep at the table and vote what's for lunch. >>> As the MPAA knows, people do want to share, and >>>forcing them not to do so is impossible without turning the world into >>>a police state. >Socialism is unpopular for many reasons, and many of them are indeed to >do with maintaining the separation between individuals and thereby >retaining the ability to treat them as separate economic units. But we >aren't going to change that by insisting on particular software >licenses. Realize this is a very small part of a very large debate. Absolutely. I have discussed intellectual property rights issues with friends to great lengths, not just regarding the software. >And that is their choice. They should realize, however, that some >licenses (including the more recent Python licenses) are cleared as >"GPL-compatible". I believe this means that if I receive software >licensed under a GPL-compatible license, I am at liberty to distribute >it under the GPL. >I suspect that this point is far too infrequently stressed. I really don't find it very important: where the main battle is, and where some vendors achieve domination and some fail are precisely indirect economic effects of what they do. >> Actually, I get the impression that GPL-ed software is written by >> programmers for programmers, not really for end users. >> >Not at all. It's written to be redistributed under specific terms, and >anyone who doesn't like those terms has the option of redeveloping the >functionality for themselves. But they won't. And most of the time they never do. That is the very point. It's a subtle game: what you are _allowed_ to do intertwines with practical situations and what you would _will choose_ to do given how many factors influence your decisions. >You can't insist that people give you their intellectual property on >*your* terms. God forbid! This certainly not what I meant, ever, and if anybody suggests that, I have this rabbit right here that I will release to get them. :-) >That would be like insisting that the music industry bring >down the price of their clearly-overpriced products, or that the >Baltimore Orioles stop the concession stands from charging $4.50 for a >one-dollar beer. If you want a vote in such situations then your feet >are the appropriate instrument. Walk away, and stop whining :-). >Insisting will do you no good. Absolutely. However, what you present is very partial picture: there's much more to it. >> It's a man's life in a Python Programming Association. >Since I'm taking issue with you, I will end by gently pointing out that >there's a substantial minority (? - my impression) of people who might >find your tag line (which I am sure is intended to be supportive of >Python and the c.l.py ethic, such as we might agree exists), >gender-biased and therefore just as unacceptable to them as the GPL >appears to be to you. You haven't seen the episode of "Owl Stretching Time" by MP I see. :-) No worries, you just need a little re-education. ;-) -- It's a man's life in a Python Programming Association. From mahs at telcopartners.com Tue Jan 25 03:01:29 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 25 Jan 2005 00:01:29 -0800 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <200501241624.41889.francis.girard@free.fr> References: <63b5e209.0501210558.686f5c10@posting.google.com> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> <200501241624.41889.francis.girard@free.fr> Message-ID: Francis Girard wrote: > The following implementation is even more speaking as it makes self-evident > and almost mechanical how to translate algorithms that run after their tail > from recursion to "tee" usage : > Thanks, Francis and Jeff for raising a fascinating topic. I've enjoyed trying to get my head around both the algorithm and your non-recursive implementation. Here's a version of your implementation that uses a helper class to make the algorithm itself prettier. from itertools import tee, imap def hamming(): def _hamming(): yield 1 for n in imerge(2 * hamming, imerge(3 * hamming, 5 * hamming)): yield n hamming = Tee(_hamming()) return iter(hamming) class Tee(object): """Provides an indepent iterator (using tee) on every iteration request Also implements lazy iterator arithmetic""" def __init__(self, iterator): self.iter = tee(iterator,1)[0] def __iter__(self): return self.iter.__copy__() def __mul__(self, number): return imap(lambda x: x * number,self.__iter__()) def imerge(xs, ys): x = xs.next() y = ys.next() while True: if x == y: yield x x = xs.next() y = ys.next() elif x < y: yield x x = xs.next() else: # if y < x: yield y y = ys.next() >>> hg = hamming() >>> for i in range(10000): ... n = hg.next() ... if i % 1000 == 0: print i, n ... 0 1 1000 51840000 2000 8100000000 3000 279936000000 4000 4707158941350 5000 50960793600000 6000 409600000000000 7000 2638827906662400 8000 14332723200000000 9000 68024448000000000 Regards Michael From pedro.werneck at terra.com.br Mon Jan 24 06:07:43 2005 From: pedro.werneck at terra.com.br (Pedro Werneck) Date: Mon, 24 Jan 2005 09:07:43 -0200 Subject: Asynchronous event handling...? In-Reply-To: References: Message-ID: <20050124090743.78801c54.pedro.werneck@terra.com.br> Hi, Maybe something like this... from Tkinter import * import itertools class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.grid() self.createWidgets() def createWidgets(self): self.stop = Button(self,text='Emergency Stop!',command=self.stop) self.count = Button(self,text='Count',command=self.count) self.count.grid(row=0,column=0) self.stop. grid(row=0,column=1) def count(self): self._counter = itertools.count() self._id = self.after(0, self._count) def _count(self, event=None): i = self._counter.next() print i self.update_idletasks() self._id = self.after(0, self._count) def stop(self): self.after_cancel(self._id) app = Application() app.mainloop() On Mon, 24 Jan 2005 16:52:51 +1100 "Chris Line" wrote: > -- > http://mail.python.org/mailman/listinfo/python-list From fredrik at pythonware.com Sat Jan 22 08:49:59 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 22 Jan 2005 14:49:59 +0100 Subject: What YAML engine do you use? References: <35a6tpF4gmat2U1@individual.net><7x1xcfwbab.fsf@ruckus.brouhaha.com><35csm7F4l57inU1@individual.net> <35d3bcF4k9t5mU1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Agreed. If you just want to use it, you don't need the spec anyway. but the guy who wrote the parser you're using had to read it, and understand it. judging from the number of crash reports you see in this thread, chances are that he didn't. From steven.bethard at gmail.com Fri Jan 7 13:23:28 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 07 Jan 2005 11:23:28 -0700 Subject: python3: 'where' keyword In-Reply-To: References: <3480qqF46jprlU1@individual.net> Message-ID: <1dSdnU52I-IBTkPcRVn-1A@comcast.com> Steven Bethard wrote: > How often is this really necessary? Could you describe some benefits of > this? I think the only time I've ever run into scoping problems is with > lambda, e.g. > > [lambda x: f(x) for x, f in lst] > > instead of > > [lambda x, f=f: for x, f in lst] Sorry, bad example, this should have looked something more like: [lambda y: f(x, y) for x, f in lst] ... [lambda y, x=x, f=f: f(x, y) for x, f in lst] where you actually need the lambda. Steve From http Wed Jan 5 01:29:00 2005 From: http (Paul Rubin) Date: 04 Jan 2005 22:29:00 -0800 Subject: Embedding a restricted python interpreter References: <41db7e8f$1@news.unimelb.edu.au> Message-ID: <7xllb8jsnn.fsf@ruckus.brouhaha.com> Maurice LING writes: > I won't really count on that. In my opinions, which may be wrong, > Python is not constructed to work in a sandbox like Java. Java does it > by subjecting all classes that it loads through a security > manager. What you seems to want is a Python to have Java applet-typed > of restrictions. Java has also been subject to years and years of attacks against the sandbox, followed by patches, followed by more attacks and more patches, so at this point it's not so easy to get past the security any more. But in the beginning it was full of bugs, and it may still have bugs. Python's rexec never attracted the attention of serious attackers. If you really have to do restricted execution, your best bet is to put the sandbox in a separate process chrooted to where it can't mess with the file system, and have it communicate with your application through a socket. I think there may be a way now to trap any system calls that it attempts, too. Of course none of that stops resource exhaustion attacks, etc. I don't have direct knowledge but it seems to me that there's potential for the situation to improve under PyPy, whose interpreter will have an extra layer where various bad operations can be trapped, if my impression is correct. So the long term prospects for secure rexec may be better than the immediate ones. From fredrik at pythonware.com Thu Jan 13 10:01:48 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 13 Jan 2005 16:01:48 +0100 Subject: Unclear On Class Variables References: Message-ID: Tim Daneliuk wrote: >I am a bit confused. I was under the impression that: > > class foo(object): > x = 0 > y = 1 > > means that x and y are variables shared by all instances of a class. > But when I run this against two instances of foo, and set the values > of x and y, they are indeed unique to the *instance* rather than the > class. "set" as in: obj = foo() obj.x = 10 # set x ? if so, the "obj.x=" line is *adding* an instance variable to the "x" object, which will then hide the "x" at the class level. >>> class foo(object): ... x = 0 ... y = 1 ... >>> obj = foo() >>> obj.__dict__ {} >>> obj.x 0 >>> obj.y 1 >>> foo.x 0 >>> obj.x = 10 >>> obj.__dict__ {'x': 10} >>> obj.x 10 >>> foo.x 0 if you want to assign to the class variable, assign to the class variable: >>> obj = foo() >>> obj.x 0 >>> foo.x = 20 >>> obj.__dict__ {} >>> obj.x 20 >>> foo().x 20 From tjreedy at udel.edu Tue Jan 25 16:20:01 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 Jan 2005 16:20:01 -0500 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net><35lbvdF4k3ss4U1@individual.net> <1106666051.334641.70740@z14g2000cwz.googlegroups.com> Message-ID: wrote in message news:1106666051.334641.70740 at z14g2000cwz.googlegroups.com... > > Terry Reedy wrote: >> In other words, if you don't really want slices copied out of the >> sequence, >> then don't slice! Just use 2 ints to indicate the working region or >> view. >> Both this and using a nested function with additional params are >> standard >> techniques. This also works when the seq is mutable and you want >> changes >> to the 'slice' to change the original, as in quicksort. > > I would say these are standard *C/C++* techniques; slicing simplifies > things and thus seems more 'pythonic' to me. Unless you are GvR or Tim Peters, throwing 'pythonic' at me doesn't cut it with me, especially when you use it so shallowly. The current Pythonic meaning of 'slice', as defined by GvR and implemented in core Python sequence objects and documented in the reference manuals and reiterated by GvR on PyDev in just the last day, is to make an independent in-memory #copy# of the indicated part of a sequence. Both aspects are intentional and desired features, not accidents. Yes, slicing, even in the Pythonic sense, may well simplify the OP's algorithm (of which he gave almost no detail), but the whole point of this thread is that he does not want to do that (make copy slices). While he might shortsightedly think that he wants Guido to redefine slice and replace the current implementation of tuple with a more spacious, possibly slower one that would allow that definition, that will not solve his current problem, if indeed he has one. As George Sakkis the OP noted, the essential data constituting a contiguous section view are the underlying sequence and two position markers. Whether one works with these directly or packages them into a tuple or user class instance is a matter of relative conveniences. As it turns out, I was thinking about the design choices involved in a generic sequence view class just the morning before reading the original post. But I have no idea whether GS's foo function would justify the added overhead of such a thing. It partly depends on what he wishes to optimize, which I asked about, but have not yet seen an answer about. So I suggested the simplest approach that would work. And that, to me, *is* pythonic! Terry J. Reedy From patolivares at gmail.com Mon Jan 3 20:28:35 2005 From: patolivares at gmail.com (Pato Olivares) Date: 3 Jan 2005 17:28:35 -0800 Subject: How do I make Windows Application with Python ? References: <6zmwoasy10u4$.f3k91xbegrcz.dlg@40tude.net> <1uus5gx5sfemv.1xp4xtmzz9u66.dlg@40tude.net> Message-ID: <1104802115.543884.96150@z14g2000cwz.googlegroups.com> BOOGIEMAN wrote: > Well, I programmed a little in MS Visual Studio 2003, and there you have > Console apllication and Windows application (among others). Windows one is > with buttons and other gadgets. So, I want to make applications that > doesn't open console to display result, I want to display it into the > message box. Also, I want to use that application on the computers where > Python isn't installed Well, in Python you can code "Windows Applications": see WxPython, AnyGUI, PyGTK, etc. There'is at least one RAD if you don't want to code the gui yourself (Boa Constructor). See http://www.python.org/cgi-bin/moinmoin/GuiProgramming. And about using your applications where Python is not installed, look at http://www.python.org/moin/Py2Exe -- Pato./ From luismgz at gmail.com Fri Jan 7 11:10:14 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 7 Jan 2005 08:10:14 -0800 Subject: Getting rid of "self." References: <740c3aec05010705393048a374@mail.gmail.com> Message-ID: <1105114214.359029.152240@f14g2000cwb.googlegroups.com> You can do it easier now without any black magic: class c: def __init__(s): s.x = 1 s.y = 2 s.hi = "Hi there!" The word "self" is not mandatory. You can type anything you want instead of self, as long as you supply a keyword in its place (it can be "self", "s" or whatever you want). From peter at engcorp.com Sat Jan 8 12:47:52 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 08 Jan 2005 12:47:52 -0500 Subject: Python Operating System??? In-Reply-To: <7xhdlss0tl.fsf@ruckus.brouhaha.com> References: <10trb0mgiflcj4f@corp.supernews.com> <10tteh884ivk6c9@corp.supernews.com> <7xr7kx0w4m.fsf@ruckus.brouhaha.com> <7xhdlss0tl.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > When Unix was first written, people thought implementing an OS in C > was ludicrous. Everyone knew OS's had to be written in assembler. Actually, when Unix was first written that belief was entirely correct, and OSes *did* have to be written in assembler. That is, pure C did not have the capability to handle all that was required. I recall it taking a good decade before it became *common* to find C compilers with, for example, @interrupt support to let the compiler generate code that properly saved all registers and used RTI instead of RTS (or whatever it might have been called one one's particular flavour of CPU). Now, once you added a few tiny interrupt handlers, and some context switching (stack manipulation) routines, pretty much everything else *could* be done in C, but that doesn't invalidate the point. I think it's safe to say that none of pure C, pure Lisp, or pure Python are really capable of being used as the *sole* language to build an operating system. It's also safe to say that this is a largely irrelevant point. It would probably only be of academic interest to try to do something like that. Any practical attempt would not think more than twice of resorting to a little "glue" in assembler or in the form of "canned" byte sequences built by hand and stuck into the appropriate places in memory... -Peter From tim.peters at gmail.com Mon Jan 24 22:29:17 2005 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 24 Jan 2005 22:29:17 -0500 Subject: Classical FP problem in python : Hamming problem In-Reply-To: <200501241409.25598.francis.girard@free.fr> References: <63b5e209.0501210558.686f5c10@posting.google.com> <200501232255.08496.francis.girard@free.fr> <20050123222743.GA32583@unpythonic.net> <200501241409.25598.francis.girard@free.fr> Message-ID: <1f7befae05012419297085cdf@mail.gmail.com> [Francis Girard] > For all the algorithms that run after their tail in an FP way, like the > Hamming problem, or the Fibonacci sequence, (but unlike Sieve of Eratosthene > -- there's a subtle difference), i.e. all those algorithms that typically > rely upon recursion to get the beginning of the generated elements in order > to generate the next one ... > > ... so for this family of algorithms, we have, somehow, to abandon recursion, > and to explicitely maintain one or many lists of what had been generated. > > One solution for this is suggested in "test_generators.py". But I think that > this solution is evil as it looks like recursion is used but it is not and it > depends heavily on how the m235 function (for example) is invoked. Well, yes -- "Heh. Here's one way to get a shared list, complete with an excruciating namespace renaming trick" was intended to warn you in advance that it wasn't pretty . > Furthermore, it is _NOT_ memory efficient as pretended : it leaks ! Yes. But there are two solutions to the problem in that file, and the second one is in fact extremely memory-efficient compared to the first one. "Efficiency" here was intended in a relative sense. > It internally maintains a lists of generated results that grows forever while it > is useless to maintain results that had been "consumed". Just for a gross > estimate, on my system, percentage of memory usage for this program grows > rapidly, reaching 21.6 % after 5 minutes. CPU usage varies between 31%-36%. > Ugly and inefficient. Try the first solution in the file for a better understanding of what "inefficient" means . > The solution of Jeff Epler is far more elegant. The "itertools.tee" function > does just what we want. It internally maintain a list of what had been > generated and deletes the "consumed" elements as the algo unrolls. To follow > with my gross estimate, memory usage grows from 1.2% to 1.9% after 5 minutes > (probably only affected by the growing size of Huge Integer). CPU usage > varies between 27%-29%. > Beautiful and effecient. Yes, it is better. tee() didn't exist when generators (and test_generators.py) were written, so of course nothing in the test file uses them. > You might think that we shouldn't be that fussy about memory usage on > generating 100 digits numbers but we're talking about a whole family of > useful FP algorithms ; and the best way to implement them should be > established. Possibly -- there really aren't many Pythonistas who care about this. > For this family of algorithms, itertools.tee is the way to go. > > I think that the semi-tutorial in "test_generators.py" should be updated to > use "tee". Or, at least, a severe warning comment should be written. Please submit a patch. The purpose of that file is to test generators, so you should add a third way of doing it, not replace the two ways already there. It should also contain prose explaining why the third way is better (just as there's prose now explaining why the second way is better than the first). From premshree.pillai at gmail.com Wed Jan 26 05:16:46 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Wed, 26 Jan 2005 15:46:46 +0530 Subject: python without OO In-Reply-To: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> References: <1106689788.676121.48490@c13g2000cwb.googlegroups.com> Message-ID: On 25 Jan 2005 13:49:48 -0800, Davor wrote: > Is it possible to write purely procedural code in Python, or the OO > constructs in both language and supporting libraries have got so > embedded that it's impossible to avoid them? Also, is anyone aware of > any scripting language that could be considered as "Python minus OO > stuff"? (As you can see I'm completely new to Python and initially > believed it's a nice&simple scripting language before seeing all this > OO stuff that was added in over time) > Thanks, > Davor Umm, just curious -- why would you want to not use the OO stuff? Python is like pseudocode (the basic OO, which is mostly common to most OO languages, isn't really complicated). Moreover, using Python without OO would be like, um, eating mango seed without the pulp. :) > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From kraus at hagen-partner.de Thu Jan 27 07:53:26 2005 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu, 27 Jan 2005 13:53:26 +0100 Subject: how to pass attribute name via sys.argv In-Reply-To: <41f8e31a$1@idnews.unizh.ch> References: <41f8e31a$1@idnews.unizh.ch> Message-ID: Felix Hebeler wrote: > Hi all, I am doing some Python scripting for a while, but I'm not too > deep into it yet. So I have a problem I can't solve. > > I need to call an object attribute: > > value = object.attrName[0] > > the problem is, that the attribute name can only be specified at > runtime. > > So what I have is something like > >>>> attrName = sys.argv[1] attrName > 'cellsize' > > and I need to pass it on so I can call > > value = object.cellsize[0] Use getattr: value = getattr(object, attrName)[0] > > Can this be done using Python? > > Thanks for any hints > > Cheers Felix HTH, Wolfram From steve at holdenweb.com Fri Jan 7 06:41:38 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 07 Jan 2005 06:41:38 -0500 Subject: Asyncore In-Reply-To: <1105085666.634359.33640@z14g2000cwz.googlegroups.com> References: <1105085666.634359.33640@z14g2000cwz.googlegroups.com> Message-ID: export at hope.cz wrote: > Is there any tutorial and docs with samples how to use asyncore module? > Thanks > Lad > Well, here's a very simple web server from Chapter 7 of "Python Web Programming" which might help get you started. You can see a few more examples if you download the code from the book, which you can do at http://pydish.holdenweb.com/pwp/download.htm -------- import socket import asyncore import time class http_server(asyncore.dispatcher): def __init__(self, ip, port): self.ip= ip self.port = port self.count = 0 asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.bind((ip, port)) self.listen(5) def writable(self): return 0 def handle_read(self): pass def readable(self): return self.accepting def handle_connect(self): pass def handle_accept(self): try: conn, addr = self.accept() except socket.error: # rare Linux error print "Socket error on server accept()" return except TypeError: # rare FreeBSD3 error print "EWOULDBLOCK exception on server accept()" return self.count += 1 handler = http_handler(conn, addr, self, self.count) def decrement(self): self.count -= 1 class http_handler(asyncore.dispatcher): def __init__(self, conn, addr, server, count): asyncore.dispatcher.__init__(self, sock=conn) self.addr = addr self.buffer = "" self.time = time.time() self.count = count self.server = server def handle_read(self): rq = self.recv(1024) self.buffer = """HTTP/1.0 200 OK Canned Response Follows Content-Type: text/html Response from server

          This is socket number %d """ % self.count def writable(self): if time.time()-self.time > 10: return len(self.buffer) > 0 else: return 0 def handle_write(self): sent = self.send(self.buffer) self.buffer = self.buffer[sent:] if len(self.buffer) == 0: self.close() self.server.decrement() server = http_server('', 8080) asyncore.loop(timeout=4.0) -------- regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From xah at xahlee.org Mon Jan 31 15:30:10 2005 From: xah at xahlee.org (Xah Lee) Date: 31 Jan 2005 12:30:10 -0800 Subject: [perl-python] find & replace strings for all files in a dir Message-ID: <1107203410.397877.309750@c13g2000cwb.googlegroups.com> suppose you want to do find & replace of string of all files in a directory. here's the code: ?# -*- coding: utf-8 -*- ?# Python ? ?import os,sys ? ?mydir= '/Users/t/web' ? ?findStr='' ?repStr='' ? ?def replaceStringInFile(findStr,repStr,filePath): ? "replaces all findStr by repStr in file filePath" ? tempName=filePath+'~~~' ? input = open(filePath) ? output = open(tempName,'w') ? ? for s in input: ? output.write(s.replace(findStr,repStr)) ? output.close() ? input.close() ? os.rename(tempName,filePath) ? print filePath ? ?def myfun(dummy, dirr, filess): ? for child in filess: ? if '.html' == os.path.splitext(child)[1] and ?os.path.isfile(dirr+'/'+child): ? replaceStringInFile(findStr,repStr,dirr+'/'+child) ?os.path.walk(mydir, myfun, 3) note that files will be overwritten. be sure to backup the folder before you run it. try to edit the code to suite your needs. previous tips can be found at: http://xahlee.org/perl-python/python.html --------------------------------------- the following is a Perl version i wrote few years ago. Note: if regex is turned on, correctness is not guranteed. it is very difficult if not impossible in Perl to move regex pattern around and preserve their meanings. #!/usr/local/bin/perl =pod Description: This script does find and replace on a given foler recursively. Features: * multiple Find and Replace string pairs can be given. * The find/replace strings can be set to regex or literal. * Files can be filtered according to file name suffix matching or other criterions. * Backup copies of original files will be made at a user specified folder that preserves all folder structures of original folder. * A report will be generated that indicates which files has been changed, how many changes, and total number of files changed. * files will retain their own/group/permissions settings. usage: 1. edit the parts under the section '#-- arguments --'. 2. edit the subroutine fileFilterQ to set which file will be checked or skipped. to do: * in the report, print the strings that are changed, possibly with surrounding lines. * allow just find without replace. * add the GNU syntax for unix command prompt. * Report if backup directory exists already, or provide toggle to overwrite, or some other smarties. Date created: 2000/02 Author: Xah =cut #-- modules -- use strict; use File::Find; use File::Path; use File::Copy; use Data::Dumper; #-- arguments -- # the folder to be search on. my $folderPath = q[/Users/t/web/UnixResource_dir]; # this is the backup folder path. my $backupFolderPath = q[/Users/t/xxxb]; my %findReplaceH = ( q[

          back to Unix
          Pestilence
          ]=>q[
          ? Back to Unix
          Pestilence
          ], ); # $useRegexQ has values 1 or 0. If 1, inteprets the pairs in %findReplaceH # to be regex. my $useRegexQ = 0; # in bytes. larger files will be skipped my $fileSizeLimit = 500 * 1000; #-- globals -- $folderPath =~ s[/$][]; # e.g. '/home/joe/public_html' $backupFolderPath =~ s[/$][]; # e.g. '/tmp/joe_back'; $folderPath =~ m[/(\w+)$]; my $previousDir = $`; # e.g. '/home/joe' my $lastDir = $1; # e.g. 'public_html' my $backupRoot = $backupFolderPath . '/' . $1; # e.g. '/tmp/joe_back/public_html' my $refLargeFiles = []; my $totalFileChangedCount = 0; #-- subroutines -- # fileFilterQ($fullFilePath) return true if file is desired. sub fileFilterQ ($) { my $fileName = $_[0]; if ((-s $fileName) > $fileSizeLimit) { push (@$refLargeFiles, $fileName); return 0; }; if ($fileName =~ m{\.html$}) { print "processing: $fileName\n"; return 1;}; ## if (-d $fileName) {return 0;}; # directory ## if (not (-T $fileName)) {return 0;}; # not text file return 0; }; # go through each file, accumulate a hash. sub processFile { my $currentFile = $File::Find::name; # full path spect my $currentDir = $File::Find::dir; my $currentFileName = $_; if (not fileFilterQ($currentFile)) { return 1; } # open file. Read in the whole file. if (not(open FILE, "<$currentFile")) {die("Error opening file: $!");}; my $wholeFileString; {local $/ = undef; $wholeFileString = ;}; if (not(close(FILE))) {die("Error closing file: $!");}; # do the replacement. my $replaceCount = 0; foreach my $key1 (keys %findReplaceH) { my $pattern = ($useRegexQ ? $key1 : quotemeta($key1)); $replaceCount = $replaceCount + ($wholeFileString =~ s/$pattern/$findReplaceH{$key1}/g); }; if ($replaceCount > 0) { # replacement has happened $totalFileChangedCount++; # do backup # make a directory in the backup path, make a backup copy. my $pathAdd = $currentDir; $pathAdd =~ s[$folderPath][]; mkpath("$backupRoot/$pathAdd", 0, 0777); copy($currentFile, "$backupRoot/$pathAdd/$currentFileName") or die "error: file copying file failed on $currentFile\n$!"; # write to the original # get the file mode. my ($mode, $uid, $gid) = (stat($currentFile))[2,4,5]; # write out a new file. if (not(open OUTFILE, ">$currentFile")) {die("Error opening file: $!");}; print OUTFILE $wholeFileString; if (not(close(OUTFILE))) {die("Error closing file: $!");}; # set the file mode. chmod($mode, $currentFile); chown($uid, $gid, $currentFile); print "-----^$*%$@#-------------------------------\n"; print "$replaceCount replacements made at\n"; print "$currentFile\n"; } }; #-- main body -- find(\&processFile, $folderPath); print "--------------------------------------------\n\n\n"; print "Total of $totalFileChangedCount files changed.\n"; if (scalar @$refLargeFiles > 0) { print "The following large files are skipped:\n"; print Dumper($refLargeFiles); } __END__ Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From peter at engcorp.com Sat Jan 22 20:18:56 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 22 Jan 2005 20:18:56 -0500 Subject: [OT] XML design intent [was Re: What YAML engine do you use?] In-Reply-To: References: <35a6tpF4gmat2U1@individual.net> <7x1xcfwbab.fsf@ruckus.brouhaha.com> <35csm7F4l57inU1@individual.net> <41f1a3e6.1477492061@news.oz.net> <41F2C840.2050304@comcast.net> Message-ID: Stephen Waterbury wrote: > it's interesting to note that the intent > Steve Holden imputed to it earlier is not explicitly among them: > > Steve Holden wrote: > >> It seems to me the misunderstanding here is that XML was ever intended >> to be generated directly by typing in a text editor. It was rather >> intended (unless I'm mistaken) as a process-to-process data >> interchange metalanguage that would be *human_readable*. > > Not unless you interpret "XML shall support a wide variety of applications" > as "XML shall provide a process-to-process data interchange metalanguage". > It might have been a hidden agenda, but it certainly was not an > explicit design goal. If merely thinking about the purpose of XML doesn't make it clear where Steve got that idea, read up a little bit more in the spec to the very first paragraph in the Introduction, and click on the little M-in-a-circle next to the phrase "data objects". I'll even quote it here for you, to save time: """What Do You Mean By "Data Object?" Good question. The point is that an XML document is sometimes a file, sometimes a record in a relational database, sometimes an object delivered by an Object Request Broker, and sometimes a stream of bytes arriving at a network socket. These can all be described as "data objects". """ I would ask what part of that, or of the simple phrase "data object", or even of the basic concept of a markup language, doesn't cry out "data interchange metalanguage" to you? -Peter From martin at v.loewis.de Fri Jan 14 12:25:15 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 14 Jan 2005 18:25:15 +0100 Subject: Static executable with shared modules In-Reply-To: References: Message-ID: <41e80078$0$1518$9b622d9e@news.freenet.de> Rickard Lind wrote: > Is there any way to build the python executable statically and > still be able to load modules built as shared libraries? I'm not what "build statically" means; if you talking about building a statically linked interpreter binary - then no, this is not possible. At a minimum, you need to link with -ldl, or else you cannot perform dlopen(3). > I'm trying to run python scripts on a stripped down FreeBSD (4.9) > machine which has no shared system libraries so I want to link it > statically against libc et al, but it would be nice to still be > able to load modules which were built as shared libraries. Does that system support shared libraries? What is the API for loading shared libraries, and finding a symbol in a dynamically-loaded shared library, on that system? > In > particular I have a library for which I've generated a wrapper > with swig which I'd like to import. If shared libraries are not supported, you could link the swig module statically as well. Regards, Martin From donald.welch at NOSPAM.hp.com Tue Jan 11 19:18:09 2005 From: donald.welch at NOSPAM.hp.com (Don) Date: Tue, 11 Jan 2005 16:18:09 -0800 Subject: python guy ide References: Message-ID: <41e46d24@usenet01.boi.hp.com> ionel wrote: > i'm looking for a clean gui for python with a visual editor of some sort > any sugestions (i know of wxPython but i want to find out if there are > other alternatives) > and it's on win32 :P > Eric? http://www.die-offenbachs.de/detlev/eric3.html From devries at idolstarastronomer.com Fri Jan 14 12:18:12 2005 From: devries at idolstarastronomer.com (Christopher De Vries) Date: 14 Jan 2005 09:18:12 -0800 Subject: Integration with java References: Message-ID: <1105723092.315634.181590@z14g2000cwz.googlegroups.com> It is possible, though possibly painful, to call java modules from CPython using JNI. This is more difficult than Jython integration, but probably required if you want to keep using your extension modules. The JNI tutorial is available at http://java.sun.com/docs/books/tutorial/native1.1/index.html . I probably would not take this approach unless java offered some incredibly substantial benefit or I was integrating a complex python system with a complex java sytem. I would also probably start by creating a good C API to access the required java modules via JNI and then use SWIG (http://www.swig.org/) to generate the python wrapper. Of course if you can drop the extension modules you have already written, accessing Java from Jython is just an import statement away. Good luck, Chris From t-meyer at ihug.co.nz Thu Jan 13 15:15:28 2005 From: t-meyer at ihug.co.nz (Tony Meyer) Date: Fri, 14 Jan 2005 09:15:28 +1300 Subject: site.here on python 2.4 In-Reply-To: Message-ID: > can we assume that, on all platforms, the old site.here is > the same as: > > >>> os.path.join(sys.prefix, 'lib', 'python%s' % sys.version[:3]) > '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3' > > or is it better to use, as you suggest, > > >>> import os > >>> os.path.dirname(os.__file__) > '/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3' These are not the same on Windows: >>> os.path.join(sys.prefix, 'lib', 'python%s' % sys.version[:3]) 'c:\\python24\\lib\\python2.4' >>> os.path.dirname(os.__file__) 'c:\\python24\\lib' (The latter is correct, if you want the directory that site-packages and idlelib are in. (And, for reference, with Python 2.3: >>> site.here 'c:\\python23\\lib' ) =Tony.Meyer From tim.golden at viacom-outdoor.co.uk Fri Jan 21 04:01:41 2005 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 21 Jan 2005 09:01:41 -0000 Subject: Print to Windows default Printer Message-ID: <9A28C052FF32734DACB0A288A35339910359DC@vogbs009.gb.vo.local> [Samantha] | Thanks for the URL. I finally am able to print the temp file. | Not exactly | what I wanted, but it will work. The code I used to print was this: | | os.system ("start /min notepad /P temp.txt") | | Thanks ALL! | S Glad you got it sorted. What you describe is, in fact, the slightly more specific version of this technique: http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html#shellexecute which relies on the fact that .txt files are bound to notepad.exe for printing. (Or that they're bound to *something* for printing, since you don't care what it is, so long as it prints!) TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From tundra at tundraware.com Thu Jan 13 07:18:26 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 13 Jan 2005 07:18:26 EST Subject: Unclear On Class Variables Message-ID: I am a bit confused. I was under the impression that: class foo(object): x = 0 y = 1 means that x and y are variables shared by all instances of a class. But when I run this against two instances of foo, and set the values of x and y, they are indeed unique to the *instance* rather than the class. It is late and I am probably missing the obvious. Enlightenment appreciated ... -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From skip at pobox.com Tue Jan 4 20:22:47 2005 From: skip at pobox.com (Skip Montanaro) Date: Tue, 4 Jan 2005 19:22:47 -0600 Subject: coding conventions, PEP vs. practice In-Reply-To: <200501050150.43556.r.roelofsen@tuxed.de> References: <200501050150.43556.r.roelofsen@tuxed.de> Message-ID: <16859.16743.978284.447718@montanaro.dyndns.org> Roman> These frameworks are using "mixedCase" but PEP8 suggests Roman> "lower_case_with_underscores" except "in contexts where that's Roman> already the prevailing style" which is not the case here IMHO. Roman> So, are there any specific reasons for breaking the rules here? Since they aren't really rules, people and organizations can and do use their own personal preferences when naming things. Skip From peter at engcorp.com Sun Jan 9 09:43:32 2005 From: peter at engcorp.com (Peter Hansen) Date: Sun, 09 Jan 2005 09:43:32 -0500 Subject: windows mem leak In-Reply-To: <41E06C18.6050407@hotmail.com> References: <41XDd.70234$Jk5.40626@lakeread01> <41E06C18.6050407@hotmail.com> Message-ID: Bob Smith wrote: > Attached is the code. Run it yourself and see. You too Peter. Be gentle > with me, this was my first attempt with threads. Thanks, Bob, and I will, but not before you answer some of my questions. I had good reasons to ask them, one of which is that I don't feel like wasting my time if, for example, you are using an older version of Python that *did* have a memory leak. Python 2.2, for example, (if my memory serves me right) had a leak in the first release which would have affected pretty much all software which did network work. The most important answers you can provide will be versions, platform (pretty clearly Linux, but please confirm and give version), and what "bombs" means and how you are measuring the memory leak. (I presume you're using a version of nmap that's compiled for Windows XP then? It's certainly not standard. How have you proven that it is not *that* program which is at fault?) -Peter From snail at objmedia.demon.co.uk Fri Jan 28 05:03:30 2005 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Fri, 28 Jan 2005 10:03:30 +0000 Subject: Profiling and speed up References: Message-ID: <04CCzECy3g+BFwrK@objmedia.demon.co.uk> In message , Franz Steinhaeusler writes >best if it would be graphical like performance analysis from DevPartner >for Visual C++? Python Performance Validator http://www.softwareverify.com/pythonPerformanceValidator/index.html Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From yaipa at yahoo.com Mon Jan 31 01:06:36 2005 From: yaipa at yahoo.com (yaipa) Date: 30 Jan 2005 22:06:36 -0800 Subject: Redirecting stdout/err under win32 platform In-Reply-To: <41fbd6b5$0$6098$626a14ce@news.free.fr> References: <41fbd6b5$0$6098$626a14ce@news.free.fr> Message-ID: <1107149696.809645.56180@z14g2000cwz.googlegroups.com> David, Googling comp.lang.python /w this string "stderr win32" yielded 109 results. So I think if you poke around a bit you will find your answer in the archives. Sorry for no direct help tonight... Cheers, --Alan David Douard wrote: > Hi everybody, > > let me explain by problem: > I am working on an application which consists in a C++ dll (numeric > computations) and a Python IHM (Python/Tk), which must run under Linux and > win32. My problem is the C++ lib does write stuffs on its stdout, and I > would like to print those messages in a Tk frame. When I run the > computation, it has it's own thread. > > So my question is : how van I redirect the dll's stdout to something I can > retrieve in Python (pipe, socket,...)? > > I can do it easily under Linux. I made tests with a socket which just works > fine. In the threaded function (that will do the heavy computation), I > write: > > import os, sys > from socket import * > s=socket(AF_UNIX, SOCK_STREAM) > s.connect(...) > os.dup2(sys.__stdout__.fileno(), s.fileno()) > very_intensive_function(many_parameters) > s.close() > > That's OK under Linux, but does not work under win32 (even if I use an INET > localhost socket), cause I cannot do the os.dup2 trick (Windows does not > want to consider a socket as a file! What a shity system!). > > So my question is : is there a simple solution ? I have tested different > solutions. I am trying hacks with pipes created with the win32api. But I > have not yet managed this simple operation. > > Note that I have no access to the dll source code, so I cannot modify it so > it uses a named pipe (for example) as message output pipe instead os > stdout... > > Thanks, > David From cookedm+news at physics.mcmaster.ca Mon Jan 10 22:57:41 2005 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 10 Jan 2005 22:57:41 -0500 Subject: Python3: on removing map, reduce, filter References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> <-7mdndrwD_1qOHzcRVn-qQ@comcast.com> Message-ID: Steven Bethard writes: > Some timings to verify this: > > $ python -m timeit -s "def square(x): return x*x" "map(square, range(1000))" > 1000 loops, best of 3: 693 usec per loop > > $ python -m timeit -s "[x*x for x in range(1000)]" > 10000000 loops, best of 3: 0.0505 usec per loop Maybe you should compare apples with apples, instead of oranges :-) You're only running the list comprehension in the setup code... $ python2.4 -m timeit -s "def square(x): return x*x" "map(square, range(1000))" 1000 loops, best of 3: 464 usec per loop $ python2.4 -m timeit "[x*x for x in range(1000)]" 1000 loops, best of 3: 216 usec per loop So factor of 2, instead of 13700 ... -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From jriveramerla at yahoo.com Wed Jan 26 10:28:20 2005 From: jriveramerla at yahoo.com (Jose Rivera) Date: 26 Jan 2005 07:28:20 -0800 Subject: Sorry for the multiple posts !! Message-ID: <11e94203.0501260728.68d788e3@posting.google.com> My broswser stoped working when I posted, and I tought it didn't work, so I tried a more times until did not report an error. Bye From aleaxit at yahoo.com Mon Jan 31 06:56:38 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 31 Jan 2005 12:56:38 +0100 Subject: Dynamic class methods misunderstanding References: <35v5jdF4rk3m7U1@individual.net> <1gr5b2x.1s7zqt9ufc993N%aleaxit@yahoo.com> <7i3sv0lk63gmnh8q3a532gon7f1gg3bab9@4ax.com> Message-ID: <1gr97a7.9e2p12f7rlwvN%aleaxit@yahoo.com> Christos TZOTZIOY Georgiou wrote: ... > >> > class Test: > >> > def __init__(self, method): > >> > self.m = new.instancemethod(method, self, Test) ... > >self.m = method.__get__(self, Test) > > Almost true; not all builtin functions are descriptors though. ... > AttributeError: 'builtin_function_or_method' object has no attribute > '__get__' > > I didn't run an extensive test, but it's possible that all builtin > functions are not descriptors. Indeed, many callables (builtin-functions, types, ...) are not descriptors, so you can't call __get__ on them. But then, many descriptors (statimethods, classmethods, ...) are not callable, so you can't pass them as the first argument to instancemethod. Not having any indication of what the author of class Test means to pass in as "method", it's not clear whether Test(divmod) or Test(staticmethod(foo)) is more likely to be of interest to them as a use case. If ``method'' is a function, which is both a descriptor AND callable, either approach works; otherwise, one has to pick an approach, or try both approaches with a try/except. Alex From stingray20166 at yahoo.com Thu Jan 27 17:02:08 2005 From: stingray20166 at yahoo.com (Nick Caldwell) Date: Thu, 27 Jan 2005 22:02:08 -0000 Subject: WSDL parsing problem Message-ID: Y'all, Problem: Reading complex data types returned from WSDL I'll present this in 3 sections. 1. Output of WSDL parser on Google API 2. Output of WSDL parser on Custom API 3. WSDL parser code 1. Output of WSDL parser on Google API So far I have a very simple WSDL reader which gathers the commnads and arguments of the WSDL. For instance, running against the google API generates: Commands: [u'doGoogleSearch', u'doGetCachedPage', u'doSpellingSuggestion'] Arguments for "doGoogleSearch": key (u'http://www.w3.org/2001/XMLSchema', u'string') q (u'http://www.w3.org/2001/XMLSchema', u'string') start (u'http://www.w3.org/2001/XMLSchema', u'int') maxResults (u'http://www.w3.org/2001/XMLSchema', u'int') filter (u'http://www.w3.org/2001/XMLSchema', u'boolean') restrict (u'http://www.w3.org/2001/XMLSchema', u'string') safeSearch (u'http://www.w3.org/2001/XMLSchema', u'boolean') lr (u'http://www.w3.org/2001/XMLSchema', u'string') ie (u'http://www.w3.org/2001/XMLSchema', u'string') oe (u'http://www.w3.org/2001/XMLSchema', u'string') With this it is easy to create a command and send it the proper value types. You still have to know what each does, but the type is obvious. 2. Output of WSDL parser on Custom API When I run this against my company's custom API, though, I see the comnmands fine: Commands: [u'getCustomerInformation'] But the argument names and types look like: getCustomerInformationRequest (u'java:com.productname.productversion.soap', u'ge tCustomerInformation') Now, according to my developers this is because they treat each api call like a separate document which returns several values, whereas the google API treats each as a separate data type (string). The WSDL would look like this: Can I somehow parse the response from the WSDL to get at the atomic data types? The goal is to do this programmatically to provide a GUI front end for the APIs for testing. 3. WSDL reader #!/usr/bin/env python #http level debugging import httplib httplib.HTTPConnection.debuglevel = 1 from SOAPpy import WSDL server = WSDL.Proxy('d:/googleapi/GoogleSearch.wsdl') print server.methods.keys() callInfo = server.methods['doGoogleSearch'] for arg in callInfo.inparams: print arg.name.ljust(15), arg.type Any help at all would be appreciated. Sincerely, Nick From fumanchu at amor.org Thu Jan 6 18:38:26 2005 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 6 Jan 2005 15:38:26 -0800 Subject: Pre/Postconditions with decorators Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398121@exchange.hqamor.amorhq.net> Stephen Thorne wrote: > On 6 Jan 2005 13:33:42 -0800, Rittersporn > wrote: > > @condition("number>0 and number<2","result>=0") > > def sqrt(number): > > import math > > return math.sqrt(number) > > > > @condition("list(seq) is not None","sum(seq)==result") > > def my_sum(seq): > > tmp=0 > > for element in seq: > > tmp+=element > > return tmp > > > > print sqrt(1.2) > > print my_sum([1,2,3]) > > I think it would be nicer to have the pre and post conditions > being compilable. Me too. > @condition((list(seq) is not None for seq in args), (sum(seq)==result > for ((seq,), result) in (args, result)) > > or something silly like that. Ian Bicking was just talking about @require decorators: http://blog.ianbicking.org/already-under-our-noses.html @require(int, int) def gcd(a, b): ... If we made a "checker" module for such things in the stdlib, we could write most of that: from checker import * @args((list, itemsnotNone, )) @returns((any, )) def my_sum(seq): tmp=0 for element in seq: tmp+=element return tmp Robert Brewer MIS Amor Ministries fumanchu at amor.org From daniel at bowettsolutions.com Wed Jan 26 05:14:21 2005 From: daniel at bowettsolutions.com (Daniel Bowett) Date: Wed, 26 Jan 2005 10:14:21 +0000 Subject: MySQLdb In-Reply-To: <41F6AF8A.3040102@bowettsolutions.com> References: <41F6AF8A.3040102@bowettsolutions.com> Message-ID: Daniel Bowett wrote: > I have just started playing around with MySQLdb for a project I am > planning. > > As a test I have written a script that executes 3000 insert statements > on a table. The table contains 10 fields with a mix of text and numbers > - its a product table for a website eg UPC, ProductName, Price etc. > > The problem I have is that it takes just over two minuted to execute the > 3000 insert statements which seems really slow! I am running it on a > machine with a 1.5 Ghz Pentium M Processor and Gig Of Ram. I dont think > the machine is to blame for the speed because during execution the > processor sits at about 10% and there is loads of free RAM. > > Does anyone know if this sort of speed sounds right? > > Cheers, > > Dan. > > UPDATE ------ I have found the "executemany" function! It now takes around a second to complete the 3000 inserts. Lesson learnt - I should have posted my code... Thanks for your help everyone. From tjreedy at udel.edu Thu Jan 13 15:35:08 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Jan 2005 15:35:08 -0500 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com><7xmzvfn096.fsf@ruckus.brouhaha.com> Message-ID: "Antoon Pardon" wrote in message news:slrncucmeo.5qu.apardon at rcpc42.vub.ac.be... > Op 2005-01-13, Fredrik Lundh schreef : >> Antoon Pardon wrote: >> >>> Well, it seems that Guido is wrong then. The documentation clearly >>> states that an expression is a statement. >> >> no, it says that an expression statement is a statement. if you don't >> understand the difference, please *plonk* yourself. > > And what else is an expression statement but an expression (list) used > as a statement. Whereas an expression used within a statement is not a statement, and that is the difference. And of course, statements, in general, are not expressions and are not used within statements (except within compound statements). Terry J. Reedy From xah at xahlee.org Fri Jan 28 04:42:18 2005 From: xah at xahlee.org (Xah Lee) Date: 28 Jan 2005 01:42:18 -0800 Subject: [perl-python] daily tip website In-Reply-To: References: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> <1106875259.426213.252030@z14g2000cwz.googlegroups.com> Message-ID: <1106905338.224003.216840@c13g2000cwb.googlegroups.com> for those interested, i've created a webpage for these perl-python daily tips. The url is: http://xahlee.org/perl-python/python.html Thanks to those who have made useful comments. They will be assimilated. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html > Hey all, I have seen no evidence that XL even reads the responses that have > been directed thereto. > Why don't you ever answer the messages > ... From steven.bethard at gmail.com Mon Jan 3 13:54:06 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 03 Jan 2005 18:54:06 GMT Subject: Lambda as declarative idiom (was RE: what is lambda used for in real code?) In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E3024F6B@exchange.hqamor.amorhq.net> Message-ID: Roman Suzi wrote: > I wish lambdas will not be deprecated in Python but the key to that is > dropping the keyword (lambda). If anybody could think of a better syntax for > lambdas _with_ arguments, we could develop PEP 312 further. Some suggestions from recent lambda threads (I only considered the ones that keep lambda as an expression): ***** Args Before Expression ***** Nick Coghlan: def-to syntax [1] (def (a, b, c) to f(a) + o(b) - o(c)) (def (x) to x * x) (def () to x) (def (*a, **k) to x.bar(*a, **k)) ((def () to x(*a, **k)) for x, a, k in funcs_and_args_list) Nick Coghlan: def-arrow syntax [1] (def (a, b, c) -> f(a) + o(b) - o(c)) (def (x) -> x * x) (def () -> x) (def (*a, **k) -> x.bar(*a, **k)) ((def () -> x(*a, **k)) for x, a, k in funcs_and_args_list) Alex Martelli: def-as syntax [2] (def (a, b, c) as f(a) + o(b) - o(c)) (def (x) as x * x) (def () as x) (def (*a, **k) as x.bar(*a, **k)) ((def () as x(*a, **k)) for x, a, k in funcs_and_args_list) Dave Benjamin: fun syntax [7] (fun(a, b, c): f(a) + o(b) - o(c)) (fun(x): x * x) (fun(): x) (fun(*a, **k): x.bar(*a, **k)) ((fun(): x(*a, **k)) for x, a, k in funcs_and_args_list) ***** Expression Before Args ***** Robert Brewer: for (no-parens) syntax [3] (f(a) + o(b) - o(c) for a, b, c) (x * x for x) (x for ()) (x.bar(*a, **k) for *a, **k) ((x(*a, **k) for ()) for x, a, k in funcs_and_args_list) Nick Coghlan: for syntax [6] (f(a) + o(b) - o(c) for (a, b, c)) (x * x for (x)) (x for ()) (x.bar(*a, **k) for (*a, **k)) ((x(*a, **k) for ()) for x, a, k in funcs_and_args_list) Nick Coghlan: def-from syntax [4] (def f(a) + o(b) - o(c) from (a, b, c)) (def x * x from (x)) (def x from ()) (def x.bar(*a, **k) from (*a, **k)) ((def x(*a, **k) from ()) for x, a, k in funcs_and_args_list) Michael Spencer: from-args syntax [5] (f(a) + o(b) - o(c) from args(a, b, c)) (x * x from args(x)) (x from args()) (x.bar(*a, **k) from args(*a, **k)) ((x(*a, **k) from args()) for x, a, k in funcs_and_args_list) Michael Spencer: for-args syntax [5] (f(a) + o(b) - o(c) for args(a, b, c)) (x * x for args(x)) (x for args()) (x.bar(*a, **k) for args(*a, **k)) ((x(*a, **k) for args()) for x, a, k in funcs_and_args_list) So there's a bunch of ideas out there. I don't know if any of them could be overwhelmingly preferred over lambda. Personally, I lean slightly towards the def-from syntax because it uses the 'def' keyword to bring your attention to the fact that a function is being defined, and it gives the expression precedence over the arglist, which makes sense to me for an anonymous function, where (IMHO) the expression is really the most important part of the declaration. OTOH, I think Michael Spencer's args() function, if implementable, could have a lot of cool uses, like getting the arguments passed to next within a generator. (See the thread about that[8].) Steve [1]http://mail.python.org/pipermail/python-list/2004-December/256859.html [2]http://mail.python.org/pipermail/python-list/2004-December/256881.html [3]http://mail.python.org/pipermail/python-list/2004-December/257023.html [4]http://boredomandlaziness.skystorm.net/2004/12/anonymous-functions-in-python.html [5]http://mail.python.org/pipermail/python-list/2004-December/257893.html [6]http://mail.python.org/pipermail/python-list/2004-December/257977.html [7]http://mail.python.org/pipermail/python-list/2005-January/258441.html [8]http://mail.python.org/pipermail/python-list/2005-January/258238.html From aorfanakos at gmail.com Fri Jan 28 10:18:28 2005 From: aorfanakos at gmail.com (Aggelos I. Orfanakos) Date: 28 Jan 2005 07:18:28 -0800 Subject: python: can't open file 'timeit.py' References: <1106921858.598528.77300@f14g2000cwb.googlegroups.com> Message-ID: <1106925508.626504.302240@c13g2000cwb.googlegroups.com> OK, the symbolic link solved the "problem". I thought that there was something wrong with my Python configuration; that's why I asked in the first place. Thanks. From wittempj at hotmail.com Mon Jan 10 05:52:09 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 10 Jan 2005 02:52:09 -0800 Subject: Datetime module In-Reply-To: <1105335972.454019.46450@c13g2000cwb.googlegroups.com> References: <1105335972.454019.46450@c13g2000cwb.googlegroups.com> Message-ID: <1105354329.352322.136930@c13g2000cwb.googlegroups.com> take a look at the logging module as well, in the documentation (paragraph 6.29.2 for release 2.4) you find a basic example From godoy at ieee.org Wed Jan 19 12:18:27 2005 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Wed, 19 Jan 2005 15:18:27 -0200 Subject: Accessing MDB files on Windows References: <1635068.ZTfiooUzB4@strongwill.g2ctech> <4262806.PViGKJWPeZ@strongwill.g2ctech> Message-ID: <1575169.hWfiKyiV09@strongwill.g2ctech> Jorge Luiz Godoy Filho, Quarta 19 Janeiro 2005 14:25, wrote: > Thanks! I'm looking at it. Worked like a charm! And just now I noticed who's the author of the recipe ;-) Thanks! -- Godoy. From cam.ac.uk at mh391.invalid Sun Jan 16 06:43:10 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 16 Jan 2005 11:43:10 +0000 Subject: How to del item of a list in loop? In-Reply-To: <1105844790.287893.75860@c13g2000cwb.googlegroups.com> References: <1105838984.045727.55730@f14g2000cwb.googlegroups.com> <1105844790.287893.75860@c13g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > I've taken your code and improved it along the > suggested lines, added timing for first, middle, and last elements, > added several more methods, and added a testing facility as well. Would > you like a copy? Actually I think it would be great if you posted it here for our combined edification. I would have been considerably less annoyed if you had done that and explained why it is better rather than nitpicking my version. -- Michael Hoffman From intager at gmail.com Sun Jan 30 17:30:28 2005 From: intager at gmail.com (int) Date: 30 Jan 2005 14:30:28 -0800 Subject: gmail access with python! Message-ID: <1107124228.920210.141920@f14g2000cwb.googlegroups.com> hi, i want to write a python program which will grab all my gmail msgs and store them on my hard drive. i've done an extensive google search and tried _every_ possible gmail python script i could find (including of course libgmail) and none of them seem to work, even on trivial example code. (perhaps all these scripts are out of date due to recent changes in gmail itself?) my question is: does anyone have a working script which can grab msgs from a gmail inbox ? Thanks! From jeff at ccvcorp.com Wed Jan 12 15:42:30 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 12 Jan 2005 12:42:30 -0800 Subject: Refactoring; arbitrary expression in lists In-Reply-To: References: Message-ID: <10ub2jk2euh14d@corp.supernews.com> Paul McGuire wrote: > "Frans Englich" wrote in message > news:mailman.576.1105553330.22381.python-list at python.org... >>#-------------------------------------------------------------- >>def detectMimeType( filename ): >> >> extension = filename[-3:] You might consider using os.path.splitext() here, instead of always assuming that the last three characters are the extension. That way you'll be consistent even with extensions like .c, .cc, .h, .gz, etc. Note that os.path.splitext() does include the extension separator (the dot), so that you'll need to test against, e.g., ".php" and ".cpp". > Since the majority of your tests will be fairly direct 'extension "XYZ" > means mimetype "aaa/bbb"', this really sounds like a dictionary type > solution is called for. I strongly agree with this. The vast majority of your cases seem to be a direct mapping of extension-string to mimetype-string; using a dictionary (i.e. mapping ;) ) for this is ideal. For those cases where you can't key off of an extension string (such as makefiles), you can do special-case processing if the dictionary lookup fails. > if extension.endswith("cc"): > return extToMimeDict["cpp"] If the intent of this is to catch .cc files, it's easy to add an extra entry into the dict to map '.cc' to the same string as '.cpp'. Jeff Shannon Technician/Programmer Credit International From francis.girard at free.fr Sat Jan 22 05:06:41 2005 From: francis.girard at free.fr (Francis Girard) Date: Sat, 22 Jan 2005 11:06:41 +0100 Subject: need help on need help on generator... In-Reply-To: <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> References: <63b5e209.0501210558.686f5c10@posting.google.com> <1gqsbex.hooytt14zucw2N%aleaxit@yahoo.com> Message-ID: <200501221106.49241.francis.girard@free.fr> Le samedi 22 Janvier 2005 10:10, Alex Martelli a ?crit?: > Francis Girard wrote: > ... > > > But besides the fact that generators are either produced with the new > > "yield" reserved word or by defining the __new__ method in a class > > definition, I don't know much about them. > > Having __new__ in a class definition has nothing much to do with > generators; it has to do with how the class is instantiated when you > call it. Perhaps you mean 'next' (and __iter__)? That makes instances > of the class iterators, just like iterators are what you get when you > call a generator. > Yes, I meant "next". > > In particular, I don't know what Python constructs does generate a > > generator. > > A 'def' of a function whose body uses 'yield', and in 2.4 the new genexp > construct. > Ok. I guess I'll have to update to version 2.4 (from 2.3) to follow the discussion. > > I know this is now the case for reading lines in a file or with the new > > "iterator" package. > > Nope, besides the fact that the module you're thinking of is named > 'itertools': itertools uses a lot of C-coded special types, which are > iterators but not generators. Similarly, a file object is an iterator > but not a generator. > > > But what else ? > > Since you appear to conflate generators and iterators, I guess the iter > built-in function is the main one you missed. iter(x), for any x, > either raises an exception (if x's type is not iterable) or else returns > an iterator. > You're absolutly right, I take the one for the other and vice-versa. If I understand correctly, a "generator" produce something over which you can iterate with the help of an "iterator". Can you iterate (in the strict sense of an "iterator") over something not generated by a "generator" ? > > Does Craig Ringer answer mean that list > > comprehensions are lazy ? > > Nope, those were generator expressions. > > > Where can I find a comprehensive list of all the > > lazy constructions built in Python ? > > That's yet a different question -- at least one needs to add the > built-in xrange, which is neither an iterator nor a generator but IS > lazy (a historical artefact, admittedly). > > But fortunately Python's built-ins are not all THAT many, so that's > about it. > > > (I think that to easily distinguish lazy > > from strict constructs is an absolute programmer need -- otherwise you > > always end up wondering when is it that code is actually executed like in > > Haskell). > > Encapsulation doesn't let you "easily distinguish" issues of > implementation. For example, the fact that a file is an iterator (its > items being its lines) doesn't tell you if that's internally implemented > in a lazy or eager way -- it tells you that you can code afile.next() to > get the next line, or "for line in afile:" to loop over them, but does > not tell you whether the code for the file object is reading each line > just when you ask for it, or whether it reads all lines before and just > keeps some state about the next one, or somewhere in between. > You're right. I was much more talking (mistakenly) about lazy evaluation of the arguments to a function (i.e. the function begins execution before its arguments get evaluated) -- in such a case I think it should be specified which arguments are "strict" and which are "lazy" -- but I don't think there's such a thing in Python (... well not yet as Python get more and more akin to FP). > The answer for the current implementation, BTW, is "in between" -- some > buffering, but bounded consumption of memory -- but whether that tidbit > of pragmatics is part of the file specs, heh, that's anything but clear > (just as for other important tidbits of Python pragmatics, such as the > facts that list.sort is wickedly fast, 'x in alist' isn't, 'x in adict' > IS...). > > > Alex Thank you Francis Girard FRANCE From elephantum at dezcom.mephi.ru Sun Jan 9 11:10:49 2005 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 09 Jan 2005 19:10:49 +0300 Subject: Python3: on removing map, reduce, filter In-Reply-To: <5CcEd.70344$Jk5.19962@lakeread01> References: <34csn1F4a46hqU1@individual.net> <5CcEd.70344$Jk5.19962@lakeread01> Message-ID: <34d3c9F477m01U1@individual.net> Steve Holden wrote: > Andrey Tatarinov wrote: > >> Hi. >> >> How does GvR suggestions on removing map(), reduce(), filter() >> correlate with the following that he wrote himself (afaik): >> >> http://www.python.org/doc/essays/list2str.html > > And note that the summary in the conclusiogn BEGINS with "Rule number > one: only optimize when there is a proven speed bottleneck", which seems > to adequately imply that straightforward code is to be preferred unless > speed requirements override that. My main question was: "how could be this advices applied, when map, reduce and filter would be removed?" but earlier I got answers about speed of list comprehensions, though they need to be proved. From ncoghlan at iinet.net.au Thu Jan 6 06:02:43 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 06 Jan 2005 21:02:43 +1000 Subject: Securing a future for anonymous functions in Python In-Reply-To: <7xd5wjiuko.fsf@ruckus.brouhaha.com> References: <7x3bxnewmx.fsf@ruckus.brouhaha.com> <7xd5wjiuko.fsf@ruckus.brouhaha.com> Message-ID: <41DD1AD3.5030504@iinet.net.au> Paul Rubin wrote: > Nick Coghlan writes: > >>Do you consider generator expressions or list comprehensions deficient >>because they don't allow several statements in the body of the for >>loop? > > > I don't see what it would mean to do otherwise. Exactly the same as a suite would in the innermost portion of the equivalent explicit generator (i.e. where the implicit "yield " currently ends up). If you could put a suite inside a function expression (i.e. replacing the implicit "return ") why not inside generator expressions as well? Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From skip at pobox.com Wed Jan 19 15:02:51 2005 From: skip at pobox.com (Skip Montanaro) Date: Wed, 19 Jan 2005 14:02:51 -0600 Subject: Zen of Python In-Reply-To: <797fe3d405011911465ab59acd@mail.gmail.com> References: <972ec5bd050119111359e358f5@mail.gmail.com> <797fe3d405011911465ab59acd@mail.gmail.com> Message-ID: <16878.48363.334975.58163@montanaro.dyndns.org> Bill> The example that occurs to me is that "import smtplib" is better Bill> than "import stdlib.inet.services.smtp". Sure. There is a balance to be achieved however. "import std.smtplib" might be better than "import smtplib", simply because making the standard library a package reduces the possibility of namespace collisions. Skip From c00lways at gmail.com Fri Jan 28 14:05:29 2005 From: c00lways at gmail.com (James) Date: Sat, 29 Jan 2005 03:05:29 +0800 Subject: threading and internet explorer com In-Reply-To: <41f9dc43$1_2@127.0.0.1> References: <41f9777f_2@news.tm.net.my> <41f9dc43$1_2@127.0.0.1> Message-ID: <41fa8cf7$1_2@news.tm.net.my> thannnnk you Roger :) thank you so much :) best regards, James Roger Upole wrote: > You'll need to call pythoncom.CoInitialize() in each thread. > > Roger > > "James" wrote in message > news:41f9777f_2 at news.tm.net.my... > >>hi, >> >>i'm using python 2.4 with pywin32... >>I've tried to use internet explorer control with a class. >>it was fine until i decided to inherit thread for the class... >> >>class domain01(threading.Thread): >>def __init__(self): >>#blabla >>threading.Thread.__init__(self) >> >>def run(self): >>self.ie = win32com.client.Dispatch('InternetExplorer.Application.1') #this >>line gives error if i use .start(), but if i use .run.. no error... >>self.ie.Visibble = 1 >>print "running" >> >> >> >>xyz = domain() >>xyz.start() >> >>=========== >>this is what i get: >>Exception in thread Thread-23: >>Traceback (most recent call last): >> File "C:\Python24\lib\threading.py", line 442, in __bootstrap >> self.run() >> File "C:\python2exe\domain01.py", line 41, in run >> self.dologin() >> File "C:\python2exe\domain01.py", line 56, in dologin >> self.ie=win32com.client.Dispatch('InternetExplorer.Application.1') >> File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line >>95, in Dispatch >> dispatch, userName = >>dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) >> File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line >>91, in _GetGoodDispatchAndUserName >> return (_GetGoodDispatch(IDispatch, clsctx), userName) >> File "C:\Python24\Lib\site-packages\win32com\client\dynamic.py", line >>79, in _GetGoodDispatch >> IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, >>pythoncom.IID_IDispatch) >>com_error: (-2147221008, 'CoInitialize has not been called.', None, None) >> >> >> >>===== >>but if i run: >>xyz = domain() >>xyz.run() >> >>##no error! it's weird.... >> >>anyone know how to solve this problem? >> >>thank you :) >> >>best regards, >> >>James > > > > > > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- > http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups > ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From tiltonj at erols.com Tue Jan 18 08:36:59 2005 From: tiltonj at erols.com (Jay Tilton) Date: Tue, 18 Jan 2005 13:36:59 GMT Subject: [perl-python] 20050118 keyed list References: <1106027360.920787.321590@z14g2000cwz.googlegroups.com> Message-ID: <41ed0f4d.39606090@news.erols.com> "Xah Lee" wrote: : # the syntax of keyed list in Perl is too complex : # to be covered in a short message. You've got to be joking. You couldn't even muster enough skill to provide Perl equivalents for the four simple Python statements you showed? : # see "perldoc perldata" for an unix-styled course. It's good to see your opinion on the _fantastic incompetent writting_[1] of Perl's documentation has changed enough that you can recommend it to novices. [1]Message-ID: <7fe97cc4.0401242131.22acf485 at posting.google.com> From hellcore at hellcore.com Thu Jan 6 11:48:15 2005 From: hellcore at hellcore.com (Steve Hughes) Date: Thu, 06 Jan 2005 16:48:15 +0000 Subject: Developing Commercial Applications in Python In-Reply-To: References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> <87pt0iegga.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: <41DD6BCF.7070007@hellcore.com> >>>Can somebody there to point me any good commercial applications >>>developed using python ? Yet another game but it's a huge one with a massive DB behind it. http://www.eve-online.com -- Steve Hughes From mt at 3planes.com Sun Jan 23 15:50:17 2005 From: mt at 3planes.com (Michael Tobis) Date: 23 Jan 2005 12:50:17 -0800 Subject: finding name of instances created References: <1106352799.481829.279900@c13g2000cwb.googlegroups.com> Message-ID: <1106513417.897059.92250@c13g2000cwb.googlegroups.com> I have a similar problem. Here's what I do: .def new_robot_named(name,indict=globals()): . execstr = name + " = robot('" + name + "')" . exec(execstr,indict) .class robot(object): . def __init__(self,name): . self.name = name . def sayhi(self): . print "Hi! I'm %s!" % self.name .if __name__=="__main__": . new_robot_named('Bert') . new_robot_named('Ernie') . Ernie.sayhi() . Bert.sayhi() From steve at holdenweb.com Sun Jan 9 10:45:58 2005 From: steve at holdenweb.com (Steve Holden) Date: Sun, 09 Jan 2005 10:45:58 -0500 Subject: python3: accessing the result of 'if' In-Reply-To: References: <3480qqF46jprlU1@individual.net> <1105169372.800346.298830@f14g2000cwb.googlegroups.com> <1105236383.521393.40680@c13g2000cwb.googlegroups.com> Message-ID: Nick Coghlan wrote: > Carl Banks wrote: > >> What if the condition you wanted to test wasn't the same as the thing >> you want to save? In other words, how would you convert this? >> >> . where: >> . m = something() >> . if m > 20: >> . do_something_with(m) > > > Yeah, this problem eventually occurred to me as well. However, I think a > little utility function can help solve it: > > def test(val, condition): > if condition(val): > return val > else: > return None > > if test(something(), lambda x: x < 10) as m: > print "Case 1:", m > elif test(something(), lambda x: x > 20) as m: > print "Case 2:", m > else: > print "No case at all!" > > If we were to use a where clause instead, it looks like: > > if test(something(), less_than(10)) as m: > print "Case 1:", m > elif test(something(), more_than(20)) as m: > print "Case 2:", m > else: > print "No case at all!" > where: > def less_than(y): > def lt(x): > return x < y > return lt > > def more_than(y): > def gt(x): > return x > y > return lt > > This is an example of why I don't think where clauses would completely > eliminate the utility of deferred expressions. Here's a version using my > preferred syntax from the AlternateLambdaSyntax page: > > if test(something(), (def x < 10 from x)) as m: > print "Case 1:", m > elif test(something(), (def x > 20 from x)) as m: > print "Case 2:", m > else: > print "No case at all!" > Excuse me, these are supposed to be IMPROVEMENTS to Python? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From steven.bethard at gmail.com Wed Jan 26 14:45:42 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 12:45:42 -0700 Subject: inherit without calling parent class constructor? In-Reply-To: References: Message-ID: <8IadnVLUPfL7bmrcRVn-tg@comcast.com> Christian Dieterich wrote: > The size attribute only needs to be computed once and stays constant > after that. The lazy property recipe of Scott David Daniels looks > promising. I'll try that, when I've installed Python 2.4. However, I > need my package to work on machines where there is Python 2.2 and 2.3 only. Note that: @deco def func(...): ... is basically just syntactic sugar for: def func(...): ... func = deco(func) So you don't need 2.4 to use the recipe; you just need a version of Python that supports descriptors (2.2 or later) since the recipe uses a class with __get__. I believe the following code should work for Python 2.2 and later, though I only have 2.4 to test it on at home. py> class LazyAttribute(object): ... def __init__(self, calculate_function): ... self._calculate = calculate_function ... def __get__(self, obj, _=None): ... if obj is None: ... return self ... value = self._calculate(obj) ... setattr(obj, self._calculate.func_name, value) ... return value ... py> class B(object): ... def __init__(self, length): ... self._length = length ... def size(self): ... print 'some expensive calculation' ... return self._length ... size = LazyAttribute(size) ... py> class D(B): ... def __init__(self, length): ... super(D, self).__init__(length) ... self.value = 1 ... py> b = B(5) py> b.size some expensive calculation 5 py> b.size 5 py> d = D(6) py> d.size some expensive calculation 6 py> d.size 6 Note that b.size and d.size are only calculated once each, and if d.size is never accessed, you'll never incur the costs of calculating it. Steve From ola.natvig at infosense.no Wed Jan 26 09:45:27 2005 From: ola.natvig at infosense.no (Ola Natvig) Date: Wed, 26 Jan 2005 15:45:27 +0100 Subject: 4suite XSLT thread safe ? In-Reply-To: <35pntaF4os76kU1@individual.net> References: <6lkkc2-fbd.ln1@pluto.i.infosense.no> <35pntaF4os76kU1@individual.net> Message-ID: <71nkc2-pbg.ln1@pluto.i.infosense.no> Diez B. Roggisch wrote: > Ola Natvig wrote: > > >>Anybody out there who knows if the 4suite implementation of XSLT are a >>threadsafe one? > > > What do you mean by that? You can of course transform xml using xslt in as > many threads as you like - but what do you want with two or more threads in > _one_ transformation? You start it, and some time later the result is > there. > If a thread that are using a XSLT processor looses the GIL within the transformation process and another one starts processing on the same processor will this work? Will the half-way finished thread be in the way of the one starting the processing before the stoped thread are done. I think that's what I ment. Can a XSLT processor object be shared between multiple threads? -- -------------------------------------- Ola Natvig infoSense AS / development From xah at xahlee.org Thu Jan 27 14:37:05 2005 From: xah at xahlee.org (Xah Lee) Date: 27 Jan 2005 11:37:05 -0800 Subject: [perl-python] 20050127 traverse a dir Message-ID: <1106854625.289187.28710@z14g2000cwz.googlegroups.com> # -*- coding: utf-8 -*- # Python suppose you want to walk into a directory, say, to apply a string replacement to all html files. The os.path.walk() rises for the occasion. ? import os ? mydir= '/Users/t/Documents/unix_cilre/python' ? def myfun(s1, s2, s3): ? print s2 # current dir ? print s3 # list of files there ? print '------==(^_^)==------' ? os.path.walk(mydir, myfun, 'somenull') ---------------------- os.path.walk(base_dir,f,arg) will walk a dir tree starting at base_dir, and whenever it sees a directory (including base_dir), it will call f(arg,current_dir,children), where the current_dir is the string of the current directory, and children is a *list* of all children of the current directory. That is, a list of strings that are file names and directory names. Try the above and you'll see. now, suppose for each file ending in .html we want to apply function g to it. So, when ever myfun is called, we need to loop thru the children list, find files and ending in html (and not a directory), then call g. Here's the code. ? import os ? mydir= '/Users/t/web/SpecialPlaneCurves_dir' ? def g(s): print "g touched:", s ? def myfun(dummy, dirr, filess): ? for child in filess: ? if '.html' == os.path.splitext(child)[1] \ ? and os.path.isfile(dirr+'/'+child): ? g(dirr+child) ? os.path.walk(mydir, myfun, 3) note that os.path.splitext splits a string into two parts, a portion before the last period, and the rest in the second portion. Effectively it is used for getting file suffix. And the os.path.isfile() make sure that this is a file not a dir with .html suffix... Test it yourself. one important thing to note: in the mydir, it must not end in a slash. One'd think Python'd take care of such trivia but no. This took me a while to debug. also, the way of the semantics of os.path.walk is nice. The myfun can be a recursive function, calling itself, crystalizing a program's semantic. --------------------------- # in Perl, similar program can be had. # the prototypical way to traverse a dir # is thru File::Find; use File::Find qw(find); $mydir= '/Users/t/web/SpecialPlaneCurves_dir'; find(\&wanted, $mydir); sub g($){print shift, "\n";} sub wanted { if ($_ =~/\.html$/ && -T $File::Find::name) { g $File::Find::name;} $File::Find::name; } # the above showcases a quick hack. # File::Find is one of the worst module # there is in Perl. One cannot use it # with a recursive (so-called) "filter" # function. And because the way it is # written, one cannot make the filter # function purely functional. (it relies # on the $_) And the filter function # must come in certain order. (for # example, the above program won't work # if g is moved to the bottom.) ... # the quality of modules in Perl are # all like that. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From duncan.booth at invalid.invalid Mon Jan 17 06:37:28 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jan 2005 11:37:28 GMT Subject: Writing huge Sets() to disk References: Message-ID: Martin MOKREJ? wrote: > Hi, > could someone tell me what all does and what all doesn't copy > references in python. I have found my script after reaching some > state and taking say 600MB, pushes it's internal dictionaries > to hard disk. The for loop consumes another 300MB (as gathered > by vmstat) to push the data to dictionaries, then releases > little bit less than 300MB and the program start to fill-up > again it's internal dictionaries, when "full" will do the > flush again ... Almost anything you do copies references. > > The point here is, that this code takes a lot of extra memory. > I believe it's the references problem, and I remeber complains > of frineds facing same problem. I'm a newbie, yes, but don't > have this problem with Perl. OK, I want to improve my Pyhton > knowledge ... :-)) > > > > > > > The above routine doesn't release of the memory back when it > exits. That's probably because there isn't any memory it can reasonable be expected to release. What memory would *you* expect it to release? The member variables are all still accessible as member variables until you run your loop at the end to clear them, so no way could Python release them. Some hints: When posting code, try to post complete examples which actually work. I don't know what type the self._dict_on_diskXX variables are supposed to be. It makes a big difference if they are dictionaries (so you are trying to hold everything in memory at one time) or shelve.Shelf objects which would store the values on disc in a reasonably efficient manner. Even if they are Shelf objects, I see no reason here why you have to process everything at once. Write a simple function which processes one tmpdict object into one dict_on_disk object and then closes the dict_on_disk object. If you want to compare results later then do that by reopening the dict_on_disk objects when you have deleted all the tmpdicts. Extract out everything you want to do into a class which has at most one tmpdict and one dict_on_disk That way your code will be a lot easier to read. Make your code more legible by using fewer underscores. What on earth is the point of an explicit call to __add__? If Guido had meant us to use __add__ he woudn't have created '+'. What is the purpose of dict_on_disk? Is it for humans to read the data? If not, then don't store everything as a string. Far better to just store a tuple of your values then you don't have to use split or cast the strings to integers. If you do want humans to read some final output then produce that separately from the working data files. You split out 4 values from dict_on_disk and set three of them to 0. If that really what you meant or should you be preserving the previous values? Here is some (untested) code which might help you: import shelve def push_to_disc(data, filename): database = shelve.open(filename) try: for key in data: if database.has_key(key): count, a, b, expected = database[key] database[key] = count+data[key], a, b, expected else: database[key] = data[key], 0, 0, 0 finally: database.close() data.clear() Call that once for each input dictionary and your data will be written out to a disc file and the internal dictionary cleared without any great spike of memory use. From apardon at forel.vub.ac.be Thu Jan 20 09:07:57 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Jan 2005 14:07:57 GMT Subject: Freezing a mutable (was Re: lambda) References: <41EBA021.5060903@holdenweb.com> <41ed8c13.1209309354@news.oz.net> Message-ID: Op 2005-01-20, Nick Coghlan schreef : > Antoon Pardon wrote: >> I missed that you would use it with the idiom: dct[x.frozen()] > > The list itself isn't hashable with this approach, so you don't have much > choice. I wasn't particularly clear about that point, though. > >> I have two problems with this approach. >> >> 1) It doesn't work when you get your keys via the keys/items >> methods. > > True - the frozen object has no link back to the original object. That could be > added though (by returning a tuple subtype with the extra attribute) > >> 2) This is rather minor, but a user could still unfreeze >> untimely > > True - doing that is less likely than mutating a hashable list though :) > > I'm just noting this as a way to avoid copying data more than once when storing > immutable copies of mutable data in a dictionary. You're quite right that there > isn't a really clean idiom for doing that in Python (aside from moving to a > different data structure that works natively as a dict key, naturally). The problem here is IMO is the, we are all consenting adults (which we are not but I wont start on this now), approach. I have been thinking a bit in your freeze direction, but more thorough. The idea i had was that freeze would replace all mutating methods with methods that would throw an exception. a thaw method would inverse the proces. It would then be the responsibilty of the dictionary to freeze an object on entry and thaw it when removed. However this wouldn't work with ordinary python objects, since there is no easy way to have readonly or private variables. -- Antoon Pardon From kerysso at gmail.com Wed Jan 12 21:27:11 2005 From: kerysso at gmail.com (kery) Date: 12 Jan 2005 18:27:11 -0800 Subject: what would you like to see in a 2nd edition Nutshell? References: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> <8y7h3xsz.fsf@python.net> <1gpkwdy.14p3pn1pgdadfN%aleaxit@yahoo.com> Message-ID: <1105583231.665909.239500@z14g2000cwz.googlegroups.com> Alex Martelli wrote: > Craig Ringer wrote: > > > On Wed, 2004-12-29 at 23:54, Thomas Heller wrote: > > > > > I found the discussion of unicode, in any python book I have, insufficient. > > > > I couldn't agree more. I think explicit treatment of implicit > > conversion, the role of sysdefaultencoding, the u'' constructor and > > unicode() built in, etc would be helpful to many. > > Thanks! BTW, thanks first and foremost to Holger Krekel (who was a very > "activist" tech reviewer and specifically contributed a recipe for this > purpose), there's what I believe is a pretty good treatment of Unicode > in the Cookbook's forthcoming 2nd edition -- still "insufficient" in > some sense, no doubt (it IS just a few pages), but, I believe, pretty > good. Nevertheless, I'll ensure I focus on this in the 2nd ed Nutshell, > too. > > > It wouldn't hurt to point C extension authors at things like the 'es' > > encoded string format for PyArg_ParseTuple to help them make their code > > better behaved with non-ascii text. > > Good sub-point, thanks. > > > Alex Any schedule for publication of 2nd Ed? I just bought 1st Ed. From dfg at DFg.com Mon Jan 10 10:59:56 2005 From: dfg at DFg.com (bob) Date: Mon, 10 Jan 2005 15:59:56 -0000 Subject: pulling info from website Message-ID: <41e2a556$0$14576$ed2619ec@ptn-nntp-reader01.plus.net> i am trying to write a script for Xbox media center that will pull information from the bbc news website and display the headlines , how do i pull this info into a list??? From Noah.Richards at infineon.com Mon Jan 3 14:26:31 2005 From: Noah.Richards at infineon.com (Richards Noah (IFR LIT MET)) Date: Mon, 3 Jan 2005 14:26:31 -0500 Subject: Developing Commercial Applications in Python References: <1104750017.235937.181370@c13g2000cwb.googlegroups.com> Message-ID: "It's me" wrote in message news:ozgCd.5867$5R.2655 at newssvr21.news.prodigy.com... > > "Richards Noah (IFR LIT MET)" wrote in message > news:crbur8$edu$1 at athen03.muc.infineon.com... > > > > Begging your pardon, but a better resource would be the brochure available > > (http://www.pti-us.com/PTI/company/brochures/PSSE.pdf). It appears that > the > > program was probably (originally) written in C/C++ (using MFC for the > GUI), > > and now employs Python for adding modules and scripting support. Very > > interesting stuff :) > > > > > > It was actually developed in Fortran some 35 years ago. Then migrated to > F77. Then added a C/C++ layer to sit ontop. Then converted to API based. > Then added a Python layer on top. > > The only thing unfortunate is that they went with MFC on the newest version. > Yuck! > Hahaha, sounds like a party to me. And they didn't even throw in a layer of Lisp for good effort? Too bad, if you ask me :) From len-1 at telus.net Sun Jan 2 16:26:28 2005 From: len-1 at telus.net (Lenard Lindstrom) Date: Sun, 02 Jan 2005 21:26:28 GMT Subject: ctypes NULL pointers; was: Python To Send Emails Via Outlook Express Message-ID: Posted in a previous thread was some Python code for accessing Window's Simple MAPI api using the ctypes module. http://groups-beta.google.com/group/comp.lang.python/msg/56fa74cdba9b7be9 This Simple MAPI module was Ian's completed version of an example I had posted in an earlier message. In it I had to set some pointer fields in a C structure to NULL. I was not happy with the solution I used so I made an inquiry on the ctypes-users mailing list. Thanks to Thomas Heller I got some answers. The simplest way to create a NULL pointer instance in ctypes is to call the pointer class without an argument. from ctypes import POINTER, c_int INT_P = POINTER(c_int) # A pointer to a C integer p = INT_P() # An INT_P instance set to NULL When the pointer is a member of a structure things are a little different. For the ctypes primatives c_void_p, c_char_p and c_wchar_p one can simply use None to set the field NULL. from ctypes import Structure, c_void_p class STRUCT(Structure): _fields_ = [('voidptr', c_void_p)] s=STRUCT( None ) # Create an instance with voidptr field NULL This is documented in the ctypes tutorial. A problem with ctypes 0.9.2 prevents using None to initialize POINTER derived fields. This has been fixed so future releases will allow it. In the meantime the following will work. class IPSTRUCT(Structure): _fields_ [('intptr'), INT_P] s=IPSTRUCT( INT_P() ) A null pointer of the correct type is assigned to the field. I hope this clears up any confusion my Simple MAPI example may have caused regarding ctypes pointers. Lenard Lindstrom From gh at ghaering.de Wed Jan 12 10:58:21 2005 From: gh at ghaering.de (Gerhard Haering) Date: Wed, 12 Jan 2005 16:58:21 +0100 Subject: Python.org, Website of Satan In-Reply-To: References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: <20050112155821.GA12428@mylene.ghaering.de> On Wed, Jan 12, 2005 at 10:15:34AM -0500, Jane wrote: > [...] Some people have too much time on their hands... OMG, PyPy is full of evil, too!!!1 print sum([ord(x) for x in "PyPy!!!!!!!!"]) or, if you haven't upgraded to 2.4, yet: import operator print reduce(operator.add, [ord(x) for x in "PyPy!!!!!!!!"]) -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From bob_smith_17280 at hotmail.com Fri Jan 21 20:49:35 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Fri, 21 Jan 2005 20:49:35 -0500 Subject: getting file size Message-ID: Are these the same: 1. f_size = os.path.getsize(file_name) 2. fp1 = file(file_name, 'r') data = fp1.readlines() last_byte = fp1.tell() I always get the same value when doing 1. or 2. Is there a reason I should do both? When reading to the end of a file, won't tell() be just as accurate as os.path.getsize()? Thanks guys, Bob From steven.bethard at gmail.com Wed Jan 26 12:23:03 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 26 Jan 2005 10:23:03 -0700 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) In-Reply-To: References: <17fpi4ewvvz3h.dlg@usenet.alexanderweb.de> <1a72l6umj80r6.dlg@usenet.alexanderweb.de> Message-ID: <_IadnVdKPJhrTGrcRVn-uA@comcast.com> Jack Diederich wrote: > Yes, this comes up every couple months and there is only one answer: > This is the job of the OS. > Java largely succeeds at doing sandboxy things because it was written that > way from the ground up (to behave both like a program interpreter and an OS). > Python the language was not, and the CPython interpreter definitely was not. > > Search groups.google.com for previous discussions of this on c.l.py Could you give some useful queries? Every time I do this search, I get a few results, but never anything that really goes into the security holes in any depth. (They're ususally something like -- "look, given object, I can get int" not "look, given object, I can get eval, __import__, etc.) Steve From swerdlow at maine.rr.com Tue Jan 11 11:22:53 2005 From: swerdlow at maine.rr.com (Bob Swerdlow) Date: Tue, 11 Jan 2005 16:22:53 GMT Subject: Windows GUIs from Python Message-ID: Anyone have opinions about whether we will be better off using PythonNet or wxPython for the GUI layer of our application on Windows? Our code is all Python and is now running on Mac OS X with PyObjC and Cocoa, which works very well. Our goal is not necessarily to move to a cross-platform solution, but rather to create a solid Windows version that looks and feels like a native application. All the code that interacts with the user is factored out of our business logic, so it is a matter of find a good view/controller library and writing a thin glue layer. And, of course, we want to build it as efficiently and robustly as we can. Thanks, Bob From jhargraveiii at msn.com Sun Jan 23 01:22:44 2005 From: jhargraveiii at msn.com (Jim Hargrave) Date: Sun, 23 Jan 2005 01:22:44 -0500 Subject: embedding jython in CPython... In-Reply-To: References: Message-ID: > I am curious to know what makes your Jython code incompatible with > CPython. If it is only because it uses Java classes, it might > not be too > difficult to port them to CPython+Jpype. CPython+Jpype may indeed be the way to go in the long run - it's only my ignorance stoping me at this point :-) I'll code some tests and give it a whirl. Thanks for the help! From invalidemail at aerojockey.com Mon Jan 31 16:03:30 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 31 Jan 2005 13:03:30 -0800 Subject: variable declaration In-Reply-To: References: Message-ID: <1107205410.367521.50490@f14g2000cwb.googlegroups.com> Thomas Bartkus wrote: > Python *does* require that your variables be declared and initialized before > you use them. You did that with epsilon=0 and S=0 at the top. It is > unfortunate, however, that the statement epselon=epsilon+1 also declares a > new variable in the wrong place at the wrong time. Such mispellings are a > *common* error caught instantly in languages that require a more formal > declaration procedure. I have no interest in arguing this right now, but it does raise a question for me: How common is it for a local variable to be bound in more than one place within a function? It seems that it isn't (or shouldn't be) too common. Certainly the most common case where this occurs is for temporary variables and counters and stuff. These typically have short names and thus are not as likely to be misspelled. Another common place is for variables that get bound before and inside a loop. I would guess that's not as common in Python as it is in other languages, seeing that Python has features like iterators that obviate the need to do this. (The OP's original example should have been "for epsilon in range(10)"; epsilon only needed bound in one place.) I guess this might be why, in practice, I don't seem to encounter the misspelling-a-rebinding error too often, even though I'm prone to spelling errors. Perhaps, if someone runs into this error a lot, the problem is not with Python, but with their tendency to rebind variables too much? Just a thought. -- CARL BANKS From itsme at yahoo.com Thu Jan 6 13:23:03 2005 From: itsme at yahoo.com (It's me) Date: Thu, 06 Jan 2005 18:23:03 GMT Subject: Another PythonWin Excel question References: <1104968382.403653.267060@f14g2000cwb.googlegroups.com> Message-ID: Thanks, "David Bolen" wrote in message news:u1xcyl90a.fsf at fitlinxx.com... > "It's me" writes: > > > Yes, I read about that but unfortunately I have no experience with VBA *at > > all*. :=( > > You don't really have to know VBA, but if you're going to try to > interact with COM objects from Python, you'll find it much smoother if > you at least use any available reference information for the COM > object model and interfaces you are using. > > In the Excel case, that means understanding - or at least knowing how > to look in a reference - its object model, since that will tell you > exactly what parameters an Add method on a worksheet object will take > and how they work. > > For excel, online documentation can be found in a VBAXL9.CHM help file > (the "9" may differ based on Excel release), but it might not always > be installed depending on what options were selected on your system. In > my English, Office 2000 installation, for example, the files are located in: > c:\Program Files\Microsoft Office\Office\1033 > > You can load that file directly, or Excel itself will reference it > from within the script editor help (Tools->Macro->Visual Basic Editor, > then F1 for help). If you methods or classes and have the help > installed it'll bring in the reference. > > You can also find it on MSDN on the web, although it can be tricky to > navigate down to the right section - the top of the Office 2000 object > documentation should be available at: > > http://msdn.microsoft.com/library/en-us/odeomg/html/deovrobjectmodelguide.asp > > This is mostly reference information, but there are some higher level > discussions of overall objects (e.g., worksheets, workbooks, cells, > etc...) too. > > -- David From peter at somewhere.com Wed Jan 26 11:08:55 2005 From: peter at somewhere.com (Peter Maas) Date: Wed, 26 Jan 2005 17:08:55 +0100 Subject: Help With Python In-Reply-To: References: Message-ID: Judi Keplar schrieb: > I am currently taking a course to learn Python and was looking for > some help. I need to write a Python statement to print a comma- > separated repetition of the word, "Spam", written 511 times ("Spam, > Spam, ? Spam"). > > Can anybody help me get started? I am completely new to programming! Online: - http://www.python.org/moin/BeginnersGuide (Beginner, Advanced) - http://www.freenetpages.co.uk/hp/alan.gauld/ (Beginner) - http://docs.python.org/tut/tut.html (Beginner) - http://diveintopython.org/ (Advanced) Books (Look for most recent editions): - Mark Lutz, Learning Python (Beginner) - Alex Martelli, Python in a Nutshell (Beginner, Advanced) - Frederik Lundh, Python Standard Library (Beginner, Advanced) - Alex Martelli, Python Cookbook (Beginner, Advanced) - Mark Pilgrim Dive Into Python (Advanced) -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From http Thu Jan 6 17:26:53 2005 From: http (Paul Rubin) Date: 06 Jan 2005 14:26:53 -0800 Subject: Embedding a restricted python interpreter References: <7xbrc2a7zq.fsf@ruckus.brouhaha.com> Message-ID: <7xr7kyurbm.fsf@ruckus.brouhaha.com> Gerhard Haering writes: > > But mod_python is an apache module and runs in the same apache process > > with other users' scripts. > > Which is why it's a good idea for each customer to have it's own > system user and their virtual hosts running under this uid. Which > was the idea for the perchild MPM for Apache 2 - which is abandoned > now :-( muxmpm is a replacement project in beta. I'm not familiar with perchild MPM or muxmpm, but it sounds like you'd need a separate process per user for it to work. That would seriously increase the cost of operating mass vhosts. It's not uncommon for one apache/mod_php server to support thousands of users. > - go back to Apache 1.3.x, missing some nice improvements > - use different webservers per user, put them together with mod_proxy (yuck!) If it's for low-traffic vhosts without enormous processing complexity, you could use Python cgi's instead of mod_python. From lee at example.com Sat Jan 8 09:48:22 2005 From: lee at example.com (Lee Harr) Date: Sat, 08 Jan 2005 14:48:22 GMT Subject: why not datetime.strptime() ? References: Message-ID: On 2005-01-07, Skip Montanaro wrote: > > josh> Shouldn't datetime have strptime? > > Sure, but it's not quite as trivial to implement as was strftime() support. > While strftime() is a C library function and thus easily called from within > the datetime C code, strptime() is implemented in Python as part of the time > module for portability (strptime(3) is not universally available). You'd > need to import the time module, call its strptime() function with the input > string and format, then use the tuple it returns to initialize a new > datetime object. > Not sure this is exactly related, but I was using datetime the other day to make timestamps: >>> import datetime >>> ts = datetime.datetime.now().isoformat() >>> ts '2005-01-08T09:45:16.896805' and figured there would be an easy way to reverse that. Something along the lines of: dt = datetime.datetime.fromisoformat(ts) From http Wed Jan 19 15:15:18 2005 From: http (Paul Rubin) Date: 19 Jan 2005 12:15:18 -0800 Subject: python/cgi/html bug References: <1106137924.918776.9090@f14g2000cwb.googlegroups.com> Message-ID: <7xmzv5yy3t.fsf@ruckus.brouhaha.com> Dfenestr8 writes: > No glaring security holes that you noticed? Other than being able to hide > things in html tags? Looks like you can also embed arbitrary javascript (I just tried it). I haven't looked at the script itself yet. From dayzman at hotmail.com Tue Jan 4 00:18:13 2005 From: dayzman at hotmail.com (dayzman at hotmail.com) Date: 3 Jan 2005 21:18:13 -0800 Subject: Using ICL to compile C extensions Message-ID: <1104815892.984903.182190@f14g2000cwb.googlegroups.com> Hi, Does anyone know how I can use "icl" (Intel C++) to compile C extensions? I'm on Windows, and my Python is compiled using VS7.1 (binary distribution). Right now, when I run setup.py install, it uses cl.exe (MSVC++ Toolkit 2003), and I would like to use icl because MSVC++ 2003 does not support C99. Any help will be much appreciated. Cheers, Michael From josh-tmda at yucs.org Fri Jan 7 13:05:00 2005 From: josh-tmda at yucs.org (josh) Date: Fri, 7 Jan 2005 18:05:00 +0000 (UTC) Subject: why not datetime.strptime() ? Message-ID: Shouldn't datetime have strptime? It already has strftime, and it'd be really nice to obviate datetime.fromtimestamp(time.mktime(time.strptime(...))) thanks in advance From zhen.ren at gmail.com Thu Jan 27 17:56:08 2005 From: zhen.ren at gmail.com (Blues) Date: 27 Jan 2005 14:56:08 -0800 Subject: gnuplot on Canvas widget In-Reply-To: <1106865871.537454.128830@c13g2000cwb.googlegroups.com> References: <1106852695.371569.234820@f14g2000cwb.googlegroups.com> <1106865871.537454.128830@c13g2000cwb.googlegroups.com> Message-ID: <1106866568.153145.265050@f14g2000cwb.googlegroups.com> Thanks, Jonathan. Can you please give a little more information here? From theller at python.net Tue Jan 4 15:15:18 2005 From: theller at python.net (Thomas Heller) Date: Tue, 04 Jan 2005 21:15:18 +0100 Subject: [Hack] Import binary extensions from zipfiles, windows only References: <1104809102.966779.18480@f14g2000cwb.googlegroups.com> Message-ID: "PJDM" writes: > I'm trying to make ZopeX3 start faster by zipping up the "zope" > directory. (Because this will be stored on a CD, having less data to > read will make it quicker to start.) > > The standard python zipimporter won't work with the ZopeX3 .pyd files, > so zipextimporter came along at just the right time. However, it > doesn't seem to work for me (Python 2.3.4 (#53, May 25 2004, 21:17:02) > [MSC v.1200 32 bit (Intel)] on win32, Windows XP SP2). > > Sample script: > ---- > import zipextimporter > zipextimporter.install() > > import sys > print 'Hooks:\n', sys.path_hooks > > sys.path.append(r'C:\tmp\zope.zip') > print 'Path:\n', sys.path > > # Try an innocuous import first to make sure we have the path correct. > import zope.server > print 'Server file:\n', zope.server.__file__ > > # Now try a .pyd import. > import zope.thread._zope_thread > print 'Thread file:\n', zope.thread._zope_thread.__file__ > ---- > > Output: > ---- > Hooks: > [, 'zipimport.zipimporter'>] > Path: > ['C:\\tmp', 'C:\\WINDOWS\\system32\\python23.zip', 'C:\\tmp', > 'C:\\opt\\Python23\\DLLs', 'C:\\opt\\Python23\\lib', > 'C:\\opt\\Python23\\lib\\plat-win', 'C:\\opt\\Python23\\lib\\lib-tk', > 'C:\\opt\\Python23', 'C:\\opt\\Python23\\lib\\site-packages', > 'C:\\tmp\\zope.zip'] > Server file: > C:\tmp\zope.zip\zope\server\__init__.py > Traceback (most recent call last): > File "zei.py", line 15, in ? > import zope.thread._zope_thread > ImportError: No module named _zope_thread > ---- > > The zope.zip file contains zope.thread: > ---- > $ unzip -l zope.zip |grep zope/thread > 0 11-08-04 11:00 zope/thread/ > 0 07-03-04 04:34 zope/thread/DEPENDENCIES.cfg > 65 07-28-04 22:52 zope/thread/SETUP.cfg > 994 07-03-04 04:34 zope/thread/tests.py > 748 11-08-04 11:00 zope/thread/tests.pyc > 748 11-08-04 11:00 zope/thread/tests.pyo > 20480 11-07-04 00:54 zope/thread/_zope_thread.pyd > 7838 08-17-04 17:20 zope/thread/__init__.py > 7808 11-08-04 11:00 zope/thread/__init__.pyc > 7808 11-08-04 11:00 zope/thread/__init__.pyo > ---- zipextimporter, as published, doesn't handle extensions in packages. The patch I attached at the end, may fix this - I tested it with PIL. It may work with zope, or may not - depends on how the extensions are structured. If there are extensions/pyds that link to other extensions/pyds, then it will most certainly not work. If it doesn't work, you could still try the py2exe approach: py2exe bundles the .py modules in a zip file, and also inserts loaders for extensions into the zip file. The loaders load the .pyd extensions from the file system. Thomas Index: zipextimporter.py =================================================================== RCS file: /cvsroot/py2exe/py2exe/hacks/memimp/zipextimporter.py,v retrieving revision 1.2 diff -c -r1.2 zipextimporter.py *** zipextimporter.py 16 Dec 2004 09:29:42 -0000 1.2 --- zipextimporter.py 4 Jan 2005 20:08:08 -0000 *************** *** 50,55 **** --- 50,56 ---- if result: return result + fullname = fullname.replace(".", "\\") for s in self._suffixes: if (fullname + s) in self._files: return self *************** *** 60,72 **** return zipimport.zipimporter.load_module(self, fullname) except zipimport.ZipImportError: pass for s in self._suffixes: path = fullname + s if path in self._files: # XXX should check sys.modules first ? See PEP302 on reload # XXX maybe in C code... code = self.get_data(path) ! mod = _memimporter.import_module(code, "init" + fullname) mod.__file__ = "%s\\%s" % (self.archive, path) mod.__loader__ = self if _memimporter.get_verbose_flag(): --- 61,75 ---- return zipimport.zipimporter.load_module(self, fullname) except zipimport.ZipImportError: pass + initname = fullname.split(".")[-1] + fullname = fullname.replace(".", "\\") for s in self._suffixes: path = fullname + s if path in self._files: # XXX should check sys.modules first ? See PEP302 on reload # XXX maybe in C code... code = self.get_data(path) ! mod = _memimporter.import_module(code, "init" + initname) mod.__file__ = "%s\\%s" % (self.archive, path) mod.__loader__ = self if _memimporter.get_verbose_flag(): From jerf at jerf.org Fri Jan 7 23:48:43 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 07 Jan 2005 23:48:43 -0500 Subject: Getting rid of "self." References: Message-ID: On Fri, 07 Jan 2005 14:39:09 +0100, BJ?rn Lindqvist wrote: > It works! exec(magic()) does the needed hi = self.hi. No it doesn't. Try "hi = 'newValue'" and see what happens. So the next step is to write an "unmagic" function. So now how do you add instance variables? There is no way to avoid "self" *and* not pre-declare variables in some fashion as belonging to the instance (as declarations, as sigils, what have you). Given that Python is not, will not, and should not do the latter, I submit that "self" is, at least for you, the lesser of two evils. (I don't consider it evil at all, so it isn't such for me; were I programming in C++ routinely now I'd prefix "this" and dispense with that ugly "m_" garbage. (One of the things I ***hate*** about C++ culture is its acceptance of hideously ugly variable names, but now I'm two parentheticals deep so I probably ought to stop.)) From aleaxit at yahoo.com Fri Jan 21 18:18:46 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 22 Jan 2005 00:18:46 +0100 Subject: Unbinding multiple variables References: <1106277883.620769.255830@z14g2000cwz.googlegroups.com> <35bnkeF4jpeetU1@individual.net> <1106334800.868412.27650@f14g2000cwb.googlegroups.com> Message-ID: <1gqrkce.1jtex3qfem7tkN%aleaxit@yahoo.com> Johnny Lin wrote: ... > my understanding about locals() from the nutshell book was that i > should treat that dictionary as read-only. is it safe to use it to > delete entries? Speaking as the Nutshell author: it's "safe", it just doesn't DO anything. I _hoped_ locals() would become a dictionary-proxy giving at least some *warning* about futile attempts to modify things through it, on the basis of "errors shouldn't pass silently", but it just didn't happen (yet). Nevertheless, any modifications to locals() are utterly futile (within a function). Unfortunately, I believe the only way to "delete locals" automatically as you desire is through exec statements (which will inevitably turn off the normal optimizations and make the whole function unbearably slow). I also suspect this won't help you one bit in tracking down your leaks. I would rather suggest you look into module gc... Alex From claird at lairds.us Sat Jan 15 19:08:07 2005 From: claird at lairds.us (Cameron Laird) Date: Sun, 16 Jan 2005 00:08:07 GMT Subject: java 5 could like python? References: <7umnb2-rd.ln1@lairds.us> <41e99752.950044892@news.oz.net> Message-ID: In article <41e99752.950044892 at news.oz.net>, Bengt Richter wrote: . . . >This triggers a thought: Some are more passive about exploring than others, >and think there's nothing to be seen except what's pointed at. Sad for them, >but they need help too. One hopes the tutorial stuff will reawaken natural >pleasure in finding out neat stuff. After all, they came to the right place :-) >But back to my point (it's coming ;-) [1] ... . . . >What if help(something) didn't immediately give up with that last message? >If instead it looked for helpex.py on the path, and invoked >helpex(something) if found? >That way, people could easily experiment with site-specific help >extensions. ISTR a shell in the . . . I wonder if your proposal is better targeted at IPython (for example) than base Python. From david.santiago at corp.ya.com Fri Jan 21 04:27:20 2005 From: david.santiago at corp.ya.com (David) Date: Fri, 21 Jan 2005 10:27:20 +0100 Subject: TypeError error on tkinter.createfilehandler dummy example Message-ID: <41F0CAF8.3080806@corp.ya.com> Hi, I'm getting the following error: Traceback (most recent call last): File "..\kk.py", line 37, in ? tkinter.createfilehandler(filex, tkinter.READABLE, _dispatch) TypeError: 'NoneType' object is not callable when executing this code on my Windows box: from Tkinter import * def _dispatch(self, *args): print "voila" filex = open('d:\\zz.txt', 'r') tkinter.createfilehandler(filex, tkinter.READABLE, _dispatch) Any ideas? What am I missing? I've been searching for something like this with no luck. I cannot imagine a simpler code for testing tkinter.createfilehandler functionality but it does not work :( TIA -- David Santiago -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at hope.cz Tue Jan 25 11:15:24 2005 From: python at hope.cz (python at hope.cz) Date: 25 Jan 2005 08:15:24 -0800 Subject: Skype and Python Message-ID: <1106669724.307651.90150@f14g2000cwb.googlegroups.com> Does anyone played with Skype (http://www.skype.com/ free Internet telephony ) by using Python? Lad. From http Tue Jan 11 15:30:01 2005 From: http (Paul Rubin) Date: 11 Jan 2005 12:30:01 -0800 Subject: OT: MoinMoin and Mediawiki? References: <7x6524d6pv.fsf@ruckus.brouhaha.com> <7xu0pndi6n.fsf@ruckus.brouhaha.com> <1g4nx7m906q79$.dlg@usenet.alexanderweb.de> Message-ID: <7xekgr7lpy.fsf@ruckus.brouhaha.com> Alexander Schremmer <2004b at usenet.alexanderweb.de> writes: > > It doesn't have features that MW has, like user pages, > > It does. Oops, correct, however, they're not anything like MW's, which are almost like an internal email system inside the wiki. You can sign any comment with ~~~ or ~~~~ and it generates a link back to your userpage and anyone who clicks the link can leave you a message by clicking "+" at the top of your user page or any section of it. You're then notified automatically at the top of every page you visit, that someone has left you a new message. (MoinMoin also gives no apparent way to edit sections of pages, which is a big help for editing large Wikimedia pages). > > lists of incoming links to wiki pages, > > It does. Huh? I don't see those. How does it store them, that's resilient across crashes? Or does it just get wedged if there's a crash? > > automatic discussion links for every wiki page, > > Can be easily obtained manually. Just include another page where > discussion is going on. You can even protect it with different ACL > config etc. If you have to do it manually, that's very much reduced usability compared to how WM does it. With WM, the link is automatically generated and always in the same place on the page. > > automatic update notification for specific pages of your choice, > > It does. OK. I didn't find this but will take your word for it. > > support for managing image uploads and embedding them into wiki pages, > > It does. Um, how? I see you can attach files to pages and link to them, but I mean having version history and discussion section like regular wiki pages etc. All I found with MoinMoin attached files was that if you wanted to change one, you had to delete the old one and replace it with a new one. > > The BogusMixedCaseLinkNames. I'd rather have ordinary words with > > spaces between them, like we use in ordinary writing. > > Of course it does. It does not even require [[ but [" at the beginning of > the link which might be more intuitive to the writer. Hmm, maybe. [[ is certainly easier to type. It would also help to have that navigation field on every page, where you could type the name of a page you wanted to jump to. > > Well, it's gotten a lot more development attention because of that > > same Wikipedia. > > Yeah, but you know: Too many cooks spoil the broth. I don't know what the WM code is like and I can certainly believe that it's an awful mess (in PHP even). However it seems to me that they're doing a good job of usability engineering on the front side, and the page layout is much more attractive than MoinMoin's. That's not trying to knock MoinMoin, but Wikipedia is one of the top few hundred sites on the web, and it's getting a LOT of attention to detail. > > level directory, so if you have 100,000 wiki pages, the top level > > directory has that many subdirs. Most file systems are not built to > > handle such large directories with any reasonable speed. > > But many other are. Best to just use a database and be done with it, than depend on magic properties of the file system. Or else go really berserk and replace it with something more performance-intensive. > > The DBMS can also handle stuff like replication automatically. > > But this is non-trivial. Well yes, of course, that's why leaving it to a DBMS is helpful. > See above. Just because most people still work with CamelCase, they are not > the only solution. ["Stupid mixed case page names"] is a completly valid > link in MoinMoin and has been one for years. Well, they should fix the defaults. Can you set it to not automatically convert CamelCase words into links? From ncoghlan at iinet.net.au Mon Jan 10 08:22:51 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 10 Jan 2005 23:22:51 +1000 Subject: windows mem leak In-Reply-To: References: <41XDd.70234$Jk5.40626@lakeread01> <41E06C18.6050407@hotmail.com> Message-ID: <41E281AB.2050104@iinet.net.au> Bob Smith wrote: > Peter Hansen wrote: > >> Bob Smith wrote: >> >>> Attached is the code. Run it yourself and see. You too Peter. Be >>> gentle with me, this was my first attempt with threads. >> >> >> >> Thanks, Bob, and I will, but not before you answer some of my >> questions. >> >> I had good reasons to ask them, one of which is that I don't >> feel like wasting my time if, for example, you are using an >> older version of Python that *did* have a memory leak. > > > 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] Perhaps you could try using the new subprocess module, instead of using os.popen directly. A fair amount of work went into making the Windows implementation of that module as solid as the *nix implementation, whereas there may still be issues with direct os.popen calls (as Roel's investigation suggests). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jjl at pobox.com Sat Jan 1 13:25:24 2005 From: jjl at pobox.com (John J Lee) Date: Sat, 1 Jan 2005 18:25:24 +0000 (GMT) Subject: PyQT installation In-Reply-To: <41D6E175.70600@perfect-image.com> References: <1104370062.562575.88620@f14g2000cwb.googlegroups.com> <1104417268.153983.71970@z14g2000cwz.googlegroups.com> <8SVAd.64014$Jk5.26087@lakeread01> <1gpo9ow.7zqmxi1rwc564N%aleaxit@yahoo.com> <871xd5hzfc.fsf@pobox.com> <41D6E175.70600@perfect-image.com> Message-ID: On Sat, 1 Jan 2005, Ken Godee wrote: [...] > I believe the book "C++ GUI programming Qt3" comes > with a windows Qt gpl 3.x version. Just have to buy > the book. No PyQt version to match thou. "GPL only if you buy the book" makes no sense. Either it's GPL or it isn't. (It isn't, in fact.) [...] > > IIRC, people have already run some KDE apps under Windows (though > > still needing X, so far). > > > > I wonder how TrollTech will react as (and if) it progresses. > > > > I don't think your giving TrollTech any credit here, yes they have > a business model and need to make money, but not everybody is > Microsoft. They are fully aware and supportive of the project > and I remember reading not to long ago they struck an aggrement > with the project that if anything ever happened to TrollTech they > would release Qt to project under gpl, or something like that. I'd forgotten about that agreement (again, driven by KDE). Reassuring, assuming the legalese corresponds to what one assumes is the spirit of it, and that it will hold water if/when tested in the courts. I am surprised if they support the effort to make a GPL native MS Windows version of Qt. They wouldn't have to be evil monopolists to be concerned about this development, IMHO. John From charlie at iwec.com Wed Jan 19 21:04:31 2005 From: charlie at iwec.com (Charlie Taylor) Date: Thu, 20 Jan 2005 02:04:31 +0000 (UTC) Subject: Python and Excel References: <1106179117.094466.305960@f14g2000cwb.googlegroups.com> Message-ID: If it helps, I started a similar project a few years ago on SourceForge when I was just learning python called python2xlw. I haven't supported it for quite a while, however, I still use it a lot in my own work. I needed to create Excel files with scatter charts in them for a web interface so I went through the excercise of disassembling the BIFF codes of the older XLW format of excel and creating a byte stream representation of the spreadsheet that could be saved to file or sent directly to the web user as an excel application in there browser. The newer XLS format is a bit more complex and I didn't have enough documentation to create the charts I needed directly from python in the newer XLS format. (the current version of excel still understands XLW, however, so you're just a "SAVE AS" away from XLS.) As I think was mentioned in another post, you can create charts etc. using the COM interface for a client-type application, however, my goal was to create them on-the-fly directly from the web server without launching a server-side excel application. There is a nice Perl project called Spreadsheet::WriteExcel that John McNamara created that was very helpful to me at that time, however, it only created the worksheets, not charts. From phil at riverbankcomputing.co.uk Fri Jan 28 18:14:24 2005 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Fri, 28 Jan 2005 23:14:24 +0000 Subject: Problems with PyQt In-Reply-To: <1106948570.216167.302060@z14g2000cwz.googlegroups.com> References: <1106948570.216167.302060@z14g2000cwz.googlegroups.com> Message-ID: <200501282314.24251.phil@riverbankcomputing.co.uk> I suggest that you post your question to the PyKDE mailing list and include a complete example that demonstrates your problem as an attachment (so the indentation is preserved). Phil On Friday 28 January 2005 9:42 pm, Michael McGarry wrote: > Hi, > > I am having a problem making a widget appear. I have 5 widgets which > are windows with no parents. 3 of the widgets appear without a problem > the other 2 widgets will not appear when I invoke widget.show() from > within a handler for another widget. I am completely clueless as to why > these 2 widgets will not draw. One of them is simply a wait window I > want to appear while I am performing a time consuming task. > > Here is a snippet of code: > > def viewSimButton_pressed(self): > wait_win.waitProgressBar.setPercentageVisible(1) > wait_win.waitProgressBar.setTotalSteps(5) > wait_win.waitProgressBar.setProgress(0) > wait_win.show() > self.hide() > self.viewSimButton.setDown(0) > for loopIdx in range(self.simListBox.count()): > if self.simListBox.isSelected(loopIdx) == 1: > simIdx = loopIdx > simID = self.simListBox.item(simIdx).text().ascii() > # Clear list box > sim_view_win.simOutputListBox.clear() > if os.path.exists(simID) == 1: > os.chdir(simID) > wait_win.waitProgressBar.setProgress(1) > # Check process ID file > if os.path.exists('pid') == 1: > time.sleep(1) # wait 1 second, then check again > pidFile = open('pid','r') > pidStr = pidFile.readline() > if pidStr == 'done\n': > sim_view_win.simStatusLbl.setText('Completed') > else: > sim_view_win.simStatusLbl.setText('Running') > simData = sims[simID] > sim_view_win.simIDEdit.setText(simID) > sim_view_win.hostEdit.setText(simData['host']) > wait_win.waitProgressBar.setProgress(3) > # Fill list box with output files > # > filedir = os.popen('ls','r') > filename = filedir.readline() > while filename: > filename = string.rstrip(filename) > if ((filename != 'pid') and (filename != 'sim_cfg') and (filename != > 'sim_log') > and (filename != 'sim_core') > and (string.find(filename,'.fig') == -1) > and (string.find(filename,'.gp') == -1)): > sim_view_win.simOutputListBox.insertItem(filename) > filename = filedir.readline() > os.chdir('..') > wait_win.waitProgressBar.setProgress(5) > wait_win.hide() > sim_view_win.show() > > wait_win will show on the screen but not with it's progress bar. Can > anyone help? > > Thanks, > > Michael From sjmachin at lexicon.net Mon Jan 3 15:35:26 2005 From: sjmachin at lexicon.net (John Machin) Date: 3 Jan 2005 12:35:26 -0800 Subject: Speed ain't bad References: <0189t05r3226bkp5e1vtmp0gd6odcsf2qp@4ax.com> <41d6a39b$0$33656$edfadb0f@dread16.news.tele.dk> Message-ID: <1104784526.014246.13300@z14g2000cwz.googlegroups.com> Anders J. Munch wrote: > Another way is the strategy of "it's easier to ask forgiveness than to > ask permission". > If you replace: > if(not os.path.isdir(zfdir)): > os.makedirs(zfdir) > with: > try: > os.makedirs(zfdir) > except EnvironmentError: > pass > > then not only will your script become a micron more robust, but > assuming zfdir typically does not exist, you will have saved the call > to os.path.isdir. 1. Robustness: Both versions will "crash" (in the sense of an unhandled exception) in the situation where zfdir exists but is not a directory. The revised version just crashes later than the OP's version :-( Trapping EnvironmentError seems not very useful -- the result will not distinguish (on Windows 2000 at least) between the 'existing dir' and 'existing non-directory' cases. Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 >>> import os, os.path >>> os.path.exists('fubar_not_dir') True >>> os.path.isdir('fubar_not_dir') False >>> os.makedirs('fubar_not_dir') Traceback (most recent call last): File "", line 1, in ? File "c:\Python24\lib\os.py", line 159, in makedirs mkdir(name, mode) OSError: [Errno 17] File exists: 'fubar_not_dir' >>> try: ... os.mkdir('fubar_not_dir') ... except EnvironmentError: ... print 'trapped env err' ... trapped env err >>> os.mkdir('fubar_is_dir') >>> os.mkdir('fubar_is_dir') Traceback (most recent call last): File "", line 1, in ? OSError: [Errno 17] File exists: 'fubar_is_dir' >>> 2. Efficiency: I don't see the disk I/O inefficiency in calling os.path.isdir() before os.makedirs() -- if the relevant part of the filesystem wasn't already in memory, the isdir() call would make it so, and makedirs() would get a free ride, yes/no? From tundra at tundraware.com Sat Jan 22 05:48:21 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 22 Jan 2005 05:48:21 EST Subject: re Insanity Message-ID: <4ln9c2-0mh1.ln1@eskimo.tundraware.com> For some reason, I am having the hardest time doing something that should be obvious. (Note time of posting ;) Given an arbitrary string, I want to find each individual instance of text in the form: "[PROMPT:optional text]" I tried this: y=re.compile(r'\[PROMPT:.*\]') Which works fine when the text is exactly "[PROMPT:whatever]" but does not match on: "something [PROMPT:foo] something [PROMPT:bar] something ..." The overall goal is to identify the beginning and end of each [PROMPT...] string in the line. Ideas anyone? -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From binux.lists at gmail.com Wed Jan 5 09:26:45 2005 From: binux.lists at gmail.com (Binu K S) Date: Wed, 5 Jan 2005 19:56:45 +0530 Subject: date/time In-Reply-To: References: Message-ID: <2b7d8b420501050626a09c048@mail.gmail.com> >>> import time >>> time.strftime('%Y%m%d',time.localtime()) '20050105' On Wed, 05 Jan 2005 15:08:37 +0100, Nader Emami wrote: > L.S., > > Could somebody help me how I can get the next format of date > from the time module? > > example: I have to have this time 20050105. It is the next > attributes of format %Y%m%d. > > with regards, > Nader > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Mon Jan 24 16:40:30 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 24 Jan 2005 22:40:30 +0100 Subject: What's so funny? WAS Re: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com><41EE24F7.7030303@jessikat.fsnet.co.uk><7x1xchlpqv.fsf@ruckus.brouhaha.com><41efeb82$0$27807$9b622d9e@news.freenet.de><41f1a70b$0$25959$9b622d9e@news.freenet.de><7xbrbiqdhk.fsf@ruckus.brouhaha.com><7xllalljah.fsf@ruckus.brouhaha.com><7xekgdmpll.fsf@ruckus.brouhaha.com><7xpszxcnfa.fsf@ruckus.brouhaha.com><7xllalcmqc.fsf@ruckus.brouhaha.com><7xbrbhosh7.fsf@ruckus.brouhaha.com><7xzmz0lw6h.fsf@ruckus.bro Message-ID: wrote: > Maybe we're not thinking about the same problems. Say I'm an app > writer and I want to use one of your modules. My development > environment is GNU/Linux, and I want to ship a self-contained app that > anyone can run without having to download additional components. That > includes people wanting to run my app on Windows, Macintosh, Amiga, > and various other Python target platforms that I don't have compilers > for. How do I do it? have you tried this, or are you just making things up to be able to continue the argument? (hint: it doesn't work; python portability means that it's fairly easy to write programs that run on multiple platforms, not that they will run on all available platforms without porting and testing). From tim.peters at gmail.com Wed Jan 26 00:10:31 2005 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 26 Jan 2005 00:10:31 -0500 Subject: threading.py Condition wait overflow error In-Reply-To: <40E605146701DE428FAF21286A97D309174515@wphexa02.corp.lh.int> References: <40E605146701DE428FAF21286A97D309174515@wphexa02.corp.lh.int> Message-ID: <1f7befae05012521105ddcd0d4@mail.gmail.com> [Mark English] > Every once in a while since I moved to Python 2.4 I've been seeing the > following exception in threading.py Condition: > > File "mctest3.py", line 1598, in WaitForMessages > self.condResponses.wait(1.0) > File "C:\Program Files\Python24\lib\threading.py", line 221, in wait > delay = min(delay * 2, remaining, .05) > OverflowError: long int too large to convert to int > > Is there something I'm doing wrong here ? I've looked at my code, and > glanced at threading.py, and I can't see any obvious errors (multiplying > a float by 2, using the result of the time.time() call none of which use > longs as far as I know). > > I added some print statements to threading.py and the exception is > thrown on the first iteration when delay is 0.0005 and remaining is 1.0 > However the code does keep running... The error is particularly bizarre, since none of min's arguments are even integers (they're all floats). The only int in sight is "2". Which C extension modules (outside of the ones shipped with Python) are you using? The most common cause for "impossible exceptions" is flawed C code in an extension that fails to check a Python C API call for an error return. The exception remains set then, but the flawed C code doesn't tell the interpreter that it failed. The exception gets raised at a seemingly random later time then. This is usually in a non-core extension just because the core C code is so heavily used that such problems rarely survive to a final release. Do you use long (unbounded) ints _anywhere_ in the app that you know of? > ----------------------- > Delay: 0.0005 Remaining: 1.0 > Traceback (most recent call last): > File "", line 1, in ? > File "mctest3.py", line 2665, in getLogonResponse > respLogon.WaitForMessages() > File "mctest3.py", line 1598, in WaitForMessages > self.condResponses.wait(1.0) > File "C:\Program Files\Python24\lib\threading.py", line 222, in wait > delay = min(delay * 2, remaining, .05) > OverflowError: long int too large to convert to int > Delay: 0.016 Remaining: 8.07899999619 > Delay: 0.032 Remaining: 8.01600003242 > Delay: 0.05 Remaining: 7.95399999619 > Done > Message response handler got message > ----------------------- > > Is this something to do with min ? Converting 1.0 ? Almost certainly neither, and there have been no other reports of this. That's more reason to suspect a non-core extension module. From tim.peters at gmail.com Thu Jan 13 14:04:52 2005 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 13 Jan 2005 14:04:52 -0500 Subject: python 2.3.4 for windows: float("NaN") throws exception In-Reply-To: <1105637733.557859.85000@c13g2000cwb.googlegroups.com> References: <1105629033.442397.124820@c13g2000cwb.googlegroups.com> <1105637733.557859.85000@c13g2000cwb.googlegroups.com> Message-ID: <1f7befae05011311046de0269@mail.gmail.com> [beliavsky at aol.com] > C99 and Fortran 2003 have IEEE arithmetic. Not that simple (e.g., C99 doesn't *require* it; but it has a pile of specified IEEE behaviors a conforming C99 compiler can choose to support (or not), along with a preprocessor symbol those that do so choose can #define to advertise that decision). > If CPython could be compiled with a C99 compiler, would it > also have IEEE arithmetic? Fully define "have IEEE arithmetic". Not that simple either. Even on Windows using Microsoft's C89 compiler, Python's float + - * and / meet the 754 standard provided you're running on a Pentium or AMD chip. The IEEE standard says nothing about how a 754-conforming implementation has to spell infinities or NaNs in string<->float conversions, so that MS produces -1.#IND for a NaN doesn't oppose the 754 standard. > Do Python number-crunchers think this is important? Some do, some don't. The only contributors motivated enough to "do something about it" gave us Python's fpectl module, which is aimed mostly at making it look like 754 gimmicks don't exist (fiddling the C runtime system so that operations that try to produce a NaN or infinity from finite operands raise exceptions instead). From fredrik at pythonware.com Fri Jan 28 04:34:42 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 28 Jan 2005 10:34:42 +0100 Subject: A proposal idea for string.split with negative maxsplit References: Message-ID: Antoon Pardon wrote: > This behaviour would remain but additionally we would have the > following. > >>>> "st1:st2:st3:st4:st5".split(':',-2) > ["st1:st2:st3" , "st4" , "st5"] > > What do people think here? >>> "st1:st2:st3:st4:st5".rsplit(':', 2) ['st1:st2:st3', 'st4', 'st5'] From binux.lists at gmail.com Thu Jan 6 02:25:22 2005 From: binux.lists at gmail.com (Binu K S) Date: Thu, 6 Jan 2005 12:55:22 +0530 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: References: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> <003801c4f3b9$af17fa20$0800a8c0@vishnu> Message-ID: <2b7d8b42050105232546083758@mail.gmail.com> There's nothing crazy going on here. The file's current position moves as you write into it. Both read and write operation use the same offset. The tell() method gives you the current position at any time. When you append to a file the position moves to the end of the file so that the next write happens at the end. You normally wouldn't read from the file that you are writing into. To read from the beginning, change the position with seek. Here's how you do it: >>> logfile=file(r'test.txt','a+') >>> logfile.write('datetime') >>> logfile.flush() >>> test=logfile.readlines() >>> print test [] >>> logfile.tell() 8L >>> logfile.seek(0,0) >>> test=logfile.readlines() >>> print test ['datetime'] On Thu, 6 Jan 2005 12:30:03 +0530, Gurpreet Sachdeva wrote: > logfile=file(r'test.txt','a+') > logfile.write('datetime') > logfile.flush() > test=logfile.readlines() > print test > > I added logfile.flush(), the 'datetime' was written in the file > correctly but I couldn't get any result... > > Crazy! > Garry > -- > http://mail.python.org/mailman/listinfo/python-list > From aleaxit at yahoo.com Tue Jan 4 11:55:53 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 4 Jan 2005 17:55:53 +0100 Subject: Python evolution: Unease References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl> <1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> <41DA79DB.7020507@none.net> Message-ID: <1gpvjtu.16x4hww1trmzitN%aleaxit@yahoo.com> Iwan van der Kleyn wrote: ... > And I do sense (reading planet python/this newsgroup) a mindset or at > least a tendency by the people who really matter in these discussion to > keep on adding features to the syntax; to add "structure" to Python. My > personal preference would be to leave the language alone for a while and > to improve its infrastructure. I happen to agree with this preference as stated here -- the time to change the language is at 3.0 release time (say a few years from now). It _is_, of course, perfectly sensible for Guido to start musing out loud on the only major addition he really wants to make at that distant time a few years from now, namely optional static typing -- it will be a biggie when it comes, so it should not be sprung on us all by surprise; the more (and the earlier) feedback comes to help him decide the exact details of that addition, the merrier. Meanwhile, over on python-dev, the discussion is on completing the AST-branch (so the standard library may finally include a full python-coded Python compiler when 2.5 is released, likely in 2006), dealing (in distutils, mostly) with the fact that the Mac may use some case-sensitive filesystems but its default one is case-preserving but insensitive, issues with memory allocation strategies triggered by Darwin's weird realloc behavior (a realloc there never shrinks an allocation, eek), the best maintenance strategy for old FAQs, what functionality is to be added to the zipfile module (e.g., removing files from a zip archive), and the fix of a misspelling in the docs. I kid you not: these are the threads going on today in the python-dev list, where most of [the discussion about] Python's development really takes place. Not sure who you believe "really matter in these discussion" (sic), but the discussants today included Guido van Rossum, Tim Peters, Martin v. Loewis, and many others. How one can possibly infer from such raw data "a mindset or at least a tendency ... to keep adding features to the syntax" is really hard to explain, at least for me. Almost invariably, the great majority of proposals to change the language, most particularly the syntax, come on this list, fortunately, since that leaves python-dev essentially free to keep focusing on the huge nitty-gritty daily work of enhancing the implementation (and other aspects of the infrastruture, such as the spelling of the docs...); almost invariably, moreover, the great majority of such proposals come from clueless or semi-clueless newbies or semi-newbies. You appear to have taken the fact that Guido appears to want lot of early discussion about his ideas on optional static typing, presumably to help those ideas develop, and drawn from that tiny speck of 'fact' the most absurdly extrapolated conclusions, totally and utterly ignoring the overwhelming countervailing mass of facts and evidence that point exactly in the opposite direction. Of course, what YOU think should happen regarding the infrastructure, and what the people who donate their time to actually make things happen want, may be totally at odds. For example, you appear to keenly want one standard IDE to be blessed and receive all attention, one standard web framework ditto, and so on, and so forth; most core developers, on the other hand, appear to be very modestly inclined to spend their time and energy in that direction, so that only a rather minor fraction of the python-dev effort is channeled that way. Innovative efforts are best kept OUT of the core Python standard, many of us believe, as long as their innovative fervor continues: once something does get into the standard Python library &c, it won't and shouldn't develop very fast, nor at all freely, due to the tiranny of backwards compatibility, cross platform support, and the huge increase in maintenance/support efforts that comes when something suddenly becomes much more widespread and widely used than it previously used to be. Enhancements in library organization and functionality, fixing typos in the docs, or deciding whether and how to work around some platform's quirks, are definitely less glamorous than inventing new grand unification projects, but nevertheless this kinds of things IS by far the vastest part of the work in a large and mature open-source project. Wonderfully innovative projects, *OUT* of the core language/library, are very abundant. Come to PyCon in March and you'll probably hear several eye-opening, possibly mind-boggling talks about such things as the type inferencing and optimizations of the pypy project, or Enthought's breathtaking Traits and Envisage technologies -- all "infrastructure", btw, no language changes involved. It's perfectly fit and proper that such work takes place exactly where it's taking place now. If and when it matures and stabilizes, to the point of not needing any more innovation but rather consolidation and spreading, _then_ some part of it may be merged into the standard core. Many people contributing to such innovative projects are also Python core committers, of course. Alex From fuzzyman at gmail.com Mon Jan 24 05:10:58 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Jan 2005 02:10:58 -0800 Subject: Help on project, anyone? In-Reply-To: <35ienhF4lu88lU1@individual.net> References: <35ienhF4lu88lU1@individual.net> Message-ID: <1106561458.167373.303270@c13g2000cwb.googlegroups.com> Hello Chap, I work on various projects. Several of them would *greatly* benefit from input from another programmer. You can see them at : http://www.voidspace.org.uk/python/index.shtml Specifically, I have three projects that I'm looking for someone to work on, but they are all on the 'small' scale. I couldn't tell whether you would be happy with that, or if you wanted to join a larger team. I have listed them in order of difficulty (easiest first). With all of them I would work with you or offer whatever level of support you want. 1) My dateutils module is out of date and needs work on it. http://www.voidspace.org.uk/python/modules.shtml#dateutils [1] 2) I need an online bookmarks manager. This is a CGI script that will allow you to keep/manage an online bookmarks page. [2] 3) Simple Version Control program for single programmer. A very simple way of doing version control/releases for small projects with only a single programmer. [3] If any of these interest you then please contact me - fuzzyman _AT_ voidspace _DOT_ org _DOT_ uk (in preference to my gmail account). Whatever you decide to do, good luck with your pythoneering. Regards, Fuzzyman [1] Several of the functions shadow functions in the standard library calender.py. Some of the return values are in illogical orders and a couple don't behave *exactly* as documented (when adding months to a date that is at the end of a month). Basically it's in need of an update/clean up. It is incorporated into a couple of other projects - and it works fine for those, so *I* don't need it cleaned up. However, it's one of my most popular downloads - so it's obviously something people want and would appreciate an updated version. [2] I work in several locations and really *need* a single bookmarks repository. I have a clear idea of what I would like *and* how to do ti. I just don't have the time to work on it. None of the existing perl/php ones I explored did quite what I hoped. The advantage of this project is that you could start simple and just incrementally add features. You could have something working *very* quickly. Basically phase 1 - a simple bookmark manager with add/delete links. Phase 2 - parse IE/Firefox/opera bookmark files and check for duplicates (including sections). Phase 3 - multiple users, client prorgram with automatic synchronization. (plus lots more) [3] I think lots of people would find this useful. A version control system for projects where CVS/Subversion is overkill. This would be based on DirWatcher/FSDM ( http://www.voidspace.org.uk/python/programs.shtml#dirwatcher ) - All the code for finding which files have changed is already there, and there is an existing Tkinter GUI for Dirwatcher. From gandalf at geochemsource.com Wed Jan 26 06:57:21 2005 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Wed, 26 Jan 2005 12:57:21 +0100 Subject: wx.Image: Couldn't add an image to the image list. Message-ID: <41F785A1.8030800@geochemsource.com> I would like to load image from a directory right into an image list. I wrote a simple library that loads the images in the directory and resizes them as needed before adding to the wx.ImageList. This is not the same code but some snippets. I resize the image this way (using Python Imaging Library): def resizeimage(image,newsize): oldsize = (image.GetWidth(),image.GetHeight()) if oldsize != newsize: return piltoimage(resizepil(imagetopil(image),newsize)) else: return image This is how I convert images to a bitmaps: bmp = wx.BitmapFromImage(image,depth=depth) I have a directory with 16x16 bmp images in it. Everything works fine for sizes 16x16 and below. When I try to use a bigger size (say, 32x32) I get the following message: Couldn't add an image to the image list. It is repeated for every image. (I used wx.PySimpleApp.) There is the same problem when I try to force 8bit color depth. Where is the problem? Is this related to my Windows XP platform? Best, Laci 2.0 p.s.: I wonder why it is not named wx.BitmapList since one can only store wx.Bitmap instances in it. Late sorrow. :-) From Florian.Lindner at xgm.de Mon Jan 3 19:20:07 2005 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Tue, 04 Jan 2005 00:20:07 +0000 Subject: How to access database? Message-ID: Hello, AFAIK python has a generic API for database access which adapters are supposed to implement. How can I found API documentation on the API? Thanks, Florian From cam.ac.uk at mh391.invalid Sat Jan 15 21:50:32 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 16 Jan 2005 02:50:32 +0000 Subject: How to del item of a list in loop? In-Reply-To: <1105838984.045727.55730@f14g2000cwb.googlegroups.com> References: <1105838984.045727.55730@f14g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > Three significant figures is plenty. Showing just the minimum of the > results might be better. It might be, but how much time do you want to spend on getting your results for a benchmark that will be run once in the "better" format? Next time you can run the benchmark yourself and it will be in exactly the format you want. Give me a break. -- Michael Hoffman From harold.fellermann at upf.edu Tue Jan 11 13:26:58 2005 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 11 Jan 2005 19:26:58 +0100 Subject: how to set doc-string of new-style classes Message-ID: <610CA378-63FE-11D9-B3E0-003065FB7B26@upf.edu> Hello, does anyone know a way to set the __doc__ string of a new style class? Any attempt I tried results in the following error: Python 2.4 (#1, Dec 30 2004, 08:00:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> class Foo(object) : ... pass ... >>> Foo.__doc__ = "bar" Traceback (most recent call last): File "", line 1, in ? TypeError: attribute '__doc__' of 'type' objects is not writable I can understand someone arguing that "changing a doc string is during programm execution and should therefore be forbidden!" But, I cannot even find out a way to set the doc string, when I CREATE a class using type(name,bases,dict) ... At least this should be possible, IMHO. - harold - -- If you make people think they're thinking, they'll love you; but if you really make them think they'll hate you. From joshway_without_spam at myway.com Fri Jan 14 14:53:02 2005 From: joshway_without_spam at myway.com (JCM) Date: Fri, 14 Jan 2005 19:53:02 +0000 (UTC) Subject: Octal notation: severe deprecation References: <1105481767.711530.116290@z14g2000cwz.googlegroups.com> <1105587098.932273.315230@c13g2000cwb.googlegroups.com> Message-ID: and-google at doxdesk.com wrote: ... > In Mythical Future Python I would like to be able to use any base in > integer literals, which would be better. Example random syntax: > flags= 2x00011010101001 > umask= 8x664 > answer= 10x42 > addr= 16x0E800004 # 16x == 0x > gunk= 36x8H6Z9A0X I'd prefer using the leftmost character as a two's complement extension bit. 0x1 : 1 in hex notation 1xf : -1 in hex notation, or conceptually an infinitely long string of 1s 0c12 : 10 in octal noataion 1c12 : -54 in octal (I think) 0d12 : 12 in decimal 0b10 : 2 in binary etc I leave it to the reader to decide whether I'm joking. From steven.bethard at gmail.com Fri Jan 21 14:32:35 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 21 Jan 2005 12:32:35 -0700 Subject: Print a string in binary format In-Reply-To: References: <1106268802.094106.122090@c13g2000cwb.googlegroups.com> <1106270502.219126.322790@f14g2000cwb.googlegroups.com> Message-ID: <7pidncDdVepNxWzcRVn-jQ@comcast.com> Stephen Thorne wrote: > On Fri, 21 Jan 2005 01:54:34 GMT, Kartic > wrote: >>Aha..I guess I posted too soon. >> >>You might want to take a look at this cookbook entry: >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/219300 >> >>Defines lambdas to convert integer to binary. The one you probably want is - >> >>> bstr = lambda n, l=16: n<0 and binarystr((2L<>bstr(n>>1).lstrip('0')+str(n&1) or '0' >> >>> bstr(ord('a')) >>'1100001' > > > Death to inappropriate usage of lambda. > First of all, that lambda is buggy, it doesn't work for negative > numbers, but you can't immediately see that because of the compressed > nature of the code. > [snip how to write better code without lambdas] Your discussion here was nicely illustrative. You might consider adding something to the "Overuse of Lambda" discussion in: http://www.python.org/moin/DubiousPython Steve From dieter at handshake.de Thu Jan 27 14:02:59 2005 From: dieter at handshake.de (Dieter Maurer) Date: 27 Jan 2005 20:02:59 +0100 Subject: limited python virtual machine (WAS: Another scripting language implemented into Python itself?) References: Message-ID: Steven Bethard writes on Tue, 25 Jan 2005 12:22:13 -0700: > Fuzzyman wrote: > ... > > A better (and of course *vastly* more powerful but unfortunately only > > a dream ;-) is a similarly limited python virutal machine..... I already wrote about the "RestrictedPython" which is part of Zope, didn't I? Please search the archive to find a description... Dieter From exarkun at divmod.com Tue Jan 4 11:01:43 2005 From: exarkun at divmod.com (Jp Calderone) Date: Tue, 04 Jan 2005 16:01:43 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) In-Reply-To: Message-ID: <20050104160143.25734.1149531237.divmod.quotient.725@ohm> On Tue, 04 Jan 2005 16:41:05 +0100, Thomas Heller wrote: >Skip Montanaro writes: > > > michele> BTW what's the difference between .encode and .decode ? > > > > I started to answer, then got confused when I read the docstrings for > > unicode.encode and unicode.decode: > > > > [snip - docstrings] > > > > It probably makes sense to one who knows, but for the feeble-minded like > > myself, they seem about the same. > > It seems also the error messages aren't too helpful: > > >>> "??".encode("latin-1") > Traceback (most recent call last): > File "", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0x84 in position 0: ordinal not in range(128) > >>> > > Hm, why does the 'encode' call complain about decoding? > > Why do string objects have an encode method, and why do unicode objects > have a decode method, and what does this error message want to tell me: > > >>> u"??".decode("latin-1") > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 0: ordinal not in range(128) > >>> The call unicode.decode(codec) is actually doing this unicode.encode(sys.getdefaultencoding()).decode(codec) This is not a particularly nice thing. I'm not sure who thought it was a good idea. One possibility is that .encode() and .decode() are not _only_ for converting between unicode and encoded bytestrings. For example, there is the zlib codec, the rot13 codec, and applications can define their own codecs with arbitrary behavior. It's entirely possible to write a codec that decodes _from_ unicode objects _to_ unicode objects and encodes the same way. So unicode objects need both methods to support this use case. Jp From jeff at ccvcorp.com Thu Jan 13 13:03:55 2005 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 13 Jan 2005 10:03:55 -0800 Subject: reference or pointer to some object? In-Reply-To: References: <10ubcp136drsu97@corp.supernews.com> Message-ID: <10uddmb5gkk0v71@corp.supernews.com> Antoon Pardon wrote: > Op 2005-01-12, Jeff Shannon schreef : > >>It's also rather less necessary to use references in Python than it is >>in C et. al. > > You use nothing but references in Python, that is the reason why > if you assign a mutable to a new name and modify the object through > either name, you see the change through both names. Perhaps it would've been better for me to say that the sorts of problems that are solved by (pointers and) references in C/C++ can be better solved in other ways in Python... One can take the position that every variable in Python is a reference; the semantics work out the same. But I find it clearer to view the Python model as conceptually distinct from the "classic" value/reference model. Re-using the old terms is likely to lead to making mistakes based on inapplicable presumptions. Jeff Shannon Technician/Programmer Credit International From ajikoe at gmail.com Wed Jan 26 15:03:10 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 26 Jan 2005 12:03:10 -0800 Subject: can not use __methods__ Message-ID: <1106769790.604491.290680@c13g2000cwb.googlegroups.com> Hello, I try to use __methods__ in python 2.4 and 2.2 it always fail. Can some one tell me if I want to itterate the methods in a class and print it in a string format ( it is possible using __methods__ ). Is there any replacement? Sincerely Yours, Pujo From claird at lairds.us Tue Jan 18 16:08:03 2005 From: claird at lairds.us (Cameron Laird) Date: Tue, 18 Jan 2005 21:08:03 GMT Subject: script to automate GUI application (newbie) References: <1106071392.908441.262500@c13g2000cwb.googlegroups.com> Message-ID: <9q90c2-tou.ln1@lairds.us> In article <1106071392.908441.262500 at c13g2000cwb.googlegroups.com>, Jim wrote: > >It sounds like a case for the Expect program, to me. Try Google-ing >for "Expect". If you are looking for a Python approach, then try >googling for "Expect Python". > >Jim > No--that is, I find his description unambiguous in NOT allowing for "keyboard control", which is Expect's domain. Expect, of any flavor, will not help. Along with the Java-savvy solutions already mentioned, several general-purpose record-playback tools are available for Windows. mentions several. From luismgz at gmail.com Sun Jan 9 16:31:28 2005 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 9 Jan 2005 13:31:28 -0800 Subject: else condition in list comprehension In-Reply-To: References: <1105302040.286420.313240@c13g2000cwb.googlegroups.com> Message-ID: <1105306288.348394.275100@c13g2000cwb.googlegroups.com> Thank you guys! From ebolonev at mail.ru Thu Jan 13 02:05:39 2005 From: ebolonev at mail.ru (Egor Bolonev) Date: Thu, 13 Jan 2005 17:05:39 +1000 Subject: newbie q References: <34mgq0F4dq4buU1@individual.net> Message-ID: <34mku4F4c8bdkU1@individual.net> "Stephen Thorne" ???????/???????? ? ???????? ?????????: news:mailman.611.1105598828.22381.python-list at python.org... On Thu, 13 Jan 2005 15:55:10 +1000, Egor Bolonev wrote: > how to get rid of 'for' operator in the code? > > import os, os.path > > def _test(): > src = 'C:\\Documents and Settings\\????\\My Documents\\My Music\\' > > for i in [x for x in os.listdir(src) if > os.path.isfile(os.path.join(src, > x)) and len(x.split('.')) > 1 and x.split('.')[-1].lower() == 'm3u']: > os.remove(os.path.join(src, i)) > > if __name__ == '__main__': > _test() import glob for x in glob.glob("*.m3u"): os.remove(x) i want to wipe out 'for x in []: f(x)' using map, lambda, reduce, filter and List Comprehensions [x for x in []] just don't get how to add string to all elements of list From bj_666 at gmx.net Tue Jan 18 18:21:21 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 19 Jan 2005 00:21:21 +0100 Subject: Assigning to self References: <10uo6hbn040qt24@news.supernews.com> Message-ID: In , Frans Englich wrote: > Then I have some vague, general questions which perhaps someone can reason > from: what is then the preferred methods for solving problems which requires > Singletons? As already mentioned it's similar to a global variable. If I need a "Singleton" I just put it as global into a module. Either initialize it at module level or define a function with the content of your __init__(). Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Thu Jan 20 01:22:17 2005 From: sjmachin at lexicon.net (John Machin) Date: Thu, 20 Jan 2005 17:22:17 +1100 Subject: list item's position References: Message-ID: On Wed, 19 Jan 2005 22:02:51 -0700, Steven Bethard wrote: > >See Mark's post, if you "need to know the index of something" this is >the perfect case for enumerate (assuming you have at least Python 2.3): But the OP (despite what he says) _doesn't_ need to know the index of the first thingy containing both a bar and a baz, if all he wants to do is remove earlier thingies. def barbaz(iterable, bar, baz): seq = iter(iterable) for anobj in seq: if bar in anobj and baz in anobj: yield anobj break for anobj in seq: yield anobj >>> import barbaz >>> bars = ["str", "foobaz", "barbaz", "foobar"] >>> print list(barbaz.barbaz(bars, 'bar', 'baz')) ['barbaz', 'foobar'] >>> print list(barbaz.barbaz(bars, 'o', 'b')) ['foobaz', 'barbaz', 'foobar'] >>> print list(barbaz.barbaz(bars, '', 'b')) ['foobaz', 'barbaz', 'foobar'] >>> print list(barbaz.barbaz(bars, '', '')) ['str', 'foobaz', 'barbaz', 'foobar'] >>> print list(barbaz.barbaz(bars, 'q', 'x')) [] >>> From steve at holdenweb.com Sat Jan 15 10:40:42 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 15 Jan 2005 10:40:42 -0500 Subject: [perl-python] 20050115, for statement In-Reply-To: References: <1105783084.748174.307680@f14g2000cwb.googlegroups.com> Message-ID: <41E9397A.90301@holdenweb.com> Michael Hoffman wrote: > Xah Lee wrote: > >> ? a = range(1,51) >> ? for x in a: >> ? if x % 2 == 0: >> ? print x, 'even' > > > Now he's mixing tabs and spaces. Hideous. > > Are you doing things wrong on purpose? Actually Xah is to be commended, since he's united the Perl and Python camps. Both agree he's a nuisance who is ill-informed about Perl *and* Python ;-) I can only presume it's egocentricity that keeps him cross-posting this nonsense to c.l.py and c.l.pe.misc despite the many deficiencies that have been remarked upon in both newsgroups. fraternal-greetings-to-the-perl-wordl-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From kristian.zoerhoff at gmail.com Thu Jan 20 14:19:49 2005 From: kristian.zoerhoff at gmail.com (Kristian Zoerhoff) Date: Thu, 20 Jan 2005 13:19:49 -0600 Subject: Print to Windows default Printer In-Reply-To: <9A28C052FF32734DACB0A288A35339910359DA@vogbs009.gb.vo.local> References: <9A28C052FF32734DACB0A288A35339910359DA@vogbs009.gb.vo.local> Message-ID: <3511dc7505012011191a78e7e9@mail.gmail.com> On Thu, 20 Jan 2005 19:14:10 -0000, Tim Golden wrote: > [Kristian Zoerhoff] > | > | On Thu, 20 Jan 2005 18:58:25 -0000, Tim Golden > | wrote: > | > > | > Can anyone else try a "PRINT blah" or a "COPY blah LPT1:" > | > on XP SP2? > | > | The printer is probably connected via USB, not the parallel port > | (LPT1), so the above won't work. I googled, and found some sage advice > | here: > | > | http://www.winnetmag.com/Article/ArticleID/39674/39674.html > | > | that may assist the OP. > > Ah. I'm so old-fashioned, the idea of a USB printer had > never occurred to me (I've never used one, in fact). > > Thanks for the info. Did you post back to the list as well? > Whoops. I am now :-) -- Kristian kristian.zoerhoff(AT)gmail.com zoerhoff(AT)freeshell.org From sjmachin at lexicon.net Tue Jan 25 21:42:04 2005 From: sjmachin at lexicon.net (John Machin) Date: 25 Jan 2005 18:42:04 -0800 Subject: Browsing text ; Python the right tool? References: <10vdpohm549g44a@corp.supernews.com> Message-ID: <1106707324.874852.208520@z14g2000cwz.googlegroups.com> Jeff Shannon wrote: > Paul Kooistra wrote: > > > 1. Does anybody now of a generic tool (not necessarily Python based) > > that does the job I've outlined? > > 2. If not, is there some framework or widget in Python I can adapt to > > do what I want? > > Not that I know of, but... > > > 3. If not, should I consider building all this just from scratch in > > Python - which would probably mean not only learning Python, but some > > other GUI related modules? > > This should be pretty easy. If each record is CRLF terminated, then > you can get one record at a time simply by iterating over the file > ("for line in open('myfile.dat'): ..."). You can have a dictionary of > classes or factory functions, one for each record type, keyed off of > the 2-character identifier. Each class/factory would know the layout > of that record type, This is plausible only under the condition that Santa Claus is paying you $X per class/factory or per line of code, or you are so speed-crazy that you are machine-generating C code for the factories. I'd suggest "data driven" -- you grab the .doc or .pdf that describes your layouts, ^A^C, fire up Excel, paste special, massage it, so you get one row per field, with start & end posns, type, dec places, optional/mandatory, field name, whatever else you need. Insert a column with the record name. Save it as a CSV file. Then you need a function to load this layout file into dictionaries, and build cross-references field_name -> field_number (0,1,2,...) and vice versa. As your record name is not in a fixed position in the record, you will also need to supply a function (file_type, record_string) -> record_name. Then you have *ONE* function that takes a file_type, a record_name, and a record_string, and gives you a list of the values. That is all you need for a generic browser application. For working on a _specific_ known file_type, you can _then_ augment that to give you record objects that you use like a0.zipcode or record dictionaries that you use like a0['zipcode']. You *don't* have to hand-craft a class for each record type. And you wouldn't want to, if you were dealing with files whose spec keeps on having fields added and fields obsoleted. Notice: in none of the above do you ever have to type in a column position, except if you manually add updates to your layout file. Then contemplate how productive you will be when/if you need to _create_ such files -- you will push everything through one function which will format each field correctly in the correct column positions (and chuck an exception if it won't fit). Slightly better than an approach that uses something like nbytes = sprintf(buffer, "%04d%-20s%-5s", a0_num, a0_phone, a0_zip); HTH, John From invalidemail at aerojockey.com Sat Jan 8 03:02:15 2005 From: invalidemail at aerojockey.com (Carl Banks) Date: 8 Jan 2005 00:02:15 -0800 Subject: python3: 'where' keyword References: <3480qqF46jprlU1@individual.net> Message-ID: <1105169372.800346.298830@f14g2000cwb.googlegroups.com> Nick Coghlan wrote: > Andrey Tatarinov wrote: > > Hi. > > > > It would be great to be able to reverse usage/definition parts in > > haskell-way with "where" keyword. Since Python 3 would miss lambda, that > > would be extremly useful for creating readable sources. > > > > Usage could be something like: > > > > >>> res = [ f(i) for i in objects ] where: > > >>> def f(x): > > >>> #do something > [snip] > For compound statements, a where clause probably isn't appropriate, as it would > be rather unclear what the where clause applied to. Right. But you know that as soon as you add this to simple expressions, a bunch of people are going to come here whining about how they don't get to use where with if-expressions. Frankly, they might have a point here. Although we have replacing lambda expressions on our minds, I have in mind a different problem that a where-statement would solve perfectly. But it would have to be used with an if-expression. However, I think it might not be so hard. Let's take Paul Rubin's advice and precede the if statement with where. Let's also allow "elif" clauses to be replaced with "else where ... if" clauses. That which is bound in the while-block would be visible in both the if-expression and if-block. Then we could do this: . where: . m = someregexp.match(somestring) . if m: . blah blah blah . else where: . m = someotherregexp.match(somestring) . if m: . blah blah blah We might want to spell "else where" instead as "elwhere", to match "elif", but that's not important now. This would take away one of the major minor annoyances of Python. (In fact, I've suggested something like this as a solution to the set-and-test idiom, which Python makes difficult, only I used the keyword "suppose" instead of "where".) Ok, but if you do that, now you have people whining that "where" comes after some expressions, and before others. (This would not bother me one bit, BTW, but I'm pretty sure I'd lose the popular vote on this one.) So, let's go all out and say that while could precede any statement. We now have consistency. Well, that really wouldn't work for the if-statement, though, because then how could we apply a different while-block to an else clause? We'd have to treat if-statements specially anyways. So we don't have consistency. My solution would be to propose two different where statements: a where...do statement, and a separate where...if statement. The where...do statement would look like this: . where: . def whatever(): pass . do: . blah blah use whatever blah It has the advantage of being able to apply the where bindings to several statements, and is, IMO, much cleaner looking than simply applying where's bindings to the single following unindented statement. I would recommend against where...while and where...for statements. They can't accomplish anything you couldn't do with a break statement inside the block, and it's not obvious whether the where clause gets executed once or for each loop (since it's physically outside the loop part). One question: what do you do with a variable bound inside a while-block that has the same name as a local variable? (Or, horrors, a surrounding while-block?) I'm inclined to think it should be illegal, but maybe it would be too restrictive. Anyways, I like this idea a lot. +1 -- CARL BANKS From jacek.generowicz at cern.ch Thu Jan 13 08:11:45 2005 From: jacek.generowicz at cern.ch (Jacek Generowicz) Date: 13 Jan 2005 14:11:45 +0100 Subject: from __future__ import decorators References: Message-ID: Thomas Heller writes: > Jacek Generowicz writes: > > > I have some code, which makes copious use of the @decorator syntax > > which was introduced in Python2.4. Now I find myself in a situation > > where I have to run the code under Python 2.3. However, I would like > > to keep developing the code with the new syntax. > > > > How could I best automate the process of making the syntax digestible > > by Python2.3 ? > > The only way that I know of is this, although you have to rewrite your > code somewhat: The whole point would be to keep on developing perfectly normal Python2.4 code, but have some means of getting it to run on 2.3, without modification. > http://dirtsimple.org/2004/11/using-24-decorators-with-22-and-23.html Certainly an interesting approach. Perhaps this can be combined with a simple textual transformation of the source code which simply replaces @decorator with add_assignment_advisor(decorator) ... or something along those lines. Still, I'd prefer to find a solution on the AST level, but I guess that's not possible without re-writing the praser. Crazy idea ... would it be possible to shadow 2.3's parser with one stolen from 2.4 ? From marklists at mceahern.com Mon Jan 17 14:02:04 2005 From: marklists at mceahern.com (Mark McEahern) Date: Mon, 17 Jan 2005 13:02:04 -0600 Subject: Assigning to self In-Reply-To: <200501171845.46766.frans.englich@telia.com> References: <200501171845.46766.frans.englich@telia.com> Message-ID: <41EC0BAC.10102@mceahern.com> Frans Englich wrote: >Hello, > >I am having trouble with throwing class instances around. Perhaps I'm >approaching my goals with the wrong solution, but here's nevertheless a >stripped down example which demonstrates my scenario: > > [snip] The basic problem seems to be that you're trying to avoid creating a new instance in __init__--which is too late. By that point, the new object is already created. Rebinding the name self in __init__ doesn't do what you seem to think it will. Basically, you need to move the "only create this object if it doesn't already exist" logic outside of __init__. Here's an alternative approach: #!/usr/bin/env python class Item: def __init__(self, name): self.name = name class Factory: items = {} def getItemByName(self, name): item = Factory.items.get(name) if not item: item = Item(name) Factory.items[name] = item return item def main(): factory = Factory() name = 'foo' for x in range(10): i = factory.getItemByName(name) print i print len(factory.items) if __name__ == "__main__": main() From peter at engcorp.com Thu Jan 13 20:52:29 2005 From: peter at engcorp.com (Peter Hansen) Date: Thu, 13 Jan 2005 20:52:29 -0500 Subject: porting C code In-Reply-To: <0NidnetRONZTgHrcRVn-oQ@powergate.ca> References: <9GEFd.5899$KJ2.3726@newsread3.news.atl.earthlink.net> <0NidnetRONZTgHrcRVn-oQ@powergate.ca> Message-ID: Peter Hansen wrote: > but merely a "b[3]" reference somewhere, it would be referencing > the third element of an array called "b", which is possibly a byte, "*Fourth* element... I'll come in again. Amongst our elements..." -Peter From cam.ac.uk at mh391.invalid Fri Jan 14 20:39:11 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 15 Jan 2005 01:39:11 +0000 Subject: Python.org, Website of Satan In-Reply-To: References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: Denis S. Otkidach wrote: > Certainly, it can be done more efficient: Yes, of course. I should have thought about the logic of my code before posting. But I didn't want to spend any more time on it than I had to. ;-) -- Michael Hoffman From steve at holdenweb.com Sat Jan 8 13:49:59 2005 From: steve at holdenweb.com (Steve Holden) Date: Sat, 08 Jan 2005 13:49:59 -0500 Subject: DOS problem (simple fix??) In-Reply-To: References: Message-ID: <41E02B57.2010500@holdenweb.com> Gavin Bauer wrote: > My DOS window (running in windows ME) closes the second it finishes > running my programs. As you can imagine, this makes it hard to see the > results. I've gotten in the habit of putting raw_input("Press enter to > exit") at the end of every program, and in addition to being pain in > the butt, it often fails to work. Being new to programming in general, > I make more mistakes than most people. My programs often have errors > before they get to my raw_input command. They then display the error > and immediately close. It is naturally a lot easier to fix an error > when you know what the error is. This makes debugging even more > annoying than it ordinarily would be, if you can imagine that. I've > heard that it should be a simple preference fix, but I've asked around > and no one seems to know how. > I presume this means you are starting the program by the time-honored expedient of double-clicking on it. For debugging you would probably find it more satisfactory to run your programs from the command line, and there's a FAQ that explains how at http://www.python.org/doc/faq/windows.html If that isn't simple enough then please let me know, as it's *supposed* to be. > Thank you, and please make all answers simple enough to be understood > by a highschool student and his father :) . If you wanted to get really adventurous you could try tweaking the command that Windows runs when you double-click a Python script, but we'll leave that for another time. Welcome to Python! regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From john at grulic.org.ar Fri Jan 14 17:58:43 2005 From: john at grulic.org.ar (John Lenton) Date: Fri, 14 Jan 2005 19:58:43 -0300 Subject: Producer/consumer Queue "trick" In-Reply-To: References: Message-ID: <20050114225843.GB7241@grulic.org.ar> On Fri, Jan 14, 2005 at 04:26:02PM -0600, Evan Simpson wrote: > WEBoggle needs a new game board every three minutes. Boards take an > unpredictable (much less than 3min, but non-trivial) amount of time to > generate. The system is driven by web requests, and I don't want the > request that happens to trigger the need for the new board to have to > pay the time cost of generating it. > > I set up a producer thread that does nothing but generate boards and put > them into a length-two Queue (blocking). At the rate that boards are > pulled from the Queue, it's almost always full, but my poor consumer > thread was still being blocked for "a long time" each time it fetched a > board. > > At this point I realized that q.get() on a full Queue immediately wakes > up the producer, which has been blocked waiting to add a board to the > Queue. It sets about generating the next board, and the consumer > doesn't get to run again until the producer blocks again or is preempted. > > The solution was simple: have the producer time.sleep(0.001) when > q.put(board) returns. If I had had that problem, I would probably have set up different server processes (consumer(s), producer(s), and queue(s)), coordinated by somthing like pyro's event server. But I don't really know the problem, so it's probably just bad guesswork on my part---you probably don't need to scale at all. -- John Lenton (john at grulic.org.ar) -- Random fortune: Tonight's the night: Sleep in a eucalyptus tree. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From deetsNOSPAM at web.de Wed Jan 26 07:25:23 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 26 Jan 2005 13:25:23 +0100 Subject: OT References: Message-ID: <35pge0F4pkd7gU1@individual.net> > However, i know for a fact that phr is _not_ a user at > sextans.lowell.edu. > > Is this a problem with my dns? Most probably - he shows up as phr at localhost.localhost for me. -- Regards, Diez B. Roggisch From ajikoe at gmail.com Mon Jan 31 19:03:16 2005 From: ajikoe at gmail.com (ajikoe at gmail.com) Date: 31 Jan 2005 16:03:16 -0800 Subject: How can I use PyDoc to generate html file (modul in directory d) Message-ID: <1107216196.502024.157500@z14g2000cwz.googlegroups.com> Hello How can I use PyDoc to generate html file when my file.py is in other directory. Sincerely Yours, Pujo From morphex at gmail.com Wed Jan 5 20:48:31 2005 From: morphex at gmail.com (morphex) Date: 5 Jan 2005 17:48:31 -0800 Subject: Example of using pty to control a process? Message-ID: <1104976111.041702.255710@c13g2000cwb.googlegroups.com> Hi, I'm trying to get the output from the command top on Linux, using python. I'd like to start top, get a page of output, and then send top the letter 'q' to end the process. Looking around I've figured that the module pty can be used for this, however, I can't find any good examples of how to use it. Any ideas as to where I can look? Thanks, Morten From peter at engcorp.com Mon Jan 24 16:18:13 2005 From: peter at engcorp.com (Peter Hansen) Date: Mon, 24 Jan 2005 16:18:13 -0500 Subject: Tuple slices In-Reply-To: <35l5d9F4licj2U1@individual.net> References: <35kn4mF4o44ufU1@individual.net> <35l5d9F4licj2U1@individual.net> Message-ID: George Sakkis wrote: > Fair enough. So perhaps the question is whether such cases are more regular than something like: > a = give_me_a_huge_tuple() > slices = [a[i:j] for i in xrange(len(a)) for j in xrange(i+1, len(a)+1)] I believe the general usage of tuples tends to mean that "give_me_a_huge_tuple()" just doesn't happen except with those who insist on using tuples as though they were nothing other than read-only lists. If you use a tuple the way it was apparently intended, you are extraordinarily unlikely to find yourself with a huge one requiring slicing in such a way that you care whether it is a "view" or a new object. -Peter From roy at panix.com Fri Jan 7 16:42:36 2005 From: roy at panix.com (Roy Smith) Date: 7 Jan 2005 16:42:36 -0500 Subject: how to extract columns like awk $1 $5 References: Message-ID: In article , Anand S Bisen wrote: >Hi > >Is there a simple way to extract words speerated by a space in python >the way i do it in awk '{print $4 $5}' . I am sure there should be some >but i dont know it. Something along the lines of: words = input.split() print words[4], words[5] From peter at engcorp.com Fri Jan 14 07:54:02 2005 From: peter at engcorp.com (Peter Hansen) Date: Fri, 14 Jan 2005 07:54:02 -0500 Subject: [perl-python] 20050113 looking up syntax In-Reply-To: <1105699357.565028.107750@c13g2000cwb.googlegroups.com> References: <1105699357.565028.107750@c13g2000cwb.googlegroups.com> Message-ID: Xah Lee wrote: [snip] > Note: this post is from the Perl-Python a-day mailing list at > http://groups.yahoo.com/group/perl-python/ > to subscribe, send an email to perl-python-subscribe at yahoogroups.com So why duplicate the posts by posting them to the newsgroups? Now that you've advertised the mailing list (and thank you, I'll be sure to hurry off now and subscribe) there's no longer any reason to post to the newsgroups, is there? Please? -Peter From rbt at athop1.ath.vt.edu Thu Jan 13 21:23:14 2005 From: rbt at athop1.ath.vt.edu (rbt) Date: Thu, 13 Jan 2005 21:23:14 -0500 Subject: Debian says "Warning! you are running an untested version of Python." on 2.3 References: Message-ID: Nick Craig-Wood wrote: > Alex Stapleton wrote: >> Whenever I run python I get >> >> "Warning! you are running an untested version of Python." >> >> prepended to the start of any output on stdout. >> >> This is with Debian and python 2.3 (running the debian 2.1 and 2.2 >> binaries doesn't have this effect) > > What version of a) Debian and b) python are you running? > > I don't have that problem here (I'm running testing/sarge) Same here... Debian testing with Python2.3 no problem. Perhaps he's running Debian unstable? Cheers From premshree.pillai at gmail.com Wed Jan 5 05:10:58 2005 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Wed, 5 Jan 2005 15:40:58 +0530 Subject: Cookbook 2nd ed Credits In-Reply-To: <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> Message-ID: On Wed, 5 Jan 2005 08:55:39 +0100, Alex Martelli wrote: > Premshree Pillai wrote: > > > Do contributors of less than 5 recipes get a copy too? :-? > > Of course! > > > Btw, is there a comprehensive list of ALL contributors put up anywhere? > > Not yet -- do you think I should put it up on my website? If you can, why not! > > Alex > -- > http://mail.python.org/mailman/listinfo/python-list > -- Premshree Pillai http://www.livejournal.com/~premshree From steve at holdenweb.com Fri Jan 14 17:17:55 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Jan 2005 17:17:55 -0500 Subject: Python.org, Website of Satan In-Reply-To: References: <1105495569.479185.166340@z14g2000cwz.googlegroups.com> Message-ID: Lucas Saab wrote: > Arich Chanachai wrote: > >> Jane wrote: >> >>> "Lucas Raab" wrote in message >>> news:UsuFd.5434$KJ2.1253 at newsread3.news.atl.earthlink.net... >>> >>> >>>> Jane wrote: >>>> >>>> >>>>> wrote in message >>>>> news:1105495569.479185.166340 at z14g2000cwz.googlegroups.com... >>>>> >>>>> >>>>> >>>>>> python.org = 194.109.137.226 >>>>>> >>>>>> 194 + 109 + 137 + 226 = 666 >>>>>> >>>>>> What is this website with such a demonic name and IP address? What >>>>>> evils are the programmers who use this language up to? >>>>>> >>>>>> >>>>> >>>>> >>>>> Some people have too much time on their hands... >>>>> >>>>> Jane >>>>> >>>>> >>>>> >>>> >>>> >>>> Better get some ointment for that burn!! >>>> >>> >>> >>> >>> Huh??? >>> >>> Jane >>> >>> >>> >>> >> You said that people have too much "time" on their "hands", so he >> suggested ointment to prevent the irritation etc... He was probably >> also getting at the topic of this thread (hint: Satan = Hell = Fire), >> so the ointment puts out the burn. >> Have fun folks! >> >> - Arich > > > I'd also like to add that the term "burn" means to be made look stupid > or be insulted. And here was me just thinking that the burn would result from the inevitable flames. Newsgroups really re a continual surprise. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From benji at benjiyork.com Wed Jan 19 08:51:01 2005 From: benji at benjiyork.com (Benji York) Date: Wed, 19 Jan 2005 08:51:01 -0500 Subject: delay and force in Python In-Reply-To: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> References: <1106133430.957592.62750@f14g2000cwb.googlegroups.com> Message-ID: <41EE65C5.8080403@benjiyork.com> Will Stuyvesant wrote: > Streams are interesting because they are to lists like > xrange is to range. Could save a lot on memory and > computations. I think you're looking for generators. > Below is my straight translation from Scheme code in the > Wizard book to Python. > Something else: this crashes with a "maximum recursion reached" > . print stream_enumerate_interval(1,998) Unlike Scheme, Python isn't designed for heavily recursive algorithms. Here's a more Pythonic equivalent of your code: def count(start, stop): i = start while i < stop: yield i i += 1 def even(gen): for x in gen: if x % 2 == 0: yield x numbers = even(count(1, 999)) first = numbers.next() second = numbers.next() print second -- Benji York benji at benjiyork.com From cam.ac.uk at mh391.invalid Sat Jan 15 12:16:07 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 15 Jan 2005 17:16:07 +0000 Subject: Pointer or unique id In-Reply-To: <41e94d40$0$29202$636a15ce@news.free.fr> References: <1q9pydh06wjuk.fexsf964ckya$.dlg@40tude.net> <41e94d40$0$29202$636a15ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > hash(obj) -> integer > Return a hash value for the object. Two objects with the same value > have the same hash value. The reverse is not necessarily true, but likely. Of course not all Python objects are hashable: >>> hash([]) Traceback (most recent call last): File "", line 1, in ? TypeError: list objects are unhashable -- Michael Hoffman From tjreedy at udel.edu Thu Jan 6 23:42:40 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 6 Jan 2005 23:42:40 -0500 Subject: Python evolution: Unease References: <7xacrpdxy3.fsf@ruckus.brouhaha.com><7x652che6z.fsf@ruckus.brouhaha.com><7x4qhw859p.fsf@ruckus.brouhaha.com><7xk6qrnbum.fsf@ruckus.brouhaha.com><41dcaa00.102858012@news.oz.net> <7x652bnhx0.fsf@ruckus.brouhaha.com> <5fGdnfXE0u2qd0DcRVn-iQ@powergate.ca> Message-ID: "Peter Hansen" wrote in message news:5fGdnfXE0u2qd0DcRVn-iQ at powergate.ca... > Terry Reedy wrote: >> Would it be possible, at least for Windows, to write a Python script >> implementing a 'virtual distribution'? IE, download Python, install it, >> download next package, install it, etc. -- prefereably table driven? > > How would you run the script in the first place? Duh... with my existing version of Python (which I have had some version of for so long that I had forgotten what it is to not have one handy) ;-). Ok, 2 step process for first timers. Terry J. Reedy From duncan.booth at invalid.invalid Mon Jan 24 07:43:07 2005 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Jan 2005 12:43:07 GMT Subject: short programming projects for kids References: <1106332638.595750.150590@c13g2000cwb.googlegroups.com> Message-ID: bobdc wrote: > I will be teaching an "Introduction to Programming" class to some > middle school aged children and will be using Python, obviously. Does > anyone have suggestions for simple little programs to create and > analyze with them after I get past turtle graphics? > > Turtle graphics will be plenty for the first session, and I will leave > time to ask them what they'd like to do in later sessions, but I was > curious if anyone on the list has experience picking pedagogical > programming examples appropriate for twelve-year-olds' attention spans. > thanks, > Have you looked at http://www.livewires.org.uk/python/ ? From tundra at tundraware.com Thu Jan 27 06:38:22 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 27 Jan 2005 06:38:22 EST Subject: tkinter: Can You Underline More Than 1 Char In A Menu Title Message-ID: I am currently underling the first character of a menu title (to indicate its shortcut/accelerator key) like this: self.WildBtn = Menubutton(self.mBar, text=WILDMENU, underline=0, state=DISABLED) However, I intend to actually have two separate keys invoke this menu to have it behave differently in different circumstances. Is it possible to underline more than a single character as I am doing with the 'underline=0' above. I tried 'underline=(0,2)' but that didn't work. Ideas? TIA, -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From hancock at anansispaceworks.com Fri Jan 28 10:35:02 2005 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 28 Jan 2005 09:35:02 -0600 Subject: One-Shot Property? In-Reply-To: <20050118183245.GA13370@grulic.org.ar> References: <20050118115456510-0500@braeburn.themorgue.org> <20050118183245.GA13370@grulic.org.ar> Message-ID: <200501280935.02368.hancock@anansispaceworks.com> On Tuesday 18 January 2005 12:33 pm, John Lenton wrote: > > consider this: > > 1 >>> class C: > 2 ... x = property(str) > 3 ... > 4 >>> c = C() > 5 >>> c.x > 6 '<__main__.C instance at 0x4008d92c>' > 7 >>> setattr(c, 'x', c.x) > 8 >>> c.x > 9 '<__main__.C instance at 0x4008d92c>' > 10 >>> C.x > 11 > 12 >>> c.x = 2 > 13 >>> > > in line 5 you see that the x property so defined works. In line 7 you > remove it, replacing it with the computed value of the property. Line > 9 shows that it worked, line 11 shows that it didn't break the class, > and line 13 (through the absence of an exception) shows that it no > longer is 'special' (as it shouldn't be). It wasn't "special" before, either -- I tried this myself, because I wasn't familiar with properties yet, and I was trying to figure out what you meant by that. The catch is that I think you meant to type: > 1 >>> class C(object): (i.e. so that C is a "new-style" class). Then we get "special" behavior (which answers my first question): >>> class C(object): ... x = property(str) ... >>> C.x >>> c = C() >>> c.x '<__main__.C object at 0x401e984c>' >>> c.x = 2 Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute >>> Unfortunately this seems to break your technique, too: >>> setattr(c, 'x', c.x) Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute Too bad. I was kind of hoping it was just a typo. :-( Unless I'm missing something, anyway. Cheers, Terry -- -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From ncoghlan at iinet.net.au Thu Jan 20 07:35:18 2005 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 20 Jan 2005 22:35:18 +1000 Subject: Freezing a mutable (was Re: lambda) In-Reply-To: References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> <41ed8c13.1209309354@news.oz.net> Message-ID: <41EFA586.2020901@iinet.net.au> Antoon Pardon wrote: > I missed that you would use it with the idiom: dct[x.frozen()] The list itself isn't hashable with this approach, so you don't have much choice. I wasn't particularly clear about that point, though. > I have two problems with this approach. > > 1) It doesn't work when you get your keys via the keys/items > methods. True - the frozen object has no link back to the original object. That could be added though (by returning a tuple subtype with the extra attribute) > 2) This is rather minor, but a user could still unfreeze > untimely True - doing that is less likely than mutating a hashable list though :) I'm just noting this as a way to avoid copying data more than once when storing immutable copies of mutable data in a dictionary. You're quite right that there isn't a really clean idiom for doing that in Python (aside from moving to a different data structure that works natively as a dict key, naturally). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From richie at entrian.com Tue Jan 25 12:14:20 2005 From: richie at entrian.com (Richie Hindle) Date: Tue, 25 Jan 2005 17:14:20 +0000 Subject: "private" variables a.k.a. name mangling (WAS: What is print? A function?) In-Reply-To: <200501251257.39751.tdickenson@geminidataloggers.com> References: <200501251257.39751.tdickenson@geminidataloggers.com> Message-ID: [Toby] > The problem occured because the double-underscore mangling uses the class > name, but ignores module names. A related project already had a class named C > derived from B (same name - different module). Yikes! A pretty bizarre case, but nasty when it hits. I guess the double-underscore system can give you a false sense of security. -- Richie Hindle richie at entrian.com From levub137 at wi.rr.com Sat Jan 1 13:18:08 2005 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sat, 01 Jan 2005 18:18:08 GMT Subject: exposing C array to python namespace: NumPy and array module. In-Reply-To: References: Message-ID: Bo Peng wrote: > Dear list, > > I am writing a Python extension module that needs a way to expose pieces > of a big C array to python. Currently, I am using NumPy like the following: > > PyObject* res = PyArray_FromDimsAndData(1, int*dim, PyArray_DOUBLE, > char*buf); > > Users will get a Numeric Array object and can change its values (and > actually change the underlying C array). > > This works fine. However, when I deliver my module, I find NumPy is > unnecessarily large for this simple task. As a matter of fact, I had to > build from source NumPy, ATLAS etc on Solaris, Linux, Mac.... and if a > user would like to use my module, he has to do the same thing! > > Python's array module is built-in, easy to use, but *without* a > FromLenAndData function! Even the buffer interface provides only 'get > buffer' but no 'set buffer' functions. Could anyone tell me how I can > create an array object from existing data? Some vague ideas might be > used: 1. PyCObject (I do not really understand the manual), 2. copy and > modify arraymodule.c to my project (doable at all? License issue?) 3. > Create an array object and hack it. (no api to do this.) > > I would strongly suggest an arraymodule.h with Array_FromLenAndData. > > Many thanks in advance. > Bo I don't know how much this will help but when I am faced with a problem like this, I use Pyrex and look at the generated code. All you need to do in Pyrex is import the array module and create your array like you would in Python. To get the data into the array you will need to use the buffer interface and fill it in from your C code. From aleaxit at yahoo.com Wed Jan 5 13:05:38 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 5 Jan 2005 19:05:38 +0100 Subject: Cookbook 2nd ed Credits References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> Message-ID: <1gpxjfg.thnaf0oys6jrN%aleaxit@yahoo.com> Dan Perl wrote: > "Alex Martelli" wrote in message > news:1gpvtjk.3jf7dc1cch7yfN%aleaxit at yahoo.com... > > Premshree Pillai wrote: > >> Btw, is there a comprehensive list of ALL contributors put up anywhere? > > > > Not yet -- do you think I should put it up on my website? > > Updating the status of the recipes on the web site would be nice. Please take this up with Activestate guys -- I have no say on what happens on the website they own, nor any special status there. Alex From exarkun at divmod.com Fri Jan 7 09:29:05 2005 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 07 Jan 2005 14:29:05 GMT Subject: Asyncore In-Reply-To: <1105085666.634359.33640@z14g2000cwz.googlegroups.com> Message-ID: <20050107142905.32125.1439814328.divmod.quotient.977@ohm> On 7 Jan 2005 00:14:26 -0800, export at hope.cz wrote: >Is there any tutorial and docs with samples how to use asyncore module? See these threads: http://mail.python.org/pipermail/python-list/2004-March/214105.html http://mail.python.org/pipermail/python-dev/2004-November/049819.html Then check out: http://www.twistedmatrix.com/ Hope this helps, Jp From hans at zephyrfalcon.org Fri Jan 28 11:59:50 2005 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 28 Jan 2005 11:59:50 -0500 Subject: Dynamic class methods misunderstanding In-Reply-To: References: Message-ID: Bill Mill wrote: > On Fri, 28 Jan 2005 11:09:16 -0500, Hans Nowak wrote: > > >>To add m as a new method to the *class*, do this: >> >> >>> class test: >>... def __init__(self, method): >>... self.__class__.method = method >>... self.method() >>... >> >>> def m(self): print self >>... >> >>> test(m) >><__main__.test instance at 0x0192ED78> >><__main__.test instance at 0x0192ED78> > > > When I run it, I only get one call to m, which is how I would expect > python to work; I assume the double printing here is a typo? Actually, no. I'm using the interactive interpreter, so doing test(m) results in two lines: the first one is printed by m, the second one is the __repr__ of the test instance that was created, displayed by the interpreter. Compare: >>> x = test(m) <__main__.test instance at 0x0192ED78> >>> x <__main__.test instance at 0x0192ED78> -- Hans Nowak http://zephyrfalcon.org/ From bearophileHUGS at lycos.com Mon Jan 31 20:14:00 2005 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 31 Jan 2005 17:14:00 -0800 Subject: set, dict and other structures In-Reply-To: References: <1107214762.198058.55680@f14g2000cwb.googlegroups.com> Message-ID: <1107220440.114254.115010@f14g2000cwb.googlegroups.com> You are really gentle Raymond Hettinger, but surely I'm not asking you/anyone to write some code just for me; I don't have "real applications", I'm just learning/playing. Your words are quite good answers to most of my questions. The only left small topic is about the group/set-like operations/methods added to dicts; maybe some other person can comment that idea too. The semantic of such operations can be a little tricky, but sometimes they can avoid the use of sets (and the set-ify of dicts), sometimes they can carry the dict values with them (even if they work just on the dict keys), etc. A bear hug, Bearophile From nick at craig-wood.com Thu Jan 27 10:30:01 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 27 Jan 2005 15:30:01 GMT Subject: XOR on string References: Message-ID: Peter Hansen wrote: > snacktime wrote: > > I need to calculate the lrc of a string using an exclusive or on each > > byte in the string. How would I do this in python? > > lrc == Linear Redundancy Check? or Longitudinal? Note that > such terms are not precisely defined... generally just acronyms > people make up and stick in their user manuals for stuff. :-) > > import operator > lrc = reduce(operator.xor, [ord(c) for c in string]) Or for the full functional programming effect... lrc = reduce(operator.xor, map(ord, string)) which is slightly faster and shorter... $ python2.4 -m timeit -s'import operator; string = "abcdefghij13123kj12l3k1j23lk12j3l12kj3"' \ 'reduce(operator.xor, [ord(c) for c in string])' 10000 loops, best of 3: 20.3 usec per loop $ python2.4 -m timeit -s'import operator; string = "abcdefghij13123kj12l3k1j23lk12j3l12kj3"' \ 'reduce(operator.xor, map(ord, string))' 100000 loops, best of 3: 15.6 usec per loop -- Nick Craig-Wood -- http://www.craig-wood.com/nick From ahaas at airmail.net Wed Jan 26 14:15:27 2005 From: ahaas at airmail.net (Art Haas) Date: Wed, 26 Jan 2005 13:15:27 -0600 Subject: [ANNOUNCE] Twenty-second release of PythonCAD now available Message-ID: <20050126191527.GA19380@artsapartment.org> I'm pleased to announce the twenty-second development release of PythonCAD, a CAD package for open-source software users. As the name implies, PythonCAD is written entirely in Python. The goal of this project is to create a fully scriptable drafting program that will match and eventually exceed features found in commercial CAD software. PythonCAD is released under the GNU Public License (GPL). PythonCAD requires Python 2.2 or newer. The interface is GTK 2.0 based, and uses the PyGTK module for interfacing to GTK. The design of PythonCAD is built around the idea of separating the interface from the back end as much as possible. By doing this, it is hoped that both GNOME and KDE interfaces can be added to PythonCAD through usage of the appropriate Python module. Addition of other PythonCAD interfaces will depend on the availability of a Python module for that particular interface and developer interest and action. The twenty-second release contains primarily internal code enhancements in regards to the Python language. PythonCAD running under PyGTK releases after the 2.4.0 release will now utilize the gtk.ComboBox and the gtk.ColorButton widgets, while PythonCAD running under older releases will still utilize the same widgets as before. This change removes the DeprecatationWarning users with the newer PyGTK release would see. A problem where restoring a deleted TextBlock entity was fixed, and a variety of other fixes and improvements are also included in this release. A mailing list for the development and use of PythonCAD is available. Visit the following page for information about subscribing and viewing the mailing list archive: http://mail.python.org/mailman/listinfo/pythoncad Visit the PythonCAD web site for more information about what PythonCAD does and aims to be: http://www.pythoncad.org/ Come and join me in developing PythonCAD into a world class drafting program! Art Haas -- Man once surrendering his reason, has no remaining guard against absurdities the most monstrous, and like a ship without rudder, is the sport of every wind. -Thomas Jefferson to James Smith, 1822 From nick at craig-wood.com Mon Jan 10 05:30:02 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 10 Jan 2005 10:30:02 GMT Subject: windows mem leak References: <41XDd.70234$Jk5.40626@lakeread01> <41E06C18.6050407@hotmail.com> Message-ID: Bob Smith wrote: > Attached is the code. Run it yourself and see. This seems to run nmap over series of consecutive IP addresses. nmap can do that all by itself. From its man page:: Nmap also has a more powerful notation which lets you specify an IP address using lists/ranges for each element. Thus you can scan the whole class 'B' network 128.210.*.* by specifying '128.210.*.*' or '128.210.0-255.0-255' or even '128.210.1-50,51-255.1,2,3,4,5-255'. And of course you can use the mask notation: '128.210.0.0/16'. These are all equivalent. If you use astericts ('*'), remember that most shells require you to escape them with back slashes or protect them with quotes. This setting might be useful too:: --max_parallelism Specifies the maximum number of scans Nmap is allowed to perform in parallel. Setting this to one means Nmap will never try to scan more than 1 port at a time. It also effects other parallel scans such as ping sweep, RPC scan, etc. [sorry not Python related but may solve your problem!] -- Nick Craig-Wood -- http://www.craig-wood.com/nick From aahz at pythoncraft.com Sun Jan 9 19:30:21 2005 From: aahz at pythoncraft.com (Aahz) Date: 9 Jan 2005 19:30:21 -0500 Subject: Please Contribute Python Documentation! References: Message-ID: In article , Tony Meyer wrote: > >I don't think I've seen such a statement before - the stuff I've seen >all indicates that one should be submitting proper LaTeX docs/patches. >If plain-text contributions are welcome, could this be added to the doc >about contributing to the docs? (I suppose I could submit a patch, but >that seems overkill ). It *is* in the docs now -- see the top of http://www.python.org/doc/2.4/doc/doc.html (This has been the official policy for some time, but you're right that it wasn't earlier documented. So I filed a bug report. ;-) If you think this still isn't enough, file another.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From jerf at jerf.org Tue Jan 11 07:39:21 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 11 Jan 2005 07:39:21 -0500 Subject: Checking for X availability References: Message-ID: On Tue, 11 Jan 2005 03:32:01 -0800, Flavio codeco coelho wrote: > So my question is: how can I check for the availability of X? i.e., How > will my program know if its running in a text only console or in console > window over X? The first thing that leaps to mind is... try it. If it fails, switch to the other. Remember modules are just variables and can be re-assigned, if needed. try: import xdialog as mydialog except ImportError: # user must not have it import dialog as mydialog try: # do something with mydialog here except YouDontHaveXError: # tried to use xdialog, but it failed import dialog as mydialog etc. That won't be useful, and I don't know what exception will be thrown when X isn't found, but you should get something. This should be invisible to the user, and is also the most transparent way to get it right; using environment vars and such may not be the best way to do it. This, by the way, was assuming that xdialog and dialog have identical APIs. If that is not the case, I'd suggest "process-level recursion"; try starting up with X, and if it fails, os.execl your process again with a command line parameter to use console dialog. That will be somewhat simpler than trying to detect it inside the program itself. From bob_smith_17280 at hotmail.com Sun Jan 23 18:53:35 2005 From: bob_smith_17280 at hotmail.com (Bob Smith) Date: Sun, 23 Jan 2005 18:53:35 -0500 Subject: [perl-python] 20050121 file reading & writing In-Reply-To: References: <1106395060.211314.54530@f14g2000cwb.googlegroups.com> Message-ID: Erik Max Francis wrote: > Bob Smith wrote: > >> To do this efficiently on a large file (dozens or hundreds of megs), >> you should use the 'sizehint' parameter so as not to use too much memory: >> >> sizehint = 0 >> mylist = f.readlines(sizehint) > > > It doesn't make any difference. .readlines reads the entire file into > memory at once. > Are you sure, the docs say this: "f.readlines() returns a list containing all the lines of data in the file. If given an optional parameter sizehint, it reads that many bytes from the file and enough more to complete a line, and returns the lines from that. This is often used to allow efficient reading of a large file by lines, but without having to load the entire file in memory. Only complete lines will be returned." http://docs.python.org/tut/node9.html From beliavsky at aol.com Sun Jan 9 19:20:38 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 9 Jan 2005 16:20:38 -0800 Subject: Python3: on removing map, reduce, filter References: <34csn1F4a46hqU1@individual.net> <7xekguof4a.fsf@ruckus.brouhaha.com> <34ctkpF4b9ijlU1@individual.net> <-7mdndrwD_1qOHzcRVn-qQ@comcast.com> Message-ID: <1105316438.272475.313670@c13g2000cwb.googlegroups.com> Steve Holden wrote: >> def square(x): >> return x*x >> map(square, range(1000)) >> versus >> [x*x for x in range(1000)] >> Hint: function calls are expensive. >$ python -m timeit -s "def square(x): return x*x" "map(square, range(1000))" >1000 loops, best of 3: 693 usec per loop >$ python -m timeit -s "[x*x for x in range(1000)]" >10000000 loops, best of 3: 0.0505 usec per loop Functions will often be complicated enought that inlining them is not feasible. In Fortran 95 one can define an elemental function that takes an argument of any shape (scalar, vector, matrix etc.) but of a specified type, returning a result of the same shape, so that one could write elemental function square(i) result(isq) integer, intent(in) :: i integer :: isq isq = i*i end function square and then print*,square((/i,i=0,999/)) The Numeric and Numarray Python modules have predefined ufunc's that are essentially elemental functions with one or two arguments. It would be nice if one could define new ufunc's using only Python code -- I presume new ones can currently be added by writing C code. From agriff at tin.it Mon Jan 10 15:51:48 2005 From: agriff at tin.it (Andrea Griffini) Date: Mon, 10 Jan 2005 20:51:48 GMT Subject: Speed revisited References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> <1105237556.402188.126980@c13g2000cwb.googlegroups.com> <1105303172.147395.63580@c13g2000cwb.googlegroups.com> <36c3u0tpbg6f98ta6cm4fkj2kn0dkv624m@4ax.com> Message-ID: On Mon, 10 Jan 2005 17:52:42 +0100, Bulba! wrote: >I don't see why should deleting element from a list be O(n), while >saying L[0]='spam' when L[0] previously were, say, 's', not have the >O(n) cost, if a list in Python is just an array containing the >objects itself? > >Why should JUST deletion have an O(n) cost? Because after deletion L[1] moved to L[0], L[2] moved to L[1], L[3] moved to L[2] and so on. To delete the first element you have to move n-1 pointers and this is where O(n) comes from. When you reassign any element there is no need to move the others around, so that's why you have O(1) complexity. With a data structure slightly more complex than an array you can have random access in O(1), deletion of elements O(1) at *both ends* and insertion in amortized O(1) at *both ends*. This data structure is called doubly-ended queque (nickname "deque") and is available in python. The decision was that for the basic list object the overhead added by deques for element access (it's still O(1), but a bit more complex that just bare pointer arithmetic) and, I guess, the hassle of changing a lot of working code and breaking compatibility with extensions manipulating directly lists (no idea if such a thing exists) was not worth the gain. The gain would have been that who doesn't know what O(n) means and that uses lists for long FIFOs would get fast programs anyway without understanding why. With current solution they just have to use deques instead of lists. After thinking to it for a while I agree that this is a reasonable choice. The gain is anyway IMO very little because if a programmer desn't understand what O(n) is then the probability that any reasonably complex program written is going to be fast is anyway zero... time would just be wasted somewhere else for no reason. Andrea From wittempj at hotmail.com Mon Jan 17 08:41:29 2005 From: wittempj at hotmail.com (wittempj at hotmail.com) Date: 17 Jan 2005 05:41:29 -0800 Subject: List problems in C code ported to Python In-Reply-To: References: Message-ID: <1105969289.904518.240650@z14g2000cwz.googlegroups.com> Lucas Raab wrote: > I'm done porting the C code, but now when running the script I > continually run into problems with lists. I tried appending and > extending the lists, but with no avail. Any help is much appreciated > Please see both the Python and C code at > http://home.earthlink.net/~lvraab. The two files are ENIGMA.C and engima.py > > TIA You need something like a matrix too for this, if we combine this with the already posted idea of caching of 'ord' results you could go this way: class matrix(object): """based on http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/189971 """ def __init__(self, *args): from types import IntType, StringType self.__data = [] if len(args) == 2 and type(args[0]) == IntType and type(args[1] == IntType): #args[0] = #rows, args[1] = #columns for r in range(args[0]): self.__data.append([]) for j in range(args[1]): self.__data[r].append(0) else: for arg in args: if type(arg) == StringType: self.__data.append(map(ord, list(arg))) def __repr__(self): ret = '' for r in self.__data: ret = '%s\n%s' % (ret, r) return ret def __getitem__(self, (row, col)): return self.__data[row][col] def __setitem__(self, (row, col), value): self.__data[row][col] = value #setup rotor data A = ord('A') ref_rotor = map(ord, "YRUHQSLDPXNGOKMIEBFZCWVJAT") print ref_rotor data = matrix(8, 26) for i in range(26): data[(4, i)] = (ref_rotor[i] - A + 26) % 26 print data step_data = (16, 4, 21, 9, 25) #steps at: q, e, v, j, z order = range(3) rotor = matrix("EKMFLGDQVZNTOWYHXUSPAIBRCJ", "AJDKSIRUXBLHWTMCQGZNPYFVOE", \ "BDFHJLCPRTXVZNYEIWGAKMUSQO", "ESOVPZJAYQUIRHXLNFTGKDCMWB", \ "VZBRGITYUPSDNHLXAWMJQOFECK") step = range(3) for i in range(1, 4): step[i - 1] = step_data[order[i-1]] for j in range(26): data[(i, j)] = (rotor[(order[i-1], j)] - A + 26) % 26 print data From jdhunter at ace.bsd.uchicago.edu Thu Jan 20 22:51:11 2005 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Thu, 20 Jan 2005 21:51:11 -0600 Subject: problems with duplicating and slicing an array In-Reply-To: <7cffadfa05012017337858d171@mail.gmail.com> (Yun Mao's message of "Thu, 20 Jan 2005 20:33:25 -0500") References: <7cffadfa05012017337858d171@mail.gmail.com> Message-ID: >>>>> "Yun" == Yun Mao writes: Yun> 2. Is there a way to do Matlab style slicing? e.g. if I have Yun> i = array([0, 2]) x = array([1.1, 2.2, 3.3, 4.4]) I wish y = Yun> x(i) would give me [1.1, 3.3] Now I'm using map, but it gets Yun> a little annoying when there are two dimensions. Any ideas Yun> would be deeply appreciated! numarray supports matlab style indexing if you pass the ind as an array or list of indices (but not a tuple, I found to my surprise). As pointed out already, for Numeric you need to use the take function >>> from numarray import array >>> x = array([1,2,3,4,5,6,7,8,9]) >>> ind = [3,5,7] >>> inda = array(ind) >>> indt = tuple(ind) >>> x[ind] array([4, 6, 8]) >>> x[inda] array([4, 6, 8]) >>> x[indt] Traceback (most recent call last): File "", line 1, in ? IndexError: too many indices. I'm sure the tuple "surprise" is a documented feature. JDH From craig at postnewspapers.com.au Mon Jan 17 22:31:17 2005 From: craig at postnewspapers.com.au (Craig Ringer) Date: Tue, 18 Jan 2005 11:31:17 +0800 Subject: lambda In-Reply-To: <20050117151556.GD3811@grulic.org.ar> References: <1105633239.316956.262140@f14g2000cwb.googlegroups.com> <41EBA021.5060903@holdenweb.com> <20050117151556.GD3811@grulic.org.ar> Message-ID: <1106019077.21369.13.camel@bucket.localnet> On Mon, 2005-01-17 at 12:15 -0300, John Lenton wrote: > knowledgeable and experienced users know when to ignore the rules. +1 QOTW One of the nice things is that Python permits you to do exactly that where appropriate while avoiding forcing you to do gruesome things to get a job done. I think the classic example of your statement is the use of 'goto' in C and C++ code. Don't use goto - except when there's no other sensible way to make your code clear. For example, goto and Py_XECREF seem to be very handy for cleanup after detecting an exception when working with the Python/C API. That said, I do think "the rules" deserve consideration and respect - they're usually there because of many others' experience over time. It's interesting to learn those lessons first hand, but it's nice to be able to avoid repeating every single one of them. -- Craig Ringer From ne-nospam7 at post.cybercity.dk Mon Jan 24 04:40:14 2005 From: ne-nospam7 at post.cybercity.dk (Nils Emil P. Larsen) Date: Mon, 24 Jan 2005 10:40:14 +0100 Subject: Keyboard problems with Python shell over SSH References: <8h38v0h322qokr7cgmen17805kbldhi87o@4ax.com> Message-ID: Hello Stian >Your Python installation is probably compiled without readline support. >It is the readline library that enables arrow keys and Ctrl-R and stuff >to work. >Try "import readline" - you will probably get an error. You are indeed right. "import readline" generated an error. I downloaded, compiled and installed GNU readline. Then I downloaded Python 2.4 source and configured it with ./configure --with-readline make make install This did the trick! Thank you! Nils Emil P. Larsen -- My reply-address is valid. www.bios-flash.dk Min svar-adresse er gyldig. Redning af d?de BIOS'er From merkosh at hadiko.de Fri Jan 28 18:41:29 2005 From: merkosh at hadiko.de (Uwe Mayer) Date: Sat, 29 Jan 2005 00:41:29 +0100 Subject: example needed: sip + Qt References: Message-ID: Saturday 29 January 2005 00:23 am Phil Thompson wrote: > So have you created the library you are trying to wrap? The documentation > is describing how to wrap a library and describes a fictional library as > the basis for the example. No, the extracts from before are from the code example of the fictional library with no further implementation. By now I also found the problem: the poor python programmer did not care to create the makefile (for building hello.cpp and hello.h) with qmake and thus there were no moc files and that stupid programmer (me) could not link against them. It compiles and loads in python now. Thanks Uwe From Axel.Diener at orsoft.de Tue Jan 4 02:35:17 2005 From: Axel.Diener at orsoft.de (Axel Diener) Date: Tue, 4 Jan 2005 08:35:17 +0100 Subject: Integrating Python into a C++ app In-Reply-To: <1104801230.728736.83970@f14g2000cwb.googlegroups.com> Message-ID: -----Original Message----- From: Ben Sizer [mailto:kylotan at gmail.com] Sent: Tuesday, January 04, 2005 2:14 AM To: python-list at python.org Subject: Integrating Python into a C++ app I know the conventional wisdom is to write the whole app in Python and only extend with C++ where speed is an issue, but I already have a large C++ app that I'd like to add Python to. Ideally I'd rewrite the whole app in Python but I don't have time to do that and maintain the old system at the same time. So my next thought was to perhaps integrate the two and slowly migrate modules and classes across from C++ to Python. If it matters, the main reason I'm interested in doing this is because I appreciate the productivity of Python and would like to take advantage of that as I add features to the current code, to reduce bugs and cut development time. I've read a few good things in this group about Elmer (http://elmer.sourceforge.net), but I'm not sure how simply that accommodates calls in the reverse direction (from Python code back into C++). Are there any other options that would require a minimum of rewriting of code? Does anybody have any experience of such a project? -- Ben Sizer Even embedding Python in a C++ Application is an easy task. I work at such an application since about five years. For the first steps in doing this I advice you to study the source code of the modpython apache extension. There you will see how embedding may be implemented. Bur embedding does not work well without extending. For this part I use PyCXX from http://sourceforge.net/projects/cxx/. Axel Diener From miki.tebeka at gmail.com Mon Jan 24 10:24:14 2005 From: miki.tebeka at gmail.com (Miki) Date: 24 Jan 2005 07:24:14 -0800 Subject: Python serial data aquisition In-Reply-To: References: Message-ID: <1106580254.778471.141190@f14g2000cwb.googlegroups.com> Hello Fl?vio, > My problem is to how to recover my reading from these bytes, since > pyserial gives me a character (string) from each byte... I dont know > how to throw away the unneeded bits and concatenate the remaining > bits to form a number... See the array module. Also http://tebeka.bizhat.com/Software/bitter.py HTH. Miki From aleaxit at yahoo.com Wed Jan 5 02:55:39 2005 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 5 Jan 2005 08:55:39 +0100 Subject: Cookbook 2nd ed Credits References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> <7xacrs230c.fsf@ruckus.brouhaha.com> <33q4plF410bo2U1@individual.net> <1gpsbep.13iiova6cvkayN%aleaxit@yahoo.com> <1104836129.741586.179510@c13g2000cwb.googlegroups.com> <1gpvif1.1r2osm66cmd3vN%aleaxit@yahoo.com> Message-ID: <1gpvtjk.3jf7dc1cch7yfN%aleaxit@yahoo.com> Premshree Pillai wrote: > Do contributors of less than 5 recipes get a copy too? :-? Of course! > Btw, is there a comprehensive list of ALL contributors put up anywhere? Not yet -- do you think I should put it up on my website? Alex From jerf at jerf.org Fri Jan 21 01:52:58 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Fri, 21 Jan 2005 01:52:58 -0500 Subject: Retrieving the last bit Re: File objects? - under the hood question References: <20050119034955.75129.qmail@web50306.mail.yahoo.com> Message-ID: On Thu, 20 Jan 2005 21:06:31 -0800, Eric Pederson wrote: > Here the sort of thing (seek, then read) I think I want: > >>>> IDV2=open(("http://musicsite.com/song453.mp3","rb")[:-128]) > >>>> song453.tags=IDV2.read() > >>>> len(song453.tags) > > 128 > > > But it's not a Python problem. :-( OK, HTTP. It's true that it isn't a Python problem, but the fact that this is possible and even easy isn't generally known, since it involves actually understanding HTTP as more than a protocol that says "give me this file". :-{ You need to use the Range header in HTTP to request just the end. urllib doesn't seem to like the Range header (it interprets the 206 response that results as an error, at least in 2.3.4 which I'm using here, which I would consider a bug; 2xx responses are "success"), but you can still do it with httplib: Python 2.3.4 (#1, Oct 26 2004, 20:13:42) [GCC 3.4.2 (Gentoo Linux 3.4.2-r2, ssp-3.4.1-1, pie-8.7.6.5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import httplib >>> connection = httplib.HTTPConnection("www.jerf.org") >>> connection.request("GET", "/", headers = {"Range": "bytes=-100"}) >>> response = connection.getresponse() >>> response.read() 'rch Google -->\r\n\t\t\t\t\t
\r\n\t\t\t\t\t

 

\r\n\t\t\t
\r\n\t\t\r\n\t\r\n' The bad news is I think you would have to chase redirects and such on your own. Hopefully a urllib expert will pop in and show how to quickly tell urllib to chill out when it gets a 206; I'm pretty sure it's easy, but I can't quite rattle off how. Or maybe 2.4 has a better urllib. From alipolatel at yahoo.com Sun Jan 23 13:49:55 2005 From: alipolatel at yahoo.com (Ali Polatel) Date: Sun, 23 Jan 2005 10:49:55 -0800 (PST) Subject: on the way to find pi! In-Reply-To: Message-ID: <20050123184955.25121.qmail@web61005.mail.yahoo.com> write the code type str(pi(5)) and see what I mean __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From amk at amk.ca Sat Jan 22 08:57:59 2005 From: amk at amk.ca (A.M. Kuchling) Date: Sat, 22 Jan 2005 07:57:59 -0600 Subject: rotor replacement References: <7x1xcidnp1.fsf@ruckus.brouhaha.com> <41EE24F7.7030303@jessikat.fsnet.co.uk> <7x1xchlpqv.fsf@ruckus.brouhaha.com> <41efeb82$0$27807$9b622d9e@news.freenet.de> <41f1a70b$0$25959$9b622d9e@news.freenet.de> <7xbrbiqdhk.fsf@ruckus.brouhaha.com> <7xllalljah.fsf@ruckus.brouhaha.com> Message-ID: On 22 Jan 2005 04:50:30 -0800, Paul Rubin wrote: > Martin, do you know more about this? I remember being disappointed > about the decisions since I had done some work on a new block cipher It was discussed in this thread: http://mail.python.org/pipermail/python-dev/2003-April/034959.html Guido and M.-A. Lemburg were leaning against including crypto; everyone else was positive. But Guido's the BDFL, so I interpreted his vote as being the critical one. --amk From sp1d3rx at gmail.com Tue Jan 11 14:14:32 2005 From: sp1d3rx at gmail.com (sp1d3rx at gmail.com) Date: 11 Jan 2005 11:14:32 -0800 Subject: Time script help sought! In-Reply-To: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> Message-ID: <1105470872.613166.187800@f14g2000cwb.googlegroups.com> read below for my sample script.... kpp9c wrote: > I am kind of in a bit of a jam (okay a big jam) and i was hoping that > someone here could give me a quick hand. I had a few pages of time > calculations to do. So, i just started in on them typing them in my > time calculator and writing them in by hand. Now i realize, that i > really need a script to do this because: > > 1. It turns out there are hundreds of pages of this stuff. > 2. I have to do something similar in again soon. > 3. By doing it by hand i am introducing wonderful new errors! > 4. It all has to be typed up anyway (which means weeks of work and even > more typos!) > > The input would like so: > > Item_1 TAPE_1 1 00:23 8:23 > > Item_2 TAPE_1 2 8:23 9:41 > > Item_3 TAPE_1 3 9:41 10:41 > Item_3 TAPE_1 4 10:47 11:19 > Item_3 TAPE_1 5 11:21 11:55 > Item_3 TAPE_1 6 11:58 12:10 > Item_3 TAPE_1 7 12:15 12:45 Defect in analog tape sound. > Item_3 TAPE_1 8 12:58 24:20 Defect in analog tape sound. > > Item_4 TAPE_1 9 24:33 > Item_4 TAPE_1 10 25:48 > Item_4 TAPE_1 11 29:48 > Item_4 TAPE_1 12 31:46 > Item_4 TAPE_1 13 34:17 Electronic sounds. > Item_4 TAPE_1 14 35:21 > Item_4 TAPE_1 15 36:06 > Item_4 TAPE_1 16 37:01 37:38 > > These are analog tapes that were digitized (on to CD or a digital tape) > that have now been exported as individual files that are meant to be > part of an on-line audio archive. The timings refer to the time display > on the CD or digital tape. The now all have to adjusted so that each > item starts at 0.00 since they have all been edited out of their > context and are now all individual items that start at 00:00. So Item_1 > which was started at 00:23 on the tape and ended at 8:23 needs to have > 23 seconds subtracted to it so that it says: > > Item_1 TAPE_1 1 00:00 08:00 > > Item_2 TAPE_1 2 08:23 09:41 > > would change to: > > Item_2 TAPE_1 2 00:00 01:18 > > etc. > > but as always you may notice a wrinkle.... some items have many times > (here 6) indicated: > > Item_3 TAPE_1 3 9:41 10:41 > Item_3 TAPE_1 4 10:47 11:19 > Item_3 TAPE_1 5 11:21 11:55 > Item_3 TAPE_1 6 11:58 12:10 > Item_3 TAPE_1 7 12:15 12:45 Defect in analog tape sound. > Item_3 TAPE_1 8 12:58 24:20 Defect in analog tape sound. > > This is all a single sound file and these separate times mark where > there was a break, defect, or edit in the individual item. These have > to be adjusted as well to show where these events would appear in the > new sound file which now starts at 00:00. > > Item_3 TAPE_1 3 00:00 01:00 ---- > Item_3 TAPE_1 4 01:00 01:38 ---- > Item_3 TAPE_1 5 01:38 02:14 ---- > Item_3 TAPE_1 6 02:14 02:29 ---- > Item_3 TAPE_1 7 02:29 03:04 Defect in analog tape sound. > Item_3 TAPE_1 8 03:04 14:39 Defect in analog tape sound. > > Further wrinkles: Some have start and end times indicated, some only > start times. I suppose that the output would ideally have both.... some > have comments and others don't ... and I need these comments echo-ed or > since i probably need to make a database or table eventually non > comments just have some place holder. > > I'd have a lot of similar type calculations to do... I was hoping and > praying that some one here was feeling generous and show me the way and > then, of course i could modify that to do other tasks... Usually i am > happy to take the long road and all but i'll be honest, i am in a big > jam here and this huge task was just dumped on me. I am frankly a > little desperate for help on this and hoping someone is feeling up to > spoon feeding me a clear modifiable example that works. Sorry..... > cheers, > > kevin --------START-------- inp = file("input1.txt",'r') # input file is opened readonly x = inp.readline() #read in the first line of the file x = x.upper().split(None,5) #convert it to uppercase and split into 5 segments print x #show the line as splitted and converted print x[1] #show the second element start = x[3].split(":") #split the minutes from the seconds end = x[4].split(":") #split the minutes from the seconds print "Start at:", start[0], "minutes and ", start[1], "seconds." start_in_seconds = int(start[0])*60 + int(start[1]) #converts minutes/seconds to seconds print start_in_seconds , "seconds offset." print "End at:", end[0],"minutes and",end[1], "seconds." end_in_seconds = int(end[0])*60 + int(end[1])#converts minutes/seconds to seconds print end_in_seconds , "seconds offset." totaltime = end_in_seconds - start_in_seconds #calculate the length of the segment print "Total time of segment in seconds:", totaltime print "Total time of segment in minutes/seconds:", totaltime/60, "minutes and", totaltime % 60, "seconds." # ^^^ converts seconds back to minutes and seconds. --------END-------- This should give you an excellent starting point. From http Sat Jan 29 21:32:05 2005 From: http (Paul Rubin) Date: 29 Jan 2005 18:32:05 -0800 Subject: What's so funny? WAS Re: rotor replacement References: <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> <41f97630$0$11586$9b622d9e@news.freenet.de> <7xu0p2dvsa.fsf@ruckus.brouhaha.com> <41f9f5e6$0$25927$9b622d9e@news.freenet.de> <7x4qh13o0o.fsf@ruckus.brouhaha.com> <41FACD1C.6000301@v.loewis.de> <7xacqt56ga.fsf@ruckus.brouhaha.com> <41fb646a$0$31784$9b622d9e@news.freenet.de> <7xacqsbfk2.fsf@ruckus.brouhaha.com> <41fbcb11$0$12030$9b622d9e@news.freenet.de> Message-ID: <7xsm4j1wbe.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > Apparently, people disagree on what precisely the API should be. E.g. > cryptkit has > > obj = aes(key) > obj.encrypt(data) I don't disagree about the API. The cryptkit way is better than ECB example I gave, but the ECB example shows it's possible to do it in one call. > I think I would prefer explicit encrypt/decrypt methods over a > direction parameter. Whether or not selection of mode is a separate > parameter, or a separate method, might be debatable I prefer separate methods too, however if it was done with a direction flag instead, it wouldn't really cause a problem. As long as the functionality is there, I can use it. > I would trust my intuition more for a single function than for an > entire API. In this specific proposal, I think I would trust my > intuition and reject the ECB function because of the direction argument. As an experienced user of a lot of these packages, I can tell you I've seen it done both ways and I have a slight preference for separate calls, but it really doesn't matter one way or the other and it's not worth getting in a debate about it or having a committee design the API and worry about such trivial issues. BTW, the main reason to reject the example ECB function is that creating a key object ("key schedule") from a string can take significant computation (sort of like compiling a regexp) so the ECB function for some ciphers would have to cache the object like the regexp module does. Yuck. The direction flag question would normally be between: key = aes.key(key_data) ciphertext = key(plaintext, "e") or key = aes.key(key_data) ciphertext = key.encrypt(plaintext) FWIW, another way to do it, also sometimes preferable, is: key = aes.ecb(key_data, "e") # e for encryption, or "d" for decryption ciphertext = key(plaintext) I think the module I proposed did it this last way, but I haven't looked at it in a while. The point is that when faced with yet another crypto package, I don't get in too concerned about which simple API variant it uses to do such a basic operation. I just care that the operation is available. I look in the docs to find that package's particular API for that operation, and I do what the docs say. I should make it clear that this module is like Python's low-level "thread" module in that you have to know what you're doing in order to use it directly without instantly getting in deep trouble. Most applications would instead use it indirectly through one or more intermediate layers. > I fully understand what you desire - to include the module "as a > battery". What makes this decision difficult is that you fail to > understand that I don't want included batteries so much that I > would accept empty or leaking batteries. I do understand that, and the prospect of empty or leaking batteries is vitally important to considering whether to include a battery that's included, but for the purposes of an included-battery discussion, the characteristics of NON-included batteries is not relevant, given that we know they exist. > >>http://sourceforge.net/projects/cryptkit/ ...> > > I've examined that module, I wouldn't consider it > > ideal for the core (besides AES, it has some complicated additional > > functions that aren't useful to most people) > > Ok, that would be a problem. If this is a simple removal of functions > that you'ld request (which functions?), OK. First you have to decide whether you want a general crypto toolkit, or just an AES module. I've been concentrating on just an AES module (or rather, a generic block cipher module with AES and DES) since I figure that creates fewer areas of controversy, etc. I think it's too early to standardize a fancy toolkit. Once there's block ciphers, we can think about adding more stuff afterwards. For that module, I'd say remove everything except AES and maybe SHA256, and ask that DES be added. SHA256 is possibly useful, but isn't really part of an encryption package; it can be separated out like the existing sha and md5 modules. Also, it should be brought into PEP 247 compliance if it's not already. Rationale: I'd get rid of the entropy module now that os.urandom is available. Having the OS provide entropy is much better than trying to do it in user code. I'd get rid of the elliptic curve stuff unless there's some widely used standard or protocol that needs that particular implementation. Otherwise, if I want ECC in a Python program, I'd just do it on characteristic-p curves in pure Python using Python longs. (Bryan's package uses characteristic-2 curves which means the arithmetic is all boolean operations, that are more efficient on binary CPU's, especially small ones. But that means the module has to be written in C, because doing all those boolean operations in Python is quite slow. It would be like trying to do multi-precision arithmetic in Python with Python ints instead of longs). Once there's a widely accepted standard for ECC like there is for AES, then I'd want the stdlib to have an implementation of the standard, but right now there are just a lot of incompatible, nonstandard approaches running around. If SHA256 is accepted then SHA512/SHA384 (these are basically the same) might as well also be. Not many people are using any of these hash functions right now. Usage will increase over time (they are US federal standards like AES), and they'll probably be worth adding eventually. I'm indifferent to whether they're added now. I think I'd include RC4 under the "toolkit" approach, if it's not already there. I'd also include a pair of functions like the ones in p3.py, i.e. an utterly minimal API like: ciphertext = encrypt_string(key_string, plaintext) plaintext = decrypt_string(key_string, ciphertext) that does both encryption and authentication, for key and data strings of arbitrary size. This would be what people should use instead of the rotor module. It would be about a 10 line Python function that calls the block cipher API. The block cipher API itself is intended for more advanced users. > I may have made exceptions to this rule in the past, e.g. when the > proposal is to simply wrap an existing C API in a Python module > (like shadow passwords). In this case, both the interface and > the implementation are straight-forward, and I expect no surprises. I'd be happy with an AES module that simply wrapped a C API and that should be pretty much surprise-free. It would be about like the SHA module in terms of complexity. What I proposed tries to be a bit more Pythonic but I can live without that. > For an AES module (or most other modules), I do expect surprises. Well, the hmac module was added in 2.2 or 2.3, without any fuss. It's written in Python and is somewhat slow, though. What kind of development process should it take to replace it in the stdlib with a C module with the exact same interface? I think you're imagining a basic AES module to be more complicated than it really is, because you're not so familiar with this type of module. Also, possibly because I'm making it sound like a lot of work to write. But that work is just for the C version, and assumes that it's me personally writing it. What little experience I've had with Python's C API has been painful, so I figure on having to spend considerable time wrestling with it. Someone more adapt with the C API could probably implement the module with less effort than I'd need. > I have said many times that I am in favour of including an AES > implementation in the Python distribution, e.g. in Oh, ok. Earlier you said you wanted user feedback before you could conclude that there was reason to want an AES module at all. > What I cannot promise is to include *your* AES implementation, > not without getting user feedback first. That's fine. But I think it's reasonable to actually approach some users and say "this module is being considered for addition to the core--could you try plugging it into your applications that now use other external modules, and say whether you think it will fill your needs". That's impossible if consideration doesn't even start until testing is complete. All one could say then is "here's yet another crypto module, that does less than the toolkit you're already using, could you please temporarily drop whatever you're doing and update your programs to switch from your old module that works, to a new module that MIGHT work?". If the new module is accepted into the core, of course, it becomes worth retrofitting the existing toolkits to use it. > The whole notion of creating the module from scratch just to include > it in the core strikes me as odd - when there are so many AES > implementations out there already that have been proven useful to users. We discussed this already. Here are three possible contexts for designing a crypto module: 1) You're designing it to support some specific application you're working on. The design will reflect the needs of that application and might not be so great for a wider range of applications. 2) You're writing a general purpose module for distribution outside the core (example: mxCrypto). You'll include lots of different functions, pre-built implementations of a variety of protocols, etc. You might include bindings that try to be compatible with other packages, etc. Maybe this can get added to the core someday, like numarray, but for now, that's a rather big step. 3) You're designing to add basic functionality to the core. Here, you try to pick a general purpose API not slanted towards a particular app, and provide just some standard building blocks that other stuff can be built around. This is more like the math module, which just does basics: sqrt, sin, cos, etc., with no attempt at the stuff in a package like numarray. But if there's a standard like FIPS 80 and if there's good reason to implement a big subset of it (which there is), then you may as well implement the standard completely unless there's a good reason not to (which there isn't; the less important operations are a few dozen lines of code total). I think context #3 gets you something better suited for the core and none of the existing crypto modules were written that way. The same is in fact true for many of the non-crypto modules, that seem to have been written in context #1 and would have been better under context #3. Also, there's the plain fact that none of the authors of the existing crypto modules have offered to contribute them. So somebody had to step up and do something. > > what is the your own subjective estimate of the probability? > Eventually, with hard work, I estimate the chances at, say, 90%. Hmm, this is very very interesting. I am highly confident that all the purely technical questions (i.e. everything about the API and the code quality, etc.) can converge to a consensus-acceptable solution without much hassle. I had thought there were insurmountable obstacles of a nontechnical nature, mainly caused by legal issues, and that these are beyond any influence that I might have by writing or releasing anything. From michele.simionato at gmail.com Tue Jan 11 02:51:09 2005 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 10 Jan 2005 23:51:09 -0800 Subject: readline, rlcompleter Message-ID: <1105429869.770262.14360@c13g2000cwb.googlegroups.com> This a case where the documentation is lacking. The standard library documentation (http://www.python.org/dev/doc/devel/lib/module-rlcompleter.html) gives this example try: import readline except ImportError: print "Module readline not available." else: import rlcompleter readline.parse_and_bind("tab: complete") but I don't find a list of recognized key bindings. For instance, can I would like to bind shift-tab to rlcompleter, is that possible? Can I use function keys? I did various attempt, but I did not succed :-( Is there any readline-guru here with some good pointers? Michele Simionato From mt at 3planes.com Sat Jan 29 18:18:49 2005 From: mt at 3planes.com (Michael Tobis) Date: 29 Jan 2005 15:18:49 -0800 Subject: bound vs unbound functions Message-ID: <1107040729.535936.42230@c13g2000cwb.googlegroups.com> I'm trying to do metaprogramming. I'm sure I've got this all wrong wrong wrong, but somehow my approach hasn't yet hit a brick wall. Anyway, I'd like to dynamically add a method to an instance at instantiation time. Something like ###### In [71]: class quux(object): ....: def __init__(self,stuff): ....: template = "def foo(self,b): print b + %s" % stuff ....: exec(template) ....: self.bazz = foo ....: In [72]: q = quux(5) In [73]: q.bazz(4) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /Users/tobis/PyNSol/ TypeError: foo() takes exactly 2 arguments (1 given) In [74]: q.bazz("not much",4) 9 ######## So the straightforward question is why, even though bazz is a method of class quux, it doesn't have that extra call parameter 'self'. Is this a problem? If I actually need a reference to self is it OK to do: In [76]: q.bazz(q,4) ? The more vague question is why do people despise 'exec', and how should I do this sort of thing instead? mt PS - any idea how to get past google's stupid formatting these days? I thought they were supposed to like python, but they just ignore leading blanks. From kp8 at mac.com Tue Jan 11 13:02:55 2005 From: kp8 at mac.com (kpp9c) Date: 11 Jan 2005 10:02:55 -0800 Subject: Time script help sought! In-Reply-To: <7x4qhn7u1n.fsf@ruckus.brouhaha.com> References: <1105464345.433117.109300@z14g2000cwz.googlegroups.com> <7x4qhn7u1n.fsf@ruckus.brouhaha.com> Message-ID: <1105466575.735232.272160@z14g2000cwz.googlegroups.com> Yes, Ultimately it will be part of a large digital archive available for researchers on site and eventually probably on-line for the New York Public Library. It is a huge undertaking and most of the soundfiles have been made. I (we) are struggling with the sheer size of the documentation.... Sorry about that.... i should have been more clear, epecially since i am sort of begging for a little help. Sorry, i am slightly overwhelmed at the moment... From rkern at ucsd.edu Tue Jan 4 17:36:44 2005 From: rkern at ucsd.edu (Robert Kern) Date: Tue, 04 Jan 2005 14:36:44 -0800 Subject: Python evolution: Unease In-Reply-To: References: <41da4a3f$0$17626$e4fe514c@dreader13.news.xs4all.nl><1gpv286.1kccndo1l4coseN%aleaxit@yahoo.com> Message-ID: Terry Reedy wrote: > "Bulba!" wrote in message > >>E.g. right now I would kill for a standard, built-in matrix >>type > > > The array types of Numerical Python (NumPy) and now Numarray are, defacto, > Python's standard 1 to n dimensional array types. Once installed, they are > as builtin as anything else. Several other packages build on top of them. And one of the goals of numarray (which is a complete rewrite of Numeric) *is* entry into the standard library. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From http Thu Jan 13 18:30:58 2005 From: http (Paul Rubin) Date: 13 Jan 2005 15:30:58 -0800 Subject: python and macros (again) [Was: python3: 'where' keyword] References: <1105437966.129342.304400@f14g2000cwb.googlegroups.com> <7xmzvfn096.fsf@ruckus.brouhaha.com> <7xsm559heo.fsf@ruckus.brouhaha.com> Message-ID: <7xacrcdhzh.fsf@ruckus.brouhaha.com> "Fredrik Lundh" writes: > > Huh? Expressions are not statements except when they're "expression > > statements"? What kind of expression is not an expression statement? > > any expression that is used in a content that is not an expression statement, > of course. Come on, that is vacuous. The claim was "expressions are not statements". But it turns out that expressions ARE statements. The explanation is "well, that's because they're expression statements". And there is no obvious case of an expression that can't be used as a statement. So it's not inherently obvious that there needs to be any kind of statement that can't be used as an expression. It's just an artifact. Whether the artifact is a desirable one is a matter of discussion. From simoninusa2001 at yahoo.co.uk Mon Jan 3 16:02:32 2005 From: simoninusa2001 at yahoo.co.uk (Simon John) Date: 3 Jan 2005 13:02:32 -0800 Subject: Bad Interpreter References: <1104783849.754892.47560@c13g2000cwb.googlegroups.com> Message-ID: <1104784496.231137.117250@f14g2000cwb.googlegroups.com> RajaSriniva... at hotmail.com wrote: > the script i have sock.py runs if i say something like : > > python sock.py > > but ./sock.py results in a :bad interpreter error > how do i troubleshoot something like this? sounds like you've been editting the script on a windows machine, and it's inserted it's evil linefeeds. on the unix machine run 'dos2unix sock.py', or load sock.py into vi and remove the ^M characters From steve at holdenweb.com Mon Jan 17 07:20:00 2005 From: steve at holdenweb.com (Steve Holden) Date: Mon, 17 Jan 2005 07:20:00 -0500 Subject: Writing huge Sets() to disk In-Reply-To: References: Message-ID: Martin MOKREJ? wrote: > Hi, > could someone tell me what all does and what all doesn't copy > references in python. I have found my script after reaching some > state and taking say 600MB, pushes it's internal dictionaries > to hard disk. The for loop consumes another 300MB (as gathered > by vmstat) to push the data to dictionaries, then releases > little bit less than 300MB and the program start to fill-up > again it's internal dictionaries, when "full" will do the > flush again ... > > The point here is, that this code takes a lot of extra memory. > I believe it's the references problem, and I remeber complains > of frineds facing same problem. I'm a newbie, yes, but don't > have this problem with Perl. OK, I want to improve my Pyhton > knowledge ... :-)) > Right ho! In fact I suspect you are still quite new to programming as a whole, for reasons that may become clear as we proceed. > > > > def push_to_disk(self): > _dict_on_disk_tuple = (None, self._dict_on_disk1, > self._dict_on_disk2, self._dict_on_disk3, self._dict_on_disk4, > self._dict_on_disk5, self._dict_on_disk6, self._dict_on_disk7, > self._dict_on_disk8, self._dict_on_disk9, self._dict_on_disk10, > self._dict_on_disk11, self._dict_on_disk12, self._dict_on_disk13, > self._dict_on_disk14, self._dict_on_disk15, self._dict_on_disk16, > self._dict_on_disk17, self._dict_on_disk18, self._dict_on_disk19, > self._dict_on_disk20) It's a bit unfortunate that all those instance variables are global to the method, as it means we can't clearly see what you intend them to do. However ... Whenever I see such code, it makes me suspect that the approach to the problem could be more subtle. It appears you have decided to partition your data into twenty chunks somehow. The algorithm is clearly not coded in a way that would make it easy to modify the number of chunks. [Hint: by "easy" I mean modifying a statement that reads chunks = 20 to read chunks = 40 for example]. To avoid this, we might use (say) a list of temp edicts, for example (the length of this could easily then be parameterized as mentioned. So where (my psychic powers tell me) your __init__() method currently contains self._dict_on_disk1 = something() self._dict_on_disk2 = something() ... self._dict_on_disk20 = something() I would have written self._disk_dicts = [] for i in range(20): self._disk_dicts.append(something) Than again, I probably have an advantage over you. I'm such a crappy typist I can guarantee I'd make at least six mistakes doing it your way :-) > _size = 0 What with all these leading underscores I presume it must be VERY important to keep these object's instance variables private. Do you have a particular reason for that, or just general Perl-induced paranoia? :-) > # > # sizes of these tmpdicts range from 10-10000 entries for each! > for _tmpdict in (self._tmpdict1, self._tmpdict2, self._tmpdict3, > self._tmpdict4, self._tmpdict5, self._tmpdict6, self._tmpdict7, > self._tmpdict8, self._tmpdict9, self._tmpdict10, self._tmpdict11, > self._tmpdict12, self._tmpdict13, self._tmpdict14, self._tmpdict15, > self._tmpdict16, self._tmpdict17, self._tmpdict18, self._tmpdict19, > self._tmpdict20): > _size += 1 > if _tmpdict: > _dict_on_disk = _dict_on_disk_tuple[_size] > for _word, _value in _tmpdict.iteritems(): > try: > _string = _dict_on_disk[_word] > # I discard _a and _b, maybe _string.find(' ') > combined with slice would do better? > _abs_count, _a, _b, _expected_freq = _string.split() > _abs_count = int(_abs_count).__add__(_value) > _t = (str(_abs_count), '0', '0', '0') > except KeyError: > _t = (str(_value), '0', '0', '0') > > # this writes a copy to the dict, right? > _dict_on_disk[_word] = ' '.join(_t) > > # > # clear the temporary dictionaries in ourself > # I think this works as expected and really does release memory > # > for _tmpdict in (self._tmpdict1, self._tmpdict2, self._tmpdict3, > self._tmpdict4, self._tmpdict5, self._tmpdict6, self._tmpdict7, > self._tmpdict8, self._tmpdict9, self._tmpdict10, self._tmpdict11, > self._tmpdict12, self._tmpdict13, self._tmpdict14, self._tmpdict15, > self._tmpdict16, self._tmpdict17, self._tmpdict18, self._tmpdict19, > self._tmpdict20): > _tmpdict.clear() > There you go again with that huge tuple. You just like typing, don't you? You already wrote that one out just above. Couldn't you have assigned it to a local variable? By the way, remind me again of the reason for the leading None in the _dict_on_disk_tuple, would you? The crucial misunderstanding here might be the meaning of "release memory". While clearing the dictionary will indeed remove references to the objects formerly contained therein, and thus (possibly) render those items subject to garbage collection, that *won't* make the working set (i.e. virtual memory pages allocated to your process's data storage) any smaller. The garbage collector doesn't return memory to the operating system, it merely aggregates it for use in storing new Python objects. > > > > The above routine doesn't release of the memory back when it > exits. > And your evidence for this assertion is ...? > > See, the loop takes 25 minutes already, and it's prolonging > as the program is in about 1/3 or 1/4 of the total input. > The rest of my code is fast in contrast to this (below 1 minute). > > -rw------- 1 mmokrejs users 257376256 Jan 17 11:38 diskdict12.db > -rw------- 1 mmokrejs users 267157504 Jan 17 11:35 diskdict11.db > -rw------- 1 mmokrejs users 266534912 Jan 17 11:28 diskdict10.db > -rw------- 1 mmokrejs users 253149184 Jan 17 11:21 diskdict9.db > -rw------- 1 mmokrejs users 250232832 Jan 17 11:14 diskdict8.db > -rw------- 1 mmokrejs users 246349824 Jan 17 11:07 diskdict7.db > -rw------- 1 mmokrejs users 199999488 Jan 17 11:02 diskdict6.db > -rw------- 1 mmokrejs users 66584576 Jan 17 10:59 diskdict5.db > -rw------- 1 mmokrejs users 5750784 Jan 17 10:57 diskdict4.db > -rw------- 1 mmokrejs users 311296 Jan 17 10:57 diskdict3.db > -rw------- 1 mmokrejs users 295895040 Jan 17 10:56 diskdict20.db > -rw------- 1 mmokrejs users 293634048 Jan 17 10:49 diskdict19.db > -rw------- 1 mmokrejs users 299892736 Jan 17 10:43 diskdict18.db > -rw------- 1 mmokrejs users 272334848 Jan 17 10:36 diskdict17.db > -rw------- 1 mmokrejs users 274825216 Jan 17 10:30 diskdict16.db > -rw------- 1 mmokrejs users 273104896 Jan 17 10:23 diskdict15.db > -rw------- 1 mmokrejs users 272678912 Jan 17 10:18 diskdict14.db > -rw------- 1 mmokrejs users 260407296 Jan 17 10:13 diskdict13.db > > Some spoke about mmaped files. Could I take advantage of that > with bsddb module or bsddb? > No. > Is gdbm better in some ways? Recently you have said dictionary > operations are fast ... Once more. I want to turn of locking support. > I can make the values as strings of fixed size, if mmap() would be > available. The number of keys doesn't grow much in time, mostly > there are only updates. > Also (possibly because I come late to this thread) I don't really understand your caching strategy. I presume at some stage you look in one of the twenty temp dicts, and if you don;t find something you read it back in form disk? This whole thing seems a little disorganized. Perhaps if you started with a small dataset your testing and development work would proceed more quickly, and you'd be less intimidated by the clear need to refactor your code. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From philippecmartin at sbcglobal.net Mon Jan 24 11:49:11 2005 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 24 Jan 2005 10:49:11 -0600 Subject: What is print? A function? Message-ID: <1106585352.7185.13.camel@localhost> Why don't you redirect stdout or stderr #******************************************************************************* class Debug_Stderr: __m_text = '' __m_log_text = None __m_dbg = None __m_refresh_count = 0 #******************************************************************************* def __init__(self): #******************************************************************************* def write(self,p_string): #your code here . . . my_debug = Debug_Stderr() sys.stderr = my_debug print >> sys.stderr, 'this will go into the above write method' -- *************************** Philippe C. Martin SnakeCard LLC www.snakecard.com *************************** From jerf at jerf.org Wed Jan 19 03:24:11 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Wed, 19 Jan 2005 03:24:11 -0500 Subject: File objects? - under the hood question References: <20050119034955.75129.qmail@web50306.mail.yahoo.com> Message-ID: On Tue, 18 Jan 2005 22:53:10 -0800, Eric Pederson wrote: > Perhaps I've answered my question and the under-the-hood mechanics are > handled on the OS side, and Python is just making requests of the OS... Almost by definition, the only correct way to read a file is to use the file system, which on current operating systems means going the the OS kernel. > My brain-teaser: What I'd like to do is read the last ~2K of a large > number of large files on arbitrary servers across the net, without having > to read each file from the beginning (which would be slow and resource > inefficient)... "Across the net" is not specific enough. There are generally ways to do that, subject to the support of the various relevant servers, but what protocol are you talking about using? HTTP? FTP? NFS? Generally you issue some sort of command to get the length, then some sort of "seek" or "continuation" command to get to the end, but the details are different for each protocol. (Unless someone has a convenient flattening library around? I have something almost like that in my personal collection except I have no intention of supporting "seek" behavior for various technical reasons.) And note that with the possible exception of that last one, there is no relationship between these two questions. (Maybe you know that, maybe you don't. :-) ) There is no argument you can pass to file() that will read an HTTP file. (Pedants may note this isn't an absolute truth but it's "true enough" that it's not worth sweating the details if you're still working out what "file()" does.) From maxm at mxm.dk Tue Jan 18 04:41:43 2005 From: maxm at mxm.dk (Max M) Date: Tue, 18 Jan 2005 10:41:43 +0100 Subject: [ANN] iCalendar package 0.9 In-Reply-To: <9grub2-rvf.ln1@home.rogerbinns.com> References: <41ebd292$0$253$edfadb0f@dread12.news.tele.dk> <9grub2-rvf.ln1@home.rogerbinns.com> Message-ID: <41ecd91c$0$228$edfadb0f@dread12.news.tele.dk> Roger Binns wrote: > "Max M" wrote in message news:41ebd292$0$253$edfadb0f at dread12.news.tele.dk... > >>http://www.mxm.dk/products/public/ical/ >> >>Any feedback would be welcome. > > > How well do you cope with the crud that real programs generate? Does it work > with the different dialects uses out there? Can it at least identify them? It depends on how badly the data is screwed up. But generally it should be able to work on incorrect implementations. It doesn't care of the spelling of property and parameter names. Though type conversions will need to be done slightly more manual. If something like 'dtstart' is misspelled it will not return a datetime >>> cal.decoded('datestart') But if you know that it is misspelled you can get it, and convert it manually like: >>> from PropertyValues import vDDDType >>> vDDDType.from_ical(cal['datestart']) -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From martin at v.loewis.de Thu Jan 20 12:44:25 2005 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 20 Jan 2005 18:44:25 +0100 Subject: xml parsing escape characters In-Reply-To: <359o5cF4il48kU1@individual.net> References: <357s61F4iossjU1@individual.net> <41eeda3a$0$27828$9b622d9e@news.freenet.de> <359o5cF4il48kU1@individual.net> Message-ID: <41efedf2$0$11622$9b622d9e@news.freenet.de> Luis P. Mendes wrote: > with: DataSetNode = stringNode.childNodes[0] > print DataSetNode.toxml() > > I get: > > <DataSet> > ~ <Order> > ~ <Customer>439</Customer> > > ~ </Order> > </DataSet> > _______________________________________________________________- > > so far so good, but when I issue the command: > > print DataSetNode.childNodes[0] > > I get: > IndexError: tuple index out of range > > Why the error, and why does it return a tuple? The DataSetNode has no children, because it is not an Element node, but a Text node. In XML, an element is denoted by ... and *not* by <DataSet>...</DataSet> The latter is just a single string, represented in XML as a Text node. It does not give you any hierarchy whatsoever. As a text node does not have any children, its childNode members is a empty tuple; accessing that tuple gives you an IndexError. Regards, Martin From xah at xahlee.org Fri Jan 21 06:08:50 2005 From: xah at xahlee.org (Xah Lee) Date: 21 Jan 2005 03:08:50 -0800 Subject: how to write a tutorial Message-ID: <1106305730.361540.21010@f14g2000cwb.googlegroups.com> i've started to read python tutorial recently. http://python.org/doc/2.3.4/tut/tut.html Here are some quick critique: quick example: If the input string is too long, they don't truncate it, but return it unchanged; this will mess up your column lay-out but that's usually better than the alternative, which would be lying about a value. (If you really want truncation you can always add a slice operation, as in "x.ljust( n)[:n]". better: If the input string is too long, they don't truncate it, but return it unchanged; ----------------- delete: Reverse quotes (``) are equivalent to repr(), but their use is discouraged. ----------------- similarly, many places mentioning uncritical info such as warning or reference to other languages should be deleted. the tutorial should be simple, concise, to the point, stand along. Perhaps 1/5th length of the tutorial should be deleted for better. Follow the above principles. at places often a whole paragraph on some so called computer science jargons should be deleted. They are there more to showcase inane technicality than do help the reader. (related, many passages with jargons should be rewritten sans inane jargon. e.g. mutable object.) one easy way to understand these principles is to compare perl's documentation or unix man pages to Python's. The formers are often irrelevant, rambling on, not stand-along (it is written such that it unnecessarily requires the reader to be knowledgable of lots of other things). Python docs are much better, but like many computer language manuals, also suffers from verbiage of tech jargons. (these jargons or passages about them are usually there to please the authors themselves). A exemplary writing in this direction is the Mathematica manual by Stephen Wolfram. Any intelligent layman sans computer science degree can read it straightforwardly, and learn unhindered a language that is tantamount to features of lisp languages. Such documentation is not difficult to write at all. (contrary to the lot of "computer scientists" or IT pundits morons.) All it take is some simple principles outlined above. Xah xah at xahlee.org http://xahlee.org/PageTwo_dir/more.html From tjreedy at udel.edu Sun Jan 2 18:01:15 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 2 Jan 2005 18:01:15 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com><7xmzvu1ycn.fsf@ruckus.brouhaha.com><7xd5wqd14y.fsf@ruckus.brouhaha.com><7xfz1lal5d.fsf@ruckus.brouhaha.com><7xekh423b6.fsf@ruckus.brouhaha.com> <_rTBd.66275$Jk5.46@lakeread01> Message-ID: "Steve Holden" wrote in message news:_rTBd.66275$Jk5.46 at lakeread01... > Well clearly there's a spectrum. However, I have previously written that > the number of open source projects that appear to get stuck somewhere > between release 0.1 and release 0.9 is amazingly large, and does imply > some dissipation of effort. And how do the failure and effort dissipation rates of open source code compare to those of closed source code? Of course, we have only anecdotal evidence that the latter is also 'amazingly large'. And, to be fair, the latter should include the one-programmer proprietary projects that correspond to the one-programmer open projects. Also, what is 'amazing' to one depends on one's expectations ;-). It is known, for instance, that some large fraction of visible retail business fail within a year. And that natural selection is based on that fact that failure is normal. Terry J. Reedy From yuzx at livedoor.cn Fri Jan 14 03:01:25 2005 From: yuzx at livedoor.cn (yuzx) Date: Fri, 14 Jan 2005 16:01:25 +0800 Subject: python connect to db2 In-Reply-To: <1105689253.3167.0.camel@linux.tister.com> References: <1105689253.3167.0.camel@linux.tister.com> Message-ID: <1105689685.3167.7.camel@linux.tister.com> hi,all i am python newbie,i try to connect to db2 use python,i find it on python-db2 doc: $ python >>> import DB2 >>> conn = DB2.connect(dsn='sample', uid='db2inst1', pwd='ibmdb2') >>> curs = conn.cursor() but i don't know about dsn, i think a way like python connect to mysql : db=_mysql.connect("localhost","joebob","moonpie","thangs") anyone can help me ? thank you From lbates at syscononline.com Fri Jan 28 09:42:30 2005 From: lbates at syscononline.com (Larry Bates) Date: Fri, 28 Jan 2005 08:42:30 -0600 Subject: Help with web dashboard In-Reply-To: References: Message-ID: I don't know how complicated that you want to get, but Zope has built in support for a control panel with what are called portlets. Each portlet can act as an individual sub-window on the control panel. You convert each of your individal scripts to a portlet and plug them into a control panel page. Larry Bates Chris wrote: > I've written some python scripts to handle different tasks on my Windows > network. I would like for them to be accessible via a single web page > (kind of like a dashboard) but have the scripts run on the web server > (also a Windows box). > > Can anyone recommend a way (web server / language / method) of doing > this? > > Security is important since this page will be accessible inside the > company, but only people with the appropriate user name / password > should be able to run the scripts. From pythongnome at hotmail.com Mon Jan 10 08:04:24 2005 From: pythongnome at hotmail.com (Lucas Raab) Date: Mon, 10 Jan 2005 13:04:24 GMT Subject: Old Paranoia Game in Python In-Reply-To: <1105318366.966577.107460@c13g2000cwb.googlegroups.com> References: <2005010903390916807%spk00@coxnet> <5JcEd.1988$KJ2.907@newsread3.news.atl.earthlink.net> <1105318366.966577.107460@c13g2000cwb.googlegroups.com> Message-ID: mensanator at aol.com wrote: > Aahz wrote: > >>Trust the computer, the computer is your friend. > > > However, the computer isn't a fuckin' mind reader. > > If you're going to post source code on the usenet, don't > have lines longer than 72 characters. Otherwise you'll > find your code has wrapped lines. This not only causes > syntax errors in your choose and print statements but > also fucks up the formatting of of printed paragraphs. > > Stupid human. > Temper, temper... From x2164 at mailcity.com Mon Jan 31 21:34:11 2005 From: x2164 at mailcity.com (x2164 at mailcity.com) Date: 1 Feb 2005 02:34:11 GMT Subject: test_socket.py failure References: Message-ID: Nick Coghlan wrote: > x2164 at mailcity.com wrote: > > hi all, > > > > Linux 2.4.28 > > Glibc 2.2.5 > > gcc 2.95.3 > > > > > > I'm new to Python. > > > > I've compiled Python 2.4 from tar file. > > > > When running 'make test' i'm getting a failure > > in test_socket. > > > Two questions. First, what does the following code give > when you run it at the > interactive prompt?: > Py> import socket > Py> socket.getservbyname('daytime') > 13 > Second, is there an entry for 'daytime' in /etc/services? > Cheers, > Nick. > -- > Nick Coghlan | ncoghlan at email.com | Brisbane, Australia > --------------------------------------------------------------- > http://boredomandlaziness.skystorm.net hi Nick, At the interactive python prompt i did/got the following: bash-2.04$ ./python Python 2.4 (#1, Jan 29 2005, 10:31:35) [GCC 2.95.3 20010315 (release)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import socket >>> socket.getservbyname('daytime', 'tcp') 13 # The 13 looks ok but look what happen # when i asked only for the service, like # the line that fails in test_socket. >>> socket.getservbyname('daytime') Traceback (most recent call last): File "", line 1, in ? socket.error: service/proto not found >>> From my /etc/services file: daytime 13/tcp daytime 13/udp I was trying to use gdb to watch the function socket_getservbyname, from Modules/socketmodule.c, execute but i'm not sure how to set the gdb 'break' for a function in a module that isn't imported at the time i start python in gdb. Hints welcome. ;-) pete jordan x2164 at mail.city -- ............ From kamilche at mad.scientist.com Sun Jan 2 13:59:59 2005 From: kamilche at mad.scientist.com (Kamilche) Date: Sun, 02 Jan 2005 10:59:59 -0800 Subject: Python! Is! Truly! Amazing! In-Reply-To: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> References: <1104657461.868175.252380@c13g2000cwb.googlegroups.com> Message-ID: <33qumbF41vm5fU1@individual.net> Erik Bethke wrote: > Anyways, I am now a super gushing fan-boy. I have worked my way up > from a scripter working in crappy proprietary languages to a c++ > programmer, to now biz guy. But when I walked away from programming I > gave it a grim farewell, c++ work is good, but so much mind goes into > it to make progree compared to other creative uses of the mind. But > Python rocks, it makes programming very fun again and now I finding > myself coming home earlier so I can get to work on Python and I have an > entire heap of new projects I wanted to get done. Yeah, it is really a great language. For me, it matches my internal idea of 'pseudocode' to a T. Executable shorthand - does it get any better than that? --Kamilche From aaronwmail-usenet at yahoo.com Thu Jan 27 11:34:33 2005 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 27 Jan 2005 08:34:33 -0800 Subject: On benchmarks, heaps, priority queues In-Reply-To: <1106842754.010427.74630@c13g2000cwb.googlegroups.com> References: <1106835562.598569.211370@c13g2000cwb.googlegroups.com> <1106842754.010427.74630@c13g2000cwb.googlegroups.com> Message-ID: <1106843673.755688.244160@f14g2000cwb.googlegroups.com> (re: http://xsdb.sourceforge.net/bench/pq3.py) nsz> ...bisect is not so fast for large data... Yes I know in theory the insertion sort approach should be bad for large enough values, but the weird thing is that if you mix inserts and deletes (with enough deletes) even 1M elements is not a large enough value. Anyway, for 10K or less the insertion sort priority queue implementation seems to always be better. Weird. -- Aaron Watters === Hypothetical performance improvements are the root of all evil. -- Bill Tutt (paraphrased) From rnd at onego.ru Sat Jan 1 10:33:24 2005 From: rnd at onego.ru (Roman Suzi) Date: Sat, 1 Jan 2005 18:33:24 +0300 (MSK) Subject: DB-API 2.0 in pysqlite and pgdb Message-ID: Happy New Year to all Pythoneers! I am playing with pysqlite and pgdb and their DB-API conformancy. It was quite interesting to know: - sqlite doesn't have mandatory helper-functions Date, Tim, etc. (due to an error int it's __init__, but this is quite obvious to correct or just to use mx.Date, mx.Time) more serious mishaps with pgdb (postgresql-python): it doesn't know how to quote date-time data for the objects it has constructors itself. >>> import pgdb >>> c = pgdb.connect(database="template1") >>> cu = c.cursor() >>> o = pgdb.Time(10, 0, 0) >>> cu.execute("select %(o);", vars()) Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/site-packages/pgdb.py", line 189, in execute self.executemany(operation, (params,)) File "/usr/local/lib/python2.3/site-packages/pgdb.py", line 201, in executemany sql = _quoteparams(operation, params) File "/usr/local/lib/python2.3/site-packages/pgdb.py", line 283, in _quoteparams x[k] = _quote(v) File "/usr/local/lib/python2.3/site-packages/pgdb.py", line 275, in _quote raise InterfaceError, 'do not know how to handle type %s' % type(x) pgdb.InterfaceError: do not know how to handle type This doesn't happen for strings or numbers: >>> cu.execute("select %s;", ['s']) >>> cu.execute("select %s;", [1]) >>> cu.execute("select %(k)s;", {'k': 123}) >>> o Thus, pgdb doesn't know how to handle DateTimeDelta. The same with >>> cu.execute("select %(o)s;", {'o': pgdb.Date(2005,1,1)}) . . . line 201, in executemany sql = _quoteparams(operation, params) File "/usr/local/lib/python2.3/site-packages/pgdb.py", line 283, in _quoteparams x[k] = _quote(v) File "/usr/local/lib/python2.3/site-packages/pgdb.py", line 275, in _quote raise InterfaceError, 'do not know how to handle type %s' % type(x) pgdb.InterfaceError: do not know how to handle type (It was after I commented out exception catch: # except: # raise OperationalError, "internal error in '%s'" % sql in pgdb.py to see where the error occurs) Am I missing something obvious or is it really a bug/feature of pgdb? python2.3 postgresql-7.2.1 almost fresh mx.DateTime Thank you! Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From itsme at yahoo.com Wed Jan 12 13:31:06 2005 From: itsme at yahoo.com (It's me) Date: Wed, 12 Jan 2005 18:31:06 GMT Subject: counting items References: Message-ID: Oh, darn. I asked this kind of question before. Somebody posted an answer before: def flatten(seq): for x in seq: if hasattr(x, "__iter__"): for subx in flatten(x): yield subx else: yield x data = [[1,5,2],8,4] val_to_pos = {} for i, x in enumerate(flatten(data)): val_to_pos[x] = i + 1 print val_to_pos "It's me" wrote in message news:ukdFd.10645$5R.2000 at newssvr21.news.prodigy.com... > Okay, I give up. > > What's the best way to count number of items in a list? > > For instance, > > a=[[1,2,4],4,5,[2,3]] > > I want to know how many items are there in a (answer should be 7 - I don't > want it to be 4) > > I tried: > > b=len([x for y in a for x in y]) > > That doesn't work because you would get an iteration over non-sequence. > > I tried: > > g=lambda x: (1,len(x))[isinstance(x,(list,tuple,dict))] > b=sum(lambda(x) for x in a) > > and that didn't work because I get a TypeError from the len function (don't > know why) > > I can, of course: > > i=0 > for x in a: > if isinstance(x,(list,tuple,dict)): > i += len(x) > else: > i += 1 > > but that's so C-like... > > Thanks, > > From kartic.krishnamurthy at gmail.com Sun Jan 2 23:50:10 2005 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 2 Jan 2005 20:50:10 -0800 Subject: Problem remotely shutting down a windows computer with python References: <1104725615.094931.86410@f14g2000cwb.googlegroups.com> <1104726323.505127.139360@c13g2000cwb.googlegroups.com> Message-ID: <1104727810.646660.297480@f14g2000cwb.googlegroups.com> Hi, According to the online docs for InitiateSystemShutdown() at http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/win32api__InitiateSystemShutdown_meth.html bRebootAfterShutdown : int Specifies whether the computer is to restart immediately after shutting down. If this parameter is TRUE, the computer is to restart. If this parameter is FALSE, the system flushes all caches to disk, clears the screen, and displays a message indicating that it is safe to power down. Same at Microsoft for the Win32 API Call - http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/initiatesystemshutdown.asp Looks like this is the documented outcome. You could alternatively try setting a little XML-RPC app to invoke 'shutdown -s' on the remote PC from your PC (e.g. using Twisted Python). Thanks, --Kartic From paul at prescod.net Mon Jan 3 12:33:32 2005 From: paul at prescod.net (Paul Prescod) Date: Mon, 03 Jan 2005 09:33:32 -0800 Subject: Vancouver Python/Zope/Plone Meeting Reminder Message-ID: <41D981EC.10705@prescod.net> Tuesday January 4th is the first Tuesday of the month and the Vancouver Python, Zope and Plone user's group will have its monthly meeting at ActiveState. The topic is "What's new in Python 2.4": Among other things, we will discuss: * Function/method decorators * Generator expressions * Built-in sets * Unification of integers More information is available here: http://www.vanpyz.org/news Topics for the next few months have also been tentatively scheduled: January 4, 2005 What's New in Python 2.4, Paul Prescod February 1, 2005 Creating OS X Cocoa Applications Using XML and Python, Dethe Elza March 1, 2005 GNU Radio and Python, Ian Caven April 5, 2005 Large Scale Python, TBD Paul Prescod From aahz at pythoncraft.com Wed Jan 5 16:20:37 2005 From: aahz at pythoncraft.com (Aahz) Date: 5 Jan 2005 16:20:37 -0500 Subject: Python evolution: Unease References: Message-ID: In article , Daniel Bowett wrote: > >Thanks, typically how long does it take for any documentation to be >considered and implemented? It varies. (I could write a much longer response, but it would boil down to the same thing. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From sjmachin at lexicon.net Sun Jan 9 15:39:32 2005 From: sjmachin at lexicon.net (John Machin) Date: 9 Jan 2005 12:39:32 -0800 Subject: Speed revisited In-Reply-To: References: <1104878014.903025.229710@f14g2000cwb.googlegroups.com> <4it0u01caochn54c5uodoic5g9djpke78e@4ax.com> <1105237556.402188.126980@c13g2000cwb.googlegroups.com> Message-ID: <1105303172.147395.63580@c13g2000cwb.googlegroups.com> Bulba! wrote: > On 8 Jan 2005 18:25:56 -0800, "John Machin" > wrote: > > >Secondly, you are calling cmp() up to THREE times when once is enough. > >Didn't it occur to you that your last elif needed an else to finish it > >off, and the only possible action for the else suite was "assert > >False"? > > Sure, but I was trying to make it shorter and absolutely clear > what I mean in this place (when people see the comparison in every > place, they see immediately what it was, they don't have to > recall the variable). Obviously I'd optimise it in practice. It > was supposed to be "proof of concept" rather than any working > code. Three is shorter than one? See immediately? I have to disagree. People would be more put off by looking at your overly-complicated comparison three times and having to check character-by-character that it was doing exactly the same thing each time (i.e. your copy/paste had worked) than by "recalling" a sensibly-named variable like "cmp_result". > > BTW, this particular example didn't work out, but I still found > Python to be the most convenient language for prototyping, I > wrote smth like five versions of this thing, just to learn > dictionaries, lists, sets, etc. In no other language I'd do > it so quickly. NOW we're on the same bus. > > >It would appear after reading your "snippet 2" a couple of times that > >you are trying to implement the old 3-tape update method. > > Well, ahem, I admit you got me curious just how it would work > with tapes (never used them), so I was sort of trying to simulate > that - it's just a bit weird undertaking, I did it rather to explore > the issue and try to learn smth rather than to get working code. The 3-tape technique is worth understanding, for handling datasets that won't fit into memory. More generally, when learning, you *need* to get working code out of your practice exercises. Otherwise what are you learning? You don't want to wait until you have two 10GB datasets to "diff" before you start on thinking through, implementing and testing what to do on end-of-file. > > Deleting the first item from a list was to be a convenient > equivalent of forwarding the reading head on the tape one > record ahead, because I assumed that any deletion from the > list was to take more or less the same time, just like reading > heads on tapes were probably reading the records with similar > speeds regardless of what length of tape was already read. A reasonable assumption; however if the reading stopped and restarted, an inordinate amount of time was taken accelerating the drive up to reading speed again. The idea was to keep the tape moving at all times. This required techiques like double-buffering, plus neat clean brief fast processing routines. ... but you mixed in moving the indexes (with e.g. o+=1) with confusing results. Deleting the first item of a list in this circumstance reminds me of the old joke: "Q: How many members of military organisation X does it take to paint the barracks? A: 201, 1 to hold the paint-brush and 200 to lift the barracks and rotate it." Tip 1: Once you have data in memory, don't move it, move a pointer or index over the parts you are inspecting. Tip 2: Develop an abhorrence of deleting data. > > >It would also appear that you are assuming/hoping that there are never > >more than one instance of a phrase in either list. > > Sure. Because using advice of Skip Montanaro I initially used sets > to eliminate duplicates. I see two problems with your implementation of Skip's not-unreasonable suggestion. One: You've made the exercise into a multi-pass algorithm. Two: As I posted earlier, you need to get all the instances of the same key together at the same time. Otherwise you get problems. Suppose you have in each list, two translations apple -> polish1 and apple -> polish2. How can you guarantee that you remove the same duplicate from each list, if you remove duplicates independently from each list? > It's just not shown for brevity. Then say so. On the evidence, brevity was not a plausible explanation for the absence. :-) > If the > keys are guaranteed to be unique, it makes it easier to think > about the algorithm. Unfortunately in the real world you can't just imagine the problems away. Like I said, you have to think about the requirements first -- 9 cases of (0, 1, many) x (0, 1, many); what do you need to do? Then think about an implementation. > > >Note that in your snippet2 it was not very obvious what you want to do > >in the case where a phrase is in "new" but not in "old", and vice versa > >-- under one circumstance (you haven't met "end of file") you do > >nothing but in the the other circumstance you do something but seem to > >have not only a polarity problem but also a copy-paste-edit problem. > > What exactly is a "polarity problem"? You appeared to be treating "old" like I would have expected you to treat "new" and vice versa. > > I concede that the code is rather contrived, but I didn't bother > to do smth like writing classes or functions that would simulate > a tape reader, > so the result is rather ugly. I only posted it > because I could not explain why it were so slow. > Was what I posted ugly? Did you see in it any classes or functions simulating tape drives? From beliavsky at aol.com Sat Jan 1 17:46:17 2005 From: beliavsky at aol.com (beliavsky at aol.com) Date: 1 Jan 2005 14:46:17 -0800 Subject: Looping using iterators with fractional values References: <1104609929.888351.8870@c13g2000cwb.googlegroups.com> <86is6gripu.fsf@guru.mired.org> Message-ID: <1104619577.964461.84570@c13g2000cwb.googlegroups.com> Mike Meyer wrote: >Or - and much safer when dealing with floating point numbers - iterate >over integers and generate your float values: >for j in range(1, 9): > i = j * .25 > print "%9.2f" % i I agree with this suggestion. As an historical aside, Fortran had loops with floating point variables for decades, but in 1995, the first standard in a while to REMOVE features, this was one of the few things deleted. The Fortran standards committee is very conservative about creating backwards incompatibilities, but they must have thought loops with floating point variables are so error-prone -- and alternatives with integer counters are so easy to write -- that they put their foot down. I know the OP is asking about Python, but the principle is the same. From stephen.thorne at gmail.com Wed Jan 12 23:37:56 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 13 Jan 2005 14:37:56 +1000 Subject: Gecko bindings for Python? In-Reply-To: <1105456257.275667.6260@f14g2000cwb.googlegroups.com> References: <1105456257.275667.6260@f14g2000cwb.googlegroups.com> Message-ID: <3e8ca5c8050112203748211836@mail.gmail.com> there's wxMozilla, which is for embedding mozilla's rendering engine (I assume that's what you mean by 'Gecko') within wxpython/wxwidgets. Stephen. On 11 Jan 2005 07:10:57 -0800, Cordula's Web wrote: > Hello, > > I'd like to use the Gecko engine in GTK+ or Qt programs written in > Python. Could you recommend a module for this? A tutorial to get > started? I didn't find anything useful, but I may have been looking in > all the wrong places... :) > Thanks, > -cpghost. > > -- > Cordula's Web. http://www.cordula.ws/ > > -- > http://mail.python.org/mailman/listinfo/python-list > From firstname.lastname at iki.fi-spam Sat Jan 1 16:35:34 2005 From: firstname.lastname at iki.fi-spam (Simo Melenius) Date: 01 Jan 2005 23:35:34 +0200 Subject: Securing a future for anonymous functions in Python References: <10t84q9icqjnie7@news.supernews.com> Message-ID: Doug Holton writes: > Steven Bethard wrote: > > Simo Melenius wrote: > >> map (def x: Oops, I found a typo alreay. I meant to write "def (x):" -- no name for anonymous functions but just the argument list, please :) > Right the comma plus other things make this difficult for a parser to > handle correctly. Other people have already come up with working It is difficult since in Python we don't enjoy the ugly luxury of stuffing statements inside {}s. But as Bengt pointed out, parentheses don't actually look bad at all in this case. > Then the multi-line way. I had to add an overload of map to support > reversing the order of parameters (list first, then the closure): > > newlist = map([1,2,3,4,5,6]) def (x as int): > return x*x*x That doesn't seem to scale if you want to pass more than one anonymous function arguments to the function or call an arbitrary function with parameters in arbitrary order. br, S From ed at leafe.com Sun Jan 16 09:24:15 2005 From: ed at leafe.com (Ed Leafe) Date: Sun, 16 Jan 2005 09:24:15 -0500 Subject: Newbie inheritance question. In-Reply-To: <41EA754D.8020307@gmail.com> References: <41EA754D.8020307@gmail.com> Message-ID: <4CE8F854-67CA-11D9-A18A-003065B11E84@leafe.com> On Jan 16, 2005, at 9:08 AM, bwobbones wrote: > class two(one): > def __init__(self): > print "two" You need to specifically call the superclass's __init__ here in order for it to fire. Just add the line super(two, self).__init__() as the first line of the subclass's __init__. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From tjreedy at udel.edu Sat Jan 15 14:36:13 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 15 Jan 2005 14:36:13 -0500 Subject: interpret 4 byte as 32-bit float (IEEE-754) References: <34t1p2F4foiplU1@individual.net> <41e952b9$1@nntp0.pdx.net> Message-ID: "Scott David Daniels" wrote in message news:41e952b9$1 at nntp0.pdx.net... > franzkowiak wrote: >> I've read some bytes from a file and just now I can't interpret 4 bytes >> in this dates like a real value. An extract from my program: >> def l32(c): >> return ord(c[0]) + (ord(c[1])<<8) + (ord(c[2])<<16) + >> (ord(c[3])<<24) >> ... >> value = l32(f.read(4)) <--- 3F 8C CC CD should be 1.11 >> > OK, here's the skinny (I used blocks & views to get the answer): > > import struct > bytes = ''.join(chr(int(txt, 16)) for txt in '3F 8C CC CD'.split()) > struct.unpack('>f', bytes) > > I was suspicious of that first byte, thought it might be an exponent, > since it seemed to have too many on bits in a row to be part of 1.11. I believe exponents are typically stored as a positive offset from the largest negative exponent. 3F8 is about half of 7FF, so that seems about right for an actual exponent of 0. Terry J. Reedy From mmokrejs at ribosome.natur.cuni.cz Fri Jan 14 11:29:52 2005 From: mmokrejs at ribosome.natur.cuni.cz (=?UTF-8?B?TWFydGluIE1PS1JFSsWg?=) Date: Fri, 14 Jan 2005 17:29:52 +0100 Subject: Writing huge Sets() to disk In-Reply-To: <1f7befae05011408173df5ec96@mail.gmail.com> References: <41E2A91D.7080006@ribosome.natur.cuni.cz> <1105381712.3588.15.camel@localhost.localdomain> <41E2CE0E.5000704@ribosome.natur.cuni.cz> <1f7befae050110111239496b07@mail.gmail.com> <41E2E69C.7080104@ribosome.natur.cuni.cz> <1f7befae0501101245679b26f2@mail.gmail.com> <41E7EF70.1020505@ribosome.natur.cuni.cz> <1f7befae05011408173df5ec96@mail.gmail.com> Message-ID: <41E7F380.9000704@ribosome.natur.cuni.cz> Tim Peters wrote: > [Martin MOKREJ?] > >>This comm(1) approach doesn't work for me. It somehow fails to >>detect common entries when the offset is too big. [...] > I'll repeat: > > >>>As I mentioned before, if you store keys in sorted text files ... > > > Those files aren't in sorted order, so of course `comm` can't do > anything useful with them. Do `man sort`; sorting is not optional > here. I did read the manpage, but somehow it seems I did not execute sort(1) from within my python code, so it was unsorted and did did not realize it yet. Thanks! m. From gsakkis at rutgers.edu Mon Jan 24 17:54:26 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Mon, 24 Jan 2005 17:54:26 -0500 Subject: Tuple slices References: <35kn4mF4o44ufU1@individual.net> Message-ID: <35lckuF4kbtbfU1@individual.net> "Terry Reedy" wrote in message news:mailman.1226.1106605134.22381.python-list at python.org... > > Aside from the problem of not being able to delete the underlying object, > the view object for a tuple would have to be a new type of object with a > new set of methods. It *could*, but it doesn't have to. One can represent a view as essentially an object with a pointer to a memory buffer and a (start,stop,step) triple. Then a "real tuple" is just a "view" with the triple being (0, len(sequence), 1). George From python-url at phaseit.net Fri Jan 28 09:17:43 2005 From: python-url at phaseit.net (Cameron Laird) Date: Fri, 28 Jan 2005 14:17:43 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Jan 28) Message-ID: QOTW: "It might be nice if it was widely understood (in IT) that Python was a language any competent programmer could pick up in an afternoon, such that Java, C, and Perl shops would not be concerned about the need for their staff to learn a new language." -- Eric Pederson "What's kind of surprising is that it has turned out to be easier to rewire the entire world for high-bandwidth Internet than it is to make a good replication architecture so you can work disconnected!" -- Joel http://www.salon.com/tech/feature/2004/12/09/spolsky/index4.html It's the Early Bird deadline for PyCon 2005! http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/5a0eef8d2f4b41c6 A wide-ranging thread on "security" yields, among other high points, a recommendation to read *Security Engineering* and examples of real security issues Python has: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/a5ab5a6a91590230/ Can Python operate on a Windows "desktop"? Sure, in a variety of ways. Thanks to Dennis Benzinger, Jimmy Retzlaff, Vincent Wehren, and others for their catalogue: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/f73cc8e9cad01288/ The martellibot illustrates why Python's introspection--and __subclasses__, in particular--make correct "sandboxing" so challenging for us: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d5f4d7e2c397c2ca/ After a rest of a couple months, it's time again to urge consideration of IPython as your working shell: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/3fed261a83318a1e 4XSLT is thread-safe, but individual processor instances are not. 4Suite exploits processor-per-thread: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/c118d6ead64ca003 Thread inheritance with win32com requires Co*nitialize() management: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/3e3487f970825fc8 Gerald and the timbot speak sense on the platform-specificity that is memory management. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/2bef18c56f085eeb Do NOT let your inheritance schemes complexify. One palliative tactic is to remember (lazy) "containerization" as an alternative to subclassing. And learn about decorators. And descriptors, for that matter: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/730e4e3bb3c55b28/ Do people still FTP? Well, Python people *can* ...: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/37b847a725bd8d9f ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. deli.cio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From rnd at onego.ru Wed Jan 5 04:15:29 2005 From: rnd at onego.ru (Roman Suzi) Date: Wed, 5 Jan 2005 12:15:29 +0300 (MSK) Subject: Concepts RE: Python evolution: Unease In-Reply-To: <20050105002302.542768387.EP@zomething.com> References: <20050105002302.542768387.EP@zomething.com> Message-ID: On Wed, 5 Jan 2005, EP wrote: >Roman wrote: > >> Maybe OP doesn't yet fully comprehend the ways of Python universe? > > > >> > Don't misinterpret this response. I know it was a rambling. But >> *maybe* you >> > have something to contribute to Python development, even good ideas >> only and >> > no work. >> > >> > . Facundo > > >Am I selling Snake Oil? > >What I do have is a "forest" instead of an "in the trees" perspective, and >from a forest view I see a lot of defensiveness about Python's hypothetical >shortcomings. No one needs be defensive, Python is an amazing programming >language, and everyone involved with its development, evolution, support and >codebase ought to feel quite good about it. -skip- It's c.l.p and people are free to express their opinions. Even negative. This helps improve Python. As for concepts, they are from Generic Programming (by Musser and Stepanov) and I feel that Python is in position to implement them to the fullest extent. And IMHO it will be nicer than just Java-like interfaces or Eiffel's contract approach. I can try to write a PEP "Generic Programming Concepts". Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From drs at remove-to-send-mail-ecpsoftware.com Tue Jan 11 01:11:04 2005 From: drs at remove-to-send-mail-ecpsoftware.com (drs) Date: Tue, 11 Jan 2005 06:11:04 GMT Subject: shutil.move has a mind of its own References: Message-ID: "Delaney, Timothy C (Timothy)" wrote in message news:mailman.492.1105420104.22381.python-list at python.org... Daniel Bickett wrote: > > shutil.move( "C:\omg.txt" , "C:\folder\subdir" ) ^ ^^ ^ > The problem is that backslash is the escape character. In particular, > '\f' is a form feed. > You have a couple of options: You can also include an r to make it a raw string if extra or reversed slashes look odd shutil.move( r"C:\omg.txt" , r"C:\folder\subdir" ) From __peter__ at web.de Tue Jan 25 19:31:50 2005 From: __peter__ at web.de (Peter Otten) Date: Wed, 26 Jan 2005 01:31:50 +0100 Subject: string.atoi and string.atol broken? References: Message-ID: Mike Moum wrote: > s.atoi('4',3) should result in 11 > > s.atoi('13',4) should result in 31 > > s.atoi('12',4) should result in 30 > > s.atoi('8',4) is legitimate, but it generates an error. > > Is this a bug, or am I missing something obvious? You and atoi() seem to disagree about the direction of the conversion, and atoi() wins :-). It converts a string representation of a number into the corresponding integer. The second parameter specifies in what base this string is given. You seem to want something like import string def itoa(n, base): assert 2 <= base <= 16 if n < 0: digits = ["-"] n = -n else: digits = [] while n: n, m = divmod(n, base) digits.append(string.hexdigits[m]) digits.reverse() return "".join(digits) if __name__ == "__main__": assert itoa(4, 3) == "11" assert itoa(13, 4) == "31" assert itoa(12, 4) == "30" assert itoa(8, 4) == "20" Peter From skip at pobox.com Thu Jan 27 10:00:10 2005 From: skip at pobox.com (Skip Montanaro) Date: Thu, 27 Jan 2005 09:00:10 -0600 Subject: What's so funny? WAS Re: rotor replacement In-Reply-To: References: <7xpszxcnfa.fsf@ruckus.brouhaha.com> <7xllalcmqc.fsf@ruckus.brouhaha.com> <7xbrbhosh7.fsf@ruckus.brouhaha.com> <7xzmz0lw6h.fsf@ruckus.brouhaha.com> <41f4324a$0$1547$9b622d9e@news.freenet.de> <41f589f9$0$3357$9b622d9e@news.freenet.de> <41f6a8ef$0$27790$9b622d9e@news.freenet.de> <41f7efc2$0$11596$9b622d9e@news.freenet.de> Message-ID: <16889.506.492631.398094@montanaro.dyndns.org> >> As long as we are discussing cryptography, what's wrong with m2crypto? >> Or, what about Andrew Kuchling's crypto toolkit? Lucas> Umm, is it just me or did we just discuss the legal issues of Lucas> that?? You may have. Whether or not there are legal issues with them is of little relevance to the point I was making. Anything Paul writes would probably have the same legal entanglements. I was simply pointing out that maybe, just maybe, there are already suitable candidates from a technical standpoint and that he doesn't need to write anything. Skip From binux.lists at gmail.com Thu Jan 6 05:15:39 2005 From: binux.lists at gmail.com (Binu K S) Date: Thu, 6 Jan 2005 15:45:39 +0530 Subject: file.readlines() - gives me error (bad file descriptor) In-Reply-To: References: <1104992568.755808.326490@f14g2000cwb.googlegroups.com> <003801c4f3b9$af17fa20$0800a8c0@vishnu> <2b7d8b42050105232546083758@mail.gmail.com> <2b7d8b420501060057270f1878@mail.gmail.com> Message-ID: <2b7d8b420501060215c9147a8@mail.gmail.com> http://mail.python.org/pipermail/python-bugs-list/2001-October/007650.html Rest assured you're not on drugs :) On Thu, 6 Jan 2005 14:45:24 +0530, Gurpreet Sachdeva wrote: > On Thu, 6 Jan 2005 14:27:40 +0530, Binu K S wrote: > > I'm sorry, I didn't get what you trying to say here. Where do you see > > a read altering the file? An example might help. > > Please try: > > logfile=file(r'test.txt','w+') > logfile.write('datetime') > > Check the contents of test.txt, you will get what ever was required... > > Now Run: > > logfile=file(r'test.txt','w+') > logfile.write('datetime') > logfile.readlines() > > and check the contents of test.txt??? > My doubt is that logfile.write('datetime') will write datetime that is > universaly accepted but why all that junk is appending to that when I > add logfile.readlines() > > Strange or Am I on drugs??? :o) > > Please Comment... > > Garry > From rupole at hotmail.com Sat Jan 29 16:52:53 2005 From: rupole at hotmail.com (Roger Upole) Date: Sat, 29 Jan 2005 16:52:53 -0500 Subject: Description Field in WinXP Services References: Message-ID: <41fc0646$1_1@127.0.0.1> ChangeServiceConfig2 is the api functions that sets the description, but it's not in the win32service module (yet). Roger "rbt" wrote in message news:ctgij1$diq$1 at solaris.cc.vt.edu... > How does one associate a "Description" with a Windows service written in > Python? I've just started experimenting with Python services. Here's my > code... copied straight from Mr. Hammond's "Python Programming on Win32": > > import win32serviceutil > import win32service > import win32event > > class test_py_service(win32serviceutil.ServiceFramework): > _svc_name_ = "test_py_service" > ## Tried the following to no avail. > _svc_description_ = "Test written by Brad" > _svc_display_name_ = "Test Python Service" > > def __init__(self, args): > win32serviceutil.ServiceFramework.__init__(self, args) > self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) > > def SvcStop(self): > self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) > win32event.SetEvent(self.hWaitStop) > > def SvcDoRun(self): > win32event.WaitForSingleObject(self.hWaitStop, > win32event.INFINITE) > > > if __name__ == '__main__': > win32serviceutil.HandleCommandLine(test_py_service) > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= East/West-Coast Server Farms - Total Privacy via Encryption =---